github.com/nkprince007/lab@v0.6.2-0.20171218071646-19d68b56f403/cmd/issueCreate.go (about) 1 package cmd 2 3 import ( 4 "bytes" 5 "fmt" 6 "log" 7 "runtime" 8 "strconv" 9 "strings" 10 "text/template" 11 12 "github.com/spf13/cobra" 13 "github.com/xanzy/go-gitlab" 14 "github.com/zaquestion/lab/internal/git" 15 lab "github.com/zaquestion/lab/internal/gitlab" 16 ) 17 18 var issueCreateCmd = &cobra.Command{ 19 Use: "create [remote]", 20 Short: "Open an issue on GitLab", 21 Long: ``, 22 Args: cobra.MaximumNArgs(1), 23 Run: func(cmd *cobra.Command, args []string) { 24 remote := forkedFromRemote 25 if len(args) > 0 { 26 ok, err := git.IsRemote(args[0]) 27 if err != nil { 28 log.Fatal(err) 29 } 30 if ok { 31 remote = args[0] 32 } 33 } 34 rn, err := git.PathWithNameSpace(remote) 35 if err != nil { 36 log.Fatal(err) 37 } 38 39 title, body, err := issueMsg(msgs) 40 if err != nil { 41 _, f, l, _ := runtime.Caller(0) 42 log.Fatal(f+":"+strconv.Itoa(l)+" ", err) 43 } 44 if title == "" { 45 log.Fatal("aborting issue due to empty issue msg") 46 } 47 48 issueURL, err := lab.IssueCreate(rn, &gitlab.CreateIssueOptions{ 49 Title: &title, 50 Description: &body, 51 }) 52 if err != nil { 53 log.Fatal(err) 54 } 55 fmt.Println(issueURL) 56 }, 57 } 58 59 func issueMsg(msgs []string) (string, string, error) { 60 if len(msgs) > 0 { 61 return msgs[0], strings.Join(msgs[1:], "\n\n"), nil 62 } 63 64 text, err := issueText() 65 if err != nil { 66 return "", "", err 67 } 68 return git.Edit("ISSUE", text) 69 } 70 71 func issueText() (string, error) { 72 const tmpl = `{{.InitMsg}} 73 {{.CommentChar}} Write a message for this issue. The first block 74 {{.CommentChar}} of text is the title and the rest is the description.` 75 76 issueTmpl := lab.LoadGitLabTmpl(lab.TmplIssue) 77 78 initMsg := "\n" 79 if issueTmpl != "" { 80 initMsg = "\n\n" + issueTmpl 81 } 82 83 commentChar := git.CommentChar() 84 85 t, err := template.New("tmpl").Parse(tmpl) 86 if err != nil { 87 return "", err 88 } 89 90 msg := &struct { 91 InitMsg string 92 CommentChar string 93 }{ 94 InitMsg: initMsg, 95 CommentChar: commentChar, 96 } 97 98 var b bytes.Buffer 99 err = t.Execute(&b, msg) 100 if err != nil { 101 return "", err 102 } 103 104 return b.String(), nil 105 } 106 107 func init() { 108 issueCreateCmd.Flags().StringSliceVarP(&msgs, "message", "m", []string{}, "Use the given <msg>; multiple -m are concatenated as seperate paragraphs") 109 issueCmd.AddCommand(issueCreateCmd) 110 }