-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpoi.go
722 lines (624 loc) · 16.3 KB
/
poi.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//go:generate mockgen -source=poi.go -package=mocks -destination=./mocks/poi_mock.go
package main
import (
"context"
"encoding/json"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
)
type (
Connection interface {
CheckRepos(ctx context.Context, hostname string, repoNames []string) error
GetRemoteNames(ctx context.Context) (string, error)
GetSshConfig(ctx context.Context, name string) (string, error)
GetRepoNames(ctx context.Context, hostname string, repoName string) (string, error)
GetBranchNames(ctx context.Context) (string, error)
GetMergedBranchNames(ctx context.Context, remoteName string, branchName string) (string, error)
GetRemoteHeadOid(ctx context.Context, remoteName string, branchName string) (string, error)
GetLsRemoteHeadOid(ctx context.Context, url string, branchName string) (string, error)
GetLog(ctx context.Context, branchName string) (string, error)
GetAssociatedRefNames(ctx context.Context, oid string) (string, error)
GetPullRequests(ctx context.Context, hostname string, repoNames []string, queryHashes string) (string, error)
GetUncommittedChanges(ctx context.Context) (string, error)
GetConfig(ctx context.Context, key string) (string, error)
CheckoutBranch(ctx context.Context, branchName string) (string, error)
DeleteBranches(ctx context.Context, branchNames []string) (string, error)
}
Remote struct {
Name string
Hostname string
RepoName string
}
BranchState int
Branch struct {
Head bool
Name string
IsMerged bool
RemoteHeadOid string
Commits []string
PullRequests []PullRequest
State BranchState
}
PullRequestState int
PullRequest struct {
Name string
State PullRequestState
IsDraft bool
Number int
Commits []string
Url string
Author string
}
UncommittedChange struct {
X string
Y string
Path string
}
)
const (
Unknown BranchState = iota
NotDeletable
Deletable
Deleted
)
const (
Closed PullRequestState = iota
Merged
Open
)
const (
github = "github.com"
localhost = "github.localhost"
)
var detachedBranchNameRegex = regexp.MustCompile(`^\(.+\)`)
var ErrNotFound = errors.New("not found")
func GetRemote(ctx context.Context, connection Connection) (Remote, error) {
remoteNames, err := connection.GetRemoteNames(ctx)
if err != nil {
return Remote{}, err
}
remotes := toRemotes(splitLines(remoteNames))
if remote, err := getPrimaryRemote(remotes); err == nil {
hostname := remote.Hostname
if config, err := connection.GetSshConfig(ctx, hostname); err == nil {
remote.Hostname = normalizeHostname(findHostname(splitLines(config), hostname))
}
return remote, nil
} else {
return Remote{}, err
}
}
func GetBranches(ctx context.Context, remote Remote, connection Connection, dryRun bool) ([]Branch, error) {
var repoNames []string
var defaultBranchName string
if json, err := connection.GetRepoNames(ctx, remote.Hostname, remote.RepoName); err == nil {
repoNames, defaultBranchName, err = getRepo(json)
if err != nil {
return nil, err
}
} else {
return nil, err
}
err := connection.CheckRepos(ctx, remote.Hostname, repoNames)
if err != nil {
return nil, err
}
var branches []Branch
if names, err := connection.GetBranchNames(ctx); err == nil {
branches = toBranch(splitLines(names))
mergedNames, err := connection.GetMergedBranchNames(ctx, remote.Name, defaultBranchName)
if err != nil {
return nil, err
}
branches = applyMerged(branches, extractMergedBranchNames(splitLines(mergedNames)))
branches, err = applyCommits(ctx, remote, branches, defaultBranchName, connection)
if err != nil {
return nil, err
}
} else {
return nil, err
}
prs := []PullRequest{}
for _, queryHashes := range getQueryHashes(branches) {
json, err := connection.GetPullRequests(ctx, remote.Hostname, repoNames, queryHashes)
if err != nil {
return nil, err
}
pr, err := toPullRequests(json)
if err != nil {
return nil, err
}
prs = append(prs, pr...)
}
branches = applyPullRequest(ctx, branches, prs, connection)
var uncommittedChanges []UncommittedChange
if changes, err := connection.GetUncommittedChanges(ctx); err == nil {
uncommittedChanges = toUncommittedChange(splitLines(changes))
} else {
return nil, err
}
branches = checkDeletion(branches, uncommittedChanges)
needsCheckout := false
for _, branch := range branches {
if branch.Head && branch.State == Deletable {
needsCheckout = true
break
}
}
if needsCheckout {
result := []Branch{}
if !dryRun {
_, err := connection.CheckoutBranch(ctx, defaultBranchName)
if err != nil {
return nil, err
}
}
if !branchNameExists(defaultBranchName, branches) {
result = append(result, Branch{
true, defaultBranchName,
false,
"",
[]string{},
[]PullRequest{},
NotDeletable,
})
}
for _, branch := range branches {
if branch.Name == defaultBranchName {
branch.Head = true
} else {
branch.Head = false
}
result = append(result, branch)
}
branches = result
}
sort.Slice(branches, func(i, j int) bool { return branches[i].Name < branches[j].Name })
return branches, nil
}
// https://github.com/cli/cli/blob/8f28d1f9d5b112b222f96eb793682ff0b5a7927d/internal/ghinstance/host.go#L26
func normalizeHostname(host string) string {
hostname := strings.ToLower(host)
if strings.HasSuffix(hostname, "."+github) {
return github
}
if strings.HasSuffix(hostname, "."+localhost) {
return localhost
}
return hostname
}
func toRemotes(remoteNames []string) []Remote {
results := []Remote{}
r := regexp.MustCompile(`^(.+?)\s+.+(?:@|//)(.+?)(?::|/)(.+?/.+?)(?:\.git|)\s+.+$`)
for _, name := range remoteNames {
found := r.FindStringSubmatch(name)
if len(found) == 4 {
results = append(results, Remote{found[1], found[2], found[3]})
}
}
return results
}
func getPrimaryRemote(remotes []Remote) (Remote, error) {
if len(remotes) == 0 {
return Remote{}, ErrNotFound
}
for _, remote := range remotes {
if remote.Name == "origin" {
return remote, nil
}
}
return remotes[0], nil
}
func findHostname(params []string, defaultName string) string {
for _, param := range params {
kv := strings.Split(param, " ")
if kv[0] == "hostname" {
return kv[1]
}
}
return defaultName
}
func extractMergedBranchNames(mergedNames []string) []string {
result := []string{}
r := regexp.MustCompile(`^[ *]+(.+)`)
for _, name := range mergedNames {
found := r.FindStringSubmatch(name)
if len(found) > 1 {
result = append(result, found[1])
}
}
return result
}
func applyMerged(branches []Branch, mergedNames []string) []Branch {
results := []Branch{}
for _, branch := range branches {
branch.IsMerged = nameExists(branch.Name, mergedNames)
results = append(results, branch)
}
return results
}
func nameExists(name string, names []string) bool {
for _, n := range names {
if n == name {
return true
}
}
return false
}
func applyCommits(ctx context.Context, remote Remote, branches []Branch, defaultBranchName string, connection Connection) ([]Branch, error) {
results := []Branch{}
for _, branch := range branches {
if branch.Name == defaultBranchName || branch.IsDetached() {
results = append(results, branch)
continue
}
if remoteHeadOid, err := connection.GetRemoteHeadOid(ctx, remote.Name, branch.Name); err == nil {
branch.RemoteHeadOid = splitLines(remoteHeadOid)[0]
} else {
result, _ := connection.GetConfig(ctx, fmt.Sprintf("branch.%s.remote", branch.Name))
splitResults := splitLines(result)
if len(splitResults) > 0 {
remoteUrl := splitResults[0]
if result, err := connection.GetLsRemoteHeadOid(ctx, remoteUrl, branch.Name); err == nil {
splitResults := strings.Fields(result)
if len(splitResults) > 0 {
branch.RemoteHeadOid = splitResults[0]
}
}
}
}
oids, err := connection.GetLog(ctx, branch.Name)
if err != nil {
return nil, err
}
trimmedOids, err := trimBranch(
ctx, splitLines(oids), branch.RemoteHeadOid, branch.IsMerged,
branch.Name, defaultBranchName, connection)
if err != nil {
return nil, err
}
branch.Commits = trimmedOids
results = append(results, branch)
}
return results, nil
}
func trimBranch(ctx context.Context, oids []string, remoteHeadOid string, isMerged bool,
branchName string, defaultBranchName string, connection Connection) ([]string, error) {
results := []string{}
childNames := []string{}
for i, oid := range oids {
if len(remoteHeadOid) > 0 || isMerged {
results = append(results, oid)
break
}
refNames, err := connection.GetAssociatedRefNames(ctx, oid)
if err != nil {
return nil, err
}
names := extractBranchNames(splitLines(refNames))
if i == 0 {
for _, name := range names {
if name == defaultBranchName {
return []string{}, nil
}
if name != branchName {
childNames = append(childNames, name)
}
}
}
isChild := func(name string) bool {
for _, childName := range childNames {
if name == childName {
return true
}
}
return false
}
for _, name := range names {
if name != branchName && !isChild(name) {
return results, nil
}
}
results = append(results, oid)
}
return results, nil
}
func extractBranchNames(refNames []string) []string {
result := []string{}
r := regexp.MustCompile(`^refs/(?:heads|remotes/.+?)/`)
for _, name := range refNames {
result = append(result, r.ReplaceAllString(name, ""))
}
return result
}
func applyPullRequest(ctx context.Context, branches []Branch, prs []PullRequest, connection Connection) []Branch {
prNumbers := map[string]int{}
for _, branch := range branches {
if branch.IsDetached() {
continue
}
mergeConfig, _ := connection.GetConfig(ctx, fmt.Sprintf("branch.%s.merge", branch.Name))
if n := getPRNumber(mergeConfig); n > 0 {
prNumbers[branch.Name] = n
}
}
results := []Branch{}
for _, branch := range branches {
prs := findMatchedPullRequest(branch.Name, prs, prNumbers)
sort.Slice(prs, func(i, j int) bool { return prs[i].Number < prs[j].Number })
branch.PullRequests = prs
results = append(results, branch)
}
return results
}
func getPRNumber(mergeConfig string) int {
r := regexp.MustCompile(`^refs/pull/(\d+)`)
found := r.FindStringSubmatch(mergeConfig)
if len(found) > 0 {
num, err := strconv.Atoi(found[1])
if err != nil {
return 0
}
return num
} else {
return 0
}
}
func findMatchedPullRequest(branchName string, prs []PullRequest, prNumbers map[string]int) []PullRequest {
results := []PullRequest{}
prExists := func(pr PullRequest) bool {
for _, result := range results {
if pr.Number == result.Number {
return true
}
}
return false
}
prNumberExists := func(prNumber int) bool {
for _, n := range prNumbers {
if n == prNumber {
return true
}
}
return false
}
for _, pr := range prs {
if prExists(pr) {
continue
}
if prNumberExists(pr.Number) {
if pr.Number == prNumbers[branchName] {
results = append(results, pr)
}
} else if pr.Name == branchName {
results = append(results, pr)
}
}
return results
}
func toUncommittedChange(changes []string) []UncommittedChange {
results := []UncommittedChange{}
for _, change := range changes {
results = append(results, UncommittedChange{
string(change[0]),
string(change[1]),
string(change[3:]),
})
}
return results
}
func checkDeletion(branches []Branch, uncommittedChanges []UncommittedChange) []Branch {
results := []Branch{}
for _, branch := range branches {
branch.State = getDeleteStatus(branch, uncommittedChanges)
results = append(results, branch)
}
return results
}
func getDeleteStatus(branch Branch, uncommittedChanges []UncommittedChange) BranchState {
hasTrackedChanges := false
for _, change := range uncommittedChanges {
if !change.IsUntracked() {
hasTrackedChanges = true
break
}
}
if branch.Head && hasTrackedChanges {
return NotDeletable
}
if len(branch.PullRequests) == 0 {
return NotDeletable
}
fullyMergedCnt := 0
for _, pr := range branch.PullRequests {
if pr.State == Open {
return NotDeletable
}
if isFullyMerged(branch, pr) {
fullyMergedCnt++
}
}
if fullyMergedCnt == 0 {
return NotDeletable
}
return Deletable
}
func isFullyMerged(branch Branch, pr PullRequest) bool {
if pr.State != Merged || len(branch.Commits) == 0 {
return false
}
localHeadOid := branch.Commits[0]
for _, oid := range pr.Commits {
if oid == localHeadOid {
return true
}
}
return false
}
func toBranch(branchNames []string) []Branch {
results := []Branch{}
for _, branchName := range branchNames {
splitedNames := strings.Split(branchName, ":")
results = append(results, Branch{
splitedNames[0] == "*",
splitedNames[1],
false,
"",
[]string{},
[]PullRequest{},
Unknown,
})
}
return results
}
func getRepo(jsonResp string) ([]string, string, error) {
type response struct {
DefaultBranchRef struct {
Name string
}
Name string
Owner struct {
Login string
}
Parent struct {
Name string
Owner struct {
Login string
}
DefaultBranchName string
}
}
var resp response
if err := json.Unmarshal([]byte(jsonResp), &resp); err != nil {
return nil, "", fmt.Errorf("error unmarshaling response: %w", err)
}
repoNames := []string{
resp.Owner.Login + "/" + resp.Name,
}
if len(resp.Parent.Name) > 0 {
repoNames = append(repoNames, resp.Parent.Owner.Login+"/"+resp.Parent.Name)
}
return repoNames, resp.DefaultBranchRef.Name, nil
}
func toPullRequests(jsonResp string) ([]PullRequest, error) {
type response struct {
Data struct {
Search struct {
IssueCount int
Edges []struct {
Node struct {
Number int
HeadRefName string
HeadRefOid string
Url string
State string
IsDraft bool
Commits struct {
Nodes []struct {
Commit struct {
Oid string
}
}
}
Author struct {
Login string
}
}
}
}
}
}
var resp response
if err := json.Unmarshal([]byte(jsonResp), &resp); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
results := []PullRequest{}
for _, edge := range resp.Data.Search.Edges {
state, err := toPullRequestState(edge.Node.State)
if err == ErrNotFound {
return nil, fmt.Errorf("unexpected pull request state: %s", edge.Node.State)
}
commits := []string{}
for _, node := range edge.Node.Commits.Nodes {
commits = append(commits, node.Commit.Oid)
}
results = append(results, PullRequest{
edge.Node.HeadRefName,
state,
edge.Node.IsDraft,
edge.Node.Number,
commits,
edge.Node.Url,
edge.Node.Author.Login,
})
}
return results, nil
}
func toPullRequestState(state string) (PullRequestState, error) {
switch state {
case "CLOSED":
return Closed, nil
case "MERGED":
return Merged, nil
case "OPEN":
return Open, nil
default:
return 0, ErrNotFound
}
}
func DeleteBranches(ctx context.Context, branches []Branch, connection Connection) ([]Branch, error) {
branchNames := getBranchNames(branches, Deletable)
if len(branchNames) == 0 {
return branches, nil
}
connection.DeleteBranches(ctx, branchNames)
branchNamesAfter, err := connection.GetBranchNames(ctx)
if err != nil {
return nil, err
}
branchesAfter := toBranch(splitLines(branchNamesAfter))
return checkDeleted(branches, branchesAfter), nil
}
func getBranchNames(branches []Branch, state BranchState) []string {
results := []string{}
for _, branch := range branches {
if branch.State == state {
results = append(results, branch.Name)
}
}
return results
}
func checkDeleted(branchesBefore []Branch, branchesAfter []Branch) []Branch {
results := []Branch{}
for _, branch := range branchesBefore {
if branch.State == Deletable {
if !branchNameExists(branch.Name, branchesAfter) {
branch.State = Deleted
}
}
results = append(results, branch)
}
return results
}
func branchNameExists(branchName string, branches []Branch) bool {
for _, branch := range branches {
if branch.Name == branchName {
return true
}
}
return false
}
func splitLines(text string) []string {
return strings.FieldsFunc(strings.Replace(text, "\r\n", "\n", -1),
func(c rune) bool { return c == '\n' })
}
func (b Branch) IsDetached() bool {
return detachedBranchNameRegex.MatchString(b.Name)
}
func (uc *UncommittedChange) IsUntracked() bool {
return uc.Y == "?"
}