-
Notifications
You must be signed in to change notification settings - Fork 377
/
git.go
341 lines (301 loc) · 8.71 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package release
import (
"bytes"
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"k8s.io/klog/v2"
)
// git is a wrapper to invoke git safely, similar to
// github.com/openshift/library-go/pkg/git but giving access to lower level
// calls. Consider improving pkg/git in the future.
type git struct {
path string
}
type gitInterface interface {
exec(command ...string) (string, error)
}
var noSuchRepo = errors.New("location is not a git repo")
func (g *git) exec(command ...string) (string, error) {
buf := &bytes.Buffer{}
bufErr := &bytes.Buffer{}
cmd := exec.Command("git", command...)
cmd.Dir = g.path
cmd.Stdout = buf
cmd.Stderr = bufErr
klog.V(5).Infof("Executing git: %v\n", cmd.Args)
err := cmd.Run()
if err != nil {
return bufErr.String(), err
}
return buf.String(), nil
}
func (g *git) streamExec(out, errOut io.Writer, command ...string) error {
cmd := exec.Command("git", command...)
cmd.Dir = g.path
cmd.Stdout = out
cmd.Stderr = errOut
return cmd.Run()
}
func (g *git) ChangeContext(path string) (*git, error) {
location := &git{path: path}
if errOut, err := location.exec("rev-parse", "--git-dir"); err != nil {
if strings.Contains(strings.ToLower(errOut), "not a git repository") {
return location, noSuchRepo
}
return location, err
}
return location, nil
}
func (g *git) Clone(repository string, out, errOut io.Writer) error {
cmd := exec.Command("git", "clone", repository, g.path)
cmd.Stdout = out
cmd.Stderr = errOut
return cmd.Run()
}
func (g *git) parent() *git {
return &git{path: filepath.Dir(g.path)}
}
func (g *git) basename() string {
return filepath.Base(g.path)
}
func (g *git) VerifyCommit(repo, commit string) (bool, error) {
_, err := g.exec("rev-parse", commit)
if err == nil {
return true, nil
}
// try to fetch by URL
klog.V(4).Infof("failed to find commit, fetching: %v", err)
if err := ensureFetchedRemoteForRepo(g, repo); err != nil {
return false, err
}
_, err = g.exec("rev-parse", commit)
return err == nil, nil
}
func (g *git) CheckoutCommit(repo, commit string) error {
_, err := g.exec("checkout", commit)
if err == nil {
return nil
}
// try to fetch by URL
klog.V(4).Infof("failed to checkout: %v", err)
if err := ensureFetchedRemoteForRepo(g, repo); err == nil {
if _, err := g.exec("checkout", commit); err == nil {
return nil
}
} else {
klog.V(4).Infof("failed to fetch: %v", err)
}
return fmt.Errorf("could not locate commit %s", commit)
}
var reMatch = regexp.MustCompile(`^([a-zA-Z0-9\-\_]+)@([^:]+):(.+)$`)
func sourceLocationAsURL(location string) (*url.URL, error) {
if matches := reMatch.FindStringSubmatch(location); matches != nil {
return &url.URL{Scheme: "git", User: url.UserPassword(matches[1], ""), Host: matches[2], Path: matches[3]}, nil
}
return url.Parse(location)
}
func sourceLocationAsRelativePath(dir, location string) (string, error) {
u, err := sourceLocationAsURL(location)
if err != nil {
return "", err
}
gitPath := u.Path
if strings.HasSuffix(gitPath, ".git") {
gitPath = strings.TrimSuffix(gitPath, ".git")
}
gitPath = path.Clean(gitPath)
basePath := filepath.Join(dir, u.Host, filepath.FromSlash(gitPath))
return basePath, nil
}
type MergeCommit struct {
CommitDate time.Time
Commit string
ParentCommits []string
PullRequest int
Bugs []int
Subject string
}
func gitOutputToError(err error, out string) error {
out = strings.TrimSpace(out)
if strings.HasPrefix(out, "fatal: ") {
out = strings.TrimPrefix(out, "fatal: ")
}
if len(out) == 0 {
return err
}
return fmt.Errorf(out)
}
var (
rePR = regexp.MustCompile(`^Merge pull request #(\d+) from`)
reBug = regexp.MustCompile(`^[B|b]ug(?:s)?\s([\d\s,]+)(?:-|:)\s*`)
rePrefix = regexp.MustCompile(`^(\[[\w\.\-]+\]\s*)+`)
)
func mergeLogForRepo(g gitInterface, repo string, from, to string) ([]MergeCommit, error) {
if from == to {
return nil, nil
}
args := []string{"log", "--merges", "--topo-order", "-z", "--pretty=format:%H %P%x1E%ct%x1E%s%x1E%b", fmt.Sprintf("%s..%s", from, to)}
out, err := g.exec(args...)
if err != nil {
// retry once if there's a chance we haven't fetched the latest commits
if !strings.Contains(out, "Invalid revision range") {
return nil, gitOutputToError(err, out)
}
if _, err := g.exec("fetch", "--all"); err != nil {
return nil, gitOutputToError(err, out)
}
if _, err := g.exec("cat-file", "-e", from+"^{commit}"); err != nil {
return nil, fmt.Errorf("from commit %s does not exist", from)
}
if _, err := g.exec("cat-file", "-e", to+"^{commit}"); err != nil {
return nil, fmt.Errorf("to commit %s does not exist", to)
}
out, err = g.exec(args...)
if err != nil {
return nil, gitOutputToError(err, out)
}
}
if klog.V(5).Enabled() {
klog.Infof("Got commit info:\n%s", strconv.Quote(out))
}
var commits []MergeCommit
if len(out) == 0 {
return nil, nil
}
for _, entry := range strings.Split(out, "\x00") {
records := strings.Split(entry, "\x1e")
if len(records) != 4 {
return nil, fmt.Errorf("unexpected git log output width %d columns", len(records))
}
unixTS, err := strconv.ParseInt(records[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("unexpected timestamp: %v", err)
}
commitValues := strings.Split(records[0], " ")
mergeCommit := MergeCommit{
CommitDate: time.Unix(unixTS, 0).UTC(),
Commit: commitValues[0],
ParentCommits: commitValues[1:],
}
msg := records[3]
msg = rePrefix.ReplaceAllString(strings.TrimSpace(msg), "")
if m := reBug.FindStringSubmatch(msg); m != nil {
msg = msg[len(m[0]):]
for _, part := range strings.Split(m[1], ",") {
for _, subpart := range strings.Split(part, " ") {
subpart = strings.TrimSpace(subpart)
if len(subpart) == 0 {
continue
}
bug, err := strconv.Atoi(subpart)
if err != nil {
klog.V(5).Infof("unable to parse numbers from %q: %v", part, err)
continue
}
mergeCommit.Bugs = append(mergeCommit.Bugs, bug)
}
}
}
sort.Ints(mergeCommit.Bugs)
msg = strings.TrimSpace(msg)
msg = strings.SplitN(msg, "\n", 2)[0]
mergeMsg := records[2]
if m := rePR.FindStringSubmatch(mergeMsg); m != nil {
mergeCommit.PullRequest, err = strconv.Atoi(m[1])
if err != nil {
return nil, fmt.Errorf("could not extract PR number from %q: %v", mergeMsg, err)
}
} else {
klog.V(2).Infof("Omitted commit %s which has no pull-request", mergeCommit.Commit)
continue
}
if len(msg) == 0 {
msg = "Merge"
}
mergeCommit.Subject = msg
commits = append(commits, mergeCommit)
}
return commits, nil
}
// ensureCloneForRepo ensures that the repo exists on disk, is cloned, and has remotes for
// both repo and alternateRepos defined. The remotes for alternateRepos will be file system
// relative to avoid cloning repos twice.
func ensureCloneForRepo(dir string, repo string, alternateRepos []string, out, errOut io.Writer) (*git, error) {
basePath, err := sourceLocationAsRelativePath(dir, repo)
if err != nil {
return nil, err
}
klog.V(4).Infof("Ensure repo is cloned at %s pointing to %s", basePath, repo)
fi, err := os.Stat(basePath)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if err := os.MkdirAll(basePath, 0777); err != nil {
return nil, err
}
} else {
if !fi.IsDir() {
return nil, fmt.Errorf("repo path %s is not a directory", basePath)
}
}
cloner := &git{}
extractedRepo, err := cloner.ChangeContext(basePath)
if err != nil {
if err != noSuchRepo {
return nil, err
}
klog.V(2).Infof("Cloning %s ...", repo)
if err := extractedRepo.Clone(repo, out, errOut); err != nil {
return nil, err
}
} else {
if err := ensureRemoteForRepo(extractedRepo, repo); err != nil {
return nil, err
}
}
for _, altRepo := range alternateRepos {
if altRepo == repo {
continue
}
if err := ensureRemoteForRepo(extractedRepo, altRepo); err != nil {
return nil, err
}
}
return extractedRepo, nil
}
func remoteNameForRepo(repo string) string {
sum := md5.Sum([]byte(repo))
repoName := fmt.Sprintf("up-%s", base64.RawURLEncoding.EncodeToString(sum[:])[:10])
return repoName
}
func ensureRemoteForRepo(g *git, repo string) error {
repoName := remoteNameForRepo(repo)
if out, err := g.exec("remote", "add", repoName, repo); err != nil && !strings.Contains(out, "already exists") {
return gitOutputToError(err, out)
}
return nil
}
func ensureFetchedRemoteForRepo(g *git, repo string) error {
repoName := remoteNameForRepo(repo)
if out, err := g.exec("remote", "add", repoName, repo); err != nil && !strings.Contains(out, "already exists") {
return gitOutputToError(err, out)
}
if out, err := g.exec("fetch", repoName); err != nil {
return gitOutputToError(err, out)
}
return nil
}