-
Notifications
You must be signed in to change notification settings - Fork 6
/
git.go
832 lines (647 loc) · 21.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
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
package git
import (
"context"
"errors"
"fmt"
netHttp "net/http"
"net/url"
"os"
"os/exec"
"path"
"strings"
"time"
"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/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/memory"
ctrl "sigs.k8s.io/controller-runtime"
)
const (
gitCMD = "git"
gitDirName = ".git"
gitDirArg = "--git-dir"
gitBranchArg = "branch"
gitCheckoutArg = "checkout"
getFetchArg = "fetch"
gitOriginArg = "origin"
gitUnshallowArg = "--unshallow"
gitSshVariantEnv = "GIT_SSH_VARIANT=ssh"
)
const defaultSshPort = 22
const (
logBranchNameKey = "branchName"
logDirectoryKey = "directory"
logRepositoryKey = "repository"
logOutKey = "out"
errPlainOpenTmpl = "failed to open git directory %q: %w"
errRemoveSHHKeyFile = "failed to remove key file"
)
type commitOps struct {
allowEmptyCommit bool
}
type CommitOps func(*commitOps)
func CommitAllowEmpty() func(*commitOps) {
return func(o *commitOps) {
o.allowEmptyCommit = true
}
}
// Git interface provides methods for working with git.
//
//go:generate mockery --name Git --filename git_mock.go
type Git interface {
CommitChanges(directory, commitMsg string, opts ...CommitOps) error
PushChanges(key, user, directory string, port int32, pushParams ...string) error
CheckPermissions(ctx context.Context, repo string, user, pass *string) (accessible bool)
CloneRepositoryBySsh(ctx context.Context, key, user, repoUrl, destination string, port int32) error
CloneRepository(repo string, user *string, pass *string, destination string) error
CreateRemoteBranch(key, user, path, name, fromcommit string, port int32) error
CreateRemoteTag(key, user, path, branchName, name string) error
Fetch(key, user, path, branchName string) error
Checkout(user, pass *string, directory, branchName string, remote bool) error
GetCurrentBranchName(directory string) (string, error)
Init(directory string) error
CheckoutRemoteBranchBySSH(key, user, gitPath, remoteBranchName string) error
RemoveBranch(directory, branchName string) error
RenameBranch(directory, currentName, newName string) error
CreateChildBranch(directory, currentBranch, newBranch string) error
CommitExists(directory, hash string) (bool, error)
AddRemoteLink(repoPath, remoteUrl string) error
}
type Command interface {
CombinedOutput() ([]byte, error)
}
type GitProvider struct {
CommandBuilder func(cmd string, params ...string) Command
}
func (gp *GitProvider) buildCommand(cmd string, params ...string) Command {
if gp.CommandBuilder == nil {
gp.CommandBuilder = func(cmd string, params ...string) Command {
return exec.Command(cmd, params...)
}
}
return gp.CommandBuilder(cmd, params...)
}
var log = ctrl.Log.WithName("git-provider")
func (gp *GitProvider) CreateRemoteBranch(key, user, p, name, fromcommit string, port int32) error {
log.Info("start creating remote branch", logBranchNameKey, name)
r, err := git.PlainOpen(p)
if err != nil {
return fmt.Errorf(errPlainOpenTmpl, p, err)
}
ref, err := r.Head()
if err != nil {
return fmt.Errorf("failed to get git HEAD reference: %w", err)
}
if fromcommit != "" {
_, err = r.CommitObject(plumbing.NewHash(fromcommit))
if err != nil {
return fmt.Errorf("failed to get commit %s: %w", fromcommit, err)
}
ref = plumbing.NewReferenceFromStrings(name, fromcommit)
}
branches, err := r.Branches()
if err != nil {
return fmt.Errorf("failed to get branches iterator: %w", err)
}
exists, err := isBranchExists(name, branches)
if err != nil {
return err
}
if exists {
log.Info("branch already exists. skip creating", logBranchNameKey, name)
return nil
}
newRef := plumbing.NewReferenceFromStrings(fmt.Sprintf("refs/heads/%v", name), ref.Hash().String())
err = r.Storer.SetReference(newRef)
if err != nil {
return fmt.Errorf("failed to set refference: %w", err)
}
err = gp.PushChanges(key, user, p, port, "--all")
if err != nil {
return err
}
log.Info("branch has been created", logBranchNameKey, name)
return nil
}
func (*GitProvider) CommitChanges(directory, commitMsg string, ops ...CommitOps) error {
logger := log.WithValues(logDirectoryKey, directory)
logger.Info("Start committing changes")
option := &commitOps{
allowEmptyCommit: false,
}
for _, applyOption := range ops {
applyOption(option)
}
r, err := git.PlainOpen(directory)
if err != nil {
return fmt.Errorf(errPlainOpenTmpl, directory, err)
}
w, err := r.Worktree()
if err != nil {
return fmt.Errorf("failed to get git worktree: %w", err)
}
_, err = w.Add(".")
if err != nil {
return fmt.Errorf("failed to add files to the index: %w", err)
}
if !option.allowEmptyCommit {
var status git.Status
status, err = w.Status()
if err != nil {
return fmt.Errorf("failed to get git status: %w", err)
}
if status.IsClean() {
logger.Info("Nothing to commit. Skip committing")
return nil
}
}
_, err = w.Commit(commitMsg, &git.CommitOptions{
Author: &object.Signature{
Name: "codebase",
Email: "codebase@edp.local",
When: time.Now(),
},
AllowEmptyCommits: option.allowEmptyCommit,
})
if err != nil {
return fmt.Errorf("failed to commit: %w", err)
}
logger.Info("Changes have been committed")
return nil
}
func (gp *GitProvider) RemoveBranch(directory, branchName string) error {
gitDir := path.Join(directory, gitDirName)
cmd := gp.buildCommand(gitCMD, gitDirArg, gitDir, gitBranchArg, "-D", branchName)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to remove branch, err: %s: %w", string(bts), err)
}
return nil
}
func (gp *GitProvider) RenameBranch(directory, currentName, newName string) error {
gitDir := path.Join(directory, gitDirName)
cmd := gp.buildCommand(gitCMD, gitDirArg, gitDir, gitCheckoutArg, currentName)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to checkout branch, err: %s: %w", string(bts), err)
}
cmd = gp.buildCommand(gitCMD, gitDirArg, gitDir, gitBranchArg, "-m", newName)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to rename branch, err: %s: %w", string(bts), err)
}
return nil
}
func (gp *GitProvider) CreateChildBranch(directory, currentBranch, newBranch string) error {
gitDir := path.Join(directory, gitDirName)
cmd := gp.buildCommand(gitCMD, gitDirArg, gitDir, gitCheckoutArg, currentBranch)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to checkout branch, err: %s: %w", string(bts), err)
}
cmd = gp.buildCommand(gitCMD, gitDirArg, gitDir, gitCheckoutArg, "-b", newBranch)
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to rename branch, err: %s: %w", string(bts), err)
}
return nil
}
func (*GitProvider) PushChanges(key, user, directory string, port int32, pushParams ...string) error {
log.Info("Start pushing changes", logDirectoryKey, directory)
keyPath, err := InitAuth(key, user)
if err != nil {
return err
}
defer func() {
if err = os.Remove(keyPath); err != nil {
log.Error(err, errRemoveSHHKeyFile)
}
}()
gitDir := path.Join(directory, gitDirName)
basePushParams := []string{gitDirArg, gitDir, "push", gitOriginArg}
basePushParams = append(basePushParams, pushParams...)
pushCMD := exec.Command(gitCMD, basePushParams...)
pushCMD.Env = []string{
fmt.Sprintf(`GIT_SSH_COMMAND=ssh -i %s -l %s -o StrictHostKeyChecking=no -p %d`, keyPath,
user, port),
gitSshVariantEnv,
}
pushCMD.Dir = directory
log.Info("pushCMD:", "is: ", basePushParams)
if bts, err := pushCMD.CombinedOutput(); err != nil {
return fmt.Errorf("failed to push changes, err: %s: %w", string(bts), err)
}
log.Info("Changes has been pushed", logDirectoryKey, directory)
return nil
}
func (*GitProvider) CheckPermissions(ctx context.Context, repo string, user, pass *string) (accessible bool) {
l := ctrl.LoggerFrom(ctx).WithValues(logRepositoryKey, repo)
l.Info("Checking permissions", "user", user)
if user == nil || pass == nil {
l.Info("No credentials provided. Skip checking permissions")
return true
}
r, _ := git.Init(memory.NewStorage(), nil)
remote, _ := r.CreateRemote(&config.RemoteConfig{
Name: "origin",
URLs: []string{repo},
})
rfs, err := remote.List(&git.ListOptions{
Auth: &http.BasicAuth{
Username: *user,
Password: *pass,
},
})
if err != nil {
if errors.Is(err, transport.ErrEmptyRemoteRepository) {
l.Error(err, "No refs in repository")
return false
}
l.Error(err, fmt.Sprintf("User %v do not have access to %v repository", user, repo))
return false
}
if len(rfs) == 0 {
l.Error(errors.New("there are not refs in repository"), "No refs in repository")
return false
}
return true
}
func (*GitProvider) BareToNormal(p string) error {
const readWriteExecutePermBits = 0o777
gitDir := path.Join(p, gitDirName)
if err := os.MkdirAll(gitDir, readWriteExecutePermBits); err != nil {
return fmt.Errorf("failed to create .git folder: %w", err)
}
files, err := os.ReadDir(p)
if err != nil {
return fmt.Errorf("failed to list dir: %w", err)
}
for _, f := range files {
if f.Name() == gitDirName {
continue
}
oldPath := path.Join(p, f.Name())
newPath := path.Join(p, gitDirName, f.Name())
if err := os.Rename(oldPath, newPath); err != nil {
return fmt.Errorf("failed to rename file: %w", err)
}
}
cmd := exec.Command(gitCMD, gitDirArg, gitDir, "config", "--local",
"--bool", "core.bare", "false")
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("%s: %w", string(bts), err)
}
cmd = exec.Command(gitCMD, gitDirArg, gitDir, "config", "--local",
"--bool", "remote.origin.mirror", "false")
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("%s: %w", string(bts), err)
}
cmd = exec.Command(gitCMD, gitDirArg, gitDir, "reset", "--hard")
cmd.Dir = p
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("%s: %w", string(bts), err)
}
return nil
}
func (gp *GitProvider) CloneRepositoryBySsh(ctx context.Context, key, user, repoUrl, destination string, port int32) error {
l := ctrl.LoggerFrom(ctx)
l.Info("Start cloning", logRepositoryKey, repoUrl)
keyPath, err := InitAuth(key, user)
if err != nil {
return err
}
defer func() {
if err = os.Remove(keyPath); err != nil {
l.Error(err, errRemoveSHHKeyFile)
}
}()
cloneCMD := exec.Command(gitCMD, "clone", "--mirror", "--depth", "1", repoUrl, destination)
cloneCMD.Env = []string{fmt.Sprintf(`GIT_SSH_COMMAND=ssh -i %s -l %s -o StrictHostKeyChecking=no -p %d`,
keyPath, user, port), gitSshVariantEnv}
bytes, err := cloneCMD.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to clone repo by ssh, err: %s: %w", string(bytes), err)
}
fetchCMD := exec.Command(gitCMD, gitDirArg, destination, getFetchArg, gitUnshallowArg)
fetchCMD.Env = cloneCMD.Env
bts, err := fetchCMD.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to fetch unshallow repo: %s: %w", string(bts), err)
}
l.Info("Result of `git fetch unshallow` command", logOutKey, string(bts))
err = gp.BareToNormal(destination)
if err != nil {
return fmt.Errorf("failed to covert bare repo to normal: %w", err)
}
l.Info("End cloning", logRepositoryKey, repoUrl)
return nil
}
func (gp *GitProvider) CloneRepository(repo string, user, pass *string, destination string) error {
log.Info("Start cloning", logRepositoryKey, repo)
const httpClientErrors = 400
if user != nil && pass != nil {
u, err := url.Parse(repo)
if err != nil {
return fmt.Errorf("failed to parse repo url: %w", err)
}
u.User = url.UserPassword(*user, *pass)
repo = u.String()
} else {
rsp, err := netHttp.Get(repo)
if err != nil {
return fmt.Errorf("failed to get repo: %w", err)
}
if rsp.StatusCode >= httpClientErrors {
return fmt.Errorf("repo access denied, response code: %d: %w", rsp.StatusCode, err)
}
}
cloneCMD := exec.Command(gitCMD, "clone", "--mirror", "--depth", "1", repo, destination)
if bts, err := cloneCMD.CombinedOutput(); err != nil {
return fmt.Errorf("failed to clone repo: %s: %w", string(bts), err)
}
fetchCMD := exec.Command(gitCMD, gitDirArg, destination, getFetchArg, gitUnshallowArg)
bts, err := fetchCMD.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to fetch unshallow repo: %s: %w", string(bts), err)
}
log.Info("Result of `git fetch unshallow` command", logOutKey, string(bts))
err = gp.BareToNormal(destination)
if err != nil {
return fmt.Errorf("failed to covert bare repo to normal: %w", err)
}
log.Info("End cloning", logRepositoryKey, repo)
return nil
}
func (gp *GitProvider) CreateRemoteTag(key, user, p, branchName, name string) error {
log.Info("start creating remote tag", "tagName", name)
r, err := git.PlainOpen(p)
if err != nil {
return fmt.Errorf(errPlainOpenTmpl, p, err)
}
tags, err := r.Tags()
if err != nil {
return fmt.Errorf("failed to get git tags: %w", err)
}
exists, err := isTagExists(name, tags)
if err != nil {
return err
}
if exists {
log.Info("tag already exists. skip creating", "tagName", name)
return nil
}
ref, err := r.Reference(plumbing.ReferenceName(fmt.Sprintf("refs/heads/%v", branchName)), false)
if err != nil {
return fmt.Errorf("failed to get reference: %w", err)
}
newRef := plumbing.NewReferenceFromStrings(fmt.Sprintf("refs/tags/%v", name), ref.Hash().String())
err = r.Storer.SetReference(newRef)
if err != nil {
return fmt.Errorf("failed to set refference: %w", err)
}
err = gp.PushChanges(key, user, p, defaultSshPort)
if err != nil {
return err
}
log.Info("tag has been created", "tagName", name)
return nil
}
func (*GitProvider) Fetch(key, user, workDir, branchName string) error {
log.Info("start fetching data", logBranchNameKey, branchName)
keyPath, err := InitAuth(key, user)
if err != nil {
return err
}
defer func() {
if err = os.Remove(keyPath); err != nil {
log.Error(err, errRemoveSHHKeyFile)
}
}()
gitDir := path.Join(workDir, gitDirName)
cmd := exec.Command(gitCMD, gitDirArg, gitDir, getFetchArg, fmt.Sprintf("refs/heads/%v:refs/heads/%v", branchName, branchName))
cmd.Env = []string{
fmt.Sprintf(`GIT_SSH_COMMAND=ssh -i %s -l %s -o StrictHostKeyChecking=no`, keyPath, user),
gitSshVariantEnv,
}
cmd.Dir = workDir
if bts, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to push changes, err: %s: %w", string(bts), err)
}
log.Info("end fetching data", logBranchNameKey, branchName)
return nil
}
func (*GitProvider) Checkout(user, pass *string, directory, branchName string, remote bool) error {
log.Info("trying to checkout to branch", logBranchNameKey, branchName)
r, err := git.PlainOpen(directory)
if err != nil {
return fmt.Errorf(errPlainOpenTmpl, directory, err)
}
w, err := r.Worktree()
if err != nil {
return fmt.Errorf("failed to get git worktree: %w", err)
}
createBranchOrNot := true
if remote {
gfo := &git.FetchOptions{RefSpecs: []config.RefSpec{"refs/*:refs/*"}}
if user != nil && pass != nil {
gfo = &git.FetchOptions{
RefSpecs: []config.RefSpec{"refs/*:refs/*"},
Auth: &http.BasicAuth{
Username: *user,
Password: *pass,
},
}
}
err = r.Fetch(gfo)
if err != nil {
if err.Error() != "already up-to-date" {
return fmt.Errorf("failed to fetch: %w", err)
}
}
createBranchOrNot, err = checkBranchExistence(user, pass, branchName, *r)
if err != nil {
return err
}
}
err = w.Checkout(&git.CheckoutOptions{
Branch: plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", branchName)),
Force: true,
Create: createBranchOrNot,
})
if err != nil {
return fmt.Errorf("failed to checkout git branch: %w", err)
}
return nil
}
func (*GitProvider) GetCurrentBranchName(directory string) (string, error) {
log.Info("trying to get current git branch")
r, err := git.PlainOpen(directory)
if err != nil {
return "", fmt.Errorf(errPlainOpenTmpl, directory, err)
}
ref, err := r.Head()
if err != nil {
return "", fmt.Errorf("failed to get HEAD refference: %w", err)
}
branchName := strings.ReplaceAll(ref.Name().String(), "refs/heads/", "")
return branchName, nil
}
func (*GitProvider) Init(directory string) error {
log.Info("start creating git repository")
_, err := git.PlainInit(directory, false)
if err != nil {
return fmt.Errorf("failed to init Git repository: %w", err)
}
log.Info("git repository has been created")
return nil
}
func (*GitProvider) CheckoutRemoteBranchBySSH(key, user, gitPath, remoteBranchName string) error {
log.Info("start checkout to", "branch", remoteBranchName)
keyPath, err := InitAuth(key, user)
if err != nil {
return err
}
defer func() {
if err = os.Remove(keyPath); err != nil {
log.Error(err, errRemoveSHHKeyFile)
}
}()
gitDir := path.Join(gitPath, ".git")
// running git fetch --update-head-ok
cmdFetch := exec.Command(gitCMD, gitDirArg, gitDir, getFetchArg, "--update-head-ok")
cmdFetch.Env = []string{
fmt.Sprintf(`GIT_SSH_COMMAND=ssh -i %s -l %s -o StrictHostKeyChecking=no`, keyPath, user),
gitSshVariantEnv,
}
cmdFetch.Dir = gitPath
if bts, err := cmdFetch.CombinedOutput(); err != nil {
return fmt.Errorf("failed to fetch branches, err: %s: %w", string(bts), err)
}
// here we expect that remote branch exists otherwise return error
// git checkout -b remoteBranchName remoteBranchName
cmdCheckout := exec.Command(gitCMD, gitDirArg, gitDir, gitCheckoutArg, remoteBranchName)
cmdCheckout.Dir = gitPath
if bts, err := cmdCheckout.CombinedOutput(); err != nil {
return fmt.Errorf("failed to checkout to branch, err: %s: %w", string(bts), err)
}
log.Info("end checkout to", "branch", remoteBranchName)
return nil
}
// CommitExists checks if a commit exists in the repository.
func (*GitProvider) CommitExists(directory, hash string) (bool, error) {
r, err := git.PlainOpen(directory)
if err != nil {
return false, fmt.Errorf(errPlainOpenTmpl, directory, err)
}
commit, err := r.CommitObject(plumbing.NewHash(hash))
if err != nil {
if errors.Is(err, plumbing.ErrObjectNotFound) {
return false, nil
}
return false, fmt.Errorf("failed to get commit object: %w", err)
}
return commit != nil, nil
}
// AddRemoteLink adds a remote link to the repository.
func (*GitProvider) AddRemoteLink(repoPath, remoteUrl string) error {
r, err := git.PlainOpen(repoPath)
if err != nil {
return fmt.Errorf("failed to open Git directory: %w", err)
}
err = r.DeleteRemote("origin")
if err != nil && !errors.Is(err, git.ErrRemoteNotFound) {
return fmt.Errorf("failed to delete remote origin: %w", err)
}
_, err = r.CreateRemote(&config.RemoteConfig{
Name: "origin",
URLs: []string{remoteUrl},
})
if err != nil {
return fmt.Errorf("failed to create remote origin: %w", err)
}
return nil
}
func isBranchExists(name string, branches storer.ReferenceIter) (bool, error) {
for {
b, err := branches.Next()
if err != nil {
if err.Error() == "EOF" {
return false, nil
}
return false, fmt.Errorf("failed to get next branch iterator: %w", err)
}
if b.Name().Short() == name {
return true, nil
}
}
}
func InitAuth(key, user string) (string, error) {
log.Info("Initializing auth", "user", user)
keyFile, err := os.CreateTemp("", "sshkey")
if err != nil {
return "", fmt.Errorf("failed to create temp file for ssh key: %w", err)
}
keyFileInfo, _ := keyFile.Stat()
keyFilePath := path.Join(os.TempDir(), keyFileInfo.Name())
// write the key to the file with a new line at the end to avoid ssh errors on git commands
// if the new line already exists, adding the new line will not cause any issues
if _, err = fmt.Fprintf(keyFile, "%s%s", key, "\n"); err != nil {
return "", fmt.Errorf("failed to write ssh key: %w", err)
}
if err = keyFile.Close(); err != nil {
return "", fmt.Errorf("failed to close file: %w", err)
}
const readOnlyPermBits = 0o400
if err := os.Chmod(keyFilePath, readOnlyPermBits); err != nil {
return "", fmt.Errorf("failed to chmod ssh key file: %w", err)
}
return keyFilePath, nil
}
func isTagExists(name string, tags storer.ReferenceIter) (bool, error) {
for {
t, err := tags.Next()
if err != nil {
if err.Error() == "EOF" {
return false, nil
}
return false, fmt.Errorf("failed to get next reference iterator: %w", err)
}
if t.Name().Short() == name {
return true, nil
}
}
}
func checkBranchExistence(user, pass *string, branchName string, r git.Repository) (bool, error) {
log.Info("checking if branch exist", logBranchNameKey, branchName)
remote, err := r.Remote("origin")
if err != nil {
return false, fmt.Errorf("failed to get GIT remove origin: %w", err)
}
glo := &git.ListOptions{}
if user != nil && pass != nil {
glo = &git.ListOptions{
Auth: &http.BasicAuth{
Username: *user,
Password: *pass,
},
}
}
refList, err := remote.List(glo)
if err != nil {
return false, fmt.Errorf("failed to get references on the remote repository: %w", err)
}
existBranchOrNot := true
refPrefix := "refs/heads/"
for _, ref := range refList {
refName := ref.Name().String()
if !strings.HasPrefix(refName, refPrefix) {
continue
}
b := refName[len(refPrefix):]
if b == branchName {
existBranchOrNot = false
break
}
}
log.Info("branch existence status", logBranchNameKey, branchName, "existBranchOrNot", existBranchOrNot)
return existBranchOrNot, nil
}