-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
246 lines (210 loc) · 4.69 KB
/
main.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
package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"golang.org/x/oauth2"
"github.com/github/hub/github"
api "github.com/google/go-github/github"
homedir "github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"github.com/skratchdot/open-golang/open"
)
const Usage = `Usage:
whichpr show|open SHA1
whichpr version
`
var version = "master"
type ErrorMessage struct {
message string
}
func NewErrorMessage(message string) *ErrorMessage {
var m string
if message == "" {
m = Usage
} else {
m = fmt.Sprintf("%s\n%s", Usage, message)
}
return &ErrorMessage{
message: m,
}
}
func (e *ErrorMessage) Error() string {
return e.message
}
func (e *ErrorMessage) Format(s fmt.State, verb rune) {
io.WriteString(s, e.message)
}
func main() {
if err := Main(os.Args); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}
func Main(args []string) error {
if len(args) < 2 {
return NewErrorMessage("")
}
command := args[1]
switch command {
case "show":
if len(args) != 3 {
return NewErrorMessage("")
}
sha1 := args[2]
return Show(sha1)
case "open":
if len(args) != 3 {
return NewErrorMessage("")
}
sha1 := args[2]
return Open(sha1)
case "version":
return Version()
default:
return NewErrorMessage(fmt.Sprintf("%s is unknown command", command))
}
}
func Version() error {
fmt.Println(version)
return nil
}
func Show(sha1 string) error {
prj, err := Project()
if err != nil {
return err
}
num, err := PullRequestNumber(prj, sha1)
if err != nil {
return err
}
fmt.Println(num)
return nil
}
func Open(sha1 string) error {
prj, err := Project()
if err != nil {
return err
}
num, err := PullRequestNumber(prj, sha1)
if err != nil {
return err
}
url := prj.WebURL("", "", fmt.Sprintf("pull/%d", num))
return open.Run(url)
}
func PullRequestNumber(prj *github.Project, sha1 string) (int, error) {
if len(sha1) < 7 {
return 0, NewErrorMessage("SHA1 must be at least seven characters")
}
pr, err := SquashedPullReqNum(sha1)
if err == nil {
return pr, nil
}
pr, err = MergedPullRequestNum(sha1)
if err == nil {
return pr, nil
}
repo := prj.String()
// TODO: sort
client, err := APIClient()
if err != nil {
return 0, err
}
res, _, err := client.Search.Issues(context.Background(), fmt.Sprintf("%s is:merged repo:%s", sha1, repo), nil)
if err != nil {
return 0, err
}
if len(res.Issues) == 0 {
return 0, errors.New("Pull Request is not found")
}
return *res.Issues[0].Number, nil
}
func SquashedPullReqNum(sha1 string) (int, error) {
out, err := exec.Command("git", "log", "--pretty=format:%s", "-n", "1", sha1).Output()
if err != nil {
return 0, err
}
msg := strings.Split(string(out), "\n")[0]
re := regexp.MustCompile(`\(\#(\d+)\)$`)
match := re.FindStringSubmatch(msg)
if len(match) == 0 {
return 0, errors.New("Does not match")
}
return strconv.Atoi(match[1])
}
func MergedPullRequestNum(sha1 string) (int, error) {
out, err := exec.Command("git", "log", "--merges", "--pretty=format:%P %s", "--reverse", "--ancestry-path", sha1+"..@").Output()
if err != nil {
return 0, err
}
msgs := strings.Split(string(out), "\n")
re := regexp.MustCompile(`^(?:[a-f0-9]+ ){2}Merge pull request \#(\d+) from `)
mergeCommit, err := findRegexp(msgs, re)
if err != nil {
return 0, err
}
pr := re.FindStringSubmatch(mergeCommit)[1]
if isParent(sha1, regexp.MustCompile(`\w+ (\w+) `).FindStringSubmatch(mergeCommit)[1]) {
return strconv.Atoi(pr)
} else {
return 0, errors.Errorf("%s is not parent", sha1)
}
}
// RepoName returns owner/repo.
func Project() (*github.Project, error) {
repo, err := github.LocalRepo()
if err != nil {
return nil, err
}
prj, err := repo.MainProject()
if err != nil {
return nil, err
}
return prj, nil
}
func APIClient() (*api.Client, error) {
homeDir, err := homedir.Dir()
if err != nil {
return nil, err
}
confPath := filepath.Join(homeDir, ".config", "whichpr")
err = os.Setenv("HUB_CONFIG", confPath)
if err != nil {
return nil, err
}
c := github.CurrentConfig()
host, err := c.DefaultHost()
if err != nil {
return nil, err
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: host.AccessToken},
)
tc := oauth2.NewClient(context.Background(), ts)
return api.NewClient(tc), nil
}
func findRegexp(arr []string, re *regexp.Regexp) (string, error) {
for _, str := range arr {
if re.MatchString(str) {
return str, nil
}
}
return "", fmt.Errorf("Missing")
}
func isParent(parent, child string) bool {
if strings.HasPrefix(child, parent) {
return true
}
b, err := exec.Command("git", "log", "--ancestry-path", parent+".."+child).Output()
if err != nil {
return false
}
return len(b) != 0
}