github.com/zaquestion/lab@v0.25.1/cmd/edit_common.go (about) 1 package cmd 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/ioutil" 7 "runtime" 8 "strconv" 9 "strings" 10 "text/template" 11 12 "github.com/MakeNowJust/heredoc/v2" 13 "github.com/zaquestion/lab/internal/git" 14 ) 15 16 // GetUpdateUsers returns an int slice of user IDs based on the 17 // current users and flags from the command line, and a bool 18 // indicating whether the users have changed 19 func getUpdateUsers(currentUsers []string, users []string, remove []string) ([]int, bool, error) { 20 // add the new users to the current users, then remove the "remove" group 21 users = difference(union(currentUsers, users), remove) 22 usersChanged := !same(currentUsers, users) 23 24 // turn the new user list into a list of user IDs 25 var userIDs []int 26 if usersChanged && len(users) == 0 { 27 // if we're removing all users, we have to use []int{0} 28 // see https://github.com/xanzy/go-gitlab/issues/427 29 userIDs = []int{0} 30 } else { 31 userIDs = make([]int, len(users)) 32 for i, a := range users { 33 if getUserID(a) == nil { 34 return nil, false, fmt.Errorf("%s is not a valid username", a) 35 } 36 userIDs[i] = *getUserID(a) 37 } 38 } 39 40 return userIDs, usersChanged, nil 41 } 42 43 // editDescription returns a title and description based on the 44 // current issue title and description and various flags from the command 45 // line 46 func editDescription(title string, body string, msgs []string, filename string) (string, string, error) { 47 if len(msgs) > 0 { 48 title = msgs[0] 49 50 if len(msgs) > 1 { 51 body = strings.Join(msgs[1:], "\n\n") 52 } 53 54 return title, body, nil 55 } 56 57 if filename != "" { 58 var lines []string 59 60 content, err := ioutil.ReadFile(filename) 61 if err != nil { 62 return "", "", err 63 } 64 lines = strings.Split(string(content), "\n") 65 66 title = lines[0] 67 body = strings.Join(lines[1:], "\n") 68 69 return title, body, nil 70 } 71 72 text, err := editText(title, body) 73 if err != nil { 74 return "", "", err 75 } 76 77 title, body, err = git.Edit("EDIT", text) 78 if err != nil { 79 _, f, l, _ := runtime.Caller(0) 80 log.Fatal(f+":"+strconv.Itoa(l)+" ", err) 81 } 82 83 return title, body, nil 84 } 85 86 // editText places the text title and body in a specific template following Git 87 // standards. 88 func editText(title string, body string) (string, error) { 89 tmpl := heredoc.Doc(` 90 {{.InitMsg}} 91 92 {{.CommentChar}} Edit the title and/or description. The first block of text 93 {{.CommentChar}} is the title and the rest is the description.`) 94 95 msg := &struct { 96 InitMsg string 97 CommentChar string 98 }{ 99 InitMsg: title + "\n\n" + body, 100 CommentChar: git.CommentChar(), 101 } 102 103 t, err := template.New("tmpl").Parse(tmpl) 104 if err != nil { 105 return "", err 106 } 107 108 var b bytes.Buffer 109 err = t.Execute(&b, msg) 110 if err != nil { 111 return "", err 112 } 113 114 return b.String(), nil 115 }