Add BranchIterator#ForEach.
This abstracts the branch iteration from the user.
This commit is contained in:
parent
94b1f7d07d
commit
755721e684
19
branch.go
19
branch.go
|
@ -30,10 +30,7 @@ type BranchIterator struct {
|
|||
repo *Repository
|
||||
}
|
||||
|
||||
type BranchInfo struct {
|
||||
Branch *Branch
|
||||
Type BranchType
|
||||
}
|
||||
type BranchIteratorFunc func(*Branch, BranchType) error
|
||||
|
||||
func newBranchIteratorFromC(repo *Repository, ptr *C.git_branch_iterator) *BranchIterator {
|
||||
i := &BranchIterator{repo: repo, ptr: ptr}
|
||||
|
@ -65,8 +62,20 @@ func (i *BranchIterator) Free() {
|
|||
C.git_branch_iterator_free(i.ptr)
|
||||
}
|
||||
|
||||
func (repo *Repository) NewBranchIterator(flags BranchType) (*BranchIterator, error) {
|
||||
func (i *BranchIterator) ForEach(f BranchIteratorFunc) error {
|
||||
b, t, err := i.Next()
|
||||
|
||||
for err == nil {
|
||||
err = f(b, t)
|
||||
if err == nil {
|
||||
b, t, err = i.Next()
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (repo *Repository) NewBranchIterator(flags BranchType) (*BranchIterator, error) {
|
||||
refType := C.git_branch_t(flags)
|
||||
var ptr *C.git_branch_iterator
|
||||
|
||||
|
|
|
@ -1,11 +1,8 @@
|
|||
package git
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
import "testing"
|
||||
|
||||
func TestBranchIterator(t *testing.T) {
|
||||
|
||||
repo := createTestRepo(t)
|
||||
seedTestRepo(t, repo)
|
||||
|
||||
|
@ -24,3 +21,35 @@ func TestBranchIterator(t *testing.T) {
|
|||
t.Fatal("expected iterover")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchIteratorEach(t *testing.T) {
|
||||
repo := createTestRepo(t)
|
||||
seedTestRepo(t, repo)
|
||||
|
||||
i, err := repo.NewBranchIterator(BranchLocal)
|
||||
checkFatal(t, err)
|
||||
|
||||
var names []string
|
||||
f := func(b *Branch, t BranchType) error {
|
||||
name, err := b.Name()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
names = append(names, name)
|
||||
return nil
|
||||
}
|
||||
|
||||
err = i.ForEach(f)
|
||||
if err != nil && !IsErrorCode(err, ErrIterOver) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(names) != 1 {
|
||||
t.Fatalf("expect 1 branch, but it was %d\n", len(names))
|
||||
}
|
||||
|
||||
if names[0] != "master" {
|
||||
t.Fatalf("expect branch master, but it was %s\n", names[0])
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue