forked from owenthereal/gh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pull_request.go
267 lines (222 loc) · 7.79 KB
/
pull_request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package commands
import (
"fmt"
"github.com/jingweno/gh/git"
"github.com/jingweno/gh/github"
"github.com/jingweno/gh/utils"
"io/ioutil"
"reflect"
"regexp"
"strings"
)
var cmdPullRequest = &Command{
Run: pullRequest,
Usage: "pull-request [-f] [-m <MESSAGE>|-F <FILE>|-i <ISSUE>|<ISSUE-URL>] [-b <BASE>] [-h <HEAD>] ",
Short: "Open a pull request on GitHub",
Long: `Opens a pull request on GitHub for the project that the "origin" remote
points to. The default head of the pull request is the current branch.
Both base and head of the pull request can be explicitly given in one of
the following formats: "branch", "owner:branch", "owner/repo:branch".
This command will abort operation if it detects that the current topic
branch has local commits that are not yet pushed to its upstream branch
on the remote. To skip this check, use "-f".
Without <MESSAGE> or <FILE>, a text editor will open in which title and body
of the pull request can be entered in the same manner as git commit message.
Pull request message can also be passed via stdin with "-F -".
If instead of normal <TITLE> an issue number is given with "-i", the pull
request will be attached to an existing GitHub issue. Alternatively, instead
of title you can paste a full URL to an issue on GitHub.
`,
}
var (
flagPullRequestBase,
flagPullRequestHead,
flagPullRequestIssue,
flagPullRequestMessage,
flagPullRequestFile string
flagPullRequestForce bool
)
func init() {
cmdPullRequest.Flag.StringVar(&flagPullRequestBase, "b", "", "BASE")
cmdPullRequest.Flag.StringVar(&flagPullRequestHead, "h", "", "HEAD")
cmdPullRequest.Flag.StringVar(&flagPullRequestIssue, "i", "", "ISSUE")
cmdPullRequest.Flag.StringVar(&flagPullRequestMessage, "m", "", "MESSAGE")
cmdPullRequest.Flag.BoolVar(&flagPullRequestForce, "f", false, "FORCE")
cmdPullRequest.Flag.StringVar(&flagPullRequestFile, "F", "", "FILE")
cmdPullRequest.Flag.StringVar(&flagPullRequestFile, "file", "", "FILE")
}
/*
# while on a topic branch called "feature":
$ gh pull-request
[ opens text editor to edit title & body for the request ]
[ opened pull request on GitHub for "YOUR_USER:feature" ]
# explicit pull base & head:
$ gh pull-request -b jingweno:master -h jingweno:feature
$ gh pull-request -m "title\n\nbody"
[ create pull request with title & body ]
$ gh pull-request -i 123
[ attached pull request to issue #123 ]
$ gh pull-request https://github.com/jingweno/gh/pull/123
[ attached pull request to issue #123 ]
$ gh pull-request -F FILE
[ create pull request with title & body from FILE ]
*/
func pullRequest(cmd *Command, args *Args) {
localRepo := github.LocalRepo()
currentBranch, err := localRepo.CurrentBranch()
utils.Check(err)
baseProject, err := localRepo.MainProject()
utils.Check(err)
headProject, err := localRepo.CurrentProject()
utils.Check(err)
var (
base, head string
force, explicitOwner bool
)
force = flagPullRequestForce
if flagPullRequestBase != "" {
baseProject, base = parsePullRequestProject(baseProject, flagPullRequestBase)
}
if flagPullRequestHead != "" {
headProject, head = parsePullRequestProject(headProject, flagPullRequestHead)
explicitOwner = strings.Contains(flagPullRequestHead, ":")
}
if args.ParamsSize() == 1 {
arg := args.RemoveParam(0)
flagPullRequestIssue = parsePullRequestIssueNumber(arg)
}
if base == "" {
masterBranch, err := localRepo.MasterBranch()
utils.Check(err)
base = masterBranch.ShortName()
}
trackedBranch, _ := currentBranch.Upstream()
if head == "" {
if trackedBranch != nil && trackedBranch.IsRemote() {
if reflect.DeepEqual(baseProject, headProject) && base == trackedBranch.ShortName() {
e := fmt.Errorf(`Aborted: head branch is the same as base ("%s")`, base)
e = fmt.Errorf("%s\n(use `-h <branch>` to specify an explicit pull request head)", e)
utils.Check(e)
}
} else {
// the current branch tracking another branch
// pretend there's no upstream at all
trackedBranch = nil
}
if trackedBranch == nil {
head = currentBranch.ShortName()
} else {
head = trackedBranch.ShortName()
}
}
client := github.NewClient(baseProject.Host)
// when no tracking, assume remote branch is published under active user's fork
if trackedBranch == nil && !explicitOwner && client.Credentials.User != headProject.Owner {
// disable this on gh
//headProject = github.NewProject("", headProject.Name, headProject.Host)
}
title, body, err := github.GetTitleAndBodyFromFlags(flagPullRequestMessage, flagPullRequestFile)
utils.Check(err)
fullBase := fmt.Sprintf("%s:%s", baseProject.Owner, base)
fullHead := fmt.Sprintf("%s:%s", headProject.Owner, head)
if !force && trackedBranch != nil {
remoteCommits, _ := git.RefList(trackedBranch.LongName(), "")
if len(remoteCommits) > 0 {
err = fmt.Errorf("Aborted: %d commits are not yet pushed to %s", len(remoteCommits), trackedBranch.LongName())
err = fmt.Errorf("%s\n(use `-f` to force submit a pull request anyway)", err)
utils.Check(err)
}
}
if title == "" && flagPullRequestIssue == "" {
commits, _ := git.RefList(base, head)
title, body, err = writePullRequestTitleAndBody(base, head, fullBase, fullHead, commits)
utils.Check(err)
}
if title == "" && flagPullRequestIssue == "" {
utils.Check(fmt.Errorf("Aborting due to empty pull request title"))
}
var pullRequestURL string
if args.Noop {
args.Before(fmt.Sprintf("Would request a pull request to %s from %s", fullBase, fullHead), "")
pullRequestURL = "PULL_REQUEST_URL"
} else {
if title != "" {
pr, err := client.CreatePullRequest(baseProject, base, fullHead, title, body)
utils.Check(err)
pullRequestURL = pr.HTMLURL
}
if flagPullRequestIssue != "" {
pr, err := client.CreatePullRequestForIssue(baseProject, base, fullHead, flagPullRequestIssue)
utils.Check(err)
pullRequestURL = pr.HTMLURL
}
}
args.Replace("echo", "", pullRequestURL)
}
func writePullRequestTitleAndBody(base, head, fullBase, fullHead string, commits []string) (title, body string, err error) {
return github.GetTitleAndBodyFromEditor(func(messageFile string) error {
return writePullRequestChanges(base, head, fullBase, fullHead, commits, messageFile)
})
}
func writePullRequestChanges(base, head, fullBase, fullHead string, commits []string, messageFile string) error {
var defaultMsg, commitSummary string
if len(commits) == 1 {
msg, err := git.Show(commits[0])
if err != nil {
return err
}
defaultMsg = fmt.Sprintf("%s\n", msg)
} else if len(commits) > 1 {
commitLogs, err := git.Log(base, head)
if err != nil {
return err
}
if len(commitLogs) > 0 {
startRegexp := regexp.MustCompilePOSIX("^")
endRegexp := regexp.MustCompilePOSIX(" +$")
commitLogs = strings.TrimSpace(commitLogs)
commitLogs = startRegexp.ReplaceAllString(commitLogs, "# ")
commitLogs = endRegexp.ReplaceAllString(commitLogs, "")
commitSummary = `
#
# Changes:
#
%s`
commitSummary = fmt.Sprintf(commitSummary, commitLogs)
}
}
message := `%s
# Requesting a pull to %s from %s
#
# Write a message for this pull request. The first block
# of the text is the title and the rest is description.%s
`
message = fmt.Sprintf(message, defaultMsg, fullBase, fullHead, commitSummary)
return ioutil.WriteFile(messageFile, []byte(message), 0644)
}
func parsePullRequestProject(context *github.Project, s string) (p *github.Project, ref string) {
p = context
ref = s
if strings.Contains(s, ":") {
split := strings.SplitN(s, ":", 2)
ref = split[1]
var name string
if !strings.Contains(split[0], "/") {
name = context.Name
}
p = github.NewProject(split[0], name, context.Host)
}
return
}
func parsePullRequestIssueNumber(url string) string {
u, e := github.ParseURL(url)
if e != nil {
return ""
}
r := regexp.MustCompile(`^issues\/(\d+)`)
p := u.ProjectPath()
if r.MatchString(p) {
return r.FindStringSubmatch(p)[1]
}
return ""
}