@@ -8,6 +8,7 @@ package git
8
8
9
9
import (
10
10
"context"
11
+ "sort"
11
12
"strings"
12
13
13
14
"github.com/go-git/go-git/v5/plumbing"
@@ -52,32 +53,46 @@ func (repo *Repository) IsBranchExist(name string) bool {
52
53
53
54
// GetBranches returns branches from the repository, skipping "skip" initial branches and
54
55
// returning at most "limit" branches, or all branches if "limit" is 0.
56
+ // Branches are returned with sort of `-commiterdate` as the nogogit
57
+ // implementation. This requires full fetch, sort and then the
58
+ // skip/limit applies later as gogit returns in undefined order.
55
59
func (repo * Repository ) GetBranchNames (skip , limit int ) ([]string , int , error ) {
56
- var branchNames []string
60
+ type BranchData struct {
61
+ name string
62
+ committerDate int64
63
+ }
64
+ var branchData []BranchData
57
65
58
- branches , err := repo .gogitRepo .Branches ()
66
+ branchIter , err := repo .gogitRepo .Branches ()
59
67
if err != nil {
60
68
return nil , 0 , err
61
69
}
62
70
63
- i := 0
64
- count := 0
65
- _ = branches .ForEach (func (branch * plumbing.Reference ) error {
66
- count ++
67
- if i < skip {
68
- i ++
69
- return nil
70
- } else if limit != 0 && count > skip + limit {
71
+ _ = branchIter .ForEach (func (branch * plumbing.Reference ) error {
72
+ obj , err := repo .gogitRepo .CommitObject (branch .Hash ())
73
+ if err != nil {
74
+ // skip branch if can't find commit
71
75
return nil
72
76
}
73
77
74
- branchNames = append (branchNames , strings .TrimPrefix (branch .Name ().String (), BranchPrefix ))
78
+ branchData = append (branchData , BranchData { strings .TrimPrefix (branch .Name ().String (), BranchPrefix ), obj . Committer . When . Unix ()} )
75
79
return nil
76
80
})
77
81
78
- // TODO: Sort?
82
+ sort .Slice (branchData , func (i , j int ) bool {
83
+ return ! (branchData [i ].committerDate < branchData [j ].committerDate )
84
+ })
85
+
86
+ var branchNames []string
87
+ maxPos := len (branchData )
88
+ if limit > 0 {
89
+ maxPos = min (skip + limit , maxPos )
90
+ }
91
+ for i := skip ; i < maxPos ; i ++ {
92
+ branchNames = append (branchNames , branchData [i ].name )
93
+ }
79
94
80
- return branchNames , count , nil
95
+ return branchNames , len ( branchData ) , nil
81
96
}
82
97
83
98
// WalkReferences walks all the references from the repository
0 commit comments