Added a bunch of stuff and I now need to store said stuff

This commit is contained in:
Olivier Tremblay 2018-05-02 09:36:19 -04:00
parent 1458b63287
commit 9aa31ec22c
No known key found for this signature in database
GPG key ID: D1C73ACB855E3A6D
7 changed files with 287 additions and 120 deletions

View file

@ -21,9 +21,9 @@ func NewEditCmd(args []string) (*EditCmd, error) {
ccmd := &EditCmd{project: os.Getenv("JIRA_PROJECT")} ccmd := &EditCmd{project: os.Getenv("JIRA_PROJECT")}
f := flag.NewFlagSet("x", flag.ExitOnError) f := flag.NewFlagSet("x", flag.ExitOnError)
f.StringVar(&ccmd.project, "p", "", "Jira project key") f.StringVar(&ccmd.project, "p", "", "Jira project key")
f.StringVar(&ccmd.file, "f", "filename", "File to get issue description from") f.StringVar(&ccmd.file, "f", "", "File to get issue description from")
f.Parse(args) f.Parse(args)
ccmd.taskKey = flag.Arg(0) ccmd.taskKey = f.Arg(0)
return ccmd, nil return ccmd, nil
} }

View file

@ -17,6 +17,7 @@ import (
"otremblay.com/jkl" "otremblay.com/jkl"
) )
// def get_editor do // def get_editor do
// [System.get_env("EDITOR"), "nano", "vim", "vi"] // [System.get_env("EDITOR"), "nano", "vim", "vi"]
// |> Enum.find(nil, fn (ed) -> System.find_executable(ed) != nil end) // |> Enum.find(nil, fn (ed) -> System.find_executable(ed) != nil end)
@ -154,12 +155,17 @@ func IssueFromReader(f io.Reader, editMeta *jkl.EditMeta) *jkl.JiraIssue {
} else { } else {
currentField = newfield currentField = newfield
} }
} else if editMeta != nil { } else if editMeta != nil {
// If it's not valid, throw it at the createmeta. It will probably end up in ExtraFields. // If it's not valid, throw it at the createmeta. It will probably end up in ExtraFields.
} }
if currentField.IsValid() { if currentField.IsValid() {
currentField.SetString(strings.TrimSpace(currentField.String() + "\n" + strings.Join(parts, ":"))) newpart := strings.Join(parts, ":")
newvalue := currentField.String() + "\n" + newpart
if strings.TrimSpace(newpart) != "" {
newvalue = strings.TrimSpace(newvalue)
}
currentField.SetString(newvalue)
} }
} }
return iss return iss

View file

@ -55,12 +55,20 @@ func getCmd(args []string, depth int) (Runner, error) {
case "edit": case "edit":
return NewEditCmd(args[1:]) return NewEditCmd(args[1:])
case "comment": case "comment":
if strings.Contains(strings.Join(args,""),jkl.CommentIdSeparator){ if strings.Contains(strings.Join(args, ""), jkl.CommentIdSeparator) {
return NewEditCommentCmd(args[1:]) return NewEditCommentCmd(args[1:])
} }
return NewCommentCmd(args[1:]) return NewCommentCmd(args[1:])
case "edit-comment": case "edit-comment":
return NewEditCommentCmd(args[1:]) return NewEditCommentCmd(args[1:])
case "assign":
return NewAssignCmd(args[1:])
case "flag":
return NewFlagCmd(args[1:], true)
case "unflag":
return NewFlagCmd(args[1:], false)
case "link":
return NewLinkCmd(args[1:])
default: default:
// Think about this real hard. // Think about this real hard.
// I want `jkl JIRA-1234 done` to move it to done. // I want `jkl JIRA-1234 done` to move it to done.
@ -92,9 +100,10 @@ func getCmd(args []string, depth int) (Runner, error) {
return nil, ErrTaskSubCommandNotFound return nil, ErrTaskSubCommandNotFound
} }
var verbs = []string{"list", "create", "task", "edit", "comment","edit-comment"} var verbs = []string{"list", "create", "task", "edit", "comment", "edit-comment"}
func init(){
sort.Strings(verbs) func init() {
sort.Strings(verbs)
} }
const usage = `Usage: const usage = `Usage:

View file

@ -21,6 +21,9 @@ func (l *listissue) URL() string {
} }
func (l *listissue) Color() string { func (l *listissue) Color() string {
if l.Fields == nil || l.Fields.Status == nil {
return ""
}
if os.Getenv("JKLNOCOLOR") == "true" || !terminal.IsTerminal(int(os.Stdout.Fd())) { if os.Getenv("JKLNOCOLOR") == "true" || !terminal.IsTerminal(int(os.Stdout.Fd())) {
return "" return ""
} }
@ -52,7 +55,7 @@ func NewListCmd(args []string) (*ListCmd, error) {
if *verbose { if *verbose {
fmt.Println(&ccmd.tmplstr) fmt.Println(&ccmd.tmplstr)
} }
f.StringVar(&ccmd.tmplstr, "listTemplate", "{{.Color}}{{.Key}}{{if .Color}}\x1b[39m{{end}}\t({{.Fields.IssueType.Name}}{{if .Fields.Parent}} of {{.Fields.Parent.Key}}{{end}})\t{{.Fields.Summary}}\t{{if .Fields.Assignee}}[{{.Fields.Assignee.Name}}]{{end}}\n", "Go template used in list command") f.StringVar(&ccmd.tmplstr, "listTemplate", "{{.Color}}{{.Key}}{{if .Color}}\x1b[39m{{end}}\t({{if .Fields.IssueType}}{{.Fields.IssueType.Name}}{{end}}{{if .Fields.Parent}} of {{.Fields.Parent.Key}}{{end}})\t{{.Fields.Summary}}\t{{if .Fields.Assignee}}[{{.Fields.Assignee.Name}}]{{end}}\n", "Go template used in list command")
f.Parse(args) f.Parse(args)
ccmd.args = f.Args() ccmd.args = f.Args()
if len(ccmd.args) == 0 { if len(ccmd.args) == 0 {

216
issue.go
View file

@ -19,9 +19,9 @@ type Search struct {
} }
type IssueType struct { type IssueType struct {
Name string `json:"name"` Name string `json:"name"`
IconURL string `json:",omitempty"` IconURL string `json:",omitempty"`
Fields map[string]*FieldSpec Fields map[string]*FieldSpec
} }
func (it *IssueType) RangeFieldSpecs() string { func (it *IssueType) RangeFieldSpecs() string {
@ -38,12 +38,12 @@ func (it *IssueType) RangeFieldSpecs() string {
} }
type AllowedValue struct { type AllowedValue struct {
Id string Id string
Self string Self string
Value string Value string
} }
func (a *AllowedValue) String() string{ func (a *AllowedValue) String() string {
return a.Value return a.Value
} }
@ -51,24 +51,22 @@ type FieldSpec struct {
Name string Name string
Required bool Required bool
Schema struct { Schema struct {
Type string Type string
Custom string Custom string
CustomId int CustomId int
Items string Items string
} }
Operations []string Operations []string
AllowedValues []*AllowedValue AllowedValues []*AllowedValue
} }
type CreateMeta struct { type CreateMeta struct {
Projects []*Project Projects []*Project
} }
type Project struct { type Project struct {
Key string `json:"key,omitempty"` Key string `json:"key,omitempty"`
Name string Name string
IssueTypes []*IssueType IssueTypes []*IssueType
} }
@ -82,9 +80,9 @@ func (a *Author) String() string {
} }
type Comment struct { type Comment struct {
Id string `json:"id"` Id string `json:"id"`
Author *Author `json:"author"` Author *Author `json:"author"`
Body string `json:"body"` Body string `json:"body"`
} }
type CommentColl struct { type CommentColl struct {
@ -92,7 +90,7 @@ type CommentColl struct {
} }
type Status struct { type Status struct {
Name string Name string
IconURL string `json:",omitempty"` IconURL string `json:",omitempty"`
} }
@ -107,14 +105,14 @@ func (a *Attachment) String() string {
type Attachment struct { type Attachment struct {
Filename string Filename string
Author *Author Author *Author
Content string Content string
} }
type LinkType struct { type LinkType struct {
Id string Id string
Name string Name string
Inward string Inward string
Outward string Outward string
} }
@ -129,8 +127,8 @@ func (i *IssueLink) String() string {
} }
type IssueLink struct { type IssueLink struct {
LinkType *LinkType `json:"type"` LinkType *LinkType `json:"type"`
InwardIssue *JiraIssue InwardIssue *JiraIssue
OutwardIssue *JiraIssue OutwardIssue *JiraIssue
} }
@ -139,36 +137,48 @@ func (w *Worklog) String() string {
} }
type Worklog struct { type Worklog struct {
Author *Author Author *Author
Comment string Comment string
TimeSpent string TimeSpent string
TimeSpentSeconds int TimeSpentSeconds int
Started string Started string
} }
type Worklogs struct { type Worklogs struct {
Worklogs []*Worklog `json:",omitempty"` Worklogs []*Worklog `json:",omitempty"`
} }
func (f *Fields) UnmarshalJSON(b []byte) error{ func (f *Fields) UnmarshalJSON(b []byte) error {
err := json.Unmarshal(b, &f.rawFields) err := json.Unmarshal(b, &f.rawFields)
if err != nil { if err != nil {
fmt.Println("splosion") fmt.Println("splosion")
return err return err
} }
f.rawExtraFields = map[string]json.RawMessage{} f.rawExtraFields = map[string]json.RawMessage{}
vf := reflect.ValueOf(f).Elem() if reflect.ValueOf(f) == reflect.Zero(reflect.TypeOf(f)) {
fmt.Println("wtf")
}
v := reflect.ValueOf(f)
if !v.IsValid() {
fmt.Println("What all the fucks")
}
vf := v.Elem()
for key, mess := range f.rawFields { for key, mess := range f.rawFields {
field := vf.FieldByNameFunc(func(s string)bool{return strings.ToLower(key) == strings.ToLower(s)}) field := vf.FieldByNameFunc(func(s string) bool { return strings.ToLower(key) == strings.ToLower(s) })
if field.IsValid() { if field.IsValid() {
objType := field.Type() objType := field.Type()
obj := reflect.New(objType).Interface() obj := reflect.New(objType).Interface()
err := json.Unmarshal(mess, &obj) err := json.Unmarshal(mess, &obj)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, objType, obj, string(mess)) fmt.Fprintln(os.Stderr, objType, obj, string(mess))
fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s [%s]: %s","Error allocating field",key, err))) fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s [%s]: %s", "Error allocating field", key, err)))
}
val := reflect.ValueOf(obj)
if val == reflect.Zero(reflect.TypeOf(val)) || !val.IsValid() {
field.Set(reflect.Zero(objType))
} else {
field.Set(val.Elem())
} }
field.Set(reflect.ValueOf(obj).Elem())
} else { } else {
f.rawExtraFields[key] = mess f.rawExtraFields[key] = mess
} }
@ -182,22 +192,22 @@ type Priority struct {
} }
type Fields struct { type Fields struct {
*IssueType `json:"issuetype,omitempty"` *IssueType `json:"issuetype,omitempty"`
Assignee *Author `json:",omitempty"` Assignee *Author `json:",omitempty"`
Project *Project `json:"project,omitempty"` Project *Project `json:"project,omitempty"`
Summary string `json:"summary,omitempty"` Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"` Description string `json:"description,omitempty"`
Comment *CommentColl `json:"comment,omitempty"` Comment *CommentColl `json:"comment,omitempty"`
Parent *JiraIssue `json:",omitempty"` Parent *JiraIssue `json:",omitempty"`
Status *Status `json:",omitempty"` Status *Status `json:",omitempty"`
TimeTracking *TimeTracking `json:"timetracking,omitempty"` TimeTracking *TimeTracking `json:"timetracking,omitempty"`
Attachment []*Attachment `json:"attachment,omitempty"` Attachment []*Attachment `json:"attachment,omitempty"`
IssueLinks []*IssueLink `json:"issueLinks,omitempty"` IssueLinks []*IssueLink `json:"issueLinks,omitempty"`
Priority *Priority `json:",omitempty"` Priority *Priority `json:",omitempty"`
Worklog *Worklogs `json:"worklog,omitempty"` Worklog *Worklogs `json:"worklog,omitempty"`
rawFields map[string]json.RawMessage rawFields map[string]json.RawMessage
rawExtraFields map[string]json.RawMessage rawExtraFields map[string]json.RawMessage
ExtraFields map[string]interface{} `json:"-"` ExtraFields map[string]interface{} `json:"-"`
} }
func (f *Fields) PrettyRemaining() string { func (f *Fields) PrettyRemaining() string {
@ -218,55 +228,57 @@ func PrettySeconds(seconds int) string {
return fmt.Sprintf("%dd %2dh %2dm %2ds", days, hours, minutes, seconds) return fmt.Sprintf("%dd %2dh %2dm %2ds", days, hours, minutes, seconds)
} }
type Transition struct{ type Transition struct {
Id string `json:"id"` Id string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
} }
type Schema struct { type Schema struct {
System string System string
Custom string Custom string
CustomId int CustomId int
} }
type EditMeta struct { type EditMeta struct {
Fields map[string]*FieldSpec Fields map[string]*FieldSpec
} }
type JiraIssue struct { type JiraIssue struct {
Key string `json:"key,omitempty"` Key string `json:"key,omitempty"`
Fields *Fields `json:"fields,omitempty"` Fields *Fields `json:"fields,omitempty"`
Transitions []*Transition `json:"transitions,omitempty"` Transitions []*Transition `json:"transitions,omitempty"`
EditMeta *EditMeta `json:"editmeta,omitempty"` EditMeta *EditMeta `json:"editmeta,omitempty"`
} }
var sprintRegexp = regexp.MustCompile(`name=([^,]+),`)
var sprintRegexp = regexp.MustCompile(`name=([^,]+),`)
func (i *JiraIssue) UnmarshalJSON(b []byte) error { func (i *JiraIssue) UnmarshalJSON(b []byte) error {
tmp := map[string]json.RawMessage{} tmp := map[string]json.RawMessage{}
if len(b) == 0 { if len(b) == 0 {
return nil return nil
} }
i.Fields = &Fields{} i.Fields = &Fields{}
i.EditMeta = &EditMeta{Fields:map[string]*FieldSpec{}} i.EditMeta = &EditMeta{Fields: map[string]*FieldSpec{}}
err := json.Unmarshal(b, &tmp) err := json.Unmarshal(b, &tmp)
if err != nil && *Verbose { if err != nil && *Verbose {
fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking raw json", err))) fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking raw json", err)))
} }
if _, ok := tmp["fields"]; !ok {
fmt.Fprintln(os.Stderr, "Received no fields? wtf?")
fmt.Fprintln(os.Stderr, string(b))
os.Exit(1)
}
err = json.Unmarshal(tmp["fields"], &i.Fields) err = json.Unmarshal(tmp["fields"], &i.Fields)
if err != nil && *Verbose { if err != nil && *Verbose {
fmt.Println(string(tmp["fields"]))
fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking fields", err))) fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking fields", err)))
} }
err = json.Unmarshal(tmp["transitions"], &i.Transitions) err = json.Unmarshal(tmp["transitions"], &i.Transitions)
if err != nil && *Verbose { if err != nil && *Verbose {
fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking transitions", err))) fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking transitions", err)))
} }
err = json.Unmarshal(tmp["editmeta"], &i.EditMeta) err = json.Unmarshal(tmp["editmeta"], &i.EditMeta)
if err != nil && *Verbose{ if err != nil && *Verbose {
fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking EditMeta", err))) fmt.Fprintln(os.Stderr, errors.New(fmt.Sprintf("%s: %s", "Error unpacking EditMeta", err)))
} }
err = json.Unmarshal(tmp["key"], &i.Key) err = json.Unmarshal(tmp["key"], &i.Key)
@ -282,34 +294,39 @@ func (i *JiraIssue) UnmarshalJSON(b []byte) error {
if len(results) == 2 { if len(results) == 2 {
i.Fields.ExtraFields[k] = results[1] i.Fields.ExtraFields[k] = results[1]
} }
} else {switch f.Schema.Type { } else {
case "user": switch f.Schema.Type {
a := &Author{} case "user":
json.Unmarshal(v, &a) a := &Author{}
i.Fields.ExtraFields[k] = a json.Unmarshal(v, &a)
case "option": i.Fields.ExtraFields[k] = a
val := &AllowedValue{} case "option":
err = json.Unmarshal(v, &val) val := &AllowedValue{}
if err != nil {panic(err)} err = json.Unmarshal(v, &val)
i.Fields.ExtraFields[k] = val if err != nil {
case "array": panic(err)
if f.Schema.Items == "option" { }
val := []*AllowedValue{} i.Fields.ExtraFields[k] = val
err = json.Unmarshal(v, &val) case "array":
if err != nil {panic(err)} if f.Schema.Items == "option" {
i.Fields.ExtraFields[k] = val val := []*AllowedValue{}
continue err = json.Unmarshal(v, &val)
} if err != nil {
fallthrough panic(err)
default: }
if string(v) != "null" { i.Fields.ExtraFields[k] = val
i.Fields.ExtraFields[k] = string(v) continue
}
fallthrough
default:
if string(v) != "null" {
i.Fields.ExtraFields[k] = strings.Replace(string(v), "\\r\\n", "\n", -1)
}
} }
} }
}
} }
} }
return nil return nil
} }
@ -323,6 +340,9 @@ func (i *JiraIssue) String() string {
if os.Getenv("JKLNOCOLOR") == "true" { if os.Getenv("JKLNOCOLOR") == "true" {
tmpl = issueTmplNoColor tmpl = issueTmplNoColor
} }
if customTmpl := os.Getenv("JKL_ISSUE_TMPL"); customTmpl != "" {
tmpl = template.Must(template.New("customIssueTmpl").Parse(customTmpl))
}
err := tmpl.Execute(b, i) err := tmpl.Execute(b, i)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
@ -331,7 +351,7 @@ func (i *JiraIssue) String() string {
return b.String() return b.String()
} }
func (i *JiraIssue) PrintExtraFields() string{ func (i *JiraIssue) PrintExtraFields() string {
sorter := map[string]string{} sorter := map[string]string{}
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
for k, v := range i.Fields.ExtraFields { for k, v := range i.Fields.ExtraFields {
@ -350,7 +370,7 @@ func (i *JiraIssue) PrintExtraFields() string{
return b.String() return b.String()
} }
var commentTemplate = `{{if .Fields.Comment }}{{$k := .Key}}{{range .Fields.Comment.Comments}}{{.Author.DisplayName}} [~{{.Author.Name}}] ({{$k}}`+CommentIdSeparator+`{{.Id}}): var commentTemplate = `{{if .Fields.Comment }}{{$k := .Key}}{{range .Fields.Comment.Comments}}{{.Author.DisplayName}} [~{{.Author.Name}}] ({{$k}}` + CommentIdSeparator + `{{.Id}}):
----------------- -----------------
{{.Body}} {{.Body}}
----------------- -----------------
@ -358,28 +378,28 @@ var commentTemplate = `{{if .Fields.Comment }}{{$k := .Key}}{{range .Fields.Comm
{{end}}{{end}}` {{end}}{{end}}`
var issueTmplTxt = "\x1b[1m{{.Key}}\x1b[0m\t{{if .Fields.IssueType}}[{{.Fields.IssueType.Name}}]{{end}}\t{{.Fields.Summary}}\n\n" + var issueTmplTxt = "\x1b[1m{{.Key}}\x1b[0m\t{{if .Fields.IssueType}}[{{.Fields.IssueType.Name}}]{{end}}\t{{.Fields.Summary}}\n\n" +
"\x1b[1mURL\x1b[0m: {{.URL}}\n\n" + "\x1b[1mURL\x1b[0m: {{.URL}}\n\n" +
"{{if .Fields.Status}}\x1b[1mStatus\x1b[0m:\t {{.Fields.Status.Name}}\n{{end}}" + "{{if .Fields.Status}}\x1b[1mStatus\x1b[0m:\t {{.Fields.Status.Name}}\n{{end}}" +
"{{if .Fields.Priority}}\x1b[1mStatus\x1b[0m:\t {{.Fields.Priority.Name}}\n{{end}}" + "{{if .Fields.Priority}}\x1b[1mStatus\x1b[0m:\t {{.Fields.Priority.Name}}\n{{end}}" +
"\x1b[1mTransitions\x1b[0m: {{range .Transitions}}[{{.Name}}] {{end}}\n"+ "\x1b[1mTransitions\x1b[0m: {{range .Transitions}}[{{.Name}}] {{end}}\n" +
"{{if .Fields.Assignee}}\x1b[1mAssignee:\x1b[0m\t{{.Fields.Assignee.Name}}\n{{end}}\n" + "{{if .Fields.Assignee}}\x1b[1mAssignee:\x1b[0m\t{{.Fields.Assignee.Name}}\n{{end}}\n" +
"\x1b[1mTime Remaining/Original Estimate:\x1b[0m\t{{.Fields.PrettyRemaining}} / {{.Fields.PrettyOriginalEstimate}}\n\n" + "\x1b[1mTime Remaining/Original Estimate:\x1b[0m\t{{.Fields.PrettyRemaining}} / {{.Fields.PrettyOriginalEstimate}}\n\n" +
"{{$i := .}}{{range $k, $v := .Fields.ExtraFields}}{{with index $i.EditMeta.Fields $k}}\x1b[1m{{.Name}}\x1b[0m{{end}}: {{$v}}\n{{end}}\n\n"+ "{{$i := .}}{{range $k, $v := .Fields.ExtraFields}}{{with index $i.EditMeta.Fields $k}}\x1b[1m{{.Name}}\x1b[0m{{end}}: {{$v}}\n{{end}}\n\n" +
"\x1b[1mDescription:\x1b[0m {{.Fields.Description}} \n\n" + "\x1b[1mDescription:\x1b[0m {{.Fields.Description}} \n\n" +
"\x1b[1mIssue Links\x1b[0m: \n{{range .Fields.IssueLinks}}\t{{.}}\n{{end}}\n\n" + "\x1b[1mIssue Links\x1b[0m: \n{{range .Fields.IssueLinks}}\t{{.}}\n{{end}}\n\n" +
"\x1b[1mComments:\x1b[0m\n\n" + commentTemplate + "\x1b[1mComments:\x1b[0m\n\n" + commentTemplate +
"Worklog:\n{{range .Fields.Worklog.Worklogs}}\t{{.}}\n{{end}}" "Worklog:\n{{range .Fields.Worklog.Worklogs}}\t{{.}}\n{{end}}"
var issueTmplNoColorTxt = "{{.Key}}\t{{if .Fields.IssueType}}[{{.Fields.IssueType.Name}}]{{end}}\t{{.Fields.Summary}}\n\n" + var issueTmplNoColorTxt = "{{.Key}}\t{{if .Fields.IssueType}}[{{.Fields.IssueType.Name}}]{{end}}\t{{.Fields.Summary}}\n\n" +
"URL: {{.URL}}\n\n" + "URL: {{.URL}}\n\n" +
"{{if .Fields.Status}}Status:\t {{.Fields.Status.Name}}\n{{end}}" + "{{if .Fields.Status}}Status:\t {{.Fields.Status.Name}}\n{{end}}" +
"Transitions: {{range .Transitions}}[{{.Name}}] {{end}}\n"+ "Transitions: {{range .Transitions}}[{{.Name}}] {{end}}\n" +
"{{if .Fields.Assignee}}Assignee:\t{{.Fields.Assignee.Name}}\n{{end}}\n" + "{{if .Fields.Assignee}}Assignee:\t{{.Fields.Assignee.Name}}\n{{end}}\n" +
"Time Remaining/Original Estimate:\t{{.Fields.PrettyRemaining}} / {{.Fields.PrettyOriginalEstimate}}\n\n" + "Time Remaining/Original Estimate:\t{{.Fields.PrettyRemaining}} / {{.Fields.PrettyOriginalEstimate}}\n\n" +
"{{.PrintExtraFields}}\n\n"+ "{{.PrintExtraFields}}\n\n" +
"Description: {{.Fields.Description}} \n\n" + "Description: {{.Fields.Description}} \n\n" +
"Issue Links: \n{{range .Fields.IssueLinks}}\t{{.}}\n{{end}}\n\n" + "Issue Links: \n{{range .Fields.IssueLinks}}\t{{.}}\n{{end}}\n\n" +
"Comments:\n\n" + commentTemplate+ "Comments:\n\n" + commentTemplate +
"Worklog:\n{{range .Fields.Worklog.Worklogs}}\t{{.}}\n{{end}}" "Worklog:\n{{range .Fields.Worklog.Worklogs}}\t{{.}}\n{{end}}"
var CommentIdSeparator = "~" var CommentIdSeparator = "~"

View file

@ -1,6 +1,8 @@
package jkl package jkl
import ( import (
"bytes"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -9,6 +11,8 @@ import (
"net/http/cookiejar" "net/http/cookiejar"
"net/url" "net/url"
"os" "os"
"strings"
"time"
) )
var j, _ = cookiejar.New(nil) var j, _ = cookiejar.New(nil)
@ -20,40 +24,85 @@ type JiraClient struct {
jiraRoot string jiraRoot string
} }
func init(){ func init() {
x := false x := false
Verbose = &x Verbose = &x
} }
func NewJiraClient(jiraRoot string) *JiraClient { func NewJiraClient(jiraRoot string) *JiraClient {
j := &JiraClient{ jc := &JiraClient{
&http.Client{ &http.Client{
Jar: j, Jar: j,
}, },
jiraRoot, jiraRoot,
} }
if j.jiraRoot == "" { if jc.jiraRoot == "" {
j.jiraRoot = os.Getenv("JIRA_ROOT") jc.jiraRoot = os.Getenv("JIRA_ROOT")
} }
if cookiefile := os.Getenv("JIRA_COOKIEFILE"); cookiefile != "" {
makeNewFile := false
f, err := os.Open(cookiefile)
server := jc.jiraRoot + "rest/gadget/1.0/login"
u, _ := url.Parse(server)
if err != nil {
makeNewFile = true
} else {
if stat, err := f.Stat(); err == nil {
if time.Now().Sub(stat.ModTime()).Minutes() > 60 {
makeNewFile = true
} else {
var cookies []*http.Cookie
dec := json.NewDecoder(f)
dec.Decode(&cookies)
u, _ = url.Parse(jc.jiraRoot)
jc.Jar.SetCookies(u, cookies)
}
}
f.Close()
}
if makeNewFile {
f, err = os.Create(cookiefile)
if err != nil {
panic(err)
}
http.DefaultClient.Jar = j
form := url.Values{}
form.Add("os_username", os.Getenv("JIRA_USER"))
form.Add("os_password", os.Getenv("JIRA_PASSWORD"))
req, _ := http.NewRequest("POST", server, strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode >= 400 {
fmt.Println(resp.Header)
fmt.Println(resp.Status)
fmt.Println(err)
}
b := bytes.NewBuffer(nil)
enc := json.NewEncoder(b)
enc.Encode(j.Cookies(u))
io.Copy(f, b)
f.Close()
}
}
if *Verbose { if *Verbose {
fmt.Println("Jira root:", j.jiraRoot) fmt.Println("Jira root:", jc.jiraRoot)
} }
return j return jc
} }
func (j *JiraClient) Do(req *http.Request) (*http.Response, error) { func (j *JiraClient) DoLess(req *http.Request) (*http.Response, error) {
var err error var err error
req.SetBasicAuth(os.Getenv("JIRA_USER"), os.Getenv("JIRA_PASSWORD")) if os.Getenv("JIRA_COOKIEFILE") == "" {
req.SetBasicAuth(os.Getenv("JIRA_USER"), os.Getenv("JIRA_PASSWORD"))
}
if *Verbose { if *Verbose {
fmt.Println("Jira User: ", os.Getenv("JIRA_USER")) fmt.Println("Jira User: ", os.Getenv("JIRA_USER"))
fmt.Println("Jira Password: ", os.Getenv("JIRA_PASSWORD")) fmt.Println("Jira Password: ", os.Getenv("JIRA_PASSWORD"))
} }
req.Header.Add("Content-Type", "application/json") req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json, text/plain, text/html") req.Header.Add("Accept", "application/json, text/plain, text/html")
req.URL, err = url.Parse(j.jiraRoot + "rest/" + req.URL.RequestURI())
if err != nil {
return nil, err
}
resp, err := j.Client.Do(req) resp, err := j.Client.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
@ -75,6 +124,15 @@ func (j *JiraClient) Do(req *http.Request) (*http.Response, error) {
return resp, nil return resp, nil
} }
func (j *JiraClient) Do(req *http.Request) (*http.Response, error) {
var err error
req.URL, err = url.Parse(j.jiraRoot + "rest/" + req.URL.RequestURI())
if err != nil {
return nil, err
}
return j.DoLess(req)
}
func (j *JiraClient) Put(path string, payload io.Reader) (*http.Response, error) { func (j *JiraClient) Put(path string, payload io.Reader) (*http.Response, error) {
req, err := http.NewRequest("PUT", path, payload) req, err := http.NewRequest("PUT", path, payload)
if err != nil { if err != nil {

71
jkl.go
View file

@ -8,6 +8,7 @@ import (
"io" "io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http"
"net/url" "net/url"
"os" "os"
"strings" "strings"
@ -251,6 +252,76 @@ func LogWork(taskKey string, workAmount string) error {
return nil return nil
} }
func Assign(taskKey string, user string) error {
bootHttpClient()
payload, err := serializePayload(map[string]interface{}{"name": user})
resp, err := httpClient.Put("api/2/issue/"+taskKey+"/assignee", payload)
if err != nil {
fmt.Println(resp.StatusCode)
return err
}
if resp.StatusCode >= 400 {
io.Copy(os.Stderr, resp.Body)
}
return nil
}
func FlagIssue(taskKeys []string, flg bool) error {
bootHttpClient()
payload, err := serializePayload(map[string]interface{}{"issueKeys": taskKeys, "flag": flg})
req, err := http.NewRequest("POST", "", payload)
if err != nil {
return err
}
req.URL, err = url.Parse(httpClient.jiraRoot + "rest/" + "greenhopper/1.0/xboard/issue/flag/flag.json")
if err != nil {
return err
}
resp, err := httpClient.DoLess(req)
if err != nil {
fmt.Println(resp.StatusCode)
return err
}
if resp.StatusCode >= 400 {
io.Copy(os.Stderr, resp.Body)
}
return nil
}
type msi map[string]interface{}
func LinkIssue(params []string) error {
bootHttpClient()
if len(params) == 0 {
resp, err := httpClient.Get("api/2/issueLinkType")
if err != nil {
if resp != nil {
fmt.Println(resp.StatusCode)
}
return err
}
io.Copy(os.Stdout, resp.Body)
return nil
}
payload, err := serializePayload(msi{
"type": msi{"name": strings.Join(params[1:len(params)-1], " ")},
"inwardIssue": msi{"key": params[len(params)-1]},
"outwardIssue": msi{"key": params[0]},
})
resp, err := httpClient.Post("api/2/issueLink", payload)
if err != nil {
if resp != nil {
fmt.Println(resp.StatusCode)
}
return err
}
if resp.StatusCode >= 400 {
io.Copy(os.Stderr, resp.Body)
}
return nil
}
func formatPayload(issue *JiraIssue) (io.Reader, error) { func formatPayload(issue *JiraIssue) (io.Reader, error) {
if issue.Fields != nil && if issue.Fields != nil &&
issue.Fields.Project != nil && issue.Fields.Project != nil &&