-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
739 lines (617 loc) · 16.1 KB
/
repo.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
package gitw
import (
"strings"
"github.com/gookit/gitw/brinfo"
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/errorx"
"github.com/gookit/goutil/fsutil"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/strutil"
"github.com/gookit/goutil/sysutil/cmdr"
)
const (
cacheRemoteNames = "rmtNames"
cacheRemoteInfos = "rmtInfos"
cacheLastCommitID = "lastCID"
cacheCurrentBranch = "curBranch"
cacheMaxTagVersion = "maxVersion"
cacheUpstreamPath = "upstreamTo"
)
// RepoConfig struct
type RepoConfig struct {
// DefaultBranch name, default is DefaultBranchName
DefaultBranch string
// DefaultRemote name, default is DefaultRemoteName
DefaultRemote string
}
func newDefaultCfg() *RepoConfig {
return &RepoConfig{
DefaultBranch: DefaultBranchName,
DefaultRemote: DefaultRemoteName,
}
}
// Repo struct
type Repo struct {
gw *GitWrap
// the repo dir
dir string
// save last error
err error
// config
cfg *RepoConfig
// status info
statusInfo *StatusInfo
// branch infos for the repo
branchInfos *BranchInfos
// remoteNames
remoteNames []string
// remoteInfosMp
//
// Example:
// {origin: {fetch: remote info, push: remote info}}
remoteInfosMp map[string]RemoteInfos
// cache some information of the repo
cache maputil.Data
}
// NewRepo create Repo object
func NewRepo(dir string) *Repo {
return &Repo{
dir: dir,
cfg: newDefaultCfg(),
// init gw
gw: NewWithWorkdir(dir),
// cache some information
cache: make(maputil.Data, 8),
}
}
// WithFn new repo self config func
func (r *Repo) WithFn(fn func(r *Repo)) *Repo {
fn(r)
return r
}
// WithConfig new repo config
func (r *Repo) WithConfig(cfg *RepoConfig) *Repo {
r.cfg = cfg
return r
}
// WithConfigFn new repo config func
func (r *Repo) WithConfigFn(fn func(cfg *RepoConfig)) *Repo {
fn(r.cfg)
return r
}
// PrintCmdOnExec settings.
func (r *Repo) PrintCmdOnExec() *Repo {
r.gw.BeforeExec = PrintCmdline
return r
}
// SetDryRun settings.
func (r *Repo) SetDryRun(dr bool) *Repo {
r.gw.DryRun = dr
return r
}
// Init run git init for the repo dir.
func (r *Repo) Init() error {
return r.gw.Init().Run()
}
// IsInited is init git repo dir
func (r *Repo) IsInited() bool {
return r.gw.IsGitRepo()
}
// Info get repo information
func (r *Repo) Info() *RepoInfo {
ri := &RepoInfo{
Dir: r.dir,
Name: fsutil.Name(r.dir),
// more
Branch: r.CurBranchName(),
Version: r.LargestTag(),
LastHash: r.LastAbbrevID(),
Upstream: r.UpstreamPath(),
}
rt := r.loadRemoteInfos().FirstRemoteInfo()
if rt == nil {
return ri
}
ri.Name = rt.Repo
ri.Path = rt.Path()
ri.URL = rt.URLOrBuild()
remotes := make(map[string]string)
for name, infos := range r.remoteInfosMp {
remotes[name] = infos.FetchInfo().URL
}
ri.Remotes = remotes
return ri
}
// FetchAll fetch all remote branches
func (r *Repo) FetchAll(args ...string) error {
return r.gw.Cmd("fetch", "--all").AddArgs(args).Run()
}
// -------------------------------------------------
// repo tags
// -------------------------------------------------
// ShaHead keywords
const ShaHead = "HEAD"
// some special keywords for match tag
const (
TagLast = "last"
TagPrev = "prev"
TagHead = "head"
)
// enum type value constants for fetch tags
const (
RefNameTagType int = iota
CreatorDateTagType
DescribeTagType
)
// AutoMatchTag by given sha or tag name
func (r *Repo) AutoMatchTag(sha string) string {
return r.AutoMatchTagByType(sha, RefNameTagType)
}
// AutoMatchTagByType by given sha or tag name.
func (r *Repo) AutoMatchTagByType(sha string, tagType int) string {
switch strings.ToLower(sha) {
case TagLast:
return r.LargestTagByTagType(tagType)
case TagPrev:
return r.TagSecondMaxByTagType(tagType)
case TagHead:
return ShaHead
default:
return sha
}
}
// MaxTag get max tag version of the repo
func (r *Repo) MaxTag() string {
return r.LargestTag()
}
// LargestTag get max tag version of the repo
func (r *Repo) LargestTag() string {
tagVer := r.cache.Str(cacheMaxTagVersion)
if len(tagVer) > 0 {
return tagVer
}
tags := r.TagsSortedByRefName()
if len(tags) > 0 {
r.cache.Set(cacheMaxTagVersion, tags[0])
return tags[0]
}
return ""
}
// LargestTagByTagType get max tag version of the repo by tag_type
func (r *Repo) LargestTagByTagType(tagType int) string {
tagVer := r.cache.Str(cacheMaxTagVersion)
if len(tagVer) > 0 {
return tagVer
}
tags := make([]string, 0, 2)
switch tagType {
case CreatorDateTagType:
tags = append(tags, r.TagsSortedByCreatorDate()...)
case DescribeTagType:
tags = append(tags, r.TagByDescribe(""))
default:
tags = append(tags, r.TagsSortedByRefName()...)
}
if len(tags) > 0 {
r.cache.Set(cacheMaxTagVersion, tags[0])
return tags[0]
}
return ""
}
// PrevMaxTag get second-largest tag of the repo
func (r *Repo) PrevMaxTag() string {
return r.TagSecondMax()
}
// TagSecondMax get second-largest tag of the repo
func (r *Repo) TagSecondMax() string {
tags := r.TagsSortedByRefName()
if len(tags) > 1 {
return tags[1]
}
return ""
}
// TagSecondMaxByTagType get second-largest tag of the repo by tag_type
func (r *Repo) TagSecondMaxByTagType(tagType int) string {
tags := make([]string, 0, 2)
switch tagType {
case CreatorDateTagType:
tags = append(tags, r.TagsSortedByCreatorDate()...)
case DescribeTagType:
current := r.TagByDescribe("")
if len(current) != 0 {
tags = append(tags, current, r.TagByDescribe(current))
} else {
tags = append(tags, current)
}
default:
tags = append(tags, r.TagsSortedByRefName()...)
}
if len(tags) > 1 {
return tags[1]
}
return ""
}
// TagsSortedByRefName get repo tags list
func (r *Repo) TagsSortedByRefName() []string {
str, err := r.gw.Tag("-l", "--sort=-version:refname").Output()
if err != nil {
r.setErr(err)
return nil
}
return cmdr.OutputLines(str)
}
// TagsSortedByCreatorDate get repo tags list by creator date sort
func (r *Repo) TagsSortedByCreatorDate() []string {
str, err := r.gw.
Tag("-l", "--sort=-creatordate", "--format=%(refname:strip=2)").
Output()
if err != nil {
r.setErr(err)
return nil
}
return cmdr.OutputLines(str)
}
// TagByDescribe get tag by describe command. if current not empty, will exclude it.
func (r *Repo) TagByDescribe(current string) (ver string) {
var err error
if len(current) == 0 {
ver, err = r.gw.Describe("--tags", "--abbrev=0").Output()
} else {
ver, err = r.gw.
Describe("--tags", "--abbrev=0").
Argf("tags/%s^", current).
Output()
}
if err != nil {
r.setErr(err)
return ""
}
return cmdr.FirstLine(ver)
}
// Tags get repo tags list
func (r *Repo) Tags() []string {
ss, err := r.gw.Tag("-l").OutputLines()
if err != nil {
r.setErr(err)
return nil
}
return ss
}
// -------------------------------------------------
// repo git log
// -------------------------------------------------
// LastAbbrevID get last abbrev commit ID, len is 7
func (r *Repo) LastAbbrevID() string {
cid := r.LastCommitID()
if cid == "" {
return ""
}
return strutil.Substr(cid, 0, 7)
}
// LastCommitID value
func (r *Repo) LastCommitID() string {
lastCID := r.cache.Str(cacheLastCommitID)
if len(lastCID) > 0 {
return lastCID
}
// by: git log -1 --format='%H'
lastCID, err := r.gw.Log("-1", "--format=%H").Output()
if err != nil {
r.setErr(err)
return ""
}
r.cache.Set(cacheLastCommitID, lastCID)
return lastCID
}
// -------------------------------------------------
// repo status
// -------------------------------------------------
// StatusInfo get status info of the repo
func (r *Repo) StatusInfo() *StatusInfo {
if r.statusInfo == nil {
r.statusInfo = &StatusInfo{}
lines, err := r.gw.Status("-bs", "-u").OutputLines()
if err != nil {
r.setErr(err)
return nil
}
r.statusInfo.FromLines(lines)
}
return r.statusInfo
}
// -------------------------------------------------
// repo branch
// -------------------------------------------------
func (r *Repo) HasBranch(branch string, remote ...string) bool {
return r.loadBranchInfos().branchInfos.IsExists(branch, remote...)
}
func (r *Repo) HasRemoteBranch(branch, remote string) bool {
return r.loadBranchInfos().branchInfos.HasRemote(branch, remote)
}
func (r *Repo) HasLocalBranch(branch string) bool {
return r.loadBranchInfos().branchInfos.HasLocal(branch)
}
// BranchInfos get branch infos of the repo
func (r *Repo) BranchInfos() *BranchInfos {
return r.loadBranchInfos().branchInfos
}
// ReloadBranches reload branch infos of the repo
func (r *Repo) ReloadBranches() *BranchInfos {
r.branchInfos = nil
return r.loadBranchInfos().branchInfos
}
// CurBranchInfo get current branch info of the repo
func (r *Repo) CurBranchInfo() *BranchInfo {
return r.loadBranchInfos().branchInfos.Current()
}
// BranchInfo find branch info by name, if remote is empty, find local branch
func (r *Repo) BranchInfo(branch string, remote ...string) *BranchInfo {
return r.loadBranchInfos().branchInfos.GetByName(branch, remote...)
}
// SearchBranchV2 search branch infos by keywords
func (r *Repo) SearchBranchV2(m brinfo.BranchMatcher, opt *SearchOpt) []*BranchInfo {
return r.loadBranchInfos().branchInfos.SearchV2(m, opt)
}
// SearchBranches search branch infos by name
func (r *Repo) SearchBranches(name string, flag uint8) []*BranchInfo {
return r.loadBranchInfos().branchInfos.Search(name, flag)
}
// load branch infos
func (r *Repo) loadBranchInfos() *Repo {
// has loaded
if r.branchInfos != nil {
return r
}
str, err := r.gw.Branch("-v", "--all").Output()
if err != nil {
r.setErr(err)
r.branchInfos = EmptyBranchInfos()
return r
}
r.branchInfos = NewBranchInfos(str).Parse()
return r
}
// HeadBranchName return current branch name
func (r *Repo) HeadBranchName() string { return r.CurBranchName() }
// CurBranchName return current branch name
func (r *Repo) CurBranchName() string {
brName := r.cache.Str(cacheCurrentBranch)
if len(brName) > 0 {
return brName
}
// cat .git/HEAD
// OR
// git branch --show-current // on high version git
// OR
// git symbolic-ref HEAD // out: refs/heads/fea_pref
// git symbolic-ref --short -q HEAD // on checkout tag, run will error
// Or
// git rev-parse --abbrev-ref -q HEAD // on init project, will error
str := r.gw.Branch("--show-current").SafeOutput()
if len(str) == 0 {
str, r.err = r.gw.RevParse("--abbrev-ref", "-q", "HEAD").Output()
if r.err != nil {
return ""
}
}
// eg: fea_pref
brName = cmdr.FirstLine(str)
r.cache.Set(cacheCurrentBranch, brName)
return brName
}
// SetUpstreamTo set the branch upstream remote branch.
// If `localBranch` is empty, will use `branch` as `localBranch`
//
// CMD:
//
// git branch --set-upstream-to=<remote>/<branch> <local_branch>
func (r *Repo) SetUpstreamTo(remote, branch string, localBranch ...string) error {
localBr := branch
if len(localBranch) > 0 {
localBr = localBranch[0]
}
return r.gw.Cmd("branch").
Argf("--set-upstream-to=%s/%s", remote, branch).
AddArg(localBr).
Run()
}
// BranchDelete handle
func (r *Repo) BranchDelete(name string, remote string) error {
if len(remote) > 0 {
return r.gw.Push(remote, "--delete", name).Run()
}
return r.gw.Branch("-D", name).Run()
}
// -------------------------------------------------
// repo remote
// -------------------------------------------------
// HasRemote check
func (r *Repo) HasRemote(name string) bool {
return arrutil.StringsHas(r.RemoteNames(), name)
}
// RemoteNames get
func (r *Repo) RemoteNames() []string {
return r.loadRemoteInfos().remoteNames
}
// RemoteLines get like: {origin: url, other: url}
func (r *Repo) RemoteLines() map[string]string {
remotes := make(map[string]string)
for name, infos := range r.loadRemoteInfos().remoteInfosMp {
remotes[name] = infos.FetchInfo().URL
}
return remotes
}
// UpstreamPath get current upstream remote and branch.
// Returns like: origin/main
//
// CMD:
//
// git rev-parse --abbrev-ref @{u}
func (r *Repo) UpstreamPath() string {
path := r.cache.Str(cacheUpstreamPath)
// RUN: git rev-parse --abbrev-ref @{u}
if path == "" {
path = r.Git().RevParse("--abbrev-ref", "@{u}").SafeOutput()
r.cache.Set(cacheUpstreamPath, strings.TrimSpace(path))
}
return path
}
// UpstreamRemote get current upstream remote name.
func (r *Repo) UpstreamRemote() string {
return strutil.OrHandle(r.UpstreamPath(), func(s string) string {
remote, _ := strutil.QuietCut(s, "/")
return remote
})
}
// UpstreamBranch get current upstream branch name.
func (r *Repo) UpstreamBranch() string {
return strutil.OrHandle(r.UpstreamPath(), func(s string) string {
_, branch := strutil.QuietCut(s, "/")
return branch
})
}
// RemoteInfos get by remote name
func (r *Repo) RemoteInfos(remote string) RemoteInfos {
r.loadRemoteInfos()
if len(r.remoteInfosMp) == 0 {
return nil
}
return r.remoteInfosMp[remote]
}
// DefaultRemoteInfo get
func (r *Repo) DefaultRemoteInfo(typ ...string) *RemoteInfo {
return r.RemoteInfo(r.cfg.DefaultRemote, typ...)
}
// FirstRemoteInfo get
func (r *Repo) FirstRemoteInfo(typ ...string) *RemoteInfo {
return r.RandomRemoteInfo(typ...)
}
// RandomRemoteInfo get
func (r *Repo) RandomRemoteInfo(typ ...string) *RemoteInfo {
r.loadRemoteInfos()
if len(r.remoteNames) == 0 {
return nil
}
return r.RemoteInfo(r.remoteNames[0], typ...)
}
// RemoteInfo get by remote name and type.
//
// - If remote is empty, will return default remote
// - If typ is empty, will return random type info.
//
// Usage:
//
// ri := RemoteInfo("origin")
// ri = RemoteInfo("origin", "push")
func (r *Repo) RemoteInfo(remote string, typ ...string) *RemoteInfo {
riMp := r.RemoteInfos(strutil.OrElse(remote, r.cfg.DefaultRemote))
if len(riMp) == 0 {
return nil
}
if len(typ) > 0 {
return riMp[typ[0]]
}
// get random type info
for _, info := range riMp {
return info
}
return nil // should never happen
}
// AllRemoteInfos get
func (r *Repo) AllRemoteInfos() map[string]RemoteInfos {
return r.loadRemoteInfos().remoteInfosMp
}
// AllRemoteInfos get
func (r *Repo) loadRemoteInfos() *Repo {
// has loaded
if len(r.remoteNames) > 0 {
return r
}
str, err := r.gw.Remote("-v").Output()
if err != nil {
r.setErr(err)
return r
}
// origin https://github.com/gookit/gitw.git (fetch)
// origin https://github.com/gookit/gitw.git (push)
rmp := make(map[string]RemoteInfos, 2)
str = strings.ReplaceAll(strings.TrimSpace(str), "\t", " ")
names := make([]string, 0, 2)
lines := strings.Split(str, "\n")
for _, line := range lines {
// origin https://github.com/gookit/gitw (push)
ss := strutil.SplitN(line, " ", 3)
if len(ss) < 3 {
r.setErr(errorx.Rawf("invalid remote line: %s", line))
continue
}
name, url, typ := ss[0], ss[1], ss[2]
typ = strings.Trim(typ, "()")
// create instance
ri, err := NewRemoteInfo(name, url, typ)
if err != nil {
r.setErr(err)
continue
}
rs, ok := rmp[name]
if !ok {
rs = make(RemoteInfos, 2)
}
// add
rs[typ] = ri
rmp[name] = rs
if !arrutil.StringsHas(names, name) {
names = append(names, name)
}
}
if len(names) > 0 {
r.remoteNames = names
r.remoteInfosMp = rmp
}
return r
}
// reset last error
// func (r *Repo) resetErr() {
// r.err = nil
// }
// ReadConfig contents from REPO/.git/config
func (r *Repo) ReadConfig() []byte {
return fsutil.GetContents(fsutil.JoinPaths(r.dir, GitDir, ConfFile))
}
// ReadHEAD contents from REPO/.git/HEAD
func (r *Repo) ReadHEAD() []byte {
return fsutil.GetContents(fsutil.JoinPaths(r.dir, GitDir, HeadFile))
}
// -------------------------------------------------
// helper methods
// -------------------------------------------------
// IsValid check the dir is git repo
func (r *Repo) IsValid() bool { return r.IsGitRepo() }
// IsGitRepo check the dir is git repo
func (r *Repo) IsGitRepo() bool { return r.gw.IsGitRepo() }
// reset last error
func (r *Repo) setErr(err error) {
if err != nil {
r.err = err
}
}
// Err get last error
func (r *Repo) Err() error {
return r.err
}
// Dir get repo dir
func (r *Repo) Dir() string {
return r.dir
}
// Git get git wrapper
func (r *Repo) Git() *GitWrap {
return r.gw
}
// Cmd new git command wrapper
func (r *Repo) Cmd(name string, args ...string) *GitWrap {
return r.gw.Cmd(name, args...)
}
// QuickRun git command
func (r *Repo) QuickRun(cmd string, args ...string) error {
return r.gw.Cmd(cmd, args...).Run()
}