forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
88 lines (70 loc) · 2.1 KB
/
merge.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
package commands
import (
"fmt"
"regexp"
"github.com/github/hub/github"
"github.com/github/hub/utils"
)
var cmdMerge = &Command{
Run: merge,
GitExtension: true,
Usage: "merge <PULLREQ-URL>",
Long: `Merge a pull request with a message like the GitHub Merge Button.
## Examples:
$ hub merge https://github.com/jingweno/gh/pull/73
> git fetch git://github.com/jingweno/gh.git +refs/heads/feature:refs/remotes/jingweno/feature
> git merge jingweno/feature --no-ff -m "Merge pull request #73 from jingweno/feature..."
## See also:
hub-checkout(1), hub(1), git-merge(1)
`,
}
func init() {
CmdRunner.Use(cmdMerge)
}
func merge(command *Command, args *Args) {
if !args.IsParamsEmpty() {
err := transformMergeArgs(args)
utils.Check(err)
}
}
func transformMergeArgs(args *Args) error {
words := args.Words()
if len(words) == 0 {
return nil
}
mergeURL := words[0]
url, err := github.ParseURL(mergeURL)
if err != nil {
return nil
}
pullURLRegex := regexp.MustCompile("^pull/(\\d+)")
projectPath := url.ProjectPath()
if !pullURLRegex.MatchString(projectPath) {
return nil
}
id := pullURLRegex.FindStringSubmatch(projectPath)[1]
gh := github.NewClient(url.Project.Host)
pullRequest, err := gh.PullRequest(url.Project, id)
if err != nil {
return err
}
branch := pullRequest.Head.Ref
headRepo := pullRequest.Head.Repo
if headRepo == nil {
return fmt.Errorf("Error: that fork is not available anymore")
}
u := url.GitURL(headRepo.Name, headRepo.Owner.Login, headRepo.Private)
mergeHead := fmt.Sprintf("%s/%s", headRepo.Owner.Login, branch)
ref := fmt.Sprintf("+refs/heads/%s:refs/remotes/%s", branch, mergeHead)
args.Before("git", "fetch", u, ref)
// Remove pull request URL
idx := args.IndexOfParam(mergeURL)
args.RemoveParam(idx)
mergeMsg := fmt.Sprintf("Merge pull request #%v from %s\n\n%s", id, mergeHead, pullRequest.Title)
args.AppendParams(mergeHead, "-m", mergeMsg)
if args.IndexOfParam("--ff-only") == -1 && args.IndexOfParam("--squash") == -1 && args.IndexOfParam("--ff") == -1 {
i := args.IndexOfParam("-m")
args.InsertParam(i, "--no-ff")
}
return nil
}