-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgit.go
261 lines (210 loc) · 8.16 KB
/
git.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
package main
import (
"fmt"
"time"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/attribute"
)
// GitScm represents the metadata used to build a Git SCM repository
type GitScm struct {
baseRef string
branchName string
headSha string
changeRequest bool // if the tool is evaluating a change request or a branch
provider string
repository *git.Repository
repositoryPath string
}
// NewGitScm retrieves a Git SCM repository, using the repository filesystem path to read it
func NewGitScm(repositoryPath string) *GitScm {
scm := &GitScm{
repositoryPath: repositoryPath,
}
repository, err := scm.openLocalRepository()
if err != nil {
return nil
}
scm.repository = repository
gitCtx := checkGitContext()
if gitCtx == nil {
return nil
}
scm.headSha = gitCtx.Commit
scm.branchName = gitCtx.Branch
scm.baseRef = gitCtx.GetTargetBranch()
scm.changeRequest = gitCtx.ChangeRequest
scm.provider = gitCtx.Provider
return scm
}
// calculateCommits this method calculates the commits between current branch (HEAD) and a target branch.
// - The target branch has to be set as the TARGET_BRANCH environment variable
// - HEAD branch must be a valid branch in the git repository
func (scm *GitScm) calculateCommits() (*object.Commit, *object.Commit, error) {
targetBranch, err := scm.repository.Branch(scm.baseRef)
if err != nil {
return nil, nil, errors.Wrapf(err, "not able to retrieve the %s TARGET_BRANCH: %v", scm.baseRef, err)
}
targetRef, err := scm.repository.ResolveRevision(plumbing.Revision(targetBranch.Merge))
if err != nil {
return nil, nil, errors.Wrapf(err, "not able to retrieve ref from TARGET_BRANCH: %v", err)
}
targetCommit, err := scm.repository.CommitObject(*targetRef)
if err != nil {
return nil, nil, errors.Wrapf(err, "not able to retrieve commit from TARGET_BRANCH: %v", err)
}
var headRefSha plumbing.Hash
if scm.headSha == "" {
headRef, err := scm.repository.Head()
if err != nil {
return nil, nil, errors.Wrapf(err, "not able to retrieve ref from HEAD: %v", err)
}
headRefSha = headRef.Hash()
} else {
headRefSha = plumbing.NewHash(scm.headSha)
}
headCommit, err := scm.repository.CommitObject(headRefSha)
if err != nil {
return nil, nil, errors.Wrapf(err, "not able to retrieve commit from HEAD: %v", err)
}
return headCommit, targetCommit, nil
}
// contributeAttributes this method never fails, returning the current state of the contributed attributes
// at the moment of the failure
func (scm *GitScm) contributeAttributes() []attribute.KeyValue {
// from now on, this is a Git repository
gitAttributes := []attribute.KeyValue{
attribute.Key(ScmType).String("git"),
}
if scm.provider != "" {
gitAttributes = append(gitAttributes, attribute.Key(ScmProvider).String(scm.provider))
}
shallow, err := scm.repository.Storer.Shallow()
if err != nil {
return gitAttributes
}
if shallow == nil {
gitAttributes = append(gitAttributes, attribute.Key(GitCloneShallow).Bool(false))
gitAttributes = append(gitAttributes, attribute.Key(GitCloneDepth).Int(0))
} else {
gitAttributes = append(gitAttributes, attribute.Key(GitCloneShallow).Bool(len(shallow) != 0))
gitAttributes = append(gitAttributes, attribute.Key(GitCloneDepth).Int(len(shallow)))
}
origin, err := scm.repository.Remote("origin")
if err != nil {
return gitAttributes
}
gitAttributes = append(gitAttributes, attribute.Key(ScmRepository).StringSlice(origin.Config().URLs))
// do not read HEAD, and simply use the branch name coming from the SCM struct
gitAttributes = append(gitAttributes, attribute.Key(ScmBranch).String(scm.branchName))
headCommit, targetCommit, err := scm.calculateCommits()
if err != nil {
return gitAttributes
}
contributions := []func(*object.Commit, *object.Commit) ([]attribute.KeyValue, error){
scm.contributeCommitters,
}
if scm.changeRequest {
if scm.baseRef != "" {
gitAttributes = append(gitAttributes, attribute.Key(ScmBaseRef).String(scm.baseRef))
}
// calculate modified lines for pull/merge requests
contributions = append(contributions, scm.contributeFilesAndLines)
}
for _, contribution := range contributions {
contributtedAttributes, err := contribution(headCommit, targetCommit)
if err != nil {
fmt.Printf(">> not contributing attributes: %v", err)
continue
}
gitAttributes = append(gitAttributes, contributtedAttributes...)
}
return gitAttributes
}
// contributeCommitters this algorithm will look for the first ancestor between HEAD and the TARGET_BRANCH, and will iterate through
// the list of commits, storing the author and the committer for each commit, contributing an array of Strings
// attribute including the email of the author/commiter.
// This method will return the current state of the contributed attributes at the moment of an eventual failure.
func (scm *GitScm) contributeCommitters(headCommit *object.Commit, targetCommit *object.Commit) (attributes []attribute.KeyValue, outError error) {
attributes = []attribute.KeyValue{}
commits, err := headCommit.MergeBase(targetCommit)
if err != nil {
outError = errors.Wrapf(err, "not able to find a common ancestor between HEAD and TARGET_BRANCH: %v", err)
return
}
if len(commits) == 0 {
outError = errors.Wrapf(err, "not able to find a common ancestor between HEAD and TARGET_BRANCH: %v", err)
return
}
ancestor := commits[0]
when := ancestor.Author.When.Add(time.Millisecond * 1) // adding one millisecond to avoid including the ancestor in the log
commitsIterator, err := scm.repository.Log(&git.LogOptions{From: headCommit.Hash, Since: &when})
if err != nil {
outError = errors.Wrapf(err, "not able to retrieve commits between HEAD and TARGET_BRANCH: %v", err)
return
}
authors := map[string]bool{}
committers := map[string]bool{}
commitsIterator.ForEach(func(c *object.Commit) error {
authors[c.Author.Email] = true
committers[c.Committer.Email] = true
return nil
})
if len(authors) > 0 {
attributes = append(attributes, attribute.Key(ScmAuthors).StringSlice(mapToArray(authors)))
}
if len(committers) > 0 {
attributes = append(attributes, attribute.Key(ScmCommitters).StringSlice(mapToArray(committers)))
}
return
}
// contributeFilesAndLines this algorithm will look for the first ancestor between HEAD and the TARGET_BRANCH, and will iterate through
// the list of commits, storing the modified files for each commit; for each modified file it will get the added and deleted lines.
// It will contribute an Integer attribute including number of modified files, including added and deleted lines in the changeset.
// This method will return the current state of the contributed attributes at the moment of an eventual failure.
func (scm *GitScm) contributeFilesAndLines(headCommit *object.Commit, targetCommit *object.Commit) (attributes []attribute.KeyValue, outError error) {
attributes = []attribute.KeyValue{}
headTree, err := headCommit.Tree()
if err != nil {
outError = errors.Wrapf(err, "not able to find a HEAD tree: %v", err)
return
}
targetTree, err := targetCommit.Tree()
if err != nil {
outError = errors.Wrapf(err, "not able to find a TARGET_BRANCH tree: %v", err)
return
}
patch, err := targetTree.Patch(headTree)
if err != nil {
outError = errors.Wrapf(err, "not able to find the pathc between HEAD and TARGET_BRANCH trees: %v", err)
return
}
var changedFiles []string
var additions int = 0
var deletions int = 0
for _, fileStat := range patch.Stats() {
additions += fileStat.Addition
deletions += fileStat.Deletion
changedFiles = append(changedFiles, fileStat.Name)
}
attributes = append(attributes, attribute.Key(GitAdditions).Int(additions))
attributes = append(attributes, attribute.Key(GitDeletions).Int(deletions))
attributes = append(attributes, attribute.Key(GitModifiedFiles).Int(len(changedFiles)))
return
}
func mapToArray(m map[string]bool) []string {
array := []string{}
for k := range m {
array = append(array, k)
}
return array
}
func (scm *GitScm) openLocalRepository() (*git.Repository, error) {
repository, err := git.PlainOpen(scm.repositoryPath)
if err != nil {
return nil, err
}
return repository, nil
}