This commit is contained in:
Cory Bennett
2015-02-13 15:44:07 -08:00
parent eb0c0823b0
commit a872b66777
5 changed files with 187 additions and 153 deletions
+30 -24
View File
@@ -1,28 +1,28 @@
package cli package cli
import ( import (
"github.com/op/go-logging" "bytes"
"net/http"
"net/http/cookiejar"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/op/go-logging"
"gopkg.in/yaml.v2"
"io/ioutil" "io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os" "os"
"os/exec" "os/exec"
"gopkg.in/yaml.v2"
"net/url"
"time"
"bytes"
"runtime" "runtime"
"time"
) )
var log = logging.MustGetLogger("jira.cli") var log = logging.MustGetLogger("jira.cli")
type Cli struct { type Cli struct {
endpoint *url.URL endpoint *url.URL
opts map[string]string opts map[string]string
cookieFile string cookieFile string
ua *http.Client ua *http.Client
} }
func New(opts map[string]string) *Cli { func New(opts map[string]string) *Cli {
@@ -32,10 +32,10 @@ func New(opts map[string]string) *Cli {
url, _ := url.Parse(endpoint) url, _ := url.Parse(endpoint)
cli := &Cli{ cli := &Cli{
endpoint: url, endpoint: url,
opts: opts, opts: opts,
cookieFile: fmt.Sprintf("%s/.jira.d/cookies.js", homedir), cookieFile: fmt.Sprintf("%s/.jira.d/cookies.js", homedir),
ua: &http.Client{Jar: cookieJar}, ua: &http.Client{Jar: cookieJar},
} }
cli.ua.Jar.SetCookies(url, cli.loadCookies()) cli.ua.Jar.SetCookies(url, cli.loadCookies())
@@ -80,7 +80,7 @@ func (c *Cli) loadCookies() []*http.Cookie {
log.Error("Failed to open %s: %s", c.cookieFile, err) log.Error("Failed to open %s: %s", c.cookieFile, err)
os.Exit(1) os.Exit(1)
} }
cookies := make([]*http.Cookie,0) cookies := make([]*http.Cookie, 0)
err = json.Unmarshal(bytes, &cookies) err = json.Unmarshal(bytes, &cookies)
if err != nil { if err != nil {
log.Error("Failed to parse json from file %s: %s", c.cookieFile, err) log.Error("Failed to parse json from file %s: %s", c.cookieFile, err)
@@ -103,7 +103,7 @@ func (c *Cli) makeRequestWithContent(method string, uri string, content string)
log.Info("%s %s", req.Method, req.URL.String()) log.Info("%s %s", req.Method, req.URL.String())
if log.IsEnabledFor(logging.DEBUG) { if log.IsEnabledFor(logging.DEBUG) {
logBuffer := bytes.NewBuffer(make([]byte,0,len(content))) logBuffer := bytes.NewBuffer(make([]byte, 0, len(content)))
req.Write(logBuffer) req.Write(logBuffer)
log.Debug("%s", logBuffer) log.Debug("%s", logBuffer)
// need to recreate the buffer since the offset is now at the end // need to recreate the buffer since the offset is now at the end
@@ -129,7 +129,7 @@ func (c *Cli) get(uri string) (*http.Response, error) {
req, _ := http.NewRequest("GET", uri, nil) req, _ := http.NewRequest("GET", uri, nil)
log.Info("%s %s", req.Method, req.URL.String()) log.Info("%s %s", req.Method, req.URL.String())
if log.IsEnabledFor(logging.DEBUG) { if log.IsEnabledFor(logging.DEBUG) {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
req.Write(logBuffer) req.Write(logBuffer)
log.Debug("%s", logBuffer) log.Debug("%s", logBuffer)
} }
@@ -189,7 +189,8 @@ func (c *Cli) getTemplate(path string, dflt string) string {
func (c *Cli) editTemplate(template string, tmpFilePrefix string, templateData map[string]interface{}, templateProcessor func(string) error) error { func (c *Cli) editTemplate(template string, tmpFilePrefix string, templateData map[string]interface{}, templateProcessor func(string) error) error {
tmpdir := fmt.Sprintf("%s/.jira.d/tmp", os.Getenv("HOME")) tmpdir := fmt.Sprintf("%s/.jira.d/tmp", os.Getenv("HOME"))
fh, err := ioutil.TempFile(tmpdir, tmpFilePrefix); if err != nil { fh, err := ioutil.TempFile(tmpdir, tmpFilePrefix)
if err != nil {
log.Error("Failed to make temp file in %s: %s", tmpdir, err) log.Error("Failed to make temp file in %s: %s", tmpdir, err)
return err return err
} }
@@ -201,20 +202,24 @@ func (c *Cli) editTemplate(template string, tmpFilePrefix string, templateData m
return err return err
} }
err = runTemplate(template, templateData, fh); if err != nil { err = runTemplate(template, templateData, fh)
if err != nil {
return err return err
} }
fh.Close() fh.Close()
editor, ok := c.opts["editor"]; if !ok { editor, ok := c.opts["editor"]
editor = os.Getenv("JIRA_EDITOR"); if editor == "" { if !ok {
editor = os.Getenv("EDITOR"); if editor == "" { editor = os.Getenv("JIRA_EDITOR")
if editor == "" {
editor = os.Getenv("EDITOR")
if editor == "" {
editor = "vim" editor = "vim"
} }
} }
} }
for ; true ; { for true {
log.Debug("Running: %s %s", editor, tmpFileName) log.Debug("Running: %s %s", editor, tmpFileName)
cmd := exec.Command(editor, tmpFileName) cmd := exec.Command(editor, tmpFileName)
cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin cmd.Stdout, cmd.Stderr, cmd.Stdin = os.Stdout, os.Stderr, os.Stdin
@@ -251,7 +256,7 @@ func (c *Cli) editTemplate(template string, tmpFilePrefix string, templateData m
if _, ok := templateData["meta"]; ok { if _, ok := templateData["meta"]; ok {
mf := templateData["meta"].(map[string]interface{})["fields"] mf := templateData["meta"].(map[string]interface{})["fields"]
f := edited["fields"].(map[string]interface{}) f := edited["fields"].(map[string]interface{})
for k, _ := range f { for k, _ := range f {
if _, ok := mf.(map[string]interface{})[k]; !ok { if _, ok := mf.(map[string]interface{})[k]; !ok {
err := fmt.Errorf("Field %s is not editable", k) err := fmt.Errorf("Field %s is not editable", k)
@@ -264,7 +269,8 @@ func (c *Cli) editTemplate(template string, tmpFilePrefix string, templateData m
} }
} }
json, err := jsonEncode(edited); if err != nil { json, err := jsonEncode(edited)
if err != nil {
return err return err
} }
+76 -52
View File
@@ -1,23 +1,23 @@
package cli package cli
import ( import (
"net/http"
"fmt"
"code.google.com/p/gopass"
"bytes" "bytes"
"strings" "code.google.com/p/gopass"
"fmt"
"net/http"
"os" "os"
"strings"
// "github.com/kr/pretty" // "github.com/kr/pretty"
) )
func (c *Cli) CmdLogin() (error) { func (c *Cli) CmdLogin() error {
uri := fmt.Sprintf("%s/rest/auth/1/session", c.endpoint) uri := fmt.Sprintf("%s/rest/auth/1/session", c.endpoint)
for ; true ; { for true {
req, _ := http.NewRequest("GET", uri, nil) req, _ := http.NewRequest("GET", uri, nil)
user, _ := c.opts["user"] user, _ := c.opts["user"]
prompt := fmt.Sprintf("Enter Password for %s: ", user) prompt := fmt.Sprintf("Enter Password for %s: ", user)
passwd, _ := gopass.GetPass(prompt); passwd, _ := gopass.GetPass(prompt)
req.SetBasicAuth(user, passwd) req.SetBasicAuth(user, passwd)
if resp, err := c.makeRequest(req); err != nil { if resp, err := c.makeRequest(req); err != nil {
@@ -47,14 +47,14 @@ func (c *Cli) CmdLogin() (error) {
func (c *Cli) CmdFields() error { func (c *Cli) CmdFields() error {
log.Debug("fields called") log.Debug("fields called")
uri := fmt.Sprintf("%s/rest/api/2/field", c.endpoint) uri := fmt.Sprintf("%s/rest/api/2/field", c.endpoint)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
return runTemplate(c.getTemplate(".jira.d/templates/fields", default_fields_template), data, nil) return runTemplate(c.getTemplate(".jira.d/templates/fields", default_fields_template), data, nil)
} }
func (c *Cli) CmdList() error { func (c *Cli) CmdList() error {
log.Debug("list called") log.Debug("list called")
@@ -86,15 +86,17 @@ func (c *Cli) CmdList() error {
} }
json, err := jsonEncode(map[string]string{ json, err := jsonEncode(map[string]string{
"jql": query, "jql": query,
"startAt": "0", "startAt": "0",
"maxResults": "500", "maxResults": "500",
}); if err != nil { })
if err != nil {
return err return err
} }
uri := fmt.Sprintf("%s/rest/api/2/search", c.endpoint) uri := fmt.Sprintf("%s/rest/api/2/search", c.endpoint)
data, err := responseToJson(c.post(uri, json)); if err != nil { data, err := responseToJson(c.post(uri, json))
if err != nil {
return err return err
} }
@@ -104,7 +106,8 @@ func (c *Cli) CmdList() error {
func (c *Cli) CmdView(issue string) error { func (c *Cli) CmdView(issue string) error {
log.Debug("view called") log.Debug("view called")
uri := fmt.Sprintf("%s/rest/api/2/issue/%s", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s", c.endpoint, issue)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -115,7 +118,8 @@ func (c *Cli) CmdEdit(issue string) error {
log.Debug("edit called") log.Debug("edit called")
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/editmeta", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/editmeta", c.endpoint, issue)
editmeta, err := responseToJson(c.get(uri)); if err != nil { editmeta, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -135,7 +139,8 @@ func (c *Cli) CmdEdit(issue string) error {
fmt.Sprintf("%s-edit-", issue), fmt.Sprintf("%s-edit-", issue),
issueData, issueData,
func(json string) error { func(json string) error {
resp, err := c.put(uri, json); if err != nil { resp, err := c.put(uri, json)
if err != nil {
return err return err
} }
@@ -143,7 +148,7 @@ func (c *Cli) CmdEdit(issue string) error {
fmt.Printf("OK %s %s/browse/%s\n", issueData["key"], c.endpoint, issueData["key"]) fmt.Printf("OK %s %s/browse/%s\n", issueData["key"], c.endpoint, issueData["key"])
return nil return nil
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From PUT") err := fmt.Errorf("Unexpected Response From PUT")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -156,7 +161,8 @@ func (c *Cli) CmdEdit(issue string) error {
func (c *Cli) CmdEditMeta(issue string) error { func (c *Cli) CmdEditMeta(issue string) error {
log.Debug("editMeta called") log.Debug("editMeta called")
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/editmeta", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/editmeta", c.endpoint, issue)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -166,7 +172,8 @@ func (c *Cli) CmdEditMeta(issue string) error {
func (c *Cli) CmdTransitionMeta(issue string) error { func (c *Cli) CmdTransitionMeta(issue string) error {
log.Debug("tranisionMeta called") log.Debug("tranisionMeta called")
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/transitions?expand=transitions.fields", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/transitions?expand=transitions.fields", c.endpoint, issue)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -176,7 +183,8 @@ func (c *Cli) CmdTransitionMeta(issue string) error {
func (c *Cli) CmdIssueTypes(project string) error { func (c *Cli) CmdIssueTypes(project string) error {
log.Debug("issueTypes called") log.Debug("issueTypes called")
uri := fmt.Sprintf("%s/rest/api/2/issue/createmeta?projectKeys=%s", c.endpoint, project) uri := fmt.Sprintf("%s/rest/api/2/issue/createmeta?projectKeys=%s", c.endpoint, project)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -186,7 +194,8 @@ func (c *Cli) CmdIssueTypes(project string) error {
func (c *Cli) CmdCreateMeta(project string, issuetype string) error { func (c *Cli) CmdCreateMeta(project string, issuetype string) error {
log.Debug("createMeta called") log.Debug("createMeta called")
uri := fmt.Sprintf("%s/rest/api/2/issue/createmeta?projectKeys=%s&issuetypeNames=%s&expand=projects.issuetypes.fields", c.endpoint, project, issuetype) uri := fmt.Sprintf("%s/rest/api/2/issue/createmeta?projectKeys=%s&issuetypeNames=%s&expand=projects.issuetypes.fields", c.endpoint, project, issuetype)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -202,7 +211,8 @@ func (c *Cli) CmdCreateMeta(project string, issuetype string) error {
func (c *Cli) CmdTransitions(issue string) error { func (c *Cli) CmdTransitions(issue string) error {
log.Debug("Transitions called") log.Debug("Transitions called")
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/transitions", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/transitions", c.endpoint, issue)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
return runTemplate(c.getTemplate(".jira.d/templates/transitions", default_transitions_template), data, nil) return runTemplate(c.getTemplate(".jira.d/templates/transitions", default_transitions_template), data, nil)
@@ -212,7 +222,8 @@ func (c *Cli) CmdCreate(project string, issuetype string) error {
log.Debug("create called") log.Debug("create called")
uri := fmt.Sprintf("%s/rest/api/2/issue/createmeta?projectKeys=%s&issuetypeNames=%s&expand=projects.issuetypes.fields", c.endpoint, project, issuetype) uri := fmt.Sprintf("%s/rest/api/2/issue/createmeta?projectKeys=%s&issuetypeNames=%s&expand=projects.issuetypes.fields", c.endpoint, project, issuetype)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
@@ -233,7 +244,8 @@ func (c *Cli) CmdCreate(project string, issuetype string) error {
func(json string) error { func(json string) error {
log.Debug("JSON: %s", json) log.Debug("JSON: %s", json)
uri := fmt.Sprintf("%s/rest/api/2/issue", c.endpoint) uri := fmt.Sprintf("%s/rest/api/2/issue", c.endpoint)
resp, err := c.post(uri, json); if err != nil { resp, err := c.post(uri, json)
if err != nil {
return err return err
} }
@@ -247,7 +259,7 @@ func (c *Cli) CmdCreate(project string, issuetype string) error {
} }
return nil return nil
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From POST") err := fmt.Errorf("Unexpected Response From POST")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -261,7 +273,8 @@ func (c *Cli) CmdCreate(project string, issuetype string) error {
func (c *Cli) CmdIssueLinkTypes() error { func (c *Cli) CmdIssueLinkTypes() error {
log.Debug("Transitions called") log.Debug("Transitions called")
uri := fmt.Sprintf("%s/rest/api/2/issueLinkType", c.endpoint) uri := fmt.Sprintf("%s/rest/api/2/issueLinkType", c.endpoint)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
return runTemplate(c.getTemplate(".jira.d/templates/issuelinktypes", default_fields_template), data, nil) return runTemplate(c.getTemplate(".jira.d/templates/issuelinktypes", default_fields_template), data, nil)
@@ -272,7 +285,7 @@ func (c *Cli) CmdBlocks(blocker string, issue string) error {
json, err := jsonEncode(map[string]interface{}{ json, err := jsonEncode(map[string]interface{}{
"type": map[string]string{ "type": map[string]string{
"name": "Depends", // TODO This is probably not constant across Jira installs "name": "Depends", // TODO This is probably not constant across Jira installs
}, },
"inwardIssue": map[string]string{ "inwardIssue": map[string]string{
"key": issue, "key": issue,
@@ -280,18 +293,20 @@ func (c *Cli) CmdBlocks(blocker string, issue string) error {
"outwardIssue": map[string]string{ "outwardIssue": map[string]string{
"key": blocker, "key": blocker,
}, },
}); if err != nil { })
if err != nil {
return err return err
} }
uri := fmt.Sprintf("%s/rest/api/2/issueLink", c.endpoint) uri := fmt.Sprintf("%s/rest/api/2/issueLink", c.endpoint)
resp, err := c.post(uri, json); if err != nil { resp, err := c.post(uri, json)
if err != nil {
return err return err
} }
if resp.StatusCode == 201 { if resp.StatusCode == 201 {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue) fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From POST") err := fmt.Errorf("Unexpected Response From POST")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -305,7 +320,7 @@ func (c *Cli) CmdDups(duplicate string, issue string) error {
json, err := jsonEncode(map[string]interface{}{ json, err := jsonEncode(map[string]interface{}{
"type": map[string]string{ "type": map[string]string{
"name": "Duplicate", // TODO This is probably not constant across Jira installs "name": "Duplicate", // TODO This is probably not constant across Jira installs
}, },
"inwardIssue": map[string]string{ "inwardIssue": map[string]string{
"key": duplicate, "key": duplicate,
@@ -313,18 +328,20 @@ func (c *Cli) CmdDups(duplicate string, issue string) error {
"outwardIssue": map[string]string{ "outwardIssue": map[string]string{
"key": issue, "key": issue,
}, },
}); if err != nil { })
if err != nil {
return err return err
} }
uri := fmt.Sprintf("%s/rest/api/2/issueLink", c.endpoint) uri := fmt.Sprintf("%s/rest/api/2/issueLink", c.endpoint)
resp, err := c.post(uri, json); if err != nil { resp, err := c.post(uri, json)
if err != nil {
return err return err
} }
if resp.StatusCode == 201 { if resp.StatusCode == 201 {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue) fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From POST") err := fmt.Errorf("Unexpected Response From POST")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -333,22 +350,23 @@ func (c *Cli) CmdDups(duplicate string, issue string) error {
return nil return nil
} }
func (c *Cli) CmdWatch(issue string, watcher string) error { func (c *Cli) CmdWatch(issue string, watcher string) error {
log.Debug("watch called") log.Debug("watch called")
json, err := jsonEncode(watcher); if err != nil { json, err := jsonEncode(watcher)
if err != nil {
return err return err
} }
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/watchers", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/watchers", c.endpoint, issue)
resp, err := c.post(uri, json); if err != nil { resp, err := c.post(uri, json)
if err != nil {
return err return err
} }
if resp.StatusCode == 204 { if resp.StatusCode == 204 {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue) fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From POST") err := fmt.Errorf("Unexpected Response From POST")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -360,16 +378,17 @@ func (c *Cli) CmdWatch(issue string, watcher string) error {
func (c *Cli) CmdTransition(issue string, trans string) error { func (c *Cli) CmdTransition(issue string, trans string) error {
log.Debug("transition called") log.Debug("transition called")
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/transitions", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/transitions", c.endpoint, issue)
data, err := responseToJson(c.get(uri)); if err != nil { data, err := responseToJson(c.get(uri))
if err != nil {
return err return err
} }
transitions := data.(map[string]interface{})["transitions"].([]interface{}) transitions := data.(map[string]interface{})["transitions"].([]interface{})
var transId string var transId string
found := make([]string, 0, len(transitions)) found := make([]string, 0, len(transitions))
for _, transition := range transitions { for _, transition := range transitions {
name := transition.(map[string]interface{})["name"].(string) name := transition.(map[string]interface{})["name"].(string)
id := transition.(map[string]interface{})["id"].(string) id := transition.(map[string]interface{})["id"].(string)
found = append(found, name) found = append(found, name)
if strings.Contains(strings.ToLower(name), trans) { if strings.Contains(strings.ToLower(name), trans) {
transId = id transId = id
@@ -381,7 +400,6 @@ func (c *Cli) CmdTransition(issue string, trans string) error {
return err return err
} }
payload := map[string]interface{}{ payload := map[string]interface{}{
"transition": map[string]interface{}{ "transition": map[string]interface{}{
"id": transId, "id": transId,
@@ -400,18 +418,20 @@ func (c *Cli) CmdTransition(issue string, trans string) error {
} }
} }
json, err := jsonEncode(payload); if err != nil { json, err := jsonEncode(payload)
if err != nil {
return err return err
} }
uri = fmt.Sprintf("%s/rest/api/2/issue/%s/transitions", c.endpoint, issue) uri = fmt.Sprintf("%s/rest/api/2/issue/%s/transitions", c.endpoint, issue)
resp, err := c.post(uri, json); if err != nil { resp, err := c.post(uri, json)
if err != nil {
return err return err
} }
if resp.StatusCode == 204 { if resp.StatusCode == 204 {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue) fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From POST") err := fmt.Errorf("Unexpected Response From POST")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -426,7 +446,8 @@ func (c *Cli) CmdComment(issue string) error {
handlePost := func(json string) error { handlePost := func(json string) error {
log.Debug("JSON: %s", json) log.Debug("JSON: %s", json)
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/comment", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/comment", c.endpoint, issue)
resp, err := c.post(uri, json); if err != nil { resp, err := c.post(uri, json)
if err != nil {
return err return err
} }
@@ -434,7 +455,7 @@ func (c *Cli) CmdComment(issue string) error {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue) fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
return nil return nil
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From POST") err := fmt.Errorf("Unexpected Response From POST")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -445,7 +466,8 @@ func (c *Cli) CmdComment(issue string) error {
if comment, ok := c.opts["comment"]; ok { if comment, ok := c.opts["comment"]; ok {
json, err := jsonEncode(map[string]interface{}{ json, err := jsonEncode(map[string]interface{}{
"body": comment, "body": comment,
}); if err != nil { })
if err != nil {
return err return err
} }
return handlePost(json) return handlePost(json)
@@ -465,18 +487,20 @@ func (c *Cli) CmdAssign(issue string, user string) error {
json, err := jsonEncode(map[string]interface{}{ json, err := jsonEncode(map[string]interface{}{
"name": user, "name": user,
}); if err != nil { })
if err != nil {
return err return err
} }
uri := fmt.Sprintf("%s/rest/api/2/issue/%s/assignee", c.endpoint, issue) uri := fmt.Sprintf("%s/rest/api/2/issue/%s/assignee", c.endpoint, issue)
resp, err := c.put(uri, json); if err != nil { resp, err := c.put(uri, json)
if err != nil {
return err return err
} }
if resp.StatusCode == 204 { if resp.StatusCode == 204 {
fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue) fmt.Printf("OK %s %s/browse/%s\n", issue, c.endpoint, issue)
} else { } else {
logBuffer := bytes.NewBuffer(make([]byte,0)) logBuffer := bytes.NewBuffer(make([]byte, 0))
resp.Write(logBuffer) resp.Write(logBuffer)
err := fmt.Errorf("Unexpected Response From PUT") err := fmt.Errorf("Unexpected Response From PUT")
log.Error("%s:\n%s", err, logBuffer) log.Error("%s:\n%s", err, logBuffer)
@@ -508,7 +532,7 @@ func (c *Cli) CmdExportTemplates() error {
log.Warning("Skipping %s, already exists", templateFile) log.Warning("Skipping %s, already exists", templateFile)
continue continue
} }
if fh, err := os.OpenFile(templateFile, os.O_WRONLY | os.O_CREATE, 0644); err != nil { if fh, err := os.OpenFile(templateFile, os.O_WRONLY|os.O_CREATE, 0644); err != nil {
log.Error("Failed to open %s for writing: %s", templateFile, err) log.Error("Failed to open %s for writing: %s", templateFile, err)
return err return err
} else { } else {
+7 -7
View File
@@ -1,14 +1,14 @@
package cli package cli
var all_templates = map[string]string{ var all_templates = map[string]string{
"fields": default_fields_template, "fields": default_fields_template,
"list": default_list_template, "list": default_list_template,
"view": default_view_template, "view": default_view_template,
"edit": default_edit_template, "edit": default_edit_template,
"transitions": default_transitions_template, "transitions": default_transitions_template,
"issuetypes": default_issuetypes_template, "issuetypes": default_issuetypes_template,
"create": default_create_template, "create": default_create_template,
"comment": default_comment_template, "comment": default_comment_template,
} }
const default_fields_template = "{{ . | toJson}}\n" const default_fields_template = "{{ . | toJson}}\n"
+27 -23
View File
@@ -1,28 +1,28 @@
package cli package cli
import ( import (
"os"
"fmt"
"errors"
"strings"
"net/http"
"encoding/json"
"io/ioutil"
"text/template"
"io"
"bufio" "bufio"
"bytes" "bytes"
"encoding/json"
"errors"
"fmt"
"github.com/mgutz/ansi" "github.com/mgutz/ansi"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"text/template"
) )
func FindParentPaths(fileName string) []string { func FindParentPaths(fileName string) []string {
cwd, _ := os.Getwd() cwd, _ := os.Getwd()
paths := make([]string,0) paths := make([]string, 0)
// special case if homedir is not in current path then check there anyway // special case if homedir is not in current path then check there anyway
homedir := os.Getenv("HOME") homedir := os.Getenv("HOME")
if ! strings.HasPrefix(cwd, homedir) { if !strings.HasPrefix(cwd, homedir) {
file := fmt.Sprintf("%s/%s", homedir, fileName) file := fmt.Sprintf("%s/%s", homedir, fileName)
if _, err := os.Stat(file); err == nil { if _, err := os.Stat(file); err == nil {
paths = append(paths, file) paths = append(paths, file)
@@ -44,7 +44,7 @@ func FindParentPaths(fileName string) []string {
return paths return paths
} }
func FindClosestParentPath(fileName string) (string,error) { func FindClosestParentPath(fileName string) (string, error) {
paths := FindParentPaths(fileName) paths := FindParentPaths(fileName)
if len(paths) > 0 { if len(paths) > 0 {
return paths[len(paths)-1], nil return paths[len(paths)-1], nil
@@ -78,15 +78,18 @@ func runTemplate(templateContent string, data interface{}, out io.Writer) error
}, },
"append": func(more string, content interface{}) (string, error) { "append": func(more string, content interface{}) (string, error) {
switch value := content.(type) { switch value := content.(type) {
case string: return string(append([]byte(content.(string)), []byte(more)...)), nil case string:
case []byte: return string(append(content.([]byte), []byte(more)...)), nil return string(append([]byte(content.(string)), []byte(more)...)), nil
default: return "", errors.New(fmt.Sprintf("Unknown type: %s", value)) case []byte:
return string(append(content.([]byte), []byte(more)...)), nil
default:
return "", errors.New(fmt.Sprintf("Unknown type: %s", value))
} }
}, },
"indent": func(spaces int, content string) string { "indent": func(spaces int, content string) string {
indent := make([]byte, spaces + 1, spaces +1) indent := make([]byte, spaces+1, spaces+1)
indent[0] = '\n' indent[0] = '\n'
for i := 1; i < spaces + 1; i += 1 { for i := 1; i < spaces+1; i += 1 {
indent[i] = ' ' indent[i] = ' '
} }
return strings.Replace(content, "\n", string(indent), -1) return strings.Replace(content, "\n", string(indent), -1)
@@ -132,7 +135,8 @@ func jsonEncode(data interface{}) (string, error) {
buffer := bytes.NewBuffer(make([]byte, 0)) buffer := bytes.NewBuffer(make([]byte, 0))
enc := json.NewEncoder(buffer) enc := json.NewEncoder(buffer)
err := enc.Encode(data); if err != nil { err := enc.Encode(data)
if err != nil {
log.Error("Failed to encode data %s: %s", data, err) log.Error("Failed to encode data %s: %s", data, err)
return "", err return "", err
} }
@@ -140,7 +144,7 @@ func jsonEncode(data interface{}) (string, error) {
} }
func jsonWrite(file string, data interface{}) { func jsonWrite(file string, data interface{}) {
fh, err := os.OpenFile(file, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0600) fh, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer fh.Close() defer fh.Close()
if err != nil { if err != nil {
log.Error("Failed to open %s: %s", file, err) log.Error("Failed to open %s: %s", file, err)
@@ -164,13 +168,13 @@ func promptYN(prompt string, yes bool) bool {
if ans == "" { if ans == "" {
return yes return yes
} }
if( strings.HasPrefix(ans, "y") ) { if strings.HasPrefix(ans, "y") {
return true return true
} }
return false return false
} }
func yamlFixup( data interface{} ) (interface{}, error) { func yamlFixup(data interface{}) (interface{}, error) {
switch d := data.(type) { switch d := data.(type) {
case map[interface{}]interface{}: case map[interface{}]interface{}:
// need to copy this map into a string map so json can encode it // need to copy this map into a string map so json can encode it
@@ -208,7 +212,7 @@ func yamlFixup( data interface{} ) (interface{}, error) {
} }
} }
return data, nil return data, nil
default: return d, nil default:
return d, nil
} }
} }
+9 -9
View File
@@ -1,14 +1,14 @@
package main package main
import ( import (
"fmt"
"github.com/Netflix-Skunkworks/go-jira/jira/cli"
"github.com/docopt/docopt-go" "github.com/docopt/docopt-go"
"github.com/op/go-logging" "github.com/op/go-logging"
"fmt" "gopkg.in/yaml.v2"
"io/ioutil"
"os" "os"
"strings" "strings"
"io/ioutil"
"gopkg.in/yaml.v2"
"github.com/Netflix-Skunkworks/go-jira/jira/cli"
) )
var log = logging.MustGetLogger("jira") var log = logging.MustGetLogger("jira")
@@ -67,7 +67,8 @@ Command Options:
-w --watcher=USER Watcher to add to issue (default: %s) -w --watcher=USER Watcher to add to issue (default: %s)
`, user, fmt.Sprintf("%s/.jira.d/templates", home), user) `, user, fmt.Sprintf("%s/.jira.d/templates", home), user)
args, err := docopt.Parse(usage, nil, true, "0.0.1", false, false); if err != nil { args, err := docopt.Parse(usage, nil, true, "0.0.1", false, false)
if err != nil {
log.Error("Failed to parse options: %s", err) log.Error("Failed to parse options: %s", err)
os.Exit(1) os.Exit(1)
} }
@@ -94,7 +95,7 @@ Command Options:
// strip the "--" off the command line options // strip the "--" off the command line options
// and populate the opts that we pass to the cli ctor // and populate the opts that we pass to the cli ctor
for key,val := range args { for key, val := range args {
if val != nil && strings.HasPrefix(key, "--") { if val != nil && strings.HasPrefix(key, "--") {
opt := key[2:] opt := key[2:]
if opt == "override" { if opt == "override" {
@@ -136,7 +137,7 @@ Command Options:
c := cli.New(opts) c := cli.New(opts)
log.Debug("opts: %s", opts); log.Debug("opts: %s", opts)
validCommand := func(cmd string) bool { validCommand := func(cmd string) bool {
if val, ok := args[cmd]; ok && val.(bool) { if val, ok := args[cmd]; ok && val.(bool) {
@@ -249,8 +250,7 @@ func loadConfigs(opts map[string]string) {
// prepend // prepend
paths = append([]string{"/etc/jira-cli.yml"}, paths...) paths = append([]string{"/etc/jira-cli.yml"}, paths...)
for _, file := range(paths) { for _, file := range paths {
parseYaml(file, opts) parseYaml(file, opts)
} }
} }