forked from pivotal-cf/cred-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
looper.go
101 lines (78 loc) · 1.54 KB
/
looper.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
package gitclient
import (
"path/filepath"
"gopkg.in/libgit2/git2go.v24"
)
type looper struct {
}
//go:generate counterfeiter . Looper
type Looper interface {
ScanCurrentState(repositoryPath string, callback ScanCallback) error
}
type ScanCallback func(sha string, path string, content []byte)
func NewLooper() *looper {
return &looper{}
}
func (l *looper) ScanCurrentState(repositoryPath string, callback ScanCallback) error {
repo, err := git.OpenRepository(repositoryPath)
if err != nil {
return err
}
defer repo.Free()
it, err := repo.NewBranchIterator(git.BranchRemote)
if err != nil {
return err
}
defer it.Free()
var branch *git.Branch
var target *git.Oid
var commit *git.Commit
var tree *git.Tree
var blob *git.Blob
for {
branch, _, err = it.Next()
if err != nil {
break
}
target = branch.Target()
if target == nil {
continue
}
commit, err = repo.LookupCommit(target)
if err != nil {
return err
}
commitStr := commit.Id().String()
tree, err = commit.Tree()
if err != nil {
return err
}
err = tree.Walk(func(root string, entry *git.TreeEntry) int {
if entry.Type == git.ObjectBlob {
blob, err = repo.LookupBlob(entry.Id)
if err != nil {
return -1
}
path := filepath.Join(root, entry.Name)
callback(commitStr, path, blob.Contents())
}
return 0
})
if err != nil {
return err
}
}
if blob != nil {
blob.Free()
}
if tree != nil {
tree.Free()
}
if commit != nil {
commit.Free()
}
if branch != nil {
branch.Free()
}
return nil
}