forked from git-lfs/git-lfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
1370 lines (1193 loc) · 37.5 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 git contains various commands that shell out to git
// NOTE: Subject to change, do not rely on this package from outside git-lfs source
package git
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
lfserrors "github.com/git-lfs/git-lfs/errors"
"github.com/git-lfs/git-lfs/subprocess"
"github.com/git-lfs/git-lfs/tools"
"github.com/rubyist/tracerx"
)
type RefType int
const (
RefTypeLocalBranch = RefType(iota)
RefTypeRemoteBranch = RefType(iota)
RefTypeLocalTag = RefType(iota)
RefTypeRemoteTag = RefType(iota)
RefTypeHEAD = RefType(iota) // current checkout
RefTypeOther = RefType(iota) // stash or unknown
// A ref which can be used as a placeholder for before the first commit
// Equivalent to git mktree < /dev/null, useful for diffing before first commit
RefBeforeFirstCommit = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
)
// Prefix returns the given RefType's prefix, "refs/heads", "ref/remotes",
// etc. It returns an additional value of either true/false, whether or not this
// given ref type has a prefix.
//
// If the RefType is unrecognized, Prefix() will panic.
func (t RefType) Prefix() (string, bool) {
switch t {
case RefTypeLocalBranch:
return "refs/heads", true
case RefTypeRemoteBranch:
return "refs/remotes", true
case RefTypeLocalTag:
return "refs/tags", true
case RefTypeRemoteTag:
return "refs/remotes/tags", true
case RefTypeHEAD:
return "", false
case RefTypeOther:
return "", false
default:
panic(fmt.Sprintf("git: unknown RefType %d", t))
}
}
// A git reference (branch, tag etc)
type Ref struct {
Name string
Type RefType
Sha string
}
// Some top level information about a commit (only first line of message)
type CommitSummary struct {
Sha string
ShortSha string
Parents []string
CommitDate time.Time
AuthorDate time.Time
AuthorName string
AuthorEmail string
CommitterName string
CommitterEmail string
Subject string
}
// Prepend Git config instructions to disable Git LFS filter
func gitConfigNoLFS(args ...string) []string {
// Before git 2.8, setting filters to blank causes lots of warnings, so use cat instead (slightly slower)
// Also pre 2.2 it failed completely. We used to use it anyway in git 2.2-2.7 and
// suppress the messages in stderr, but doing that with standard StderrPipe suppresses
// the git clone output (git thinks it's not a terminal) and makes it look like it's
// not working. You can get around that with https://github.com/kr/pty but that
// causes difficult issues with passing through Stdin for login prompts
// This way is simpler & more practical.
filterOverride := ""
if !Config.IsGitVersionAtLeast("2.8.0") {
filterOverride = "cat"
}
return append([]string{
"-c", fmt.Sprintf("filter.lfs.smudge=%v", filterOverride),
"-c", fmt.Sprintf("filter.lfs.clean=%v", filterOverride),
"-c", "filter.lfs.process=",
"-c", "filter.lfs.required=false",
}, args...)
}
// Invoke Git with disabled LFS filters
func gitNoLFS(args ...string) *subprocess.Cmd {
return subprocess.ExecCommand("git", gitConfigNoLFS(args...)...)
}
func gitNoLFSSimple(args ...string) (string, error) {
return subprocess.SimpleExec("git", gitConfigNoLFS(args...)...)
}
func gitNoLFSBuffered(args ...string) (*subprocess.BufferedCmd, error) {
return subprocess.BufferedExec("git", gitConfigNoLFS(args...)...)
}
// Invoke Git with enabled LFS filters
func git(args ...string) *subprocess.Cmd {
return subprocess.ExecCommand("git", args...)
}
func gitSimple(args ...string) (string, error) {
return subprocess.SimpleExec("git", args...)
}
func gitBuffered(args ...string) (*subprocess.BufferedCmd, error) {
return subprocess.BufferedExec("git", args...)
}
func CatFile() (*subprocess.BufferedCmd, error) {
return gitNoLFSBuffered("cat-file", "--batch-check")
}
func DiffIndex(ref string, cached bool) (*bufio.Scanner, error) {
args := []string{"diff-index", "-M"}
if cached {
args = append(args, "--cached")
}
args = append(args, ref)
cmd, err := gitBuffered(args...)
if err != nil {
return nil, err
}
if err = cmd.Stdin.Close(); err != nil {
return nil, err
}
return bufio.NewScanner(cmd.Stdout), nil
}
func HashObject(r io.Reader) (string, error) {
cmd := gitNoLFS("hash-object", "--stdin")
cmd.Stdin = r
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("Error building Git blob OID: %s", err)
}
return string(bytes.TrimSpace(out)), nil
}
func Log(args ...string) (*subprocess.BufferedCmd, error) {
logArgs := append([]string{"log"}, args...)
return gitNoLFSBuffered(logArgs...)
}
func LsRemote(remote, remoteRef string) (string, error) {
if remote == "" {
return "", errors.New("remote required")
}
if remoteRef == "" {
return gitNoLFSSimple("ls-remote", remote)
}
return gitNoLFSSimple("ls-remote", remote, remoteRef)
}
func LsTree(ref string) (*subprocess.BufferedCmd, error) {
return gitNoLFSBuffered(
"ls-tree",
"-r", // recurse
"-l", // report object size (we'll need this)
"-z", // null line termination
"--full-tree", // start at the root regardless of where we are in it
ref,
)
}
func ResolveRef(ref string) (*Ref, error) {
outp, err := gitNoLFSSimple("rev-parse", ref, "--symbolic-full-name", ref)
if err != nil {
return nil, fmt.Errorf("Git can't resolve ref: %q", ref)
}
if outp == "" {
return nil, fmt.Errorf("Git can't resolve ref: %q", ref)
}
lines := strings.Split(outp, "\n")
fullref := &Ref{Sha: lines[0]}
if len(lines) == 1 {
// ref is a sha1 and has no symbolic-full-name
fullref.Name = lines[0] // fullref.Sha
fullref.Type = RefTypeOther
return fullref, nil
}
// parse the symbolic-full-name
fullref.Type, fullref.Name = ParseRefToTypeAndName(lines[1])
return fullref, nil
}
func ResolveRefs(refnames []string) ([]*Ref, error) {
refs := make([]*Ref, len(refnames))
for i, name := range refnames {
ref, err := ResolveRef(name)
if err != nil {
return refs, err
}
refs[i] = ref
}
return refs, nil
}
func CurrentRef() (*Ref, error) {
return ResolveRef("HEAD")
}
func CurrentRemoteRef() (*Ref, error) {
remoteref, err := RemoteRefNameForCurrentBranch()
if err != nil {
return nil, err
}
return ResolveRef(remoteref)
}
// RemoteForCurrentBranch returns the name of the remote that the current branch is tracking
func RemoteForCurrentBranch() (string, error) {
ref, err := CurrentRef()
if err != nil {
return "", err
}
remote := RemoteForBranch(ref.Name)
if remote == "" {
return "", fmt.Errorf("remote not found for branch %q", ref.Name)
}
return remote, nil
}
// RemoteRefForCurrentBranch returns the full remote ref (refs/remotes/{remote}/{remotebranch})
// that the current branch is tracking.
func RemoteRefNameForCurrentBranch() (string, error) {
ref, err := CurrentRef()
if err != nil {
return "", err
}
if ref.Type == RefTypeHEAD || ref.Type == RefTypeOther {
return "", errors.New("not on a branch")
}
remote := RemoteForBranch(ref.Name)
if remote == "" {
return "", fmt.Errorf("remote not found for branch %q", ref.Name)
}
remotebranch := RemoteBranchForLocalBranch(ref.Name)
return fmt.Sprintf("refs/remotes/%s/%s", remote, remotebranch), nil
}
// RemoteForBranch returns the remote name that a given local branch is tracking (blank if none)
func RemoteForBranch(localBranch string) string {
return Config.Find(fmt.Sprintf("branch.%s.remote", localBranch))
}
// RemoteBranchForLocalBranch returns the name (only) of the remote branch that the local branch is tracking
// If no specific branch is configured, returns local branch name
func RemoteBranchForLocalBranch(localBranch string) string {
// get remote ref to track, may not be same name
merge := Config.Find(fmt.Sprintf("branch.%s.merge", localBranch))
if strings.HasPrefix(merge, "refs/heads/") {
return merge[11:]
} else {
return localBranch
}
}
func RemoteList() ([]string, error) {
cmd := gitNoLFS("remote")
outp, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("Failed to call git remote: %v", err)
}
cmd.Start()
defer cmd.Wait()
scanner := bufio.NewScanner(outp)
var ret []string
for scanner.Scan() {
ret = append(ret, strings.TrimSpace(scanner.Text()))
}
return ret, nil
}
// Refs returns all of the local and remote branches and tags for the current
// repository. Other refs (HEAD, refs/stash, git notes) are ignored.
func LocalRefs() ([]*Ref, error) {
cmd := gitNoLFS("show-ref", "--heads", "--tags")
outp, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("Failed to call git show-ref: %v", err)
}
var refs []*Ref
if err := cmd.Start(); err != nil {
return refs, err
}
scanner := bufio.NewScanner(outp)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
parts := strings.SplitN(line, " ", 2)
if len(parts) != 2 || len(parts[0]) != 40 || len(parts[1]) < 1 {
tracerx.Printf("Invalid line from git show-ref: %q", line)
continue
}
rtype, name := ParseRefToTypeAndName(parts[1])
if rtype != RefTypeLocalBranch && rtype != RefTypeLocalTag {
continue
}
refs = append(refs, &Ref{name, rtype, parts[0]})
}
return refs, cmd.Wait()
}
// UpdateRef moves the given ref to a new sha with a given reason (and creates a
// reflog entry, if a "reason" was provided). It returns an error if any were
// encountered.
func UpdateRef(ref *Ref, to []byte, reason string) error {
return UpdateRefIn("", ref, to, reason)
}
// UpdateRef moves the given ref to a new sha with a given reason (and creates a
// reflog entry, if a "reason" was provided). It operates within the given
// working directory "wd". It returns an error if any were encountered.
func UpdateRefIn(wd string, ref *Ref, to []byte, reason string) error {
var refspec string
if prefix, ok := ref.Type.Prefix(); ok {
refspec = fmt.Sprintf("%s/%s", prefix, ref.Name)
} else {
refspec = ref.Name
}
args := []string{"update-ref", refspec, hex.EncodeToString(to)}
if len(reason) > 0 {
args = append(args, "-m", reason)
}
cmd := gitNoLFS(args...)
cmd.Dir = wd
return cmd.Run()
}
// ValidateRemote checks that a named remote is valid for use
// Mainly to check user-supplied remotes & fail more nicely
func ValidateRemote(remote string) error {
remotes, err := RemoteList()
if err != nil {
return err
}
for _, r := range remotes {
if r == remote {
return nil
}
}
if err = ValidateRemoteURL(remote); err == nil {
return nil
}
return fmt.Errorf("Invalid remote name: %q", remote)
}
// ValidateRemoteURL checks that a string is a valid Git remote URL
func ValidateRemoteURL(remote string) error {
u, _ := url.Parse(remote)
if u == nil || u.Scheme == "" {
// This is either an invalid remote name (maybe the user made a typo
// when selecting a named remote) or a bare SSH URL like
// "x@y.com:path/to/resource.git". Guess that this is a URL in the latter
// form if the string contains a colon ":", and an invalid remote if it
// does not.
if strings.Contains(remote, ":") {
return nil
} else {
return fmt.Errorf("Invalid remote name: %q", remote)
}
}
switch u.Scheme {
case "ssh", "http", "https", "git":
return nil
default:
return fmt.Errorf("Invalid remote url protocol %q in %q", u.Scheme, remote)
}
}
// DefaultRemote returns the default remote based on:
// 1. The currently tracked remote branch, if present
// 2. "origin", if defined
// 3. Any other SINGLE remote defined in .git/config
// Returns an error if all of these fail, i.e. no tracked remote branch, no
// "origin", and either no remotes defined or 2+ non-"origin" remotes
func DefaultRemote() (string, error) {
tracked, err := RemoteForCurrentBranch()
if err == nil {
return tracked, nil
}
// Otherwise, check what remotes are defined
remotes, err := RemoteList()
if err != nil {
return "", err
}
switch len(remotes) {
case 0:
return "", errors.New("No remotes defined")
case 1: // always use a single remote whether it's origin or otherwise
return remotes[0], nil
default:
for _, remote := range remotes {
// Use origin if present
if remote == "origin" {
return remote, nil
}
}
}
return "", errors.New("Unable to pick default remote, too ambiguous")
}
func UpdateIndexFromStdin() *subprocess.Cmd {
return git("update-index", "-q", "--refresh", "--stdin")
}
type gitConfig struct {
gitVersion string
mu sync.Mutex
}
var Config = &gitConfig{}
// Find returns the git config value for the key
func (c *gitConfig) Find(val string) string {
output, _ := gitSimple("config", val)
return output
}
// FindGlobal returns the git config value global scope for the key
func (c *gitConfig) FindGlobal(val string) string {
output, _ := gitSimple("config", "--global", val)
return output
}
// FindSystem returns the git config value in system scope for the key
func (c *gitConfig) FindSystem(val string) string {
output, _ := gitSimple("config", "--system", val)
return output
}
// Find returns the git config value for the key
func (c *gitConfig) FindLocal(val string) string {
output, _ := gitSimple("config", "--local", val)
return output
}
// SetGlobal sets the git config value for the key in the global config
func (c *gitConfig) SetGlobal(key, val string) (string, error) {
return gitSimple("config", "--global", "--replace-all", key, val)
}
// SetSystem sets the git config value for the key in the system config
func (c *gitConfig) SetSystem(key, val string) (string, error) {
return gitSimple("config", "--system", "--replace-all", key, val)
}
// UnsetGlobal removes the git config value for the key from the global config
func (c *gitConfig) UnsetGlobal(key string) (string, error) {
return gitSimple("config", "--global", "--unset", key)
}
// UnsetSystem removes the git config value for the key from the system config
func (c *gitConfig) UnsetSystem(key string) (string, error) {
return gitSimple("config", "--system", "--unset", key)
}
// UnsetGlobalSection removes the entire named section from the global config
func (c *gitConfig) UnsetGlobalSection(key string) (string, error) {
return gitSimple("config", "--global", "--remove-section", key)
}
// UnsetSystemSection removes the entire named section from the system config
func (c *gitConfig) UnsetSystemSection(key string) (string, error) {
return gitSimple("config", "--system", "--remove-section", key)
}
// UnsetLocalSection removes the entire named section from the system config
func (c *gitConfig) UnsetLocalSection(key string) (string, error) {
return gitSimple("config", "--local", "--remove-section", key)
}
// SetLocal sets the git config value for the key in the specified config file
func (c *gitConfig) SetLocal(file, key, val string) (string, error) {
args := make([]string, 1, 6)
args[0] = "config"
if len(file) > 0 {
args = append(args, "--file", file)
}
args = append(args, "--replace-all", key, val)
return gitSimple(args...)
}
// UnsetLocalKey removes the git config value for the key from the specified config file
func (c *gitConfig) UnsetLocalKey(file, key string) (string, error) {
args := make([]string, 1, 5)
args[0] = "config"
if len(file) > 0 {
args = append(args, "--file", file)
}
args = append(args, "--unset", key)
return gitSimple(args...)
}
// List lists all of the git config values
func (c *gitConfig) List() (string, error) {
return gitSimple("config", "-l")
}
// ListFromFile lists all of the git config values in the given config file
func (c *gitConfig) ListFromFile(f string) (string, error) {
return gitSimple("config", "-l", "-f", f)
}
// Version returns the git version
func (c *gitConfig) Version() (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.gitVersion) == 0 {
v, err := gitSimple("version")
if err != nil {
return v, err
}
c.gitVersion = v
}
return c.gitVersion, nil
}
// IsVersionAtLeast returns whether the git version is the one specified or higher
// argument is plain version string separated by '.' e.g. "2.3.1" but can omit minor/patch
func (c *gitConfig) IsGitVersionAtLeast(ver string) bool {
gitver, err := c.Version()
if err != nil {
tracerx.Printf("Error getting git version: %v", err)
return false
}
return IsVersionAtLeast(gitver, ver)
}
// RecentBranches returns branches with commit dates on or after the given date/time
// Return full Ref type for easier detection of duplicate SHAs etc
// since: refs with commits on or after this date will be included
// includeRemoteBranches: true to include refs on remote branches
// onlyRemote: set to non-blank to only include remote branches on a single remote
func RecentBranches(since time.Time, includeRemoteBranches bool, onlyRemote string) ([]*Ref, error) {
cmd := gitNoLFS("for-each-ref",
`--sort=-committerdate`,
`--format=%(refname) %(objectname) %(committerdate:iso)`,
"refs")
outp, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("Failed to call git for-each-ref: %v", err)
}
cmd.Start()
defer cmd.Wait()
scanner := bufio.NewScanner(outp)
// Output is like this:
// refs/heads/master f03686b324b29ff480591745dbfbbfa5e5ac1bd5 2015-08-19 16:50:37 +0100
// refs/remotes/origin/master ad3b29b773e46ad6870fdf08796c33d97190fe93 2015-08-13 16:50:37 +0100
// Output is ordered by latest commit date first, so we can stop at the threshold
regex := regexp.MustCompile(`^(refs/[^/]+/\S+)\s+([0-9A-Za-z]{40})\s+(\d{4}-\d{2}-\d{2}\s+\d{2}\:\d{2}\:\d{2}\s+[\+\-]\d{4})`)
tracerx.Printf("RECENT: Getting refs >= %v", since)
var ret []*Ref
for scanner.Scan() {
line := scanner.Text()
if match := regex.FindStringSubmatch(line); match != nil {
fullref := match[1]
sha := match[2]
reftype, ref := ParseRefToTypeAndName(fullref)
if reftype == RefTypeRemoteBranch || reftype == RefTypeRemoteTag {
if !includeRemoteBranches {
continue
}
if onlyRemote != "" && !strings.HasPrefix(ref, onlyRemote+"/") {
continue
}
}
// This is a ref we might use
// Check the date
commitDate, err := ParseGitDate(match[3])
if err != nil {
return ret, err
}
if commitDate.Before(since) {
// the end
break
}
tracerx.Printf("RECENT: %v (%v)", ref, commitDate)
ret = append(ret, &Ref{ref, reftype, sha})
}
}
return ret, nil
}
// Get the type & name of a git reference
func ParseRefToTypeAndName(fullref string) (t RefType, name string) {
const localPrefix = "refs/heads/"
const remotePrefix = "refs/remotes/"
const remoteTagPrefix = "refs/remotes/tags/"
const localTagPrefix = "refs/tags/"
if fullref == "HEAD" {
name = fullref
t = RefTypeHEAD
} else if strings.HasPrefix(fullref, localPrefix) {
name = fullref[len(localPrefix):]
t = RefTypeLocalBranch
} else if strings.HasPrefix(fullref, remotePrefix) {
name = fullref[len(remotePrefix):]
t = RefTypeRemoteBranch
} else if strings.HasPrefix(fullref, remoteTagPrefix) {
name = fullref[len(remoteTagPrefix):]
t = RefTypeRemoteTag
} else if strings.HasPrefix(fullref, localTagPrefix) {
name = fullref[len(localTagPrefix):]
t = RefTypeLocalTag
} else {
name = fullref
t = RefTypeOther
}
return
}
// Parse a Git date formatted in ISO 8601 format (%ci/%ai)
func ParseGitDate(str string) (time.Time, error) {
// Unfortunately Go and Git don't overlap in their builtin date formats
// Go's time.RFC1123Z and Git's %cD are ALMOST the same, except that
// when the day is < 10 Git outputs a single digit, but Go expects a leading
// zero - this is enough to break the parsing. Sigh.
// Format is for 2 Jan 2006, 15:04:05 -7 UTC as per Go
return time.Parse("2006-01-02 15:04:05 -0700", str)
}
// FormatGitDate converts a Go date into a git command line format date
func FormatGitDate(tm time.Time) string {
// Git format is "Fri Jun 21 20:26:41 2013 +0900" but no zero-leading for day
return tm.Format("Mon Jan 2 15:04:05 2006 -0700")
}
// Get summary information about a commit
func GetCommitSummary(commit string) (*CommitSummary, error) {
cmd := gitNoLFS("show", "-s",
`--format=%H|%h|%P|%ai|%ci|%ae|%an|%ce|%cn|%s`, commit)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("Failed to call git show: %v %v", err, string(out))
}
// At most 10 substrings so subject line is not split on anything
fields := strings.SplitN(string(out), "|", 10)
// Cope with the case where subject is blank
if len(fields) >= 9 {
ret := &CommitSummary{}
// Get SHAs from output, not commit input, so we can support symbolic refs
ret.Sha = fields[0]
ret.ShortSha = fields[1]
ret.Parents = strings.Split(fields[2], " ")
// %aD & %cD (RFC2822) matches Go's RFC1123Z format
ret.AuthorDate, _ = ParseGitDate(fields[3])
ret.CommitDate, _ = ParseGitDate(fields[4])
ret.AuthorEmail = fields[5]
ret.AuthorName = fields[6]
ret.CommitterEmail = fields[7]
ret.CommitterName = fields[8]
if len(fields) > 9 {
ret.Subject = strings.TrimRight(fields[9], "\n")
}
return ret, nil
} else {
msg := fmt.Sprintf("Unexpected output from git show: %v", string(out))
return nil, errors.New(msg)
}
}
func GitAndRootDirs() (string, string, error) {
cmd := gitNoLFS("rev-parse", "--git-dir", "--show-toplevel")
buf := &bytes.Buffer{}
cmd.Stderr = buf
out, err := cmd.Output()
output := string(out)
if err != nil {
return "", "", fmt.Errorf("Failed to call git rev-parse --git-dir --show-toplevel: %q", buf.String())
}
paths := strings.Split(output, "\n")
pathLen := len(paths)
for i := 0; i < pathLen; i++ {
paths[i], err = tools.TranslateCygwinPath(paths[i])
}
if pathLen == 0 {
return "", "", fmt.Errorf("Bad git rev-parse output: %q", output)
}
absGitDir, err := filepath.Abs(paths[0])
if err != nil {
return "", "", fmt.Errorf("Error converting %q to absolute: %s", paths[0], err)
}
if pathLen == 1 || len(paths[1]) == 0 {
return absGitDir, "", nil
}
absRootDir := paths[1]
return absGitDir, absRootDir, nil
}
func RootDir() (string, error) {
cmd := gitNoLFS("rev-parse", "--show-toplevel")
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("Failed to call git rev-parse --show-toplevel: %v %v", err, string(out))
}
path := strings.TrimSpace(string(out))
path, err = tools.TranslateCygwinPath(path)
if len(path) > 0 {
return filepath.Abs(path)
}
return "", nil
}
func GitDir() (string, error) {
cmd := gitNoLFS("rev-parse", "--git-dir")
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("Failed to call git rev-parse --git-dir: %v %v", err, string(out))
}
path := strings.TrimSpace(string(out))
if len(path) > 0 {
return filepath.Abs(path)
}
return "", nil
}
// GetAllWorkTreeHEADs returns the refs that all worktrees are using as HEADs
// This returns all worktrees plus the master working copy, and works even if
// working dir is actually in a worktree right now
// Pass in the git storage dir (parent of 'objects') to work from
func GetAllWorkTreeHEADs(storageDir string) ([]*Ref, error) {
worktreesdir := filepath.Join(storageDir, "worktrees")
dirf, err := os.Open(worktreesdir)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
var worktrees []*Ref
if err == nil {
// There are some worktrees
defer dirf.Close()
direntries, err := dirf.Readdir(0)
if err != nil {
return nil, err
}
for _, dirfi := range direntries {
if dirfi.IsDir() {
// to avoid having to chdir and run git commands to identify the commit
// just read the HEAD file & git rev-parse if necessary
// Since the git repo is shared the same rev-parse will work from this location
headfile := filepath.Join(worktreesdir, dirfi.Name(), "HEAD")
ref, err := parseRefFile(headfile)
if err != nil {
tracerx.Printf("Error reading %v for worktree, skipping: %v", headfile, err)
continue
}
worktrees = append(worktrees, ref)
}
}
}
// This has only established the separate worktrees, not the original checkout
// If the storageDir contains a HEAD file then there is a main checkout
// as well; this mus tbe resolveable whether you're in the main checkout or
// a worktree
headfile := filepath.Join(storageDir, "HEAD")
ref, err := parseRefFile(headfile)
if err == nil {
worktrees = append(worktrees, ref)
} else if !os.IsNotExist(err) { // ok if not exists, probably bare repo
tracerx.Printf("Error reading %v for main checkout, skipping: %v", headfile, err)
}
return worktrees, nil
}
// Manually parse a reference file like HEAD and return the Ref it resolves to
func parseRefFile(filename string) (*Ref, error) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
contents := strings.TrimSpace(string(bytes))
if strings.HasPrefix(contents, "ref:") {
contents = strings.TrimSpace(contents[4:])
}
return ResolveRef(contents)
}
// IsVersionAtLeast compares 2 version strings (ok to be prefixed with 'git version', ignores)
func IsVersionAtLeast(actualVersion, desiredVersion string) bool {
// Capture 1-3 version digits, optionally prefixed with 'git version' and possibly
// with suffixes which we'll ignore (e.g. unstable builds, MinGW versions)
verregex := regexp.MustCompile(`(?:git version\s+)?(\d+)(?:.(\d+))?(?:.(\d+))?.*`)
var atleast uint64
// Support up to 1000 in major/minor/patch digits
const majorscale = 1000 * 1000
const minorscale = 1000
if match := verregex.FindStringSubmatch(desiredVersion); match != nil {
// Ignore errors as regex won't match anything other than digits
major, _ := strconv.Atoi(match[1])
atleast += uint64(major * majorscale)
if len(match) > 2 {
minor, _ := strconv.Atoi(match[2])
atleast += uint64(minor * minorscale)
}
if len(match) > 3 {
patch, _ := strconv.Atoi(match[3])
atleast += uint64(patch)
}
}
var actual uint64
if match := verregex.FindStringSubmatch(actualVersion); match != nil {
major, _ := strconv.Atoi(match[1])
actual += uint64(major * majorscale)
if len(match) > 2 {
minor, _ := strconv.Atoi(match[2])
actual += uint64(minor * minorscale)
}
if len(match) > 3 {
patch, _ := strconv.Atoi(match[3])
actual += uint64(patch)
}
}
return actual >= atleast
}
// IsBare returns whether or not a repository is bare. It requires that the
// current working directory is a repository.
//
// If there was an error determining whether or not the repository is bare, it
// will be returned.
func IsBare() (bool, error) {
s, err := subprocess.SimpleExec(
"git", "rev-parse", "--is-bare-repository")
if err != nil {
return false, err
}
return strconv.ParseBool(s)
}
// For compatibility with git clone we must mirror all flags in CloneWithoutFilters
type CloneFlags struct {
// --template <template_directory>
TemplateDirectory string
// -l --local
Local bool
// -s --shared
Shared bool
// --no-hardlinks
NoHardlinks bool
// -q --quiet
Quiet bool
// -n --no-checkout
NoCheckout bool
// --progress
Progress bool
// --bare
Bare bool
// --mirror
Mirror bool
// -o <name> --origin <name>
Origin string
// -b <name> --branch <name>
Branch string
// -u <upload-pack> --upload-pack <pack>
Upload string
// --reference <repository>
Reference string
// --reference-if-able <repository>
ReferenceIfAble string
// --dissociate
Dissociate bool
// --separate-git-dir <git dir>
SeparateGit string
// --depth <depth>
Depth string
// --recursive
Recursive bool
// --recurse-submodules
RecurseSubmodules bool
// -c <value> --config <value>
Config string
// --single-branch
SingleBranch bool
// --no-single-branch
NoSingleBranch bool
// --verbose
Verbose bool
// --ipv4
Ipv4 bool
// --ipv6
Ipv6 bool
// --shallow-since <date>
ShallowSince string
// --shallow-since <date>
ShallowExclude string
// --shallow-submodules
ShallowSubmodules bool
// --no-shallow-submodules
NoShallowSubmodules bool
// jobs <n>
Jobs int64
}
// CloneWithoutFilters clones a git repo but without the smudge filter enabled
// so that files in the working copy will be pointers and not real LFS data
func CloneWithoutFilters(flags CloneFlags, args []string) error {
cmdargs := []string{"clone"}
// flags
if flags.Bare {
cmdargs = append(cmdargs, "--bare")
}
if len(flags.Branch) > 0 {
cmdargs = append(cmdargs, "--branch", flags.Branch)
}
if len(flags.Config) > 0 {
cmdargs = append(cmdargs, "--config", flags.Config)
}
if len(flags.Depth) > 0 {
cmdargs = append(cmdargs, "--depth", flags.Depth)
}