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

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

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

15 16
var cmdPullRequest = &Command{
	Run:   pullRequest,
J
Jingwen Owen Ou 已提交
17
	Usage: "pull-request [-f] [-m <MESSAGE>|-F <FILE>|-i <ISSUE>|<ISSUE-URL>] [-b <BASE>] [-h <HEAD>] ",
J
Jingwen Owen Ou 已提交
18 19 20 21 22 23 24
	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
J
Jingwen Owen Ou 已提交
25
on the remote. To skip this check, use "-f".
J
Jingwen Owen Ou 已提交
26

J
Jingwen Owen Ou 已提交
27 28 29
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 -".
J
Jingwen Owen Ou 已提交
30

J
Jingwen Owen Ou 已提交
31
If instead of normal <TITLE> an issue number is given with "-i", the pull
J
Jingwen Owen Ou 已提交
32 33 34 35 36
request will be attached to an existing GitHub issue. Alternatively, instead
of title you can paste a full URL to an issue on GitHub.
`,
}

37 38 39 40 41 42 43 44
var (
	flagPullRequestBase,
	flagPullRequestHead,
	flagPullRequestIssue,
	flagPullRequestMessage,
	flagPullRequestFile string
	flagPullRequestForce bool
)
J
Jingwen Owen Ou 已提交
45 46

func init() {
47 48 49 50 51 52
	cmdPullRequest.Flag.StringVarP(&flagPullRequestBase, "base", "b", "", "BASE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestHead, "head", "h", "", "HEAD")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestIssue, "issue", "i", "", "ISSUE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestMessage, "message", "m", "", "MESSAGE")
	cmdPullRequest.Flag.BoolVarP(&flagPullRequestForce, "force", "f", false, "FORCE")
	cmdPullRequest.Flag.StringVarP(&flagPullRequestFile, "file", "F", "", "FILE")
53 54

	CmdRunner.Use(cmdPullRequest)
J
Jingwen Owen Ou 已提交
55 56
}

57 58 59 60 61 62 63 64 65
/*
  # 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

66 67 68
  $ gh pull-request -m "title\n\nbody"
  [ create pull request with title & body  ]

69 70
  $ gh pull-request -i 123
  [ attached pull request to issue #123 ]
71 72 73

  $ gh pull-request https://github.com/jingweno/gh/pull/123
  [ attached pull request to issue #123 ]
J
Jingwen Owen Ou 已提交
74 75 76

  $ gh pull-request -F FILE
  [ create pull request with title & body from FILE ]
77
*/
78
func pullRequest(cmd *Command, args *Args) {
79 80 81
	localRepo := github.LocalRepo()

	currentBranch, err := localRepo.CurrentBranch()
J
Jingwen Owen Ou 已提交
82
	utils.Check(err)
83 84

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

J
Jingwen Owen Ou 已提交
87 88 89
	client := github.NewClient(baseProject.Host)

	trackedBranch, headProject, err := localRepo.RemoteBranchAndProject(client.Credentials.User)
90 91
	utils.Check(err)

92
	var (
J
Jingwen Owen Ou 已提交
93 94
		base, head string
		force      bool
95
	)
J
Jingwen Owen Ou 已提交
96

97
	force = flagPullRequestForce
J
Jingwen Owen Ou 已提交
98

99
	if flagPullRequestBase != "" {
J
Jingwen Owen Ou 已提交
100
		baseProject, base = parsePullRequestProject(baseProject, flagPullRequestBase)
101
	}
102

103
	if flagPullRequestHead != "" {
J
Jingwen Owen Ou 已提交
104
		headProject, head = parsePullRequestProject(headProject, flagPullRequestHead)
105
	}
106

J
Jingwen Owen Ou 已提交
107
	if args.ParamsSize() == 1 {
108
		arg := args.RemoveParam(0)
J
Jingwen Owen Ou 已提交
109
		flagPullRequestIssue = parsePullRequestIssueNumber(arg)
110 111
	}

112
	if base == "" {
J
Jingwen Owen Ou 已提交
113
		masterBranch := localRepo.MasterBranch()
114 115 116 117
		base = masterBranch.ShortName()
	}

	if head == "" {
J
Jingwen Owen Ou 已提交
118 119 120 121 122
		if !trackedBranch.IsRemote() {
			// the current branch tracking another branch
			// pretend there's no upstream at all
			trackedBranch = nil
		} else {
J
Jingwen Owen Ou 已提交
123 124 125 126
			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)
127 128 129
			}
		}

J
Jingwen Owen Ou 已提交
130
		if trackedBranch == nil {
131
			head = currentBranch.ShortName()
J
Jingwen Owen Ou 已提交
132 133
		} else {
			head = trackedBranch.ShortName()
134 135 136
		}
	}

137
	title, body, err := getTitleAndBodyFromFlags(flagPullRequestMessage, flagPullRequestFile)
138
	utils.Check(err)
139

140 141 142
	fullBase := fmt.Sprintf("%s:%s", baseProject.Owner, base)
	fullHead := fmt.Sprintf("%s:%s", headProject.Owner, head)

143 144 145 146 147 148 149
	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)
		}
150 151
	}

J
Jingwen Owen Ou 已提交
152
	if title == "" && flagPullRequestIssue == "" {
153
		commits, _ := git.RefList(base, head)
154
		title, body, err = writePullRequestTitleAndBody(base, head, fullBase, fullHead, commits)
J
Jingwen Owen Ou 已提交
155
		utils.Check(err)
J
Jingwen Owen Ou 已提交
156
	}
157

J
Jingwen Owen Ou 已提交
158 159 160
	if title == "" && flagPullRequestIssue == "" {
		utils.Check(fmt.Errorf("Aborting due to empty pull request title"))
	}
J
Jingwen Owen Ou 已提交
161

162
	var pullRequestURL string
J
Jingwen Owen Ou 已提交
163
	if args.Noop {
164
		args.Before(fmt.Sprintf("Would request a pull request to %s from %s", fullBase, fullHead), "")
165
		pullRequestURL = "PULL_REQUEST_URL"
J
Jingwen Owen Ou 已提交
166
	} else {
J
Jingwen Owen Ou 已提交
167 168 169 170 171
		var (
			pr  *octokit.PullRequest
			err error
		)

J
Jingwen Owen Ou 已提交
172
		if title != "" {
J
Jingwen Owen Ou 已提交
173 174 175
			pr, err = client.CreatePullRequest(baseProject, base, fullHead, title, body)
		} else if flagPullRequestIssue != "" {
			pr, err = client.CreatePullRequestForIssue(baseProject, base, fullHead, flagPullRequestIssue)
J
Jingwen Owen Ou 已提交
176
		}
177

J
Jingwen Owen Ou 已提交
178 179
		utils.Check(err)
		pullRequestURL = pr.HTMLURL
J
Jingwen Owen Ou 已提交
180
	}
181 182

	args.Replace("echo", "", pullRequestURL)
J
Jingwen Owen Ou 已提交
183 184 185
	if flagPullRequestIssue != "" {
		args.After("echo", "Warning: Issue to pull request conversion is deprecated and might not work in the future.")
	}
J
Jingwen Owen Ou 已提交
186
}
J
Jingwen Owen Ou 已提交
187

188
func writePullRequestTitleAndBody(base, head, fullBase, fullHead string, commits []string) (title, body string, err error) {
189
	message, err := pullRequestChangesMessage(base, head, fullBase, fullHead, commits)
190 191 192 193
	if err != nil {
		return
	}

194
	editor, err := github.NewEditor("PULLREQ", "pull request", message)
195 196 197
	if err != nil {
		return
	}
J
Jingwen Owen Ou 已提交
198

199
	return editor.EditTitleAndBody()
200 201
}

202
func pullRequestChangesMessage(base, head, fullBase, fullHead string, commits []string) (string, error) {
203 204
	var defaultMsg, commitSummary string
	if len(commits) == 1 {
J
Jingwen Owen Ou 已提交
205
		msg, err := git.Show(commits[0])
206
		if err != nil {
207
			return "", err
208
		}
J
Jingwen Owen Ou 已提交
209
		defaultMsg = fmt.Sprintf("%s\n", msg)
210
	} else if len(commits) > 1 {
211
		commitLogs, err := git.Log(base, head)
212
		if err != nil {
213
			return "", err
214 215 216 217 218 219 220 221 222 223
		}

		if len(commitLogs) > 0 {
			startRegexp := regexp.MustCompilePOSIX("^")
			endRegexp := regexp.MustCompilePOSIX(" +$")

			commitLogs = strings.TrimSpace(commitLogs)
			commitLogs = startRegexp.ReplaceAllString(commitLogs, "# ")
			commitLogs = endRegexp.ReplaceAllString(commitLogs, "")
			commitSummary = `
J
Jingwen Owen Ou 已提交
224 225 226
#
# Changes:
#
J
Jingwen Owen Ou 已提交
227
%s`
228 229
			commitSummary = fmt.Sprintf(commitSummary, commitLogs)
		}
230
	}
J
Jingwen Owen Ou 已提交
231

232 233 234 235 236 237
	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
`
238
	message = fmt.Sprintf(message, defaultMsg, fullBase, fullHead, commitSummary)
J
Jingwen Owen Ou 已提交
239

240
	return message, nil
241
}
J
Jingwen Owen Ou 已提交
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 268 269 270 271 272 273

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 ""
}