-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathgit.go
323 lines (297 loc) · 7.7 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
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
package utils
import (
"bufio"
"bytes"
"errors"
ioutils "github.com/jfrog/gofrog/io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
"github.com/jfrog/jfrog-client-go/utils/log"
)
type GitManager struct {
path string
err error
revision string
url string
branch string
message string
submoduleDotGitPath string
}
func NewGitManager(path string) *GitManager {
dotGitPath := filepath.Join(path, ".git")
return &GitManager{path: dotGitPath}
}
func (m *GitManager) ExecGit(args ...string) (string, string, error) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command("git", args...)
cmd.Stdin = nil
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), errorutils.CheckError(err)
}
func (m *GitManager) ReadConfig() error {
if m.path == "" {
return errorutils.CheckErrorf(".git path must be defined")
}
if !fileutils.IsPathExists(m.path, false) {
return errorutils.CheckErrorf(".git path must exist in order to collect vcs details")
}
m.handleSubmoduleIfNeeded()
m.readRevisionAndBranch()
m.readUrl()
if m.revision != "" {
m.readMessage()
}
return m.err
}
// If .git is a file and not a directory, assume it is a git submodule and extract the actual .git directory of the submodule.
// The actual .git directory is under the parent project's .git/modules directory.
func (m *GitManager) handleSubmoduleIfNeeded() {
exists, err := fileutils.IsFileExists(m.path, false)
if err != nil {
m.err = err
return
}
if !exists {
// .git is a directory, continue extracting vcs details.
return
}
// ask git for where the .git directory is directly for submodules and worktrees
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command("git", "rev-parse", "--git-common-dir")
cmd.Dir = filepath.Dir(m.path)
cmd.Stdin = nil
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if m.err = errors.Join(m.err, err); m.err != nil {
return
}
resolvedGitPath := strings.TrimSpace(stdout.String())
exists, err = fileutils.IsDirExists(resolvedGitPath, false)
if m.err = errors.Join(m.err, err); m.err != nil {
return
}
if !exists {
m.err = errorutils.CheckErrorf("path found in .git file '" + m.path + "' does not exist: '" + resolvedGitPath + "'")
return
}
m.path = resolvedGitPath
}
func (m *GitManager) GetUrl() string {
return m.url
}
func (m *GitManager) GetRevision() string {
return m.revision
}
func (m *GitManager) GetBranch() string {
return m.branch
}
func (m *GitManager) GetMessage() string {
return m.message
}
func (m *GitManager) readUrl() {
if m.err != nil {
return
}
dotGitPath := filepath.Join(m.path, "config")
file, err := os.Open(dotGitPath)
if err != nil {
m.err = err
return
}
defer func() {
if file != nil {
m.err = errors.Join(m.err, errorutils.CheckError(file.Close()))
}
}()
scanner := bufio.NewScanner(file)
var IsNextLineUrl bool
var originUrl string
for scanner.Scan() {
if IsNextLineUrl {
text := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(text, "url") {
originUrl = strings.TrimSpace(strings.SplitAfter(text, "=")[1])
break
}
}
if scanner.Text() == "[remote \"origin\"]" {
IsNextLineUrl = true
}
}
if err := scanner.Err(); err != nil {
m.err = errorutils.CheckError(err)
return
}
if !strings.HasSuffix(originUrl, ".git") {
originUrl += ".git"
}
m.url = originUrl
// Mask url if required
matchedResult := regexp.MustCompile(CredentialsInUrlRegexp).FindString(originUrl)
if matchedResult == "" {
return
}
m.url = RemoveCredentials(originUrl, matchedResult)
}
func (m *GitManager) getRevisionAndBranchPath() (revision, refUrl string, err error) {
dotGitPath := filepath.Join(m.path, "HEAD")
file, err := os.Open(dotGitPath)
if errorutils.CheckError(err) != nil {
return
}
defer ioutils.Close(file, &err)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if strings.HasPrefix(text, "ref") {
refUrl = strings.TrimSpace(strings.SplitAfter(text, ":")[1])
break
}
revision = text
}
err = errorutils.CheckError(scanner.Err())
return
}
func (m *GitManager) readRevisionAndBranch() {
if m.err != nil {
return
}
// This function will either return the revision or the branch ref:
revision, ref, err := m.getRevisionAndBranchPath()
if err != nil {
m.err = err
return
}
if ref != "" {
// Get branch short name (refs/heads/master > master)
m.branch = plumbing.ReferenceName(ref).Short()
}
// If the revision was returned, then we're done:
if revision != "" {
m.revision = revision
return
}
// Else, if found ref try getting revision using it.
refPath := filepath.Join(m.path, ref)
exists, err := fileutils.IsFileExists(refPath, false)
if err != nil {
m.err = err
return
}
if exists {
m.readRevisionFromRef(refPath)
return
}
// Otherwise, try to find .git/packed-refs and look for the HEAD there
m.readRevisionFromPackedRef(ref)
}
func (m *GitManager) readRevisionFromRef(refPath string) {
revision := ""
file, err := os.Open(refPath)
if err != nil {
m.err = err
return
}
defer func() {
if file != nil {
m.err = errors.Join(m.err, errorutils.CheckError(file.Close()))
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
revision = strings.TrimSpace(text)
break
}
if err := scanner.Err(); err != nil {
m.err = errorutils.CheckError(err)
return
}
m.revision = revision
}
func (m *GitManager) readRevisionFromPackedRef(ref string) {
packedRefPath := filepath.Join(m.path, "packed-refs")
exists, err := fileutils.IsFileExists(packedRefPath, false)
if err != nil {
m.err = err
return
}
if exists {
file, err := os.Open(packedRefPath)
if err != nil {
m.err = err
return
}
defer func() {
if file != nil {
m.err = errors.Join(m.err, errorutils.CheckError(file.Close()))
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Expecting to find the revision (the full extended SHA-1, or a unique leading substring) followed by the ref.
if strings.HasSuffix(line, ref) {
split := strings.Split(line, " ")
if len(split) == 2 {
m.revision = split[0]
} else {
m.err = errors.Join(err, errorutils.CheckErrorf("failed fetching revision for ref :"+ref+" - Unexpected line structure in packed-refs file"))
}
return
}
}
if err = scanner.Err(); err != nil {
m.err = errorutils.CheckError(err)
return
}
}
log.Debug("No packed-refs file was found. Assuming git repository is empty")
}
func (m *GitManager) readMessage() {
if m.err != nil {
return
}
var err error
m.message, err = m.doReadMessage()
if err != nil {
log.Debug("Latest commit message was not extracted due to", err.Error())
}
}
func (m *GitManager) doReadMessage() (string, error) {
path := m.getPathHandleSubmodule()
gitRepo, err := git.PlainOpenWithOptions(path, &git.PlainOpenOptions{DetectDotGit: false})
if errorutils.CheckError(err) != nil {
return "", err
}
hash, err := gitRepo.ResolveRevision(plumbing.Revision(m.revision))
if errorutils.CheckError(err) != nil {
return "", err
}
message, err := gitRepo.CommitObject(*hash)
if errorutils.CheckError(err) != nil {
return "", err
}
return strings.TrimSpace(message.Message), nil
}
func (m *GitManager) getPathHandleSubmodule() (path string) {
if m.submoduleDotGitPath == "" {
path = m.path
} else {
path = m.submoduleDotGitPath
}
path = strings.TrimSuffix(path, filepath.Join("", ".git"))
return
}