pull_request.go 8.0 KB
Newer Older
1
package commands
J
Jingwen Owen Ou 已提交
2 3

import (
J
Jingwen Owen Ou 已提交
4
	"fmt"
J
Jingwen Owen Ou 已提交
5
	"regexp"
6
	"strings"
J
Jingwen Owen Ou 已提交
7 8 9 10

	"github.com/github/hub/git"
	"github.com/github/hub/github"
	"github.com/github/hub/utils"
11
	"github.com/octokit/go-octokit/octokit"
J
Jingwen Owen Ou 已提交
12 13
)

14
var cmdPullRequest = &Command{
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
	Run: pullRequest,
	Usage: `
pull-request [-fo] [-b <BASE>] [-h <HEAD>] [-a <USER>] [-M <MILESTONE>] [-l <LABELS>]
pull-request -m <MESSAGE>
pull-request -F <FILE>
pull-request -i <ISSUE>
`,
	Long: `Create a GitHub pull request.

## Options:
	-f, --force
		Skip the check for unpushed commits.

	-m, --message <MESSAGE>
		Use the first line of <MESSAGE> as pull request title, and the rest as pull
		request description.

	-F, --file <FILE>
		Read the pull request title and description from <FILE>.

	-i, --issue <ISSUE>, <ISSUE-URL>
		(Deprecated) Convert <ISSUE> to a pull request.

	-o, --browse
		Open the new pull request in a web browser.

	-b, --base <BASE>
		The base branch in "[OWNER:]BRANCH" format. Defaults to the default branch
		(usually "master").

	-h, --head <HEAD>
		The base branch in "[OWNER:]BRANCH" format. Defaults to the current branch.

	-a, --assign <USER>
		Assign GitHub <USER> to this pull request.

	-M, --milestone <ID>
		Add this pull request to a GitHub milestone with id <ID>.

	-l, --labels <LABELS>
		Add a comma-separated list of labels to this pull request.
J
Jingwen Owen Ou 已提交
56 57 58
`,
}

59 60 61 62 63
var (
	flagPullRequestBase,
	flagPullRequestHead,
	flagPullRequestIssue,
	flagPullRequestMessage,
64
	flagPullRequestAssignee,
65
	flagPullRequestLabels,
66
	flagPullRequestFile string
67
	flagPullRequestBrowse,
68
	flagPullRequestForce bool
69
	flagPullRequestMilestone uint64
70
)
J
Jingwen Owen Ou 已提交
71 72

func init() {
73 74 75
	cmdPullRequest.Flag.StringVarP(&flagPullRequestBase, "base", "b", "", "BASE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestHead, "head", "h", "", "HEAD")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestIssue, "issue", "i", "", "ISSUE")
76
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestBrowse, "browse", "o", false, "BROWSE")
77 78 79
	cmdPullRequest.Flag.StringVarP(&flagPullRequestMessage, "message", "m", "", "MESSAGE")
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestForce, "force", "f", false, "FORCE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestFile, "file", "F", "", "FILE")
80
	cmdPullRequest.Flag.StringVarP(&flagPullRequestAssignee, "assign", "a", "", "USER")
81 82
	cmdPullRequest.Flag.Uint64VarP(&flagPullRequestMilestone, "milestone", "M", 0, "MILESTONE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestLabels, "labels", "l", "", "LABELS")
83 84

	CmdRunner.Use(cmdPullRequest)
J
Jingwen Owen Ou 已提交
85 86
}

87
func pullRequest(cmd *Command, args *Args) {
88 89
	localRepo, err := github.LocalRepo()
	utils.Check(err)
90 91

	currentBranch, err := localRepo.CurrentBranch()
J
Jingwen Owen Ou 已提交
92
	utils.Check(err)
93 94

	baseProject, err := localRepo.MainProject()
J
Jingwen Owen Ou 已提交
95
	utils.Check(err)
96

97
	host, err := github.CurrentConfig().PromptForHost(baseProject.Host)
98 99 100
	if err != nil {
		utils.Check(github.FormatError("creating pull request", err))
	}
J
Jingwen Owen Ou 已提交
101

102
	trackedBranch, headProject, err := localRepo.RemoteBranchAndProject(host.User, false)
103 104
	utils.Check(err)

105
	var (
J
Jingwen Owen Ou 已提交
106 107
		base, head string
		force      bool
108
	)
J
Jingwen Owen Ou 已提交
109

110
	force = flagPullRequestForce
J
Jingwen Owen Ou 已提交
111

112
	if flagPullRequestBase != "" {
J
Jingwen Owen Ou 已提交
113
		baseProject, base = parsePullRequestProject(baseProject, flagPullRequestBase)
114
	}
115

116
	if flagPullRequestHead != "" {
J
Jingwen Owen Ou 已提交
117
		headProject, head = parsePullRequestProject(headProject, flagPullRequestHead)
118
	}
119

J
Jingwen Owen Ou 已提交
120
	if args.ParamsSize() == 1 {
121
		arg := args.RemoveParam(0)
J
Jingwen Owen Ou 已提交
122
		flagPullRequestIssue = parsePullRequestIssueNumber(arg)
123 124
	}

125
	if base == "" {
J
Jingwen Owen Ou 已提交
126
		masterBranch := localRepo.MasterBranch()
127 128 129
		base = masterBranch.ShortName()
	}

J
Jingwen Owen Ou 已提交
130
	if head == "" && trackedBranch != nil {
J
Jingwen Owen Ou 已提交
131 132 133 134 135
		if !trackedBranch.IsRemote() {
			// the current branch tracking another branch
			// pretend there's no upstream at all
			trackedBranch = nil
		} else {
136
			if baseProject.SameAs(headProject) && base == trackedBranch.ShortName() {
J
Jingwen Owen Ou 已提交
137 138 139
				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)
140 141
			}
		}
J
Jingwen Owen Ou 已提交
142 143
	}

J
Jingwen Owen Ou 已提交
144 145 146 147 148 149
	if head == "" {
		if trackedBranch == nil {
			head = currentBranch.ShortName()
		} else {
			head = trackedBranch.ShortName()
		}
150 151
	}

152
	title, body, err := getTitleAndBodyFromFlags(flagPullRequestMessage, flagPullRequestFile)
153
	utils.Check(err)
154

155 156 157
	fullBase := fmt.Sprintf("%s:%s", baseProject.Owner, base)
	fullHead := fmt.Sprintf("%s:%s", headProject.Owner, head)

158 159 160 161 162 163 164
	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)
		}
165 166
	}

167
	var editor *github.Editor
J
Jingwen Owen Ou 已提交
168
	if title == "" && flagPullRequestIssue == "" {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
		baseTracking := base
		headTracking := head

		remote := gitRemoteForProject(baseProject)
		if remote != nil {
			baseTracking = fmt.Sprintf("%s/%s", remote.Name, base)
		}
		if remote == nil || !baseProject.SameAs(headProject) {
			remote = gitRemoteForProject(headProject)
		}
		if remote != nil {
			headTracking = fmt.Sprintf("%s/%s", remote.Name, head)
		}

		message, err := pullRequestChangesMessage(baseTracking, headTracking, fullBase, fullHead)
184 185 186 187 188 189
		utils.Check(err)

		editor, err = github.NewEditor("PULLREQ", "pull request", message)
		utils.Check(err)

		title, body, err = editor.EditTitleAndBody()
J
Jingwen Owen Ou 已提交
190
		utils.Check(err)
J
Jingwen Owen Ou 已提交
191
	}
192

J
Jingwen Owen Ou 已提交
193 194 195
	if title == "" && flagPullRequestIssue == "" {
		utils.Check(fmt.Errorf("Aborting due to empty pull request title"))
	}
J
Jingwen Owen Ou 已提交
196

197
	var pullRequestURL string
J
Jingwen Owen Ou 已提交
198
	if args.Noop {
199
		args.Before(fmt.Sprintf("Would request a pull request to %s from %s", fullBase, fullHead), "")
200
		pullRequestURL = "PULL_REQUEST_URL"
J
Jingwen Owen Ou 已提交
201
	} else {
J
Jingwen Owen Ou 已提交
202 203 204 205 206
		var (
			pr  *octokit.PullRequest
			err error
		)

207
		client := github.NewClientWithHost(host)
J
Jingwen Owen Ou 已提交
208
		if title != "" {
J
Jingwen Owen Ou 已提交
209 210 211
			pr, err = client.CreatePullRequest(baseProject, base, fullHead, title, body)
		} else if flagPullRequestIssue != "" {
			pr, err = client.CreatePullRequestForIssue(baseProject, base, fullHead, flagPullRequestIssue)
J
Jingwen Owen Ou 已提交
212
		}
213

214 215 216 217
		if err == nil && editor != nil {
			defer editor.DeleteFile()
		}

J
Jingwen Owen Ou 已提交
218
		utils.Check(err)
219

J
Jingwen Owen Ou 已提交
220
		pullRequestURL = pr.HTMLURL
221

222 223 224
		if flagPullRequestAssignee != "" || flagPullRequestMilestone > 0 ||
			flagPullRequestLabels != "" {

225 226 227 228 229 230 231
			labels := []string{}
			for _, label := range strings.Split(flagPullRequestLabels, ",") {
				if label != "" {
					labels = append(labels, label)
				}
			}

232 233 234
			params := octokit.IssueParams{
				Assignee:  flagPullRequestAssignee,
				Milestone: flagPullRequestMilestone,
235
				Labels:    labels,
236 237 238
			}

			err = client.UpdateIssue(baseProject, pr.Number, params)
239 240
			utils.Check(err)
		}
J
Jingwen Owen Ou 已提交
241
	}
242

243 244 245 246 247 248 249 250 251
	if flagPullRequestBrowse {
		launcher, err := utils.BrowserLauncher()
		utils.Check(err)
		args.Replace(launcher[0], "", launcher[1:]...)
		args.AppendParams(pullRequestURL)
	} else {
		args.Replace("echo", "", pullRequestURL)
	}

J
Jingwen Owen Ou 已提交
252 253 254
	if flagPullRequestIssue != "" {
		args.After("echo", "Warning: Issue to pull request conversion is deprecated and might not work in the future.")
	}
J
Jingwen Owen Ou 已提交
255
}
J
Jingwen Owen Ou 已提交
256

J
Jingwen Owen Ou 已提交
257 258 259 260 261 262 263 264
func pullRequestChangesMessage(base, head, fullBase, fullHead string) (string, error) {
	var (
		defaultMsg string
		commitLogs string
		err        error
	)

	commits, _ := git.RefList(base, head)
265
	if len(commits) == 1 {
J
Jingwen Owen Ou 已提交
266
		defaultMsg, err = git.Show(commits[0])
267
		if err != nil {
268
			return "", err
269 270
		}
	} else if len(commits) > 1 {
J
Jingwen Owen Ou 已提交
271
		commitLogs, err = git.Log(base, head)
272
		if err != nil {
273
			return "", err
274
		}
J
Jingwen Owen Ou 已提交
275 276
	}

J
Jingwen Owen Ou 已提交
277
	cs := git.CommentChar()
J
Jingwen Owen Ou 已提交
278

J
Jingwen Owen Ou 已提交
279
	return renderPullRequestTpl(defaultMsg, cs, fullBase, fullHead, commitLogs)
J
Jingwen Owen Ou 已提交
280 281
}

J
Jingwen Owen Ou 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
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 ""
}