github.com/abhinav/git-pr@v0.6.1-0.20171029234004-54218d68c11b/pr/editor.go (about) 1 package pr 2 3 import ( 4 "bytes" 5 "errors" 6 "strings" 7 "text/template" 8 9 "github.com/abhinav/git-pr/editor" 10 11 "github.com/google/go-github/github" 12 ) 13 14 // UpdateMessage uses the given editor to edit the commit message of the given 15 // PR. 16 func UpdateMessage(ed editor.Editor, pr *github.PullRequest) error { 17 var buff bytes.Buffer 18 if err := _interactiveTmpl.Execute(&buff, pr); err != nil { 19 return err 20 } 21 22 message, err := ed.EditString(buff.String()) 23 if err != nil { 24 return err 25 } 26 27 title, body, err := _parseMessage(message) 28 if err != nil { 29 return err 30 } 31 32 pr.Title = &title 33 pr.Body = &body 34 return nil 35 } 36 37 var _interactiveTmpl = template.Must(template.New("interactive").Parse( 38 `{{.Title}} (#{{.Number}}) 39 40 {{if .Body}}{{.Body}} 41 42 {{end}}# Landing Pull Request: {{.HTMLURL}} 43 # 44 # Enter the commit message above. Lines starting with '#' will be 45 # ignored. There must be an empty line between the title and the body. 46 # Leaving this file empty will abort the operation. 47 `)) 48 49 func _parseMessage(s string) (title string, body string, err error) { 50 lines := strings.Split(s, "\n") 51 { 52 newLines := lines[:0] 53 for _, l := range lines { 54 if len(l) > 0 && l[0] == '#' { 55 continue 56 } 57 58 newLines = append(newLines, l) 59 } 60 lines = newLines 61 } 62 63 if len(lines) == 0 { 64 err = errors.New("file is empty") 65 return 66 } 67 68 if len(lines) > 1 && len(lines[1]) > 0 { 69 err = errors.New("there must be an empty line between the title and the body") 70 return 71 } 72 73 title = lines[0] 74 if len(lines) > 2 { 75 body = strings.Join(lines[2:], "\n") 76 } 77 return 78 }