-
Notifications
You must be signed in to change notification settings - Fork 11
/
git.go
1018 lines (873 loc) · 20.8 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
package vcs
import (
"github.com/apex/log"
"github.com/crawlab-team/go-trace"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"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/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
gitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/go-git/go-git/v5/storage/memory"
"golang.org/x/crypto/ssh"
"io/ioutil"
"os"
"path"
"regexp"
"sort"
"strings"
)
var headRefRegexp, _ = regexp.Compile("^ref: (.*)")
type GitClient struct {
// settings
path string
remoteUrl string
isMem bool
authType GitAuthType
username string
password string
privateKey string
privateKeyPath string
defaultBranch string
// internals
r *git.Repository
}
func (c *GitClient) Init() (err error) {
initType := c.getInitType()
switch initType {
case GitInitTypeFs:
err = c.initFs()
case GitInitTypeMem:
err = c.initMem()
}
if err != nil {
return err
}
// if remote url is not empty and no remote exists
// create default remote and pull from remote url
remotes, err := c.r.Remotes()
if err != nil {
return err
}
if c.remoteUrl != "" && len(remotes) == 0 {
// attempt to get default remote
if _, err := c.r.Remote(GitRemoteNameOrigin); err != nil {
if err != git.ErrRemoteNotFound {
return trace.TraceError(err)
}
err = nil
// create default remote
if err := c.createRemote(GitRemoteNameOrigin, c.remoteUrl); err != nil {
return err
}
//// pull
//opts := []GitPullOption{
// WithRemoteNamePull(GitRemoteNameOrigin),
//}
//if err := c.Pull(opts...); err != nil {
// return err
//}
}
}
return nil
}
func (c *GitClient) Dispose() (err error) {
switch c.getInitType() {
case GitInitTypeFs:
if err := os.RemoveAll(c.path); err != nil {
return trace.TraceError(err)
}
case GitInitTypeMem:
GitMemStorages.Delete(c.path)
GitMemFileSystem.Delete(c.path)
}
return nil
}
func (c *GitClient) Checkout(opts ...GitCheckoutOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// apply options
o := &git.CheckoutOptions{}
for _, opt := range opts {
opt(o)
}
// checkout to the branch
if err := wt.Checkout(o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Commit(msg string, opts ...GitCommitOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// apply options
o := &git.CommitOptions{}
for _, opt := range opts {
opt(o)
}
// commit
if _, err := wt.Commit(msg, o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Pull(opts ...GitPullOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// auth
auth, err := c.getGitAuth()
if err != nil {
return err
}
if auth != nil {
opts = append(opts, WithAuthPull(auth))
}
// apply options
o := &git.PullOptions{}
for _, opt := range opts {
opt(o)
}
// pull
if err := wt.Pull(o); err != nil {
if err == transport.ErrEmptyRemoteRepository {
return nil
}
if err == git.NoErrAlreadyUpToDate {
return nil
}
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Push(opts ...GitPushOption) (err error) {
// auth
auth, err := c.getGitAuth()
if err != nil {
return err
}
if auth != nil {
opts = append(opts, WithAuthPush(auth))
}
// apply options
o := &git.PushOptions{}
for _, opt := range opts {
opt(o)
}
// push
if err := c.r.Push(o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) Reset(opts ...GitResetOption) (err error) {
// apply options
o := &git.ResetOptions{
Mode: git.HardReset,
}
for _, opt := range opts {
opt(o)
}
// worktree
wt, err := c.r.Worktree()
if err != nil {
return err
}
// reset
if err := wt.Reset(o); err != nil {
return err
}
// clean
if err := wt.Clean(&git.CleanOptions{Dir: true}); err != nil {
return err
}
return nil
}
func (c *GitClient) CreateBranch(branch, remote string, ref *plumbing.Reference) (err error) {
return c.createBranch(branch, remote, ref)
}
func (c *GitClient) CheckoutBranchFromRef(branch string, ref *plumbing.Reference, opts ...GitCheckoutOption) (err error) {
return c.CheckoutBranchWithRemote(branch, "", ref, opts...)
}
func (c *GitClient) CheckoutBranchWithRemoteFromRef(branch, remote string, ref *plumbing.Reference, opts ...GitCheckoutOption) (err error) {
return c.CheckoutBranchWithRemote(branch, remote, ref, opts...)
}
func (c *GitClient) CheckoutBranch(branch string, opts ...GitCheckoutOption) (err error) {
return c.CheckoutBranchWithRemote(branch, "", nil, opts...)
}
func (c *GitClient) CheckoutBranchWithRemote(branch, remote string, ref *plumbing.Reference, opts ...GitCheckoutOption) (err error) {
if remote == "" {
remote = GitRemoteNameOrigin
}
// remote
if _, err := c.r.Remote(remote); err != nil {
return trace.TraceError(err)
}
// check if the branch exists
b, err := c.r.Branch(branch)
if err != nil {
if err == git.ErrBranchNotFound {
// create a new branch if it does not exist
if err := c.createBranch(branch, remote, ref); err != nil {
return err
}
b, err = c.r.Branch(branch)
if err != nil {
return trace.TraceError(err)
}
} else {
return trace.TraceError(err)
}
}
// set branch remote
if remote != "" {
b.Remote = remote
}
// add to options
opts = append(opts, WithBranch(branch))
return c.Checkout(opts...)
}
func (c *GitClient) CheckoutHash(hash string, opts ...GitCheckoutOption) (err error) {
// add to options
opts = append(opts, WithHash(hash))
return c.Checkout(opts...)
}
func (c *GitClient) MoveBranch(from, to string) (err error) {
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
if err := wt.Checkout(&git.CheckoutOptions{
Create: true,
Branch: plumbing.NewBranchReferenceName(to),
}); err != nil {
return trace.TraceError(err)
}
fromRef, err := c.r.Reference(plumbing.NewBranchReferenceName(from), false)
if err != nil {
return trace.TraceError(err)
}
if err := c.r.Storer.RemoveReference(fromRef.Name()); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) CommitAll(msg string, opts ...GitCommitOption) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
// add all files
if _, err := wt.Add("."); err != nil {
return trace.TraceError(err)
}
return c.Commit(msg, opts...)
}
func (c *GitClient) GetLogs() (logs []GitLog, err error) {
iter, err := c.r.Log(&git.LogOptions{
All: true,
})
if err != nil {
return nil, trace.TraceError(err)
}
if err := iter.ForEach(func(commit *object.Commit) error {
log := GitLog{
Hash: commit.Hash.String(),
Msg: commit.Message,
AuthorName: commit.Author.Name,
AuthorEmail: commit.Author.Email,
Timestamp: commit.Author.When,
}
logs = append(logs, log)
return nil
}); err != nil {
return nil, trace.TraceError(err)
}
return
}
func (c *GitClient) GetLogsWithRefs() (logs []GitLog, err error) {
// logs without tags
logs, err = c.GetLogs()
if err != nil {
return nil, err
}
// branches
branches, err := c.GetBranches()
if err != nil {
return nil, err
}
// tags
tags, err := c.GetTags()
if err != nil {
return nil, err
}
// refs
refs := append(branches, tags...)
// refs map
refsMap := map[string][]GitRef{}
for _, ref := range refs {
_, ok := refsMap[ref.Hash]
if !ok {
refsMap[ref.Hash] = []GitRef{}
}
refsMap[ref.Hash] = append(refsMap[ref.Hash], ref)
}
// iterate logs
for i, l := range logs {
refs, ok := refsMap[l.Hash]
if ok {
logs[i].Refs = refs
}
}
return logs, nil
}
func (c *GitClient) GetRepository() (r *git.Repository) {
return c.r
}
func (c *GitClient) GetPath() (path string) {
return c.path
}
func (c *GitClient) SetPath(path string) {
c.path = path
}
func (c *GitClient) GetRemoteUrl() (path string) {
return c.remoteUrl
}
func (c *GitClient) SetRemoteUrl(url string) {
c.remoteUrl = url
}
func (c *GitClient) GetIsMem() (isMem bool) {
return c.isMem
}
func (c *GitClient) SetIsMem(isMem bool) {
c.isMem = isMem
}
func (c *GitClient) GetAuthType() (authType GitAuthType) {
return c.authType
}
func (c *GitClient) SetAuthType(authType GitAuthType) {
c.authType = authType
}
func (c *GitClient) GetUsername() (username string) {
return c.username
}
func (c *GitClient) SetUsername(username string) {
c.username = username
}
func (c *GitClient) GetPassword() (password string) {
return c.password
}
func (c *GitClient) SetPassword(password string) {
c.password = password
}
func (c *GitClient) GetPrivateKey() (key string) {
return c.privateKey
}
func (c *GitClient) SetPrivateKey(key string) {
c.privateKey = key
}
func (c *GitClient) GetPrivateKeyPath() (path string) {
return c.privateKeyPath
}
func (c *GitClient) SetPrivateKeyPath(path string) {
c.privateKeyPath = path
}
func (c *GitClient) GetCurrentBranch() (branch string, err error) {
// attempt to get branch from .git/HEAD
headRefStr, err := c.getHeadRef()
if err != nil {
return "", err
}
// if .git/HEAD points to refs/heads/master, return branch as master
if headRefStr == plumbing.Master.String() {
return GitBranchNameMaster, nil
}
// attempt to get head ref
headRef, err := c.r.Head()
if err != nil {
return "", trace.TraceError(err)
}
if !headRef.Name().IsBranch() {
return "", trace.TraceError(ErrUnableToGetCurrentBranch)
}
return headRef.Name().Short(), nil
}
func (c *GitClient) GetCurrentBranchRef() (ref *GitRef, err error) {
currentBranch, err := c.GetCurrentBranch()
if err != nil {
return nil, err
}
branches, err := c.GetBranches()
if err != nil {
return nil, err
}
for _, branch := range branches {
if branch.Name == currentBranch {
return &branch, nil
}
}
return nil, trace.TraceError(ErrUnableToGetCurrentBranch)
}
func (c *GitClient) GetBranches() (branches []GitRef, err error) {
iter, err := c.r.Branches()
if err != nil {
return nil, trace.TraceError(err)
}
_ = iter.ForEach(func(r *plumbing.Reference) error {
branches = append(branches, GitRef{
Type: GitRefTypeBranch,
Name: r.Name().Short(),
Hash: r.Hash().String(),
})
return nil
})
return branches, nil
}
func (c *GitClient) GetRemoteRefs(remoteName string) (gitRefs []GitRef, err error) {
// remote
r, err := c.r.Remote(remoteName)
if err != nil {
if err == git.ErrRemoteNotFound {
return nil, nil
}
return nil, trace.TraceError(err)
}
// auth
auth, err := c.getGitAuth()
if err != nil {
return nil, err
}
// refs
refs, err := r.List(&git.ListOptions{Auth: auth})
if err != nil {
if err != transport.ErrEmptyRemoteRepository {
return nil, trace.TraceError(err)
}
return nil, nil
}
// iterate refs
for _, ref := range refs {
// ref type
var refType string
if strings.HasPrefix(ref.Name().String(), "refs/heads") {
refType = GitRefTypeBranch
} else if strings.HasPrefix(ref.Name().String(), "refs/tags") {
refType = GitRefTypeTag
} else {
continue
}
// add to branches
gitRefs = append(gitRefs, GitRef{
Type: refType,
Name: ref.Name().Short(),
FullName: ref.Name().String(),
Hash: ref.Hash().String(),
})
}
// logs without tags
logs, err := c.GetLogs()
if err != nil {
return nil, err
}
// logs map
logsMap := map[string]GitLog{}
for _, l := range logs {
logsMap[l.Hash] = l
}
// iterate git refs
for i, gitRef := range gitRefs {
l, ok := logsMap[gitRef.Hash]
if !ok {
continue
}
gitRefs[i].Timestamp = l.Timestamp
}
// sort git refs
sort.Slice(gitRefs, func(i, j int) bool {
return gitRefs[i].Timestamp.Unix() > gitRefs[j].Timestamp.Unix()
})
return gitRefs, nil
}
func (c *GitClient) GetTags() (tags []GitRef, err error) {
iter, err := c.r.Tags()
if err != nil {
return nil, trace.TraceError(err)
}
_ = iter.ForEach(func(r *plumbing.Reference) error {
tags = append(tags, GitRef{
Type: GitRefTypeTag,
Name: r.Name().Short(),
Hash: r.Hash().String(),
})
return nil
})
return tags, nil
}
func (c *GitClient) GetStatus() (statusList []GitFileStatus, err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return nil, trace.TraceError(err)
}
// status
status, err := wt.Status()
if err != nil {
log.Warnf("failed to get worktree status: %v", err)
}
// file status list
var list []GitFileStatus
for filePath, fileStatus := range status {
// file name
fileName := path.Base(filePath)
// file status
s := GitFileStatus{
Path: filePath,
Name: fileName,
IsDir: false,
Staging: c.getStatusString(fileStatus.Staging),
Worktree: c.getStatusString(fileStatus.Worktree),
Extra: fileStatus.Extra,
}
// add to list
list = append(list, s)
}
// sort list ascending
sort.Slice(list, func(i, j int) bool {
return list[i].Path < list[j].Path
})
return list, nil
}
func (c *GitClient) Add(filePath string) (err error) {
// worktree
wt, err := c.r.Worktree()
if err != nil {
return trace.TraceError(err)
}
if _, err := wt.Add(filePath); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) GetRemote(name string) (r *git.Remote, err error) {
return c.r.Remote(name)
}
func (c *GitClient) CreateRemote(cfg *config.RemoteConfig) (r *git.Remote, err error) {
return c.r.CreateRemote(cfg)
}
func (c *GitClient) DeleteRemote(name string) (err error) {
return c.r.DeleteRemote(name)
}
func (c *GitClient) IsRemoteChanged() (ok bool, err error) {
return c.isRemoteChanged()
}
func (c *GitClient) initMem() (err error) {
// validate options
if !c.isMem || c.path == "" {
return trace.TraceError(ErrInvalidOptions)
}
// get storage and worktree
storage, wt := c.getMemStorageAndMemFs(c.path)
// attempt to init
c.r, err = git.Init(storage, wt)
if err != nil {
if err == git.ErrRepositoryAlreadyExists {
// if already exists, attempt to open
c.r, err = git.Open(storage, wt)
if err != nil {
return trace.TraceError(err)
}
} else {
return trace.TraceError(err)
}
}
return nil
}
func (c *GitClient) initFs() (err error) {
// validate options
if c.path == "" {
return trace.TraceError(ErrInvalidOptions)
}
// create directory if not exists
_, err = os.Stat(c.path)
if err != nil {
if err := os.MkdirAll(c.path, os.ModePerm); err != nil {
return trace.TraceError(err)
}
err = nil
}
// try to open repo
c.r, err = git.PlainOpen(c.path)
if err == git.ErrRepositoryNotExists {
// repo not exists, init
c.r, err = git.PlainInit(c.path, false)
if err != nil {
return trace.TraceError(err)
}
} else if err != nil {
// error
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) clone() (err error) {
// validate
if c.remoteUrl == "" {
return trace.TraceError(ErrUnableToCloneWithEmptyRemoteUrl)
}
// auth
auth, err := c.getGitAuth()
if err != nil {
return err
}
// options
o := &git.CloneOptions{
URL: c.remoteUrl,
Auth: auth,
}
// clone
if _, err := git.PlainClone(c.path, false, o); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *GitClient) getInitType() (res GitInitType) {
if c.isMem {
return GitInitTypeMem
} else {
return GitInitTypeFs
}
}
func (c *GitClient) createRemote(remoteName string, url string) (err error) {
_, err = c.r.CreateRemote(&config.RemoteConfig{
Name: remoteName,
URLs: []string{url},
})
if err != nil {
return trace.TraceError(err)
}
return
}
func (c *GitClient) getMemStorageAndMemFs(key string) (storage *memory.Storage, fs billy.Filesystem) {
// storage
storageItem, ok := GitMemStorages.Load(key)
if !ok {
storage = memory.NewStorage()
GitMemStorages.Store(key, storage)
} else {
switch storageItem.(type) {
case *memory.Storage:
storage = storageItem.(*memory.Storage)
default:
storage = memory.NewStorage()
GitMemStorages.Store(key, storage)
}
}
// file system
fsItem, ok := GitMemFileSystem.Load(key)
if !ok {
fs = memfs.New()
GitMemFileSystem.Store(key, fs)
} else {
switch fsItem.(type) {
case billy.Filesystem:
fs = fsItem.(billy.Filesystem)
default:
fs = memfs.New()
GitMemFileSystem.Store(key, fs)
}
}
return storage, fs
}
func (c *GitClient) getGitAuth() (auth transport.AuthMethod, err error) {
switch c.authType {
case GitAuthTypeNone:
return nil, nil
case GitAuthTypeHTTP:
if c.username == "" && c.password == "" {
return nil, nil
}
auth = &http.BasicAuth{
Username: c.username,
Password: c.password,
}
return auth, nil
case GitAuthTypeSSH:
var privateKeyData []byte
if c.privateKey != "" {
// private key content
privateKeyData = []byte(c.privateKey)
} else if c.privateKeyPath != "" {
// read from private key file
privateKeyData, err = ioutil.ReadFile(c.privateKeyPath)
if err != nil {
return nil, trace.TraceError(err)
}
} else {
// no private key
return nil, nil
}
var signer ssh.Signer
if c.password != "" {
signer, err = ssh.ParsePrivateKeyWithPassphrase(privateKeyData, []byte(c.password))
} else {
signer, err = ssh.ParsePrivateKey(privateKeyData)
}
if err != nil {
return nil, trace.TraceError(err)
}
auth = &gitssh.PublicKeys{
User: c.username,
Signer: signer,
HostKeyCallbackHelper: gitssh.HostKeyCallbackHelper{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
},
}
return auth, nil
default:
return nil, trace.TraceError(ErrInvalidAuthType)
}
}
func (c *GitClient) getHeadRef() (ref string, err error) {
wt, err := c.r.Worktree()
if err != nil {
return "", trace.TraceError(err)
}
fh, err := wt.Filesystem.Open(path.Join(".git", "HEAD"))
if err != nil {
return "", trace.TraceError(err)
}
data, err := ioutil.ReadAll(fh)
if err != nil {
return "", trace.TraceError(err)
}
m := headRefRegexp.FindStringSubmatch(string(data))
if len(m) < 2 {
return "", trace.TraceError(ErrInvalidHeadRef)
}
return m[1], nil
}
func (c *GitClient) getStatusString(statusCode git.StatusCode) (code string) {
return string(statusCode)
//switch statusCode {
//}
//Unmodified StatusCode = ' '
//Untracked StatusCode = '?'
//Modified StatusCode = 'M'
//Added StatusCode = 'A'
//Deleted StatusCode = 'D'
//Renamed StatusCode = 'R'
//Copied StatusCode = 'C'
//UpdatedButUnmerged StatusCode = 'U'
}
func (c *GitClient) getDirPaths(filePath string) (paths []string) {
pathItems := strings.Split(filePath, "/")
var items []string
for i, pathItem := range pathItems {
if i == len(pathItems)-1 {
continue
}
items = append(items, pathItem)
dirPath := strings.Join(items, "/")
paths = append(paths, dirPath)
}
return paths
}
func (c *GitClient) createBranch(branch, remote string, ref *plumbing.Reference) (err error) {
// create a new branch if it does not exist
cfg := config.Branch{
Name: branch,
Remote: remote,
}
if err := c.r.CreateBranch(&cfg); err != nil {
return err
}
// if ref is nil
if ref == nil {
// try to set to remote ref of branch first
ref, err = c.getBranchHashRef(branch, remote)
// if no matched remote branch, set to HEAD
if err == ErrNoMatchedRemoteBranch {
ref, err = c.r.Head()
if err != nil {
return trace.TraceError(err)
}
}
// error
if err != nil {
return trace.TraceError(err)
}
}
// branch reference name
branchRefName := plumbing.NewBranchReferenceName(branch)
// branch reference
branchRef := plumbing.NewHashReference(branchRefName, ref.Hash())
// set HEAD to branch reference
if err := c.r.Storer.SetReference(branchRef); err != nil {
return err
}
return nil
}
func (c *GitClient) getBranchHashRef(branch, remote string) (hashRef *plumbing.Reference, err error) {
refs, err := c.GetRemoteRefs(remote)
if err != nil {
return nil, err
}
var branchRef *GitRef
for _, r := range refs {
if r.Name == branch {
branchRef = &r
break
}
}
if branchRef == nil {
return nil, ErrNoMatchedRemoteBranch
}
branchHashRef := plumbing.NewHashReference(plumbing.NewBranchReferenceName(branch), plumbing.NewHash(branchRef.Hash))
return branchHashRef, nil
}
func (c *GitClient) isRemoteChanged() (ok bool, err error) {
b, err := c.GetCurrentBranchRef()
if err != nil {
return false, err
}
refs, err := c.GetRemoteRefs(GitRemoteNameOrigin)
if err != nil {
return false, err
}
for _, r := range refs {
if r.Name == b.Name {
return r.Hash != b.Hash, nil
}
}
return false, nil
}
func NewGitClient(opts ...GitOption) (c *GitClient, err error) {
// client
c = &GitClient{