-
Notifications
You must be signed in to change notification settings - Fork 7
/
git.go
607 lines (558 loc) · 18.3 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package git
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"runtime"
"strings"
"sync"
"github.com/lunarway/release-manager/internal/copy"
"github.com/lunarway/release-manager/internal/log"
"github.com/lunarway/release-manager/internal/tracing"
"github.com/pkg/errors"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/format/config"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
var (
ErrNothingToCommit = errors.New("nothing to commit")
ErrReleaseNotFound = errors.New("release not found")
ErrArtifactNotFound = errors.New("artifact not found")
ErrBranchBehindOrigin = errors.New("branch behind origin")
ErrUnknownGit = errors.New("unknown git error")
)
type Service struct {
Tracer tracing.Tracer
SSHPrivateKeyPath string
ConfigRepoURL string
masterMutex sync.RWMutex
masterPath string
master *git.Repository
}
// InitMasterRepo clones the configuration repository into a master directory.
func (s *Service) InitMasterRepo(ctx context.Context) (func(context.Context), error) {
span, ctx := s.Tracer.FromCtx(ctx, "git.InitMasterRepo")
defer span.Finish()
path, close, err := TempDir(ctx, s.Tracer, "k8s-master-clone")
if err != nil {
close(ctx)
return nil, errors.WithMessage(err, "get temporary directory")
}
repo, err := s.clone(ctx, path)
if err != nil {
close(ctx)
return nil, errors.WithMessagef(err, "clone into '%s'", path)
}
s.masterMutex.Lock()
defer s.masterMutex.Unlock()
s.master = repo
s.masterPath = path
log.Infof("Master repo cloned into '%s'", path)
return close, nil
}
func (s *Service) clone(ctx context.Context, destination string) (*git.Repository, error) {
span, ctx := s.Tracer.FromCtx(ctx, "git.clone")
defer span.Finish()
authSSH, err := ssh.NewPublicKeysFromFile("git", s.SSHPrivateKeyPath, "")
if err != nil {
return nil, errors.WithMessage(err, "public keys from file")
}
span, _ = s.Tracer.FromCtx(ctx, "remove destination")
span.SetTag("path", destination)
err = os.RemoveAll(destination)
span.Finish()
if err != nil {
return nil, errors.WithMessage(err, "remove existing destination")
}
span, _ = s.Tracer.FromCtx(ctx, "plain clone")
r, err := git.PlainCloneContext(ctx, destination, false, &git.CloneOptions{
URL: s.ConfigRepoURL,
Auth: authSSH,
})
span.Finish()
if err != nil {
return nil, errors.WithMessage(err, "clone repo")
}
return r, nil
}
// SyncMaster pulls latest changes from master repo.
func (s *Service) SyncMaster(ctx context.Context) error {
span, ctx := s.Tracer.FromCtx(ctx, "git.SyncMaster")
defer span.Finish()
span, _ = s.Tracer.FromCtx(ctx, "lock mutex")
s.masterMutex.Lock()
defer s.masterMutex.Unlock()
span.Finish()
span, _ = s.Tracer.FromCtx(ctx, "fetch")
err := execCommand(ctx, s.masterPath, "git", "fetch", "origin", "master")
span.Finish()
if err != nil {
return errors.WithMessage(err, "fetch changes")
}
span, _ = s.Tracer.FromCtx(ctx, "pull")
err = execCommand(ctx, s.masterPath, "git", "pull")
span.Finish()
if err != nil {
return errors.WithMessage(err, "pull latest")
}
return nil
}
// Clone returns a Git repository copy from the master repository.
func (s *Service) Clone(ctx context.Context, destination string) (*git.Repository, error) {
span, ctx := s.Tracer.FromCtx(ctx, "git.Clone")
defer span.Finish()
return s.copyMaster(ctx, destination)
}
func (s *Service) copyMaster(ctx context.Context, destination string) (*git.Repository, error) {
span, ctx := s.Tracer.FromCtx(ctx, "git.copyMaster")
defer span.Finish()
span, _ = s.Tracer.FromCtx(ctx, "remove destination")
err := os.RemoveAll(destination)
span.Finish()
if err != nil {
return nil, errors.WithMessage(err, "remove existing destination")
}
span, _ = s.Tracer.FromCtx(ctx, "lock mutex")
s.masterMutex.RLock()
defer s.masterMutex.RUnlock()
span.Finish()
span, _ = s.Tracer.FromCtx(ctx, "copy to destination")
err = copy.Copy(s.masterPath, destination)
span.Finish()
if err != nil {
return nil, errors.WithMessagef(err, "copy master from '%s'", s.masterPath)
}
span, _ = s.Tracer.FromCtx(ctx, "open repo")
r, err := git.PlainOpen(destination)
span.Finish()
if err != nil {
return nil, errors.WithMessage(err, "open repo")
}
return r, nil
}
func (s *Service) Checkout(ctx context.Context, rootPath string, hash plumbing.Hash) error {
span, ctx := s.Tracer.FromCtx(ctx, "git.Checkout")
defer span.Finish()
err := execCommand(ctx, rootPath, "git", "checkout", hash.String())
if err != nil {
return errors.WithMessage(err, "checkout hash")
}
return nil
}
// LocateRelease traverses the git log to find a release commit with id
// artifactID.
//
// It expects the commit to have a commit messages as the one returned by
// ReleaseCommitMessage.
func (s *Service) LocateRelease(ctx context.Context, r *git.Repository, artifactID string) (plumbing.Hash, error) {
span, _ := s.Tracer.FromCtx(ctx, "git.LocateRelease")
defer span.Finish()
return locate(r, locateReleaseCondition(artifactID), ErrReleaseNotFound)
}
func locateReleaseCondition(artifactID string) conditionFunc {
r := regexp.MustCompile(fmt.Sprintf(`(?i)release %s($|\r\n|\r|\n)`, regexp.QuoteMeta(artifactID)))
return func(commitMsg string) bool {
if artifactID == "" {
return false
}
return r.MatchString(commitMsg)
}
}
// LocateServiceRelease traverses the git log to find a release
// commit for a specified service and environment.
//
// It expects the commit to have a commit messages as the one returned by
// ReleaseCommitMessage.
func (s *Service) LocateServiceRelease(ctx context.Context, r *git.Repository, env, service string) (plumbing.Hash, error) {
span, _ := s.Tracer.FromCtx(ctx, "git.LocateServiceRelease")
defer span.Finish()
return locate(r, locateServiceReleaseCondition(env, service), ErrReleaseNotFound)
}
func locateServiceReleaseCondition(env, service string) conditionFunc {
r := regexp.MustCompile(fmt.Sprintf(`(?i)\[%s/%s] release`, regexp.QuoteMeta(env), regexp.QuoteMeta(service)))
return func(commitMsg string) bool {
if env == "" {
return false
}
if service == "" {
return false
}
return r.MatchString(commitMsg)
}
}
// LocateEnvRelease traverses the git log to find a release
// commit for a specified environment and artifactID.
//
// It expects the commit to have a commit messages as the one returned by
// ReleaseCommitMessage.
func (s *Service) LocateEnvRelease(ctx context.Context, r *git.Repository, env, artifactID string) (plumbing.Hash, error) {
artifactID = strings.TrimSpace(artifactID)
span, _ := s.Tracer.FromCtx(ctx, "git.LocateEnvRelease")
defer span.Finish()
return locate(r, locateEnvReleaseCondition(env, artifactID), ErrReleaseNotFound)
}
func locateEnvReleaseCondition(env, artifactId string) conditionFunc {
r := regexp.MustCompile(fmt.Sprintf(`(?i)\[%s/.*] release %s($|\r\n|\r|\n)`, regexp.QuoteMeta(env), regexp.QuoteMeta(artifactId)))
return func(commitMsg string) bool {
if env == "" {
return false
}
if artifactId == "" {
return false
}
return r.MatchString(commitMsg)
}
}
// LocateServiceReleaseRollbackSkip traverses the git log to find a release or
// rollback commit for a specified service and environment.
//
// It expects the commit to have a commit messages as the one returned by
// ReleaseCommitMessage or RollbackCommitMessage.
func (s *Service) LocateServiceReleaseRollbackSkip(ctx context.Context, r *git.Repository, env, service string, n uint) (plumbing.Hash, error) {
span, _ := s.Tracer.FromCtx(ctx, "git.LocateServiceReleaseRollbackSkip")
defer span.Finish()
return locate(r, locateServiceReleaseRollbackSkipCondition(env, service, n), ErrReleaseNotFound)
}
func locateServiceReleaseRollbackSkipCondition(env, service string, n uint) conditionFunc {
return func(commitMsg string) bool {
releaseOK := locateServiceReleaseCondition(env, service)(commitMsg)
rollbackOK := locateServiceRollbackCondition(env, service)(commitMsg)
ok := releaseOK || rollbackOK
if !ok {
return false
}
if n == 0 {
return true
}
n--
return false
}
}
func locateServiceRollbackCondition(env, service string) conditionFunc {
r := regexp.MustCompile(fmt.Sprintf(`(?i)\[%s/%s] rollback `, regexp.QuoteMeta(env), regexp.QuoteMeta(service)))
return func(commitMsg string) bool {
if env == "" {
return false
}
if service == "" {
return false
}
return r.MatchString(commitMsg)
}
}
// LocateArtifact traverses the git log to find an artifact commit with id
// artifactID.
//
// It expects the commit to have a commit messages as the one returned by
// ArtifactCommitMessage.
func (s *Service) LocateArtifact(ctx context.Context, r *git.Repository, artifactID string) (plumbing.Hash, error) {
span, _ := s.Tracer.FromCtx(ctx, "git.LocateArtifact")
defer span.Finish()
return locate(r, locateArtifactCondition(artifactID), ErrArtifactNotFound)
}
func locateArtifactCondition(artifactID string) conditionFunc {
artifactRegex := regexp.MustCompile(fmt.Sprintf(`(?i)artifact %s `, regexp.QuoteMeta(artifactID)))
return func(commitMsg string) bool {
if artifactID == "" {
return false
}
return artifactRegex.MatchString(commitMsg)
}
}
// LocateArtifacts traverses the git log to find artifact commits for a service.
//
// It expects the commit to have a commit messages as the one returned by
// ArtifactCommitMessage.
func (s *Service) LocateArtifacts(ctx context.Context, r *git.Repository, service string, n int) ([]plumbing.Hash, error) {
span, _ := s.Tracer.FromCtx(ctx, "git.LocateArtifacts")
defer span.Finish()
return locateN(r, locateArtifactServiceCondition(service), ErrArtifactNotFound, n)
}
func locateArtifactServiceCondition(service string) conditionFunc {
artifactRegex := regexp.MustCompile(fmt.Sprintf(`(?i)\[%s] artifact `, regexp.QuoteMeta(service)))
return func(commitMsg string) bool {
if service == "" {
return false
}
return artifactRegex.MatchString(commitMsg)
}
}
type conditionFunc func(commitMsg string) bool
func locate(r *git.Repository, condition conditionFunc, notFoundErr error) (plumbing.Hash, error) {
hashes, err := locateN(r, condition, notFoundErr, 1)
if err != nil {
return plumbing.ZeroHash, err
}
// locateN will return an error when reaching the end of the git log.
// So if there is no error we must have found at least one match.
return hashes[0], nil
}
func locateN(r *git.Repository, condition conditionFunc, notFoundErr error, n int) ([]plumbing.Hash, error) {
var hashes []plumbing.Hash
ref, err := r.Head()
if err != nil {
return nil, errors.WithMessage(err, "retrieve HEAD branch")
}
cIter, err := r.Log(&git.LogOptions{
From: ref.Hash(),
})
if err != nil {
return nil, errors.WithMessage(err, "retrieve commit history")
}
for {
commit, err := cIter.Next()
if err != nil {
if err == io.EOF {
return hashes, notFoundErr
}
return nil, errors.WithMessage(err, "retrieve commit")
}
if condition(commit.Message) {
hashes = append(hashes, commit.Hash)
}
if len(hashes) >= n {
return hashes, nil
}
}
}
func (s *Service) Commit(ctx context.Context, rootPath, changesPath, authorName, authorEmail, committerName, committerEmail, msg string) error {
span, ctx := s.Tracer.FromCtx(ctx, "git.Commit")
defer span.Finish()
span, _ = s.Tracer.FromCtx(ctx, "add changes")
err := execCommand(ctx, rootPath, "git", "add", ".")
span.Finish()
if err != nil {
return errors.WithMessage(err, "add changes")
}
span, _ = s.Tracer.FromCtx(ctx, "check for changes")
err = checkStatus(ctx, rootPath)
span.Finish()
if err != nil {
return errors.WithMessage(err, "check for changes")
}
span, _ = s.Tracer.FromCtx(ctx, "commit")
err = execCommand(ctx, rootPath,
"git",
"-c", fmt.Sprintf(`user.name="%s"`, committerName),
"-c", fmt.Sprintf(`user.email="%s"`, committerEmail),
"commit",
fmt.Sprintf(`--author="%s <%s>"`, authorName, authorEmail),
fmt.Sprintf(`-m%s`, msg),
)
span.Finish()
if err != nil {
return errors.WithMessage(err, "commit")
}
span, _ = s.Tracer.FromCtx(ctx, "push")
defer span.Finish()
return gitPush(ctx, rootPath)
}
func execCommand(ctx context.Context, rootPath string, cmdName string, args ...string) error {
log.WithFields("root", rootPath).Infof("git/execCommand: running: %s %s", cmdName, strings.Join(args, " "))
cmd := exec.CommandContext(ctx, cmdName, args...)
cmd.Dir = rootPath
stdout, err := cmd.StdoutPipe()
if err != nil {
return errors.WithMessage(err, "get stdout pipe for command")
}
stderr, err := cmd.StderrPipe()
if err != nil {
return errors.WithMessage(err, "get stderr pipe for command")
}
err = cmd.Start()
if err != nil {
return errors.WithMessage(err, "start command")
}
stdoutData, err := ioutil.ReadAll(stdout)
if err != nil {
return errors.WithMessage(err, "read stdout data of command")
}
stderrData, err := ioutil.ReadAll(stderr)
if err != nil {
return errors.WithMessage(err, "read stderr data of command")
}
err = cmd.Wait()
log.Infof("git/commit: exec command '%s %s': stdout: %s", cmdName, strings.Join(args, " "), stdoutData)
log.Infof("git/commit: exec command '%s %s': stderr: %s", cmdName, strings.Join(args, " "), stderrData)
if err != nil {
return errors.WithMessage(err, "execute command failed")
}
err = isKnownGitError(stderrData)
if err != nil {
return err
}
return nil
}
// knownGitErrors contains error messages that should be considered as errors by
// release-manager and because of this return an error.
var knownGitErrors = []string{
"fatal: Could not read from remote repository.",
"Connection closed by remote host",
"ssh: Could not resolve hostname github.com",
}
// isKnownGitError returns an error if stderr is identified as a known Git
// error.
func isKnownGitError(stderrData []byte) error {
if len(stderrData) == 0 {
return nil
}
for _, e := range knownGitErrors {
if bytes.Contains(stderrData, []byte(e)) {
return ErrUnknownGit
}
}
return nil
}
func checkStatus(ctx context.Context, rootPath string) error {
cmdName := "git"
args := []string{"status", "--porcelain"}
log.WithFields("root", rootPath).Infof("git/execCommand: running: %s %s", cmdName, strings.Join(args, " "))
cmd := exec.CommandContext(ctx, cmdName, args...)
cmd.Dir = rootPath
stdout, err := cmd.StdoutPipe()
if err != nil {
return errors.WithMessage(err, "get stdout pipe for command")
}
stderr, err := cmd.StderrPipe()
if err != nil {
return errors.WithMessage(err, "get stderr pipe for command")
}
err = cmd.Start()
if err != nil {
return errors.WithMessage(err, "start command")
}
stdoutData, err := ioutil.ReadAll(stdout)
if err != nil {
return errors.WithMessage(err, "read stdout data of command")
}
stderrData, err := ioutil.ReadAll(stderr)
if err != nil {
return errors.WithMessage(err, "read stderr data of command")
}
err = cmd.Wait()
log.Infof("git/commit: exec command '%s %s': stdout: %s", cmdName, strings.Join(args, " "), stdoutData)
log.Infof("git/commit: exec command '%s %s': stderr: %s", cmdName, strings.Join(args, " "), stderrData)
if err != nil {
return errors.WithMessage(err, "execute command failed")
}
if len(stdoutData) == 0 {
return ErrNothingToCommit
}
return nil
}
func gitPush(ctx context.Context, rootPath string) error {
cmdName := "git"
args := []string{"push", "origin", "master", "--porcelain"}
log.WithFields("root", rootPath).Infof("git/execCommand: running: %s %s", cmdName, strings.Join(args, " "))
cmd := exec.CommandContext(ctx, cmdName, args...)
cmd.Dir = rootPath
stdout, err := cmd.StdoutPipe()
if err != nil {
return errors.WithMessage(err, "get stdout pipe for command")
}
stderr, err := cmd.StderrPipe()
if err != nil {
return errors.WithMessage(err, "get stderr pipe for command")
}
err = cmd.Start()
if err != nil {
return errors.WithMessage(err, "start command")
}
stdoutData, err := ioutil.ReadAll(stdout)
if err != nil {
return errors.WithMessage(err, "read stdout data of command")
}
stderrData, err := ioutil.ReadAll(stderr)
if err != nil {
return errors.WithMessage(err, "read stderr data of command")
}
err = cmd.Wait()
log.Infof("git/commit: exec command '%s %s': stdout: %s", cmdName, strings.Join(args, " "), stdoutData)
log.Infof("git/commit: exec command '%s %s': stderr: %s", cmdName, strings.Join(args, " "), stderrData)
if err != nil {
match, regexpErr := regexp.Match("(?i)rejected because the remote contains work that you do", stderrData)
if regexpErr != nil {
log.Errorf("git/gitPush: failed to detect if push error is caused by master being behind: %v", regexpErr)
}
if match {
return ErrBranchBehindOrigin
}
return errors.WithMessage(err, "execute command failed")
}
return nil
}
// userHomeDir returns the home directory of the current user.
//
// It handles windows, linux and darwin operating systems by inspecting
// runtime.GOOS.
func userHomeDir() string {
switch runtime.GOOS {
case "windows":
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
case "linux":
home := os.Getenv("XDG_CONFIG_HOME")
if home != "" {
return home
}
fallthrough
default:
return os.Getenv("HOME")
}
}
// CommitterDetails returns name and email read for a Git configuration file.
//
// Configuration files are read first in the local git repository (if available)
// and then read the global Git configuration.
func CommitterDetails() (string, string, error) {
var paths []string
pwd, err := os.Getwd()
if err == nil {
paths = append(paths, path.Join(pwd, ".git", "config"))
}
paths = append(paths, path.Join(userHomeDir(), ".gitconfig"))
return credentials(paths...)
}
// credentials will try to read user name and email from provided paths.
func credentials(paths ...string) (string, string, error) {
for _, path := range paths {
c, err := parseConfig(path)
if err != nil {
continue
}
committerName := c.Section("user").Option("name")
committerEmail := c.Section("user").Option("email")
if committerEmail == "" {
continue
}
if committerName == "" {
continue
}
return committerName, committerEmail, nil
}
return "", "", errors.Errorf("failed to read Git credentials from paths: %v", paths)
}
// parseConfig returns the Git configuration parsed from provided path.
func parseConfig(path string) (config.Config, error) {
file, err := os.Open(path)
if err != nil {
return config.Config{}, err
}
decoder := config.NewDecoder(file)
var c config.Config
err = decoder.Decode(&c)
if err != nil {
return config.Config{}, err
}
return c, nil
}