-
Notifications
You must be signed in to change notification settings - Fork 12
/
repository.go
499 lines (440 loc) · 11.8 KB
/
repository.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package main
import (
"bufio"
"context"
"fmt"
"os/exec"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
)
type Repository interface {
HeadName() string
HeadShortName() string
RemoteEndpointHost() string
RemoteEndpointPath() string
RootDirectory() string
LsRemote() (RefToHash, error)
}
func OpenRepository(path string) (Repository, error) {
repo, err := git.PlainOpenWithOptions(path, &git.PlainOpenOptions{
DetectDotGit: true,
})
if err != nil {
return nil, err
}
head, err := repo.Head()
if err != nil {
return nil, err
}
remote, err := repo.Remote("origin")
if err != nil {
return nil, err
}
cfg := remote.Config()
if len(cfg.URLs) == 0 {
return nil, errors.New("could not find remote URL")
}
u := cfg.URLs[0]
ep, err := transport.NewEndpoint(u)
if err != nil {
return nil, err
}
return &repository{
repo: repo,
head: head,
ep: ep,
}, nil
}
type repository struct {
repo *git.Repository
head *plumbing.Reference
ep *transport.Endpoint
}
func (r repository) HeadName() string {
return r.head.Name().String()
}
func (r repository) HeadShortName() string {
return r.head.Name().Short()
}
func (r repository) RemoteEndpointHost() string {
return r.ep.Host
}
func (r repository) RemoteEndpointPath() string {
return r.ep.Path
}
func (r repository) RootDirectory() string {
wt, err := r.repo.Worktree()
if err != nil {
panic(err)
}
return wt.Filesystem.Root()
}
func (r repository) LsRemote() (RefToHash, error) {
cmd := exec.Command("git", "ls-remote", "-q")
out, err := cmd.Output()
if err != nil {
return nil, err
}
return toRefToHash(out), nil
}
func toRefToHash(b []byte) RefToHash {
refToHash := make(RefToHash)
remotes := strings.Split(strings.TrimSuffix(string(b), "\n"), "\n")
for _, v := range remotes {
delimited := strings.Split(v, "\t")
hash := delimited[0]
ref := delimited[1]
refToHash[ref] = hash
}
return refToHash
}
func NewBacklogRepository(repo Repository) *BacklogRepository {
spaceKey, domain := extractSpaceKeyAndDomain(repo.RemoteEndpointHost())
projectKey, repoName := extractProjectKeyAndRepoName(repo.RemoteEndpointPath())
return &BacklogRepository{
openBrowser: openBrowser,
repo: repo,
domain: domain,
spaceKey: spaceKey,
projectKey: projectKey,
repoName: repoName,
}
}
func extractSpaceKeyAndDomain(host string) (spaceKey, domain string) {
delimitedHost := strings.Split(host, ".")
spaceKey = delimitedHost[0]
domain = strings.Join(delimitedHost[len(delimitedHost)-2:], ".")
return
}
func extractProjectKeyAndRepoName(path string) (projectKey, repoName string) {
epPath := strings.TrimPrefix(path, "/git")
delimitedPath := strings.Split(epPath, "/")
projectKey = delimitedPath[1]
repoName = strings.TrimSuffix(delimitedPath[2], ".git")
return
}
type BacklogRepository struct {
openBrowser func(url string) error
repo Repository
domain string
spaceKey string
projectKey string
repoName string
}
func (b *BacklogRepository) OpenObject(absPath string, isDirectory bool, line string) error {
root := b.repo.RootDirectory()
if !strings.HasPrefix(absPath, root) {
return errors.New("path " + absPath + " is out of repository " + root)
}
if line != "" {
if isDirectory {
return errors.New("line cannot be set for directory.")
} else {
re := regexp.MustCompile("^\\d+(-\\d+)?$")
if !re.MatchString(line) {
return errors.New("line can be number or 'from-to' format. :" + line)
}
}
}
relPath := strings.TrimPrefix(absPath[len(root):], "/")
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
ObjectURL(b.repo.HeadShortName(), relPath, isDirectory, line))
}
func (b *BacklogRepository) OpenRepositoryList() error {
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
GitBaseURL())
}
func (b *BacklogRepository) OpenTree(refOrHash string) error {
if refOrHash == "" {
refOrHash = b.repo.HeadShortName()
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
TreeURL(refOrHash))
}
func (b *BacklogRepository) OpenHistory(refOrHash string) error {
if refOrHash == "" {
refOrHash = b.repo.HeadShortName()
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
HistoryURL(refOrHash))
}
func (b *BacklogRepository) OpenCommit(hash string) error {
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
CommitURL(hash))
}
func (b *BacklogRepository) OpenNetwork(refOrHash string) error {
if refOrHash == "" {
refOrHash = b.repo.HeadShortName()
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
NetworkURL(refOrHash))
}
func (b *BacklogRepository) OpenBranchList() error {
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
BranchListURL())
}
func (b *BacklogRepository) OpenTagList() error {
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
TagListURL())
}
func (b *BacklogRepository) OpenPullRequestList(status string) error {
s, err := PRStatusFromString(status)
if err != nil {
return err
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
PullRequestListURL(s.Int()))
}
type PRStatus int
const (
PRStatusAll PRStatus = iota
PRStatusOpen
PRStatusClosed
PRStatusMerged
)
func (p PRStatus) Int() int {
return int(p)
}
func PRStatusFromString(s string) (status PRStatus, err error) {
strToStatus := make(map[string]PRStatus)
strToStatus["all"] = PRStatusAll
strToStatus["open"] = PRStatusOpen
strToStatus["closed"] = PRStatusClosed
strToStatus["merged"] = PRStatusMerged
v, ok := strToStatus[s]
if !ok {
var specs []string
for s := range strToStatus {
specs = append(specs, s)
}
err = errors.Errorf("invalid pull request's. choose from %v", specs)
}
status = v
return
}
func (b *BacklogRepository) OpenPullRequestByID(id string) error {
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
PullRequestURL(id))
}
func (b *BacklogRepository) OpenPullRequest() error {
id, err := b.findPullRequestIDFromRemote(b.repo.HeadName())
if err != nil {
return err
}
return b.OpenPullRequestByID(id)
}
const (
refPrefix = "refs/"
refPullRequestPrefix = refPrefix + "pull/"
refPullRequestSuffix = "/head"
)
type RefToHash map[string]string
func (b *BacklogRepository) findPullRequestIDFromRemote(ref string) (string, error) {
refToHash, err := b.repo.LsRemote()
if err != nil {
return "", err
}
targetHash, ok := refToHash[ref]
if !ok {
return "", errors.New("not found a current branch in remote")
}
var prIDs []string
for ref, hash := range refToHash {
if !isPRRef(ref) {
continue
}
if hash != targetHash {
continue
}
prIDs = append(prIDs, extractPRID(ref))
}
if len(prIDs) == 0 {
return "", errors.New("not found a pull request related to current branch")
}
sort.Sort(sort.Reverse(sort.StringSlice(prIDs)))
return prIDs[0], nil
}
func isPRRef(ref string) bool {
return strings.HasPrefix(ref, refPullRequestPrefix) && strings.HasSuffix(ref, refPullRequestSuffix)
}
func extractPRID(ref string) string {
prID := strings.TrimPrefix(ref, refPullRequestPrefix)
return strings.TrimSuffix(prID, refPullRequestSuffix)
}
func (b *BacklogRepository) OpenAddPullRequest(base, topic string) error {
if topic == "" {
topic = b.repo.HeadShortName()
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
AddPullRequestURL(base, topic))
}
func (b *BacklogRepository) OpenIssue() error {
key := extractIssueKey(b.repo.HeadShortName())
if key == "" {
return errors.New("could not find issue key in current branch name")
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
IssueURL(key))
}
func extractIssueKey(s string) string {
matches := regexp.MustCompile("([A-Z0-9]+(?:_[A-Z0-9]+)*-[0-9]+)").FindStringSubmatch(s)
if len(matches) < 2 {
return ""
}
return matches[1]
}
func (b *BacklogRepository) OpenAddIssue() error {
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
AddIssueURL())
}
type IssueStatus int
const (
IssueStatusAll IssueStatus = iota
IssueStatusOpen
IssueStatusInProgress
IssueStatusResolved
IssueStatusClosed
IssueStatusNotClosed
)
func (p IssueStatus) Int() int {
return int(p)
}
func IssueStatusFromString(s string) (status IssueStatus, err error) {
strToStatus := make(map[string]IssueStatus)
strToStatus["all"] = IssueStatusAll
strToStatus["open"] = IssueStatusOpen
strToStatus["in_progress"] = IssueStatusInProgress
strToStatus["resolved"] = IssueStatusResolved
strToStatus["closed"] = IssueStatusClosed
strToStatus["not_closed"] = IssueStatusNotClosed
v, ok := strToStatus[s]
if !ok {
var specs []string
for s := range strToStatus {
specs = append(specs, s)
}
err = errors.Errorf("invalid issue's status. choose from %v", specs)
}
status = v
return
}
func (b *BacklogRepository) OpenIssueList(state string) error {
s, err := IssueStatusFromString(state)
if err != nil {
return err
}
var statusIds []int
switch s {
case IssueStatusAll:
// Don't specify the issue status
case IssueStatusNotClosed:
statusIds = append(statusIds, IssueStatusOpen.Int())
statusIds = append(statusIds, IssueStatusInProgress.Int())
statusIds = append(statusIds, IssueStatusResolved.Int())
default:
statusIds = append(statusIds, s.Int())
}
return b.openBrowser(NewBacklogURLBuilder(b.domain, b.spaceKey).
SetProjectKey(b.projectKey).
SetRepoName(b.repoName).
IssueListURL(statusIds))
}
func (b *BacklogRepository) BlamePR(argv []string) error {
argv = append([]string{"blame", "--first-parent"}, argv...)
cmd := exec.CommandContext(context.Background(), "git", argv...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
defer func() {
_ = cmd.Wait()
}()
cached := make(map[string]string)
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
commitAndSrc := strings.SplitN(scanner.Text(), " ", 2)
commit, src := commitAndSrc[0], commitAndSrc[1]
if _, ok := cached[commit]; !ok {
pr, err := lookup(commit)
if err != nil {
return err
}
cached[commit] = pr
}
padding := len(commit)
if size := len(cached[commit]); padding < size {
padding = size
}
format := "%-" + strconv.Itoa(padding) + "s %s\n"
fmt.Printf(format, cached[commit], src)
}
return err
}
func lookup(commit string) (string, error) {
cmd := exec.CommandContext(context.Background(), "git", "show", "--oneline", commit)
out, err := cmd.Output()
if err != nil {
return commit, err
}
reg := regexp.MustCompile(`^[a-f0-9]+ Merge pull request #([0-9]+) \S+ into \S+`)
matches := reg.FindStringSubmatch(string(out))
if len(matches) < 1 {
return commit, nil
}
id, err := strconv.Atoi(matches[1])
if err != nil {
return commit, nil
}
return fmt.Sprintf("PR #%d", id), nil
}
func openBrowser(url string) error {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err
}