-
Notifications
You must be signed in to change notification settings - Fork 28
/
git.go
1520 lines (1316 loc) · 42.6 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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package git
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/blang/semver/v4"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/storer"
"github.com/sirupsen/logrus"
"sigs.k8s.io/release-sdk/regex"
"sigs.k8s.io/release-utils/command"
"sigs.k8s.io/release-utils/util"
)
const (
// DefaultGithubOrg is the default GitHub org used for Kubernetes project
// repos
DefaultGithubOrg = "kubernetes"
// DefaultGithubRepo is the default git repository
DefaultGithubRepo = "kubernetes"
// DefaultGithubReleaseRepo is the default git repository used for
// SIG Release
DefaultGithubReleaseRepo = "sig-release"
// DefaultRemote is the default git remote name
DefaultRemote = "origin"
// DefaultRef is the default git reference name
DefaultRef = "HEAD"
// DefaultBranch is the default branch name
DefaultBranch = "master"
// DefaultGitUser is the default user name used for commits.
DefaultGitUser = "Kubernetes Release Robot"
// DefaultGitEmail is the default email used for commits.
DefaultGitEmail = "k8s-release-robot@users.noreply.github.com"
defaultGithubAuthRoot = "git@github.com:"
gitExecutable = "git"
releaseBranchPrefix = "release-"
)
// setVerboseTrace enables maximum verbosity output.
func setVerboseTrace() error {
if err := setVerbose(5, 2, 2, 2, 2, 2, 2, 2); err != nil {
return fmt.Errorf("set verbose: %w", err)
}
return nil
}
// setVerboseDebug enables a higher verbosity output for git.
func setVerboseDebug() error {
if err := setVerbose(2, 2, 2, 0, 0, 0, 2, 0); err != nil {
return fmt.Errorf("set verbose: %w", err)
}
return nil
}
// setVerbose changes the git verbosity output.
func setVerbose(
merge,
curl,
trace,
tracePackAccess,
tracePacket,
tracePerformance,
traceSetup,
traceShallow uint,
) error {
// Possible values taken from:
// https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#Debugging
for key, value := range map[string]string{
// Controls the output for the recursive merge strategy. The allowed
// values are as follows:
// 0 outputs nothing, except possibly a single error message.
// 1 shows only conflicts.
// 2 also shows file changes.
// 3 shows when files are skipped because they haven’t changed.
// 4 shows all paths as they are processed.
// 5 and above show detailed debugging information.
// The default value is 2.
"GIT_MERGE_VERBOSITY": fmt.Sprint(merge),
// Git uses the curl library to do network operations over HTTP, so
// GIT_CURL_VERBOSE tells Git to emit all the messages generated by
// that library. This is similar to doing curl -v on the command line.
"GIT_CURL_VERBOSE": fmt.Sprint(curl),
// Controls general traces, which don’t fit into any specific category.
// This includes the expansion of aliases, and delegation to other
// sub-programs.
"GIT_TRACE": fmt.Sprint(trace),
// Controls tracing of packfile access. The first field is the packfile
// being accessed, the second is the offset within that file.
"GIT_TRACE_PACK_ACCESS": fmt.Sprint(tracePackAccess),
// Enables packet-level tracing for network operations.
"GIT_TRACE_PACKET": fmt.Sprint(tracePacket),
// Controls logging of performance data. The output shows how long each
// particular git invocation takes.
"GIT_TRACE_PERFORMANCE": fmt.Sprint(tracePerformance),
// Shows information about what Git is discovering about the repository
// and environment it’s interacting with.
"GIT_TRACE_SETUP": fmt.Sprint(traceSetup),
// Debugging fetching/cloning of shallow repositories.
"GIT_TRACE_SHALLOW": fmt.Sprint(traceShallow),
} {
if err := os.Setenv(key, value); err != nil {
return fmt.Errorf("unable to set %s=%s: %w", key, value, err)
}
}
return nil
}
// GetDefaultKubernetesRepoURL returns the default HTTPS repo URL for Kubernetes.
// Expected: https://github.com/kubernetes/kubernetes
func GetDefaultKubernetesRepoURL() string {
return GetKubernetesRepoURL(DefaultGithubOrg, false)
}
// GetKubernetesRepoURL takes a GitHub org and repo, and useSSH as a boolean and
// returns a repo URL for Kubernetes.
// Expected result is one of the following:
// - https://github.com/<org>/kubernetes
// - git@github.com:<org>/kubernetes
func GetKubernetesRepoURL(org string, useSSH bool) string {
if org == "" {
org = DefaultGithubOrg
}
return GetRepoURL(org, DefaultGithubRepo, useSSH)
}
// GetRepoURL takes a GitHub org and repo, and useSSH as a boolean and
// returns a repo URL for the specified repo.
// Expected result is one of the following:
// - https://github.com/<org>/<repo>
// - git@github.com:<org>/<repo>
func GetRepoURL(org, repo string, useSSH bool) (repoURL string) {
slug := filepath.Join(org, repo)
if useSSH {
repoURL = fmt.Sprintf("%s%s", defaultGithubAuthRoot, slug)
} else {
repoURL = (&url.URL{
Scheme: "https",
Host: "github.com",
Path: slug,
}).String()
}
return repoURL
}
// ConfigureGlobalDefaultUserAndEmail globally configures the default git
// user and email.
func ConfigureGlobalDefaultUserAndEmail() error {
if err := filterCommand(
"", "config", "--global", "user.name", DefaultGitUser,
).RunSuccess(); err != nil {
return fmt.Errorf("configure user name: %w", err)
}
if err := filterCommand(
"", "config", "--global", "user.email", DefaultGitEmail,
).RunSuccess(); err != nil {
return fmt.Errorf("configure user email: %w", err)
}
return nil
}
// filterCommand returns a command which automatically filters sensitive information.
func filterCommand(workdir string, args ...string) *command.Command {
// Filter GitHub API keys
c, err := command.NewWithWorkDir(
workdir, gitExecutable, args...,
).Filter(`(?m)git:[0-9a-zA-Z]{35,40}`, "[REDACTED]")
if err != nil {
// should never happen
logrus.Fatalf("git command creation failed: %v", err)
}
return c
}
// DiscoverResult is the result of a revision discovery
type DiscoverResult struct {
startSHA, startRev, endSHA, endRev string
}
// StartSHA returns the start SHA for the DiscoverResult
func (d *DiscoverResult) StartSHA() string {
return d.startSHA
}
// StartRev returns the start revision for the DiscoverResult
func (d *DiscoverResult) StartRev() string {
return d.startRev
}
// EndSHA returns the end SHA for the DiscoverResult
func (d *DiscoverResult) EndSHA() string {
return d.endSHA
}
// EndRev returns the end revision for the DiscoverResult
func (d *DiscoverResult) EndRev() string {
return d.endRev
}
// Remote is a representation of a git remote location
type Remote struct {
name string
urls []string
}
// NewRemote creates a new remote for the provided name and URLs
func NewRemote(name string, urls []string) *Remote {
return &Remote{name, urls}
}
// Name returns the name of the remote
func (r *Remote) Name() string {
return r.name
}
// URLs returns all available URLs of the remote
func (r *Remote) URLs() []string {
return r.urls
}
// Repo is a wrapper for a Kubernetes repository instance
type Repo struct {
inner Repository
worktree Worktree
dir string
dryRun bool
maxRetries int
}
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//go:generate /usr/bin/env bash -c "cat ../scripts/boilerplate/boilerplate.generatego.txt gitfakes/fake_repository.go > gitfakes/_fake_repository.go && mv gitfakes/_fake_repository.go gitfakes/fake_repository.go"
//go:generate /usr/bin/env bash -c "cat ../scripts/boilerplate/boilerplate.generatego.txt gitfakes/fake_worktree.go > gitfakes/_fake_worktree.go && mv gitfakes/_fake_worktree.go gitfakes/fake_worktree.go"
// Repository is the main interface to the git.Repository functionality
//
//counterfeiter:generate . Repository
type Repository interface {
CreateTag(string, plumbing.Hash, *git.CreateTagOptions) (*plumbing.Reference, error)
Branches() (storer.ReferenceIter, error)
CommitObject(plumbing.Hash) (*object.Commit, error)
CreateRemote(*config.RemoteConfig) (*git.Remote, error)
DeleteRemote(name string) error
Head() (*plumbing.Reference, error)
Remote(string) (*git.Remote, error)
Remotes() ([]*git.Remote, error)
ResolveRevision(plumbing.Revision) (*plumbing.Hash, error)
Tags() (storer.ReferenceIter, error)
}
// Worktree is the main interface to the git.Worktree functionality
//
//counterfeiter:generate . Worktree
type Worktree interface {
Add(string) (plumbing.Hash, error)
Commit(string, *git.CommitOptions) (plumbing.Hash, error)
Checkout(*git.CheckoutOptions) error
Status() (git.Status, error)
}
// Dir returns the directory where the repository is stored on disk
func (r *Repo) Dir() string {
return r.dir
}
// SetDry sets the repo to dry-run mode, which does not modify any remote locations
// at all.
func (r *Repo) SetDry() {
r.dryRun = true
}
// SetWorktree can be used to manually set the repository worktree
func (r *Repo) SetWorktree(worktree Worktree) {
r.worktree = worktree
}
// SetInnerRepo can be used to manually set the inner repository
func (r *Repo) SetInnerRepo(repo Repository) {
r.inner = repo
}
// SetMaxRetries defines the number of times, the git client will retry
// some operations when timing out or network failures. Setting it to
// 0 disables retrying
func (r *Repo) SetMaxRetries(numRetries int) {
r.maxRetries = numRetries
}
func LSRemoteExec(repoURL string, args ...string) (string, error) {
cmdArgs := append([]string{"ls-remote", "--", repoURL}, args...)
cmdStatus, err := filterCommand("", cmdArgs...).
RunSilentSuccessOutput()
if err != nil {
return "", fmt.Errorf("failed to execute the ls-remote command: %w", err)
}
return strings.TrimSpace(cmdStatus.Output()), nil
}
// CloneOrOpenDefaultGitHubRepoSSH clones the default Kubernetes GitHub
// repository via SSH if the repoPath is empty, otherwise updates it at the
// expected repoPath.
func CloneOrOpenDefaultGitHubRepoSSH(repoPath string) (*Repo, error) {
return CloneOrOpenGitHubRepo(
repoPath, DefaultGithubOrg, DefaultGithubRepo, true,
)
}
// CleanCloneGitHubRepo creates a guaranteed fresh checkout of a given repository. The returned *Repo has a Cleanup()
// method that should be used to delete the repository on-disk afterwards.
func CleanCloneGitHubRepo(owner, repo string, useSSH bool) (*Repo, error) {
repoURL := GetRepoURL(owner, repo, useSSH)
// The use of a blank string for the repo path triggers special behaviour in CloneOrOpenRepo that causes a true
// temporary directory with a random name to be created.
return CloneOrOpenRepo("", repoURL, useSSH)
}
// CloneOrOpenGitHubRepo works with a repository in the given directory, or creates one if the directory is empty. The
// repo uses the provided GitHub repository via the owner and repo. If useSSH is true, then it will clone the
// repository using the defaultGithubAuthRoot.
func CloneOrOpenGitHubRepo(repoPath, owner, repo string, useSSH bool) (*Repo, error) {
repoURL := GetRepoURL(owner, repo, useSSH)
return CloneOrOpenRepo(repoPath, repoURL, useSSH)
}
// CloneOrOpenRepo creates a temp directory containing the provided
// GitHub repository via the url.
//
// If a repoPath is given, then the function tries to update the repository.
//
// The function returns the repository if cloning or updating of the repository
// was successful, otherwise an error.
func CloneOrOpenRepo(repoPath, repoURL string, useSSH bool) (*Repo, error) {
logrus.Debugf("Using repository url %q", repoURL)
targetDir := ""
if repoPath != "" {
logrus.Debugf("Using existing repository path %q", repoPath)
_, err := os.Stat(repoPath)
switch {
case err == nil:
// The file or directory exists, just try to update the repo
return updateRepo(repoPath)
case os.IsNotExist(err):
// The directory does not exists, we still have to clone it
targetDir = repoPath
default:
// Something else bad happened
return nil, fmt.Errorf("unable to update repo: %w", err)
}
} else {
// No repoPath given, use a random temp dir instead
t, err := os.MkdirTemp("", "k8s-")
if err != nil {
return nil, fmt.Errorf("unable to create temp dir: %w", err)
}
targetDir = t
}
progressBuffer := &bytes.Buffer{}
progressWriters := []io.Writer{progressBuffer}
// Only output the clone progress on debug or trace level,
// otherwise it's too boring.
logLevel := logrus.StandardLogger().Level
if logLevel >= logrus.DebugLevel {
progressWriters = append(progressWriters, os.Stderr)
}
if _, err := git.PlainClone(targetDir, false, &git.CloneOptions{
URL: repoURL,
Progress: io.MultiWriter(progressWriters...),
}); err != nil {
// Print the stack only if not already done
if logLevel < logrus.DebugLevel {
logrus.Errorf(
"Clone repository failed. Tracked progress:\n%s",
progressBuffer.String(),
)
}
return nil, fmt.Errorf("unable to clone repo: %w", err)
}
return updateRepo(targetDir)
}
// updateRepo tries to open the provided repoPath and fetches the latest
// changes from the configured remote location
func updateRepo(repoPath string) (*Repo, error) {
r, err := OpenRepo(repoPath)
if err != nil {
return nil, err
}
// Update the repo
if err := filterCommand(
r.Dir(), "pull", "--rebase",
).RunSilentSuccess(); err != nil {
return nil, fmt.Errorf("unable to pull from remote: %w", err)
}
return r, nil
}
// OpenRepo tries to open the provided repoPath
func OpenRepo(repoPath string) (*Repo, error) {
if !command.Available(gitExecutable) {
return nil, fmt.Errorf(
"%s executable is not available in $PATH", gitExecutable,
)
}
logLevel := logrus.StandardLogger().Level
if logLevel == logrus.DebugLevel {
logrus.Info("Setting verbose git output (debug)")
if err := setVerboseDebug(); err != nil {
return nil, fmt.Errorf("set debug output: %w", err)
}
} else if logLevel == logrus.TraceLevel {
logrus.Info("Setting verbose git output (trace)")
if err := setVerboseTrace(); err != nil {
return nil, fmt.Errorf("set trace output: %w", err)
}
}
if strings.HasPrefix(repoPath, "~/") {
repoPath = os.Getenv("HOME") + repoPath[1:]
logrus.Warnf("Normalizing repository to: %s", repoPath)
}
r, err := git.PlainOpenWithOptions(
repoPath, &git.PlainOpenOptions{DetectDotGit: true},
)
if err != nil {
return nil, fmt.Errorf("opening repo: %w", err)
}
worktree, err := r.Worktree()
if err != nil {
return nil, fmt.Errorf("getting repository worktree: %w", err)
}
return &Repo{
inner: r,
worktree: worktree,
dir: worktree.Filesystem.Root(),
}, nil
}
func (r *Repo) Cleanup() error {
logrus.Debugf("Deleting %s", r.dir)
return os.RemoveAll(r.dir)
}
// RevParseTag parses a git revision and returns a SHA1 on success, otherwise an
// error.
// If the revision does not match a tag add the remote origin in the revision.
func (r *Repo) RevParseTag(rev string) (string, error) {
matched, err := regexp.MatchString(`v\d+\.\d+\.\d+.*`, rev)
if err != nil {
return "", err
}
if !matched {
// Prefix all non-tags the default remote "origin"
rev = Remotify(rev)
}
// Try to resolve the rev
ref, err := r.inner.ResolveRevision(plumbing.Revision(rev))
if err != nil {
return "", err
}
return ref.String(), nil
}
// RevParse parses a git revision and returns a SHA1 on success, otherwise an
// error.
func (r *Repo) RevParse(rev string) (string, error) {
// Try to resolve the rev
ref, err := r.inner.ResolveRevision(plumbing.Revision(rev))
if err != nil {
return "", err
}
return ref.String(), nil
}
// RevParseTagShort parses a git revision and returns a SHA1 trimmed to the length
// 10 on success, otherwise an error.
// If the revision does not match a tag add the remote origin in the revision.
func (r *Repo) RevParseTagShort(rev string) (string, error) {
fullRev, err := r.RevParseTag(rev)
if err != nil {
return "", err
}
return fullRev[:10], nil
}
// RevParseShort parses a git revision and returns a SHA1 trimmed to the length
// 10 on success, otherwise an error.
func (r *Repo) RevParseShort(rev string) (string, error) {
fullRev, err := r.RevParse(rev)
if err != nil {
return "", err
}
return fullRev[:10], nil
}
// LatestReleaseBranchMergeBaseToLatest tries to discover the start (latest
// v1.x.0 merge base) and end (release-1.(x+1) or DefaultBranch) revision inside the
// repository.
func (r *Repo) LatestReleaseBranchMergeBaseToLatest() (DiscoverResult, error) {
// Find the last non patch version tag, then resolve its revision
versions, err := r.latestNonPatchFinalVersions()
if err != nil {
return DiscoverResult{}, err
}
version := versions[0]
versionTag := util.SemverToTagString(version)
logrus.Debugf("Latest non patch version %s", versionTag)
base, err := r.MergeBase(
DefaultBranch,
semverToReleaseBranch(version),
)
if err != nil {
return DiscoverResult{}, err
}
// If a release branch exists for the next version, we use it. Otherwise we
// fallback to the DefaultBranch.
end, branch, err := r.releaseBranchOrMainRef(version.Major, version.Minor+1)
if err != nil {
return DiscoverResult{}, err
}
return DiscoverResult{
startSHA: base,
startRev: versionTag,
endSHA: end,
endRev: branch,
}, nil
}
func (r *Repo) LatestNonPatchFinalToMinor() (DiscoverResult, error) {
// Find the last non patch version tag, then resolve its revision
versions, err := r.latestNonPatchFinalVersions()
if err != nil {
return DiscoverResult{}, err
}
if len(versions) < 2 {
return DiscoverResult{}, errors.New("unable to find two latest non patch versions")
}
latestVersion := versions[0]
latestVersionTag := util.SemverToTagString(latestVersion)
logrus.Debugf("Latest non patch version %s", latestVersionTag)
end, err := r.RevParseTag(latestVersionTag)
if err != nil {
return DiscoverResult{}, err
}
previousVersion := versions[1]
previousVersionTag := util.SemverToTagString(previousVersion)
logrus.Debugf("Previous non patch version %s", previousVersionTag)
start, err := r.RevParseTag(previousVersionTag)
if err != nil {
return DiscoverResult{}, err
}
return DiscoverResult{
startSHA: start,
startRev: previousVersionTag,
endSHA: end,
endRev: latestVersionTag,
}, nil
}
func (r *Repo) latestNonPatchFinalVersions() ([]semver.Version, error) {
latestVersions := []semver.Version{}
tags, err := r.inner.Tags()
if err != nil {
return nil, err
}
_ = tags.ForEach(func(t *plumbing.Reference) error { //nolint: errcheck
ver, err := util.TagStringToSemver(t.Name().Short())
if err == nil {
// We're searching for the latest, non patch final tag
if ver.Patch == 0 && len(ver.Pre) == 0 {
if len(latestVersions) == 0 || ver.GT(latestVersions[0]) {
latestVersions = append([]semver.Version{ver}, latestVersions...)
}
}
}
return nil
})
if len(latestVersions) == 0 {
return nil, fmt.Errorf("unable to find latest non patch release")
}
return latestVersions, nil
}
func (r *Repo) releaseBranchOrMainRef(major, minor uint64) (sha, rev string, err error) {
relBranch := fmt.Sprintf("%s%d.%d", releaseBranchPrefix, major, minor)
sha, err = r.RevParseTag(relBranch)
if err == nil {
logrus.Debugf("Found release branch %s", relBranch)
return sha, relBranch, nil
}
sha, err = r.RevParseTag(DefaultBranch)
if err == nil {
logrus.Debugf("No release branch found, using %s", DefaultBranch)
return sha, DefaultBranch, nil
}
return "", "", err
}
// HasBranch checks if a branch exists in the repo
func (r *Repo) HasBranch(branch string) (branchExists bool, err error) {
logrus.Infof("Verifying %s branch exists in the repo", branch)
branches, err := r.inner.Branches()
if err != nil {
return branchExists, fmt.Errorf("getting branches from repository: %w", err)
}
branchExists = false
if err := branches.ForEach(func(ref *plumbing.Reference) error {
if ref.Name().Short() == branch {
logrus.Infof("Branch %s found in the repository", branch)
branchExists = true
}
return nil
}); err != nil {
return branchExists, fmt.Errorf("iterating branches to check for existence: %w", err)
}
return branchExists, nil
}
// HasRemoteBranch takes a branch string and verifies that it exists
// on the default remote
func (r *Repo) HasRemoteBranch(branch string) (branchExists bool, err error) {
logrus.Infof("Verifying %s branch exists on the remote", branch)
branches, err := r.RemoteBranches()
if err != nil {
return false, fmt.Errorf("get remote branches: %w", err)
}
for _, remoteBranch := range branches {
if remoteBranch == branch {
logrus.Infof("Found branch %s", branch)
return true, nil
}
}
logrus.Infof("Branch %s not found", branch)
return false, nil
}
// RemoteBranches returns a list of all remotely available branches.
func (r *Repo) RemoteBranches() (branches []string, err error) {
remote, err := r.inner.Remote(DefaultRemote)
if err != nil {
return nil, NewNetworkError(err)
}
var refs []*plumbing.Reference
for i := r.maxRetries + 1; i > 0; i-- {
// We can then use every Remote functions to retrieve wanted information
refs, err = remote.List(&git.ListOptions{})
if err == nil {
break
}
logrus.Warn("Could not list references on the remote repository.")
// Convert to network error to see if we can retry the push
err = NewNetworkError(err)
if !err.(NetworkError).CanRetry() || r.maxRetries == 0 || i == 1 {
return nil, err
}
waitTime := math.Pow(2, float64(r.maxRetries-i))
logrus.Errorf(
"Error listing remote references (will retry %d more times in %.0f secs): %s",
i-1, waitTime, err.Error(),
)
time.Sleep(time.Duration(waitTime) * time.Second)
}
for _, ref := range refs {
if ref.Name().IsBranch() {
branches = append(branches, ref.Name().Short())
}
}
return branches, nil
}
// Checkout can be used to checkout any revision inside the repository
func (r *Repo) Checkout(rev string, args ...string) error {
cmdArgs := append([]string{"checkout", rev}, args...)
return command.
NewWithWorkDir(r.Dir(), gitExecutable, cmdArgs...).
RunSilentSuccess()
}
// IsReleaseBranch returns true if the provided branch is a Kubernetes release
// branch
func IsReleaseBranch(branch string) bool {
if !regex.BranchRegex.MatchString(branch) {
logrus.Warnf("%s is not a release branch", branch)
return false
}
return true
}
func (r *Repo) MergeBase(from, to string) (string, error) {
mainRef := Remotify(from)
releaseRef := Remotify(to)
logrus.Debugf("MainRef: %s, releaseRef: %s", mainRef, releaseRef)
commitRevs := []string{mainRef, releaseRef}
var res []*object.Commit
hashes := []*plumbing.Hash{}
for _, rev := range commitRevs {
hash, err := r.inner.ResolveRevision(plumbing.Revision(rev))
if err != nil {
return "", err
}
hashes = append(hashes, hash)
}
commits := []*object.Commit{}
for _, hash := range hashes {
commit, err := r.inner.CommitObject(*hash)
if err != nil {
return "", err
}
commits = append(commits, commit)
}
res, err := commits[0].MergeBase(commits[1])
if err != nil {
return "", err
}
if len(res) == 0 {
return "", fmt.Errorf("could not find a merge base between %s and %s", from, to)
}
mergeBase := res[0].Hash.String()
logrus.Infof("Merge base is %s", mergeBase)
return mergeBase, nil
}
// Remotify returns the name prepended with the default remote
func Remotify(name string) string {
split := strings.Split(name, "/")
if len(split) > 1 {
return name
}
return fmt.Sprintf("%s/%s", DefaultRemote, name)
}
// Merge does a git merge into the current branch from the provided one
func (r *Repo) Merge(from string) error {
if err := filterCommand(
r.Dir(), "merge", "-X", "ours", from,
).RunSilentSuccess(); err != nil {
return fmt.Errorf("run git merge: %w", err)
}
return nil
}
// Push does push the specified branch to the default remote, but only if the
// repository is not in dry run mode
func (r *Repo) Push(remoteBranch string) (err error) {
args := []string{"push"}
if r.dryRun {
logrus.Infof("Won't push due to dry run repository")
args = append(args, "--dry-run")
}
args = append(args, DefaultRemote, remoteBranch)
for i := r.maxRetries + 1; i > 0; i-- {
if err = filterCommand(r.Dir(), args...).RunSilentSuccess(); err == nil {
return nil
}
// Convert to network error to see if we can retry the push
err = NewNetworkError(err)
if !err.(NetworkError).CanRetry() || r.maxRetries == 0 {
return err
}
waitTime := math.Pow(2, float64(r.maxRetries-i))
logrus.Errorf(
"Error pushing %s (will retry %d more times in %.0f secs): %s",
remoteBranch, i-1, waitTime, err.Error(),
)
time.Sleep(time.Duration(waitTime) * time.Second)
}
return fmt.Errorf("trying to push %s %d times: %w", remoteBranch, r.maxRetries, err)
}
// Head retrieves the current repository HEAD as a string
func (r *Repo) Head() (string, error) {
ref, err := r.inner.Head()
if err != nil {
return "", err
}
return ref.Hash().String(), nil
}
// LatestPatchToPatch tries to discover the start (latest v1.x.[x-1]) and
// end (latest v1.x.x) revision inside the repository for the specified release
// branch.
func (r *Repo) LatestPatchToPatch(branch string) (DiscoverResult, error) {
latestTag, err := r.LatestTagForBranch(branch)
if err != nil {
return DiscoverResult{}, err
}
if len(latestTag.Pre) > 0 && latestTag.Patch > 0 {
latestTag.Patch--
latestTag.Pre = nil
}
if latestTag.Patch == 0 {
return DiscoverResult{}, fmt.Errorf(
"found non-patch version %v as latest tag on branch %s",
latestTag, branch,
)
}
prevTag := semver.Version{
Major: latestTag.Major,
Minor: latestTag.Minor,
Patch: latestTag.Patch - 1,
}
logrus.Debugf("Parsing latest tag %s%v", util.TagPrefix, latestTag)
latestVersionTag := util.SemverToTagString(latestTag)
end, err := r.RevParseTag(latestVersionTag)
if err != nil {
return DiscoverResult{}, fmt.Errorf("parsing version %v: %w", latestTag, err)
}
logrus.Debugf("Parsing previous tag %s%v", util.TagPrefix, prevTag)
previousVersionTag := util.SemverToTagString(prevTag)
start, err := r.RevParseTag(previousVersionTag)
if err != nil {
return DiscoverResult{}, fmt.Errorf("parsing previous version %v: %w", prevTag, err)
}
return DiscoverResult{
startSHA: start,
startRev: previousVersionTag,
endSHA: end,
endRev: latestVersionTag,
}, nil
}
// LatestPatchToLatest tries to discover the start (latest v1.x.x]) and
// end (release-1.x or DefaultBranch) revision inside the repository for the specified release
// branch.
func (r *Repo) LatestPatchToLatest(branch string) (DiscoverResult, error) {
latestTag, err := r.LatestTagForBranch(branch)
if err != nil {
return DiscoverResult{}, err
}
if len(latestTag.Pre) > 0 && latestTag.Patch > 0 {
latestTag.Patch--
latestTag.Pre = nil
}
logrus.Debugf("Parsing latest tag %s%v", util.TagPrefix, latestTag)
latestVersionTag := util.SemverToTagString(latestTag)
start, err := r.RevParseTag(latestVersionTag)
if err != nil {
return DiscoverResult{}, fmt.Errorf("parsing version %v: %w", latestTag, err)
}
// If a release branch exists for the latest version, we use it. Otherwise we
// fallback to the DefaultBranch.
end, branch, err := r.releaseBranchOrMainRef(latestTag.Major, latestTag.Minor)
if err != nil {
return DiscoverResult{}, fmt.Errorf("getting release branch for %v: %w", latestTag, err)
}
return DiscoverResult{
startSHA: start,
startRev: latestVersionTag,
endSHA: end,
endRev: branch,
}, nil
}
// LatestTagForBranch returns the latest available semver tag for a given branch
func (r *Repo) LatestTagForBranch(branch string) (tag semver.Version, err error) {
tags, err := r.TagsForBranch(branch)
if err != nil {
return tag, err
}
if len(tags) == 0 {
return tag, errors.New("no tags found on branch")
}
tag, err = util.TagStringToSemver(tags[0])
if err != nil {
return tag, err
}
return tag, nil
}
// PreviousTag tries to find the previous tag for a provided branch and errors
// on any failure
func (r *Repo) PreviousTag(tag, branch string) (string, error) {
tags, err := r.TagsForBranch(branch)
if err != nil {
return "", err
}
idx := -1
for i, t := range tags {
if t == tag {
idx = i
break
}
}
if idx == -1 {
return "", errors.New("could not find specified tag in branch")
}
if len(tags) < idx+1 {
return "", errors.New("unable to find previous tag")
}
return tags[idx+1], nil
}
// TagsForBranch returns a list of tags for the provided branch sorted by
// creation date
func (r *Repo) TagsForBranch(branch string) (res []string, err error) {