Debian Codegraph @

git/git.go

raw symbols SCIP
1 // Package git contains various commands that shell out to git
2 // NOTE: Subject to change, do not rely on this package from outside git-lfs source
3 package git
4
5 import (
6 "bufio"
7 "bytes"
8 "crypto/sha1"
9 "crypto/sha256"
10 "encoding/hex"
11 "errors"
12 "fmt"
13 "io"
14 "net/url"
15 "os"
16 "path/filepath"
17 "regexp"
18 "slices"
19 "strconv"
20 "strings"
21 "sync"
22 "time"
23
24 lfserrors "github.com/git-lfs/git-lfs/v3/errors"
25 "github.com/git-lfs/git-lfs/v3/subprocess"
26 "github.com/git-lfs/git-lfs/v3/tools"
27 "github.com/git-lfs/git-lfs/v3/tr"
28 "github.com/git-lfs/gitobj/v2"
29 "github.com/rubyist/tracerx"
30 )
31
32 type RefType int
33
34 const (
35 RefTypeLocalBranch = RefType(iota)
36 RefTypeRemoteBranch = RefType(iota)
37 RefTypeLocalTag = RefType(iota)
38 RefTypeRemoteTag = RefType(iota)
39 RefTypeHEAD = RefType(iota) // current checkout
40 RefTypeOther = RefType(iota) // stash or unknown
41
42 SHA1HexSize = sha1.Size * 2
43 SHA256HexSize = sha256.Size * 2
44 )
45
46 var (
47 ObjectIDRegex = fmt.Sprintf("(?:[0-9a-f]{%d}(?:[0-9a-f]{%d})?)", SHA1HexSize, SHA256HexSize-SHA1HexSize)
48 // ObjectIDLengths is a slice of valid Git hexadecimal object ID
49 // lengths in increasing order.
50 ObjectIDLengths = []int{SHA1HexSize, SHA256HexSize}
51 emptyTree = ""
52 emptyTreeMutex = &sync.Mutex{}
53 )
54
55 type IndexStage int
56
57 const (
58 IndexStageDefault IndexStage = iota
59 IndexStageBase
60 IndexStageOurs
61 IndexStageTheirs
62 )
63
64 // Prefix returns the given RefType's prefix, "refs/heads", "ref/remotes",
65 // etc. It returns an additional value of either true/false, whether or not this
66 // given ref type has a prefix.
67 //
68 // If the RefType is unrecognized, Prefix() will panic.
69 func (t RefType) Prefix() (string, bool) {
70 switch t {
71 case RefTypeLocalBranch:
72 return "refs/heads", true
73 case RefTypeRemoteBranch:
74 return "refs/remotes", true
75 case RefTypeLocalTag:
76 return "refs/tags", true
77 default:
78 return "", false
79 }
80 }
81
82 func ParseRef(absRef, sha string) *Ref {
83 r := &Ref{Sha: sha}
84 if strings.HasPrefix(absRef, "refs/heads/") {
85 r.Name = absRef[11:]
86 r.Type = RefTypeLocalBranch
87 } else if strings.HasPrefix(absRef, "refs/tags/") {
88 r.Name = absRef[10:]
89 r.Type = RefTypeLocalTag
90 } else if strings.HasPrefix(absRef, "refs/remotes/") {
91 r.Name = absRef[13:]
92 r.Type = RefTypeRemoteBranch
93 } else {
94 r.Name = absRef
95 if absRef == "HEAD" {
96 r.Type = RefTypeHEAD
97 } else {
98 r.Type = RefTypeOther
99 }
100 }
101 return r
102 }
103
104 // A git reference (branch, tag etc)
105 type Ref struct {
106 Name string
107 Type RefType
108 Sha string
109 }
110
111 // Refspec returns the fully-qualified reference name (including remote), i.e.,
112 // for a remote branch called 'my-feature' on remote 'origin', this function
113 // will return:
114 //
115 // refs/remotes/origin/my-feature
116 func (r *Ref) Refspec() string {
117 if r == nil {
118 return ""
119 }
120
121 prefix, ok := r.Type.Prefix()
122 if ok {
123 return fmt.Sprintf("%s/%s", prefix, r.Name)
124 }
125
126 return r.Name
127 }
128
129 // HasValidObjectIDLength returns true if `s` has a length that is a valid
130 // hexadecimal Git object ID length.
131 func HasValidObjectIDLength(s string) bool {
132 return slices.Contains(ObjectIDLengths, len(s))
133 }
134
135 // IsZeroObjectID returns true if the string is a valid hexadecimal Git object
136 // ID and represents the all-zeros object ID for some hash algorithm.
137 func IsZeroObjectID(s string) bool {
138 for _, length := range ObjectIDLengths {
139 if s == strings.Repeat("0", length) {
140 return true
141 }
142 }
143 return false
144 }
145
146 func EmptyTree() (string, error) {
147 emptyTreeMutex.Lock()
148 defer emptyTreeMutex.Unlock()
149
150 if len(emptyTree) == 0 {
151 cmd, err := gitNoLFS("hash-object", "-t", "tree", "/dev/null")
152 if err != nil {
153 return "", errors.New(tr.Tr.Get("failed to find `git hash-object`: %v", err))
154 }
155 cmd.Stdin = nil
156 out, _ := cmd.Output()
157 emptyTree = strings.TrimSpace(string(out))
158 }
159 return emptyTree, nil
160 }
161
162 // Some top level information about a commit (only first line of message)
163 type CommitSummary struct {
164 Sha string
165 ShortSha string
166 Parents []string
167 CommitDate time.Time
168 AuthorDate time.Time
169 AuthorName string
170 AuthorEmail string
171 CommitterName string
172 CommitterEmail string
173 Subject string
174 }
175
176 // Prepend Git config instructions to disable Git LFS filter
177 func gitConfigNoLFS(args ...string) []string {
178 // Before git 2.8, setting filters to blank causes lots of warnings, so use cat instead (slightly slower)
179 // Also pre 2.2 it failed completely. We used to use it anyway in git 2.2-2.7 and
180 // suppress the messages in stderr, but doing that with standard StderrPipe suppresses
181 // the git clone output (git thinks it's not a terminal) and makes it look like it's
182 // not working. You can get around that with https://github.com/kr/pty but that
183 // causes difficult issues with passing through Stdin for login prompts
184 // This way is simpler & more practical.
185 filterOverride := ""
186 if !IsGitVersionAtLeast("2.8.0") {
187 filterOverride = "cat"
188 }
189
190 return append([]string{
191 "-c", fmt.Sprintf("filter.lfs.smudge=%v", filterOverride),
192 "-c", fmt.Sprintf("filter.lfs.clean=%v", filterOverride),
193 "-c", "filter.lfs.process=",
194 "-c", "filter.lfs.required=false",
195 }, args...)
196 }
197
198 // Invoke Git with disabled LFS filters
199 func gitNoLFS(args ...string) (*subprocess.Cmd, error) {
200 return subprocess.ExecCommand("git", gitConfigNoLFS(args...)...)
201 }
202
203 func gitNoLFSSimple(args ...string) (string, error) {
204 return subprocess.SimpleExec("git", gitConfigNoLFS(args...)...)
205 }
206
207 func gitNoLFSBuffered(args ...string) (*subprocess.BufferedCmd, error) {
208 return subprocess.BufferedExec("git", gitConfigNoLFS(args...)...)
209 }
210
211 func gitNoLFSBufferedStdout(args ...string) (*subprocess.BufferedCmd, error) {
212 return subprocess.StdoutBufferedExec("git", gitConfigNoLFS(args...)...)
213 }
214
215 // Invoke Git with enabled LFS filters
216 func git(args ...string) (*subprocess.Cmd, error) {
217 return subprocess.ExecCommand("git", args...)
218 }
219
220 func gitSimple(args ...string) (string, error) {
221 return subprocess.SimpleExec("git", args...)
222 }
223
224 func gitBuffered(args ...string) (*subprocess.BufferedCmd, error) {
225 return subprocess.BufferedExec("git", args...)
226 }
227
228 func gitBufferedStdout(args ...string) (*subprocess.BufferedCmd, error) {
229 return subprocess.StdoutBufferedExec("git", args...)
230 }
231
232 func CatFile() (*subprocess.BufferedCmd, error) {
233 return gitNoLFSBuffered("cat-file", "--batch-check")
234 }
235
236 func Var(name string) (*subprocess.Cmd, error) {
237 return gitNoLFS("var", name)
238 }
239
240 func DiffIndex(ref string, cached bool, refresh bool, workingDir string) (*bufio.Scanner, error) {
241 if refresh {
242 _, err := gitSimple("update-index", "-q", "--refresh")
243 if err != nil {
244 return nil, lfserrors.Wrap(err, tr.Tr.Get("Failed to run `git update-index`"))
245 }
246 }
247
248 args := []string{"diff-index", "-M"}
249 if cached {
250 args = append(args, "--cached")
251 }
252 args = append(args, ref)
253
254 if workingDir != "" {
255 args = append([]string{"-C", workingDir}, args...)
256 }
257
258 cmd, err := gitBufferedStdout(args...)
259 if err != nil {
260 return nil, err
261 }
262 if err = cmd.Stdin.Close(); err != nil {
263 return nil, err
264 }
265
266 return bufio.NewScanner(cmd.Stdout), nil
267 }
268
269 func DiffIndexWithPaths(ref string, cached bool, paths []string) (string, error) {
270 args := []string{"diff-index"}
271 if cached {
272 args = append(args, "--cached")
273 }
274 args = append(args, ref)
275 args = append(args, "--")
276 args = append(args, paths...)
277
278 output, err := gitSimple(args...)
279 if err != nil {
280 return "", err
281 }
282
283 return output, nil
284 }
285
286 func HashObject(r io.Reader) (string, error) {
287 cmd, err := gitNoLFS("hash-object", "--stdin")
288 if err != nil {
289 return "", errors.New(tr.Tr.Get("failed to find `git hash-object`: %v", err))
290 }
291 cmd.Stdin = r
292 out, err := cmd.Output()
293 if err != nil {
294 return "", errors.New(tr.Tr.Get("error building Git blob OID: %s", err))
295 }
296
297 return string(bytes.TrimSpace(out)), nil
298 }
299
300 func Log(args ...string) (*subprocess.BufferedCmd, error) {
301 logArgs := append([]string{"log"}, args...)
302 return gitNoLFSBuffered(logArgs...)
303 }
304
305 func LsRemote(remote, remoteRef string) (string, error) {
306 if remote == "" {
307 return "", errors.New(tr.Tr.Get("remote required"))
308 }
309 if remoteRef == "" {
310 return gitNoLFSSimple("ls-remote", remote)
311
312 }
313 return gitNoLFSSimple("ls-remote", remote, remoteRef)
314 }
315
316 func LsTree(ref string) (*subprocess.BufferedCmd, error) {
317 return gitNoLFSBuffered(
318 "ls-tree",
319 "-r", // recurse
320 "-l", // report object size (we'll need this)
321 "-z", // null line termination
322 "--full-tree", // start at the root regardless of where we are in it
323 ref,
324 )
325 }
326
327 func LsFilesLFS() (*subprocess.BufferedCmd, error) {
328 // This requires Git 2.42.0 for `--format` with `objecttype`.
329 return gitNoLFSBuffered(
330 "ls-files",
331 "--cached",
332 "--exclude-standard",
333 "--full-name",
334 "--sparse",
335 "-z",
336 "--format=%(objectmode) %(objecttype) %(objectname) %(objectsize)\t%(path)",
337 ":(top,attr:filter=lfs)",
338 )
339 }
340
341 func ResolveRef(ref string) (*Ref, error) {
342 outp, err := gitNoLFSSimple("rev-parse", ref, "--symbolic-full-name", ref)
343 if err != nil {
344 return nil, errors.New(tr.Tr.Get("Git can't resolve ref: %q", ref))
345 }
346 if outp == "" {
347 return nil, errors.New(tr.Tr.Get("Git can't resolve ref: %q", ref))
348 }
349
350 lines := strings.Split(outp, "\n")
351 fullref := &Ref{Sha: lines[0]}
352
353 if len(lines) == 1 {
354 // ref is a sha1 and has no symbolic-full-name
355 fullref.Name = lines[0]
356 fullref.Sha = lines[0]
357 fullref.Type = RefTypeOther
358 return fullref, nil
359 }
360
361 // parse the symbolic-full-name
362 fullref.Type, fullref.Name = ParseRefToTypeAndName(lines[1])
363 return fullref, nil
364 }
365
366 func ResolveRefs(refnames []string) ([]*Ref, error) {
367 refs := make([]*Ref, len(refnames))
368 for i, name := range refnames {
369 ref, err := ResolveRef(name)
370 if err != nil {
371 return refs, err
372 }
373
374 refs[i] = ref
375 }
376 return refs, nil
377 }
378
379 func CurrentRef() (*Ref, error) {
380 return ResolveRef("HEAD")
381 }
382
383 func (c *Configuration) CurrentRemoteRef() (*Ref, error) {
384 remoteref, err := c.RemoteRefNameForCurrentBranch()
385 if err != nil {
386 return nil, err
387 }
388
389 return ResolveRef(remoteref)
390 }
391
392 // RemoteRefForCurrentBranch returns the full remote ref (refs/remotes/{remote}/{remotebranch})
393 // that the current branch is tracking.
394 func (c *Configuration) RemoteRefNameForCurrentBranch() (string, error) {
395 ref, err := CurrentRef()
396 if err != nil {
397 return "", err
398 }
399
400 if ref.Type == RefTypeHEAD || ref.Type == RefTypeOther {
401 return "", errors.New(tr.Tr.Get("not on a branch"))
402 }
403
404 remote := c.RemoteForBranch(ref.Name)
405 if remote == "" {
406 return "", errors.New(tr.Tr.Get("remote not found for branch %q", ref.Name))
407 }
408
409 remotebranch := c.RemoteBranchForLocalBranch(ref.Name)
410
411 return fmt.Sprintf("refs/remotes/%s/%s", remote, remotebranch), nil
412 }
413
414 // RemoteForBranch returns the remote name that a given local branch is tracking (blank if none)
415 func (c *Configuration) RemoteForBranch(localBranch string) string {
416 return c.Find(fmt.Sprintf("branch.%s.remote", localBranch))
417 }
418
419 // RemoteBranchForLocalBranch returns the name (only) of the remote branch that the local branch is tracking
420 // If no specific branch is configured, returns local branch name
421 func (c *Configuration) RemoteBranchForLocalBranch(localBranch string) string {
422 // get remote ref to track, may not be same name
423 merge := c.Find(fmt.Sprintf("branch.%s.merge", localBranch))
424 if strings.HasPrefix(merge, "refs/heads/") {
425 return merge[11:]
426 } else {
427 return localBranch
428 }
429 }
430
431 func RemoteList() ([]string, error) {
432 cmd, err := gitNoLFS("remote")
433 if err != nil {
434 return nil, errors.New(tr.Tr.Get("failed to find `git remote`: %v", err))
435 }
436
437 outp, err := cmd.StdoutPipe()
438 if err != nil {
439 return nil, errors.New(tr.Tr.Get("failed to call `git remote`: %v", err))
440 }
441 cmd.Start()
442 defer cmd.Wait()
443
444 scanner := bufio.NewScanner(outp)
445
446 var ret []string
447 for scanner.Scan() {
448 ret = append(ret, strings.TrimSpace(scanner.Text()))
449 }
450
451 return ret, nil
452 }
453
454 func RemoteURLs(push bool) (map[string][]string, error) {
455 cmd, err := gitNoLFS("remote", "-v")
456 if err != nil {
457 return nil, errors.New(tr.Tr.Get("failed to find `git remote -v`: %v", err))
458 }
459
460 outp, err := cmd.StdoutPipe()
461 if err != nil {
462 return nil, errors.New(tr.Tr.Get("failed to call `git remote -v`: %v", err))
463 }
464 cmd.Start()
465 defer cmd.Wait()
466
467 scanner := bufio.NewScanner(outp)
468
469 text := "(fetch)"
470 if push {
471 text = "(push)"
472 }
473 ret := make(map[string][]string)
474 for scanner.Scan() {
475 // [remote, urlpair-text]
476 pair := strings.Split(strings.TrimSpace(scanner.Text()), "\t")
477 if len(pair) != 2 {
478 continue
479 }
480 // [url, "(fetch)" | "(push)"]
481 urlpair := strings.Split(pair[1], " ")
482 if len(urlpair) != 2 || urlpair[1] != text {
483 continue
484 }
485 ret[pair[0]] = append(ret[pair[0]], urlpair[0])
486 }
487
488 return ret, nil
489 }
490
491 func MapRemoteURL(url string, push bool) (string, bool) {
492 urls, err := RemoteURLs(push)
493 if err != nil {
494 return url, false
495 }
496
497 for name, remotes := range urls {
498 if len(remotes) == 1 && url == remotes[0] {
499 return name, true
500 }
501 }
502 return url, false
503 }
504
505 // Refs returns all of the local and remote branches and tags for the current
506 // repository. Other refs (HEAD, refs/stash, git notes) are ignored.
507 func LocalRefs() ([]*Ref, error) {
508 cmd, err := gitNoLFS("show-ref")
509 if err != nil {
510 return nil, errors.New(tr.Tr.Get("failed to find `git show-ref`: %v", err))
511 }
512
513 outp, err := cmd.StdoutPipe()
514 if err != nil {
515 return nil, errors.New(tr.Tr.Get("failed to call `git show-ref`: %v", err))
516 }
517
518 var refs []*Ref
519
520 if err := cmd.Start(); err != nil {
521 return refs, err
522 }
523
524 scanner := bufio.NewScanner(outp)
525 for scanner.Scan() {
526 line := strings.TrimSpace(scanner.Text())
527 parts := strings.SplitN(line, " ", 2)
528 if len(parts) != 2 || !HasValidObjectIDLength(parts[0]) || len(parts[1]) < 1 {
529 tracerx.Printf("Invalid line from `git show-ref`: %q", line)
530 continue
531 }
532
533 rtype, name := ParseRefToTypeAndName(parts[1])
534 if rtype != RefTypeLocalBranch && rtype != RefTypeLocalTag {
535 continue
536 }
537
538 refs = append(refs, &Ref{name, rtype, parts[0]})
539 }
540
541 return refs, cmd.Wait()
542 }
543
544 // UpdateRef moves the given ref to a new sha with a given reason (and creates a
545 // reflog entry, if a "reason" was provided). It returns an error if any were
546 // encountered.
547 func UpdateRef(ref *Ref, to []byte, reason string) error {
548 args := []string{"update-ref", ref.Refspec(), hex.EncodeToString(to)}
549 if len(reason) > 0 {
550 args = append(args, "-m", reason)
551 }
552
553 _, err := gitNoLFSSimple(args...)
554 return err
555 }
556
557 // UpdateRefsFromStdinInDir initializes a "git update-ref" command which will
558 // read a series of reference update instructions from standard input and
559 // execute them. The command will operate within the given working
560 // directory "wd". The instructions should follow the NUL-terminated format.
561 func UpdateRefsFromStdin(wd string) (*subprocess.Cmd, error) {
562 cmd, err := gitNoLFS("update-ref", "--stdin", "-z")
563 cmd.Dir = wd
564 return cmd, err
565 }
566
567 // ValidateRemote checks that a named remote is valid for use
568 // Mainly to check user-supplied remotes & fail more nicely
569 func ValidateRemote(remote string) error {
570 remotes, err := RemoteList()
571 if err != nil {
572 return err
573 }
574 return ValidateRemoteFromList(remotes, remote)
575 }
576
577 // ValidateRemote checks that a named remote is valid for use given a list from
578 // RemoteList. This is completely identical to ValidateRemote, except that it
579 // allows caching the remote list.
580 func ValidateRemoteFromList(remotes []string, remote string) error {
581 if slices.Contains(remotes, remote) {
582 return nil
583 }
584
585 if err := ValidateRemoteURL(remote); err == nil {
586 return nil
587 }
588
589 return errors.New(tr.Tr.Get("invalid remote name: %q", remote))
590 }
591
592 // ValidateRemoteURL checks that a string is a valid Git remote URL
593 func ValidateRemoteURL(remote string) error {
594 u, _ := url.Parse(remote)
595 if u == nil || u.Scheme == "" {
596 // This is either an invalid remote name (maybe the user made a typo
597 // when selecting a named remote) or a bare SSH URL like
598 // "[email protected]:path/to/resource.git". Guess that this is a URL in the latter
599 // form if the string contains a colon ":", and an invalid remote if it
600 // does not.
601 if strings.Contains(remote, ":") {
602 return nil
603 } else {
604 return errors.New(tr.Tr.Get("invalid remote name: %q", remote))
605 }
606 }
607
608 switch u.Scheme {
609 case "ssh", "http", "https", "git", "file":
610 return nil
611 default:
612 return errors.New(tr.Tr.Get("invalid remote URL protocol %q in %q", u.Scheme, remote))
613 }
614 }
615
616 func RewriteLocalPathAsURL(path string) string {
617 var slash string
618 if abs, err := filepath.Abs(path); err == nil {
619 // Required for Windows paths to work.
620 if !strings.HasPrefix(abs, "/") {
621 slash = "/"
622 }
623 path = abs
624 }
625
626 var gitpath string
627 if filepath.Base(path) == ".git" {
628 gitpath = path
629 path = filepath.Dir(path)
630 } else {
631 gitpath = filepath.Join(path, ".git")
632 }
633
634 if _, err := os.Stat(gitpath); err == nil {
635 path = gitpath
636 } else if _, err := os.Stat(path); err != nil {
637 // Not a local path. We check down here because we perform
638 // canonicalization by stripping off the .git above.
639 return path
640 }
641 return fmt.Sprintf("file://%s%s", slash, filepath.ToSlash(path))
642 }
643
644 func UpdateIndexFromStdin() (*subprocess.Cmd, error) {
645 return git("update-index", "-q", "--refresh", "--stdin")
646 }
647
648 // RecentBranches returns branches with commit dates on or after the given date/time
649 // Return full Ref type for easier detection of duplicate SHAs etc
650 // since: refs with commits on or after this date will be included
651 // includeRemoteBranches: true to include refs on remote branches
652 // onlyRemote: set to non-blank to only include remote branches on a single remote
653 func RecentBranches(since time.Time, includeRemoteBranches bool, onlyRemote string) ([]*Ref, error) {
654 cmd, err := gitNoLFS("for-each-ref",
655 `--sort=-committerdate`,
656 `--format=%(refname) %(objectname) %(committerdate:iso)`,
657 "refs")
658 if err != nil {
659 return nil, errors.New(tr.Tr.Get("failed to find `git for-each-ref`: %v", err))
660 }
661 outp, err := cmd.StdoutPipe()
662 if err != nil {
663 return nil, errors.New(tr.Tr.Get("failed to call `git for-each-ref`: %v", err))
664 }
665 cmd.Start()
666 defer cmd.Wait()
667
668 scanner := bufio.NewScanner(outp)
669
670 // Output is like this:
671 // refs/heads/master f03686b324b29ff480591745dbfbbfa5e5ac1bd5 2015-08-19 16:50:37 +0100
672 // refs/remotes/origin/master ad3b29b773e46ad6870fdf08796c33d97190fe93 2015-08-13 16:50:37 +0100
673
674 // Output is ordered by latest commit date first, so we can stop at the threshold
675 regex := regexp.MustCompile(fmt.Sprintf(`^(refs/[^/]+/\S+)\s+(%s)\s+(\d{4}-\d{2}-\d{2}\s+\d{2}\:\d{2}\:\d{2}\s+[\+\-]\d{4})`, ObjectIDRegex))
676 tracerx.Printf("RECENT: Getting refs >= %v", since)
677 var ret []*Ref
678 for scanner.Scan() {
679 line := scanner.Text()
680 if match := regex.FindStringSubmatch(line); match != nil {
681 fullref := match[1]
682 sha := match[2]
683 reftype, ref := ParseRefToTypeAndName(fullref)
684 if reftype == RefTypeRemoteBranch {
685 if !includeRemoteBranches {
686 continue
687 }
688 if onlyRemote != "" && !strings.HasPrefix(ref, onlyRemote+"/") {
689 continue
690 }
691 }
692 // This is a ref we might use
693 // Check the date
694 commitDate, err := ParseGitDate(match[3])
695 if err != nil {
696 return ret, err
697 }
698 if commitDate.Before(since) {
699 // the end
700 break
701 }
702 tracerx.Printf("RECENT: %v (%v)", ref, commitDate)
703 ret = append(ret, &Ref{ref, reftype, sha})
704 }
705 }
706
707 return ret, nil
708
709 }
710
711 // Get the type & name of a git reference
712 func ParseRefToTypeAndName(fullref string) (t RefType, name string) {
713 const localPrefix = "refs/heads/"
714 const remotePrefix = "refs/remotes/"
715 const localTagPrefix = "refs/tags/"
716
717 if fullref == "HEAD" {
718 name = fullref
719 t = RefTypeHEAD
720 } else if strings.HasPrefix(fullref, localPrefix) {
721 name = fullref[len(localPrefix):]
722 t = RefTypeLocalBranch
723 } else if strings.HasPrefix(fullref, remotePrefix) {
724 name = fullref[len(remotePrefix):]
725 t = RefTypeRemoteBranch
726 } else if strings.HasPrefix(fullref, localTagPrefix) {
727 name = fullref[len(localTagPrefix):]
728 t = RefTypeLocalTag
729 } else {
730 name = fullref
731 t = RefTypeOther
732 }
733 return
734 }
735
736 // Parse a Git date formatted in ISO 8601 format (%ci/%ai)
737 func ParseGitDate(str string) (time.Time, error) {
738
739 // Unfortunately Go and Git don't overlap in their builtin date formats
740 // Go's time.RFC1123Z and Git's %cD are ALMOST the same, except that
741 // when the day is < 10 Git outputs a single digit, but Go expects a leading
742 // zero - this is enough to break the parsing. Sigh.
743
744 // Format is for 2 Jan 2006, 15:04:05 -7 UTC as per Go
745 return time.Parse("2006-01-02 15:04:05 -0700", str)
746 }
747
748 // FormatGitDate converts a Go date into a git command line format date
749 func FormatGitDate(tm time.Time) string {
750 // Git format is "Fri Jun 21 20:26:41 2013 +0900" but no zero-leading for day
751 return tm.Format("Mon Jan 2 15:04:05 2006 -0700")
752 }
753
754 // Get summary information about a commit
755 func GetCommitSummary(commit string) (*CommitSummary, error) {
756 cmd, err := gitNoLFS("show", "-s",
757 `--format=%H|%h|%P|%ai|%ci|%ae|%an|%ce|%cn|%s`, commit)
758 if err != nil {
759 return nil, errors.New(tr.Tr.Get("failed to find `git show`: %v", err))
760 }
761
762 out, err := cmd.CombinedOutput()
763 if err != nil {
764 return nil, errors.New(tr.Tr.Get("failed to call `git show`: %v %v", err, string(out)))
765 }
766
767 // At most 10 substrings so subject line is not split on anything
768 fields := strings.SplitN(string(out), "|", 10)
769 // Cope with the case where subject is blank
770 if len(fields) >= 9 {
771 ret := &CommitSummary{}
772 // Get SHAs from output, not commit input, so we can support symbolic refs
773 ret.Sha = fields[0]
774 ret.ShortSha = fields[1]
775 ret.Parents = strings.Split(fields[2], " ")
776 // %aD & %cD (RFC2822) matches Go's RFC1123Z format
777 ret.AuthorDate, _ = ParseGitDate(fields[3])
778 ret.CommitDate, _ = ParseGitDate(fields[4])
779 ret.AuthorEmail = fields[5]
780 ret.AuthorName = fields[6]
781 ret.CommitterEmail = fields[7]
782 ret.CommitterName = fields[8]
783 if len(fields) > 9 {
784 ret.Subject = strings.TrimRight(fields[9], "\n")
785 }
786 return ret, nil
787 } else {
788 msg := tr.Tr.Get("Unexpected output from `git show`: %v", string(out))
789 return nil, errors.New(msg)
790 }
791 }
792
793 func GitAndRootDirs() (string, string, error) {
794 cmd, err := gitNoLFS("rev-parse", "--git-dir", "--show-toplevel")
795 if err != nil {
796 return "", "", errors.New(tr.Tr.Get("failed to find `git rev-parse --git-dir --show-toplevel`: %v", err))
797 }
798 buf := &bytes.Buffer{}
799 cmd.Stderr = buf
800
801 out, err := cmd.Output()
802 output := string(out)
803 if err != nil {
804 // If we got a fatal error, it's possible we're on a newer
805 // (2.24+) Git and we're not in a worktree, so fall back to just
806 // looking up the repo directory.
807 if lfserrors.ExitStatus(err) == 128 {
808 absGitDir, err := GitDir()
809 return absGitDir, "", err
810 }
811 return "", "", errors.New(tr.Tr.Get("failed to call `git rev-parse --git-dir --show-toplevel`: %q", buf.String()))
812 }
813
814 paths := strings.Split(output, "\n")
815 pathLen := len(paths)
816
817 if pathLen == 0 {
818 return "", "", errors.New(tr.Tr.Get("bad `git rev-parse` output: %q", output))
819 }
820
821 absGitDir, err := tools.CanonicalizePath(paths[0], false)
822 if err != nil {
823 return "", "", errors.New(tr.Tr.Get("error converting %q to absolute: %s", paths[0], err))
824 }
825
826 if pathLen == 1 || len(paths[1]) == 0 {
827 return absGitDir, "", nil
828 }
829
830 absRootDir, err := tools.CanonicalizePath(paths[1], false)
831 return absGitDir, absRootDir, err
832 }
833
834 func RootDir() (string, error) {
835 cmd, err := gitNoLFS("rev-parse", "--show-toplevel")
836 if err != nil {
837 return "", errors.New(tr.Tr.Get("failed to find `git rev-parse --show-toplevel`: %v", err))
838 }
839 out, err := cmd.Output()
840 if err != nil {
841 return "", errors.New(tr.Tr.Get("failed to call `git rev-parse --show-toplevel`: %v %v", err, string(out)))
842 }
843
844 path := strings.TrimSpace(string(out))
845 path, err = tools.TranslateCygwinPath(path)
846 if err != nil {
847 return "", err
848 }
849
850 if len(path) == 0 {
851 return "", errors.New(tr.Tr.Get("no output from `git rev-parse --show-toplevel`"))
852 }
853
854 return tools.CanonicalizePath(path, false)
855 }
856
857 func GitDir() (string, error) {
858 cmd, err := gitNoLFS("rev-parse", "--git-dir")
859 if err != nil {
860 // The %w format specifier is unique to fmt.Errorf(), so we
861 // do not pass it to tr.Tr.Get().
862 return "", fmt.Errorf("%s: %w", tr.Tr.Get("failed to find `git rev-parse --git-dir`"), err)
863 }
864 buf := &bytes.Buffer{}
865 cmd.Stderr = buf
866 out, err := cmd.Output()
867
868 if err != nil {
869 // The %w format specifier is unique to fmt.Errorf(), so we
870 // do not pass it to tr.Tr.Get().
871 return "", fmt.Errorf("%s: %w %v: %v", tr.Tr.Get("failed to call `git rev-parse --git-dir`"), err, string(out), buf.String())
872 }
873 path := strings.TrimSpace(string(out))
874 return tools.CanonicalizePath(path, false)
875 }
876
877 func GitCommonDir() (string, error) {
878 // Versions before 2.5.0 don't have the --git-common-dir option, since
879 // it came in with worktrees, so just fall back to the main Git
880 // directory.
881 if !IsGitVersionAtLeast("2.5.0") {
882 return GitDir()
883 }
884
885 cmd, err := gitNoLFS("rev-parse", "--git-common-dir")
886 if err != nil {
887 return "", errors.New(tr.Tr.Get("failed to find `git rev-parse --git-common-dir`: %v", err))
888 }
889 out, err := cmd.Output()
890 buf := &bytes.Buffer{}
891 cmd.Stderr = buf
892 if err != nil {
893 return "", errors.New(tr.Tr.Get("failed to call `git rev-parse --git-common-dir`: %v %v: %v", err, string(out), buf.String()))
894 }
895 path := strings.TrimSpace(string(out))
896 path, err = tools.TranslateCygwinPath(path)
897 if err != nil {
898 return "", err
899 }
900 return tools.CanonicalizePath(path, false)
901 }
902
903 // A git worktree (ref + path + flags)
904 type Worktree struct {
905 Ref Ref
906 Dir string
907 Prunable bool
908 }
909
910 // GetAllWorktrees returns the refs that all worktrees are using as HEADs plus the worktree's path.
911 // This returns all worktrees plus the main working copy, and works even if
912 // working dir is actually in a worktree right now
913 //
914 // Pass in the git storage dir (parent of 'objects') to work from, in case
915 // we need to fall back to reading the worktree files directly.
916 func GetAllWorktrees(storageDir string) ([]*Worktree, error) {
917 // Versions before 2.7.0 don't support "git-worktree list", and
918 // those before 2.36.0 don't support the "-z" option, so in these
919 // cases we fall back to reading the .git/worktrees directory entries
920 // and then reading the current worktree's HEAD ref. This requires
921 // the contents of .git/worktrees/*/gitdir files to be absolute paths,
922 // which is only true for Git versions prior to 2.48.0.
923 if !IsGitVersionAtLeast("2.36.0") {
924 return getAllWorktreesFromGitDir(storageDir)
925 }
926
927 cmd, err := gitNoLFS(
928 "worktree",
929 "list",
930 "--porcelain",
931 "-z", // handle special chars in filenames
932 )
933 if err != nil {
934 return nil, errors.New(tr.Tr.Get("failed to find `git worktree`: %v", err))
935 }
936
937 stdout, err := cmd.StdoutPipe()
938 if err != nil {
939 return nil, errors.New(tr.Tr.Get("failed to open output pipe to `git worktree`: %v", err))
940 }
941 stderr, err := cmd.StderrPipe()
942 if err != nil {
943 return nil, errors.New(tr.Tr.Get("failed to open error pipe to `git worktree`: %v", err))
944 }
945
946 if err := cmd.Start(); err != nil {
947 return nil, errors.New(tr.Tr.Get("failed to start `git worktree`: %v", err))
948 }
949
950 scanner := bufio.NewScanner(stdout)
951 scanner.Split(tools.SplitOnNul)
952 var dir string
953 var ref *Ref
954 var prunable bool
955 var worktrees []*Worktree
956 for scanner.Scan() {
957 line := scanner.Text()
958
959 if len(line) == 0 {
960 if len(dir) > 0 && ref != nil && len(ref.Sha) > 0 {
961 worktrees = append(worktrees, &Worktree{
962 Ref: *ref,
963 Dir: dir,
964 Prunable: prunable,
965 })
966 }
967 dir = ""
968 ref = nil
969 continue
970 }
971
972 parts := strings.SplitN(scanner.Text(), " ", 2)
973
974 // We ignore other attributes such as "locked" for now.
975 switch parts[0] {
976 case "worktree":
977 if len(parts) == 2 && len(dir) == 0 {
978 dir = filepath.Clean(parts[1])
979 ref = &Ref{Type: RefTypeOther}
980 prunable = false
981 }
982 case "HEAD":
983 if len(parts) == 2 && ref != nil {
984 ref.Sha = parts[1]
985 ref.Name = parts[1]
986 }
987 case "branch":
988 if len(parts) == 2 && ref != nil && len(ref.Sha) > 0 {
989 ref = ParseRef(parts[1], ref.Sha)
990 }
991 case "bare":
992 // We ignore bare worktrees.
993 dir = ""
994 ref = nil
995 case "prunable":
996 prunable = true
997 }
998 }
999
1000 // We assume any error output will be short and won't block
1001 // command completion if it isn't drained by a separate goroutine.
1002 msg, _ := io.ReadAll(stderr)
1003 if err := cmd.Wait(); err != nil {
1004 return nil, errors.New(tr.Tr.Get("error in `git worktree`: %v: %s", err, msg))
1005 }
1006
1007 return worktrees, nil
1008 }
1009
1010 func getAllWorktreesFromGitDir(storageDir string) ([]*Worktree, error) {
1011 worktreesdir := filepath.Join(storageDir, "worktrees")
1012 dirf, err := os.Open(worktreesdir)
1013 if err != nil && !os.IsNotExist(err) {
1014 return nil, err
1015 }
1016
1017 var worktrees []*Worktree
1018 if err == nil {
1019 // There are some worktrees
1020 defer dirf.Close()
1021 direntries, err := dirf.Readdir(0)
1022 if err != nil {
1023 return nil, err
1024 }
1025 for _, dirfi := range direntries {
1026 if dirfi.IsDir() {
1027 // to avoid having to chdir and run git commands to identify the commit
1028 // just read the HEAD file & git rev-parse if necessary
1029 // Since the git repo is shared the same rev-parse will work from this location
1030 headfile := filepath.Join(worktreesdir, dirfi.Name(), "HEAD")
1031 ref, err := parseRefFile(headfile)
1032 if err != nil {
1033 tracerx.Printf("Error reading %v for worktree, skipping: %v", headfile, err)
1034 continue
1035 }
1036
1037 // Read the gitdir file to get the location of the git repo
1038 dirfile := filepath.Join(worktreesdir, dirfi.Name(), "gitdir")
1039 dir, err := parseDirFile(dirfile)
1040 if err != nil {
1041 tracerx.Printf("Error reading %v for worktree, skipping: %v", dirfile, err)
1042 continue
1043 }
1044
1045 // Check if the worktree exists.
1046 dir = filepath.Dir(dir)
1047 var prunable bool
1048 if _, err := os.Stat(dir); err != nil {
1049 if os.IsNotExist(err) {
1050 prunable = true
1051 } else {
1052 tracerx.Printf("Error checking worktree directory %s: %v", dir, err)
1053 }
1054 }
1055
1056 worktrees = append(worktrees, &Worktree{
1057 Ref: *ref,
1058 Dir: dir,
1059 Prunable: prunable,
1060 })
1061 }
1062 }
1063 }
1064
1065 // This has only established the separate worktrees, not the original checkout
1066 // If the storageDir contains a HEAD file and a RootDir then there is a main checkout
1067 // as well; this must be resolveable whether you're in the main checkout or
1068 // a worktree
1069 headfile := filepath.Join(storageDir, "HEAD")
1070 ref, err := parseRefFile(headfile)
1071 if err == nil {
1072 dir, err := RootDir()
1073 if err == nil {
1074 worktrees = append(worktrees, &Worktree{
1075 Ref: *ref,
1076 Dir: dir,
1077 Prunable: false,
1078 })
1079 } else { // ok if not exists, probably bare repo
1080 tracerx.Printf("Error getting toplevel for main checkout, skipping: %v", err)
1081 }
1082 } else if !os.IsNotExist(err) { // ok if not exists, probably bare repo
1083 tracerx.Printf("Error reading %v for main checkout, skipping: %v", headfile, err)
1084 }
1085 return worktrees, nil
1086 }
1087
1088 // Manually parse a reference file like HEAD and return the Ref it resolves to
1089 func parseRefFile(filename string) (*Ref, error) {
1090 bytes, err := os.ReadFile(filename)
1091 if err != nil {
1092 return nil, err
1093 }
1094 contents := strings.TrimSpace(string(bytes))
1095 if strings.HasPrefix(contents, "ref:") {
1096 contents = strings.TrimSpace(contents[4:])
1097 }
1098 return ResolveRef(contents)
1099 }
1100
1101 func parseDirFile(filename string) (string, error) {
1102 bytes, err := os.ReadFile(filename)
1103 if err != nil {
1104 return "", err
1105 }
1106 contents := strings.TrimSpace(string(bytes))
1107 return contents, nil
1108 }
1109
1110 // IsBare returns whether or not a repository is bare. It requires that the
1111 // current working directory is a repository.
1112 //
1113 // If there was an error determining whether or not the repository is bare, it
1114 // will be returned.
1115 func IsBare() (bool, error) {
1116 s, err := subprocess.SimpleExec(
1117 "git", "rev-parse", "--is-bare-repository")
1118
1119 if err != nil {
1120 return false, err
1121 }
1122
1123 return strconv.ParseBool(s)
1124 }
1125
1126 // For compatibility with git clone we must mirror all flags in CloneWithoutFilters
1127 type CloneFlags struct {
1128 // --template <template_directory>
1129 TemplateDirectory string
1130 // -l --local
1131 Local bool
1132 // -s --shared
1133 Shared bool
1134 // --no-hardlinks
1135 NoHardlinks bool
1136 // -q --quiet
1137 Quiet bool
1138 // -n --no-checkout
1139 NoCheckout bool
1140 // --progress
1141 Progress bool
1142 // --bare
1143 Bare bool
1144 // --mirror
1145 Mirror bool
1146 // -o <name> --origin <name>
1147 Origin string
1148 // -b <name> --branch <name>
1149 Branch string
1150 // -u <upload-pack> --upload-pack <pack>
1151 Upload string
1152 // --reference <repository>
1153 Reference string
1154 // --reference-if-able <repository>
1155 ReferenceIfAble string
1156 // --dissociate
1157 Dissociate bool
1158 // --separate-git-dir <git dir>
1159 SeparateGit string
1160 // --depth <depth>
1161 Depth string
1162 // --recursive
1163 Recursive bool
1164 // --recurse-submodules
1165 RecurseSubmodules bool
1166 // -c <value> --config <value>
1167 Config string
1168 // --single-branch
1169 SingleBranch bool
1170 // --no-single-branch
1171 NoSingleBranch bool
1172 // --verbose
1173 Verbose bool
1174 // --ipv4
1175 Ipv4 bool
1176 // --ipv6
1177 Ipv6 bool
1178 // --shallow-since <date>
1179 ShallowSince string
1180 // --shallow-since <date>
1181 ShallowExclude string
1182 // --shallow-submodules
1183 ShallowSubmodules bool
1184 // --no-shallow-submodules
1185 NoShallowSubmodules bool
1186 // jobs <n>
1187 Jobs int64
1188 }
1189
1190 // CloneWithoutFilters clones a git repo but without the smudge filter enabled
1191 // so that files in the working copy will be pointers and not real LFS data
1192 func CloneWithoutFilters(flags CloneFlags, args []string) error {
1193
1194 cmdargs := []string{"clone"}
1195
1196 // flags
1197 if flags.Bare {
1198 cmdargs = append(cmdargs, "--bare")
1199 }
1200 if len(flags.Branch) > 0 {
1201 cmdargs = append(cmdargs, "--branch", flags.Branch)
1202 }
1203 if len(flags.Config) > 0 {
1204 cmdargs = append(cmdargs, "--config", flags.Config)
1205 }
1206 if len(flags.Depth) > 0 {
1207 cmdargs = append(cmdargs, "--depth", flags.Depth)
1208 }
1209 if flags.Dissociate {
1210 cmdargs = append(cmdargs, "--dissociate")
1211 }
1212 if flags.Ipv4 {
1213 cmdargs = append(cmdargs, "--ipv4")
1214 }
1215 if flags.Ipv6 {
1216 cmdargs = append(cmdargs, "--ipv6")
1217 }
1218 if flags.Local {
1219 cmdargs = append(cmdargs, "--local")
1220 }
1221 if flags.Mirror {
1222 cmdargs = append(cmdargs, "--mirror")
1223 }
1224 if flags.NoCheckout {
1225 cmdargs = append(cmdargs, "--no-checkout")
1226 }
1227 if flags.NoHardlinks {
1228 cmdargs = append(cmdargs, "--no-hardlinks")
1229 }
1230 if flags.NoSingleBranch {
1231 cmdargs = append(cmdargs, "--no-single-branch")
1232 }
1233 if len(flags.Origin) > 0 {
1234 cmdargs = append(cmdargs, "--origin", flags.Origin)
1235 }
1236 if flags.Progress {
1237 cmdargs = append(cmdargs, "--progress")
1238 }
1239 if flags.Quiet {
1240 cmdargs = append(cmdargs, "--quiet")
1241 }
1242 if flags.Recursive {
1243 cmdargs = append(cmdargs, "--recursive")
1244 }
1245 if flags.RecurseSubmodules {
1246 cmdargs = append(cmdargs, "--recurse-submodules")
1247 }
1248 if len(flags.Reference) > 0 {
1249 cmdargs = append(cmdargs, "--reference", flags.Reference)
1250 }
1251 if len(flags.ReferenceIfAble) > 0 {
1252 cmdargs = append(cmdargs, "--reference-if-able", flags.ReferenceIfAble)
1253 }
1254 if len(flags.SeparateGit) > 0 {
1255 cmdargs = append(cmdargs, "--separate-git-dir", flags.SeparateGit)
1256 }
1257 if flags.Shared {
1258 cmdargs = append(cmdargs, "--shared")
1259 }
1260 if flags.SingleBranch {
1261 cmdargs = append(cmdargs, "--single-branch")
1262 }
1263 if len(flags.TemplateDirectory) > 0 {
1264 cmdargs = append(cmdargs, "--template", flags.TemplateDirectory)
1265 }
1266 if len(flags.Upload) > 0 {
1267 cmdargs = append(cmdargs, "--upload-pack", flags.Upload)
1268 }
1269 if flags.Verbose {
1270 cmdargs = append(cmdargs, "--verbose")
1271 }
1272 if len(flags.ShallowSince) > 0 {
1273 cmdargs = append(cmdargs, "--shallow-since", flags.ShallowSince)
1274 }
1275 if len(flags.ShallowExclude) > 0 {
1276 cmdargs = append(cmdargs, "--shallow-exclude", flags.ShallowExclude)
1277 }
1278 if flags.ShallowSubmodules {
1279 cmdargs = append(cmdargs, "--shallow-submodules")
1280 }
1281 if flags.NoShallowSubmodules {
1282 cmdargs = append(cmdargs, "--no-shallow-submodules")
1283 }
1284 if flags.Jobs > -1 {
1285 cmdargs = append(cmdargs, "--jobs", strconv.FormatInt(flags.Jobs, 10))
1286 }
1287
1288 // Now args
1289 cmdargs = append(cmdargs, args...)
1290 cmd, err := gitNoLFS(cmdargs...)
1291 if err != nil {
1292 return errors.New(tr.Tr.Get("failed to find `git clone`: %v", err))
1293 }
1294
1295 // Assign all streams direct
1296 cmd.Stdout = os.Stdout
1297 cmd.Stderr = os.Stderr
1298 cmd.Stdin = os.Stdin
1299
1300 err = cmd.Start()
1301 if err != nil {
1302 return errors.New(tr.Tr.Get("failed to start `git clone`: %v", err))
1303 }
1304
1305 err = cmd.Wait()
1306 if err != nil {
1307 return errors.New(tr.Tr.Get("`git clone` failed: %v", err))
1308 }
1309
1310 return nil
1311 }
1312
1313 // Checkout performs an invocation of `git-checkout(1)` applying the given
1314 // treeish, paths, and force option, if given.
1315 //
1316 // If any error was encountered, it will be returned immediately. Otherwise, the
1317 // checkout has occurred successfully.
1318 func Checkout(treeish string, paths []string, force bool) error {
1319 args := []string{"checkout"}
1320 if force {
1321 args = append(args, "--force")
1322 }
1323
1324 if len(treeish) > 0 {
1325 args = append(args, treeish)
1326 }
1327
1328 if len(paths) > 0 {
1329 args = append(args, append([]string{"--"}, paths...)...)
1330 }
1331
1332 _, err := gitNoLFSSimple(args...)
1333 return err
1334 }
1335
1336 // CachedRemoteRefs returns the list of branches & tags for a remote which are
1337 // currently cached locally. No remote request is made to verify them.
1338 func CachedRemoteRefs(remoteName string) ([]*Ref, error) {
1339 var ret []*Ref
1340 cmd, err := gitNoLFS("show-ref")
1341 if err != nil {
1342 return nil, errors.New(tr.Tr.Get("failed to find `git show-ref`: %v", err))
1343 }
1344
1345 outp, err := cmd.StdoutPipe()
1346 if err != nil {
1347 return nil, errors.New(tr.Tr.Get("failed to call `git show-ref`: %v", err))
1348 }
1349 cmd.Start()
1350 scanner := bufio.NewScanner(outp)
1351
1352 refPrefix := fmt.Sprintf("refs/remotes/%v/", remoteName)
1353 for scanner.Scan() {
1354 if sha, name, ok := parseShowRefLine(refPrefix, scanner.Text()); ok {
1355 // Don't match head
1356 if name == "HEAD" {
1357 continue
1358 }
1359 ret = append(ret, &Ref{name, RefTypeRemoteBranch, sha})
1360 }
1361 }
1362 return ret, cmd.Wait()
1363 }
1364
1365 func parseShowRefLine(refPrefix, line string) (sha, name string, ok bool) {
1366 // line format: <sha> <space> <ref>
1367 sha, ref, found := strings.Cut(line, " ")
1368 if !found {
1369 return "", "", false
1370 }
1371 if !strings.HasPrefix(ref, refPrefix) {
1372 return "", "", false
1373 }
1374 return sha, strings.TrimSpace(ref[len(refPrefix):]), true
1375 }
1376
1377 // Fetch performs a fetch with no arguments against the given remotes.
1378 func Fetch(remotes ...string) error {
1379 if len(remotes) == 0 {
1380 return nil
1381 }
1382
1383 var args []string
1384 if len(remotes) > 1 {
1385 args = []string{"--multiple", "--"}
1386 }
1387 args = append(args, remotes...)
1388
1389 _, err := gitNoLFSSimple(append([]string{"fetch"}, args...)...)
1390 return err
1391 }
1392
1393 // RemoteRefs returns a list of branches and, optionally, tags for a remote
1394 // by actually accessing the remote via git ls-remote.
1395 func RemoteRefs(remoteName string, withTags bool) ([]*Ref, error) {
1396 var ret []*Ref
1397 args := []string{"ls-remote", "--heads", "-q"}
1398 if withTags {
1399 args = append(args, "--tags")
1400 }
1401 args = append(args, remoteName)
1402
1403 cmd, err := gitNoLFS(args...)
1404 if err != nil {
1405 return nil, errors.New(tr.Tr.Get("failed to find `git ls-remote`: %v", err))
1406 }
1407
1408 outp, err := cmd.StdoutPipe()
1409 if err != nil {
1410 return nil, errors.New(tr.Tr.Get("failed to call `git ls-remote`: %v", err))
1411 }
1412 cmd.Start()
1413 scanner := bufio.NewScanner(outp)
1414
1415 for scanner.Scan() {
1416 if sha, ns, name, ok := parseLsRemoteLine(scanner.Text()); ok {
1417 // Don't match head
1418 if name == "HEAD" {
1419 continue
1420 }
1421
1422 typ := RefTypeRemoteBranch
1423 if ns == "tags" {
1424 if !withTags {
1425 return nil, errors.New(tr.Tr.Get("unexpected tag returned by `git ls-remote --heads`: %s %s", name, sha))
1426 }
1427 typ = RefTypeRemoteTag
1428 }
1429 ret = append(ret, &Ref{name, typ, sha})
1430 }
1431 }
1432 return ret, cmd.Wait()
1433 }
1434
1435 func parseLsRemoteLine(line string) (sha, ns, name string, ok bool) {
1436 const headPrefix = "refs/heads/"
1437 const tagPrefix = "refs/tags/"
1438
1439 // line format: <sha> <tab> <ref>
1440 sha, ref, found := strings.Cut(line, "\t")
1441 if !found {
1442 return "", "", "", false
1443 }
1444 switch {
1445 case strings.HasPrefix(ref, headPrefix):
1446 ns = "heads"
1447 name = ref[len(headPrefix):]
1448 case strings.HasPrefix(ref, tagPrefix):
1449 ns = "tags"
1450 name = ref[len(tagPrefix):]
1451 default:
1452 return "", "", "", false
1453 }
1454 return sha, ns, strings.TrimSpace(name), true
1455 }
1456
1457 // AllRefs returns a slice of all references in a Git repository in the current
1458 // working directory, or an error if those references could not be loaded.
1459 func AllRefs() ([]*Ref, error) {
1460 return AllRefsIn("")
1461 }
1462
1463 // AllRefs returns a slice of all references in a Git repository located in a
1464 // the given working directory "wd", or an error if those references could not
1465 // be loaded.
1466 func AllRefsIn(wd string) ([]*Ref, error) {
1467 cmd, err := gitNoLFS(
1468 "for-each-ref", "--format=%(objectname)%00%(refname)")
1469 if err != nil {
1470 return nil, lfserrors.Wrap(err, tr.Tr.Get("failed to find `git for-each-ref`: %v", err))
1471 }
1472 cmd.Dir = wd
1473
1474 outp, err := cmd.StdoutPipe()
1475 if err != nil {
1476 return nil, lfserrors.Wrap(err, tr.Tr.Get("cannot open pipe"))
1477 }
1478 cmd.Start()
1479
1480 refs := make([]*Ref, 0)
1481
1482 scanner := bufio.NewScanner(outp)
1483 for scanner.Scan() {
1484 parts := strings.SplitN(scanner.Text(), "\x00", 2)
1485 if len(parts) != 2 {
1486 return nil, lfserrors.New(tr.Tr.Get(
1487 "invalid `git for-each-ref` line: %q", scanner.Text()))
1488 }
1489
1490 sha := parts[0]
1491 typ, name := ParseRefToTypeAndName(parts[1])
1492
1493 refs = append(refs, &Ref{
1494 Name: name,
1495 Type: typ,
1496 Sha: sha,
1497 })
1498 }
1499
1500 if err := scanner.Err(); err != nil {
1501 return nil, err
1502 }
1503
1504 return refs, nil
1505 }
1506
1507 // GetTrackedFiles returns a list of files which are tracked in Git which match
1508 // the pattern specified (standard wildcard form)
1509 // Both pattern and the results are relative to the current working directory, not
1510 // the root of the repository
1511 func GetTrackedFiles(pattern string) ([]string, error) {
1512 safePattern := sanitizePattern(pattern)
1513 rootWildcard := len(safePattern) < len(pattern) && strings.ContainsRune(safePattern, '*')
1514
1515 var ret []string
1516 cmd, err := gitNoLFS(
1517 "ls-files",
1518 "--ignored",
1519 "--cached", // include things which are staged but not committed right now
1520 "-z", // handle special chars in filenames
1521 "-x",
1522 safePattern)
1523 if err != nil {
1524 return nil, errors.New(tr.Tr.Get("failed to find `git ls-files`: %v", err))
1525 }
1526
1527 outp, err := cmd.StdoutPipe()
1528 if err != nil {
1529 return nil, errors.New(tr.Tr.Get("failed to call `git ls-files`: %v", err))
1530 }
1531 cmd.Start()
1532 scanner := bufio.NewScanner(outp)
1533 scanner.Split(tools.SplitOnNul)
1534 for scanner.Scan() {
1535 line := scanner.Text()
1536
1537 // If the given pattern is a root wildcard, skip all files which
1538 // are not direct descendants of the repository's root.
1539 //
1540 // This matches the behavior of how .gitattributes performs
1541 // filename matches.
1542 if rootWildcard && filepath.Dir(line) != "." {
1543 continue
1544 }
1545
1546 ret = append(ret, strings.TrimSpace(line))
1547 }
1548 return ret, cmd.Wait()
1549 }
1550
1551 func sanitizePattern(pattern string) string {
1552 if strings.HasPrefix(pattern, "/") {
1553 return pattern[1:]
1554 }
1555
1556 return pattern
1557 }
1558
1559 // GetFilesChanged returns a list of files which were changed, either between 2
1560 // commits, or at a single commit if you only supply one argument and a blank
1561 // string for the other
1562 func GetFilesChanged(from, to string) ([]string, error) {
1563 var files []string
1564 args := []string{
1565 "-c", "core.quotepath=false", // handle special chars in filenames
1566 "diff-tree",
1567 "--no-commit-id",
1568 "--name-only",
1569 "-r",
1570 }
1571
1572 if len(from) > 0 {
1573 args = append(args, from)
1574 }
1575 if len(to) > 0 {
1576 args = append(args, to)
1577 }
1578 args = append(args, "--") // no ambiguous patterns
1579
1580 cmd, err := gitNoLFS(args...)
1581 if err != nil {
1582 return nil, errors.New(tr.Tr.Get("failed to find `git diff-tree`: %v", err))
1583 }
1584 outp, err := cmd.StdoutPipe()
1585 if err != nil {
1586 return nil, errors.New(tr.Tr.Get("failed to call `git diff-tree`: %v", err))
1587 }
1588 if err := cmd.Start(); err != nil {
1589 return nil, errors.New(tr.Tr.Get("failed to start `git diff-tree`: %v", err))
1590 }
1591 scanner := bufio.NewScanner(outp)
1592 for scanner.Scan() {
1593 files = append(files, strings.TrimSpace(scanner.Text()))
1594 }
1595 if err := cmd.Wait(); err != nil {
1596 return nil, errors.New(tr.Tr.Get("`git diff-tree` failed: %v", err))
1597 }
1598
1599 return files, err
1600 }
1601
1602 // IsFileModified returns whether the filepath specified is modified according
1603 // to `git status`. A file is modified if it has uncommitted changes in the
1604 // working copy or the index. This includes being untracked.
1605 func IsFileModified(filepath string) (bool, error) {
1606
1607 args := []string{
1608 "-c", "core.quotepath=false", // handle special chars in filenames
1609 "status",
1610 "--porcelain",
1611 "--", // separator in case filename ambiguous
1612 filepath,
1613 }
1614 cmd, err := git(args...)
1615 if err != nil {
1616 return false, lfserrors.Wrap(err, tr.Tr.Get("failed to find `git status`"))
1617 }
1618 outp, err := cmd.StdoutPipe()
1619 if err != nil {
1620 return false, lfserrors.Wrap(err, tr.Tr.Get("Failed to call `git status`"))
1621 }
1622 if err := cmd.Start(); err != nil {
1623 return false, lfserrors.Wrap(err, tr.Tr.Get("Failed to start `git status`"))
1624 }
1625 matched := false
1626 for scanner := bufio.NewScanner(outp); scanner.Scan(); {
1627 line := scanner.Text()
1628 // Porcelain format is "<I><W> <filename>"
1629 // Where <I> = index status, <W> = working copy status
1630 if len(line) > 3 {
1631 // Double-check even though should be only match
1632 if strings.TrimSpace(line[3:]) == filepath {
1633 matched = true
1634 // keep consuming output to exit cleanly
1635 // will typically fall straight through anyway due to 1 line output
1636 }
1637 }
1638 }
1639 if err := cmd.Wait(); err != nil {
1640 return false, lfserrors.Wrap(err, tr.Tr.Get("`git status` failed"))
1641 }
1642
1643 return matched, nil
1644 }
1645
1646 // IsWorkingCopyDirty returns true if and only if the working copy in which the
1647 // command was executed is dirty as compared to the index.
1648 //
1649 // If the status of the working copy could not be determined, an error will be
1650 // returned instead.
1651 func IsWorkingCopyDirty() (bool, error) {
1652 bare, err := IsBare()
1653 if bare || err != nil {
1654 return false, err
1655 }
1656
1657 out, err := gitSimple("status", "--porcelain")
1658 if err != nil {
1659 return false, err
1660 }
1661 return len(out) != 0, nil
1662 }
1663
1664 func ObjectDatabase(osEnv, gitEnv Environment, gitdir, tempdir string) (*gitobj.ObjectDatabase, error) {
1665 var options []gitobj.Option
1666 objdir, ok := osEnv.Get("GIT_OBJECT_DIRECTORY")
1667 if !ok {
1668 objdir = filepath.Join(gitdir, "objects")
1669 }
1670 alternates, _ := osEnv.Get("GIT_ALTERNATE_OBJECT_DIRECTORIES")
1671 if alternates != "" {
1672 options = append(options, gitobj.Alternates(alternates))
1673 }
1674 hashAlgo, _ := gitEnv.Get("extensions.objectformat")
1675 if hashAlgo != "" {
1676 options = append(options, gitobj.ObjectFormat(gitobj.ObjectFormatAlgorithm(hashAlgo)))
1677 }
1678 odb, err := gitobj.FromFilesystem(objdir, tempdir, options...)
1679 if err != nil {
1680 return nil, err
1681 }
1682 if odb.Hasher() == nil {
1683 return nil, errors.New(tr.Tr.Get("unsupported repository hash algorithm %q", hashAlgo))
1684 }
1685 return odb, nil
1686 }
1687
1688 func remotesForTreeish(treeish string) []string {
1689 var outp string
1690 var err error
1691 if treeish == "" {
1692 //Treeish is empty for sparse checkout
1693 tracerx.Printf("git: treeish: not provided")
1694 outp, err = gitNoLFSSimple("branch", "-r", "--contains", "HEAD")
1695 } else {
1696 tracerx.Printf("git: treeish: %q", treeish)
1697 outp, err = gitNoLFSSimple("branch", "-r", "--contains", treeish)
1698 }
1699 if err != nil || outp == "" {
1700 tracerx.Printf("git: symbolic name: can't resolve symbolic name for ref: %q", treeish)
1701 return []string{}
1702 }
1703 return strings.Split(outp, "\n")
1704 }
1705
1706 // remoteForRef will try to determine the remote from the ref name.
1707 // This will return an empty string if any of the remote names have a slash
1708 // because slashes introduce ambiguity. Consider two refs:
1709 //
1710 // 1. upstream/main
1711 // 2. upstream/test/main
1712 //
1713 // Is the remote "upstream" or "upstream/test"? It could be either, or both.
1714 // We could use git for-each-ref with %(upstream:remotename) if there were a tracking branch,
1715 // but this is not guaranteed to exist either.
1716 func remoteForRef(refname string) string {
1717 tracerx.Printf("git: working ref: %s", refname)
1718 remotes, err := RemoteList()
1719 if err != nil {
1720 return ""
1721 }
1722 parts := strings.Split(refname, "/")
1723 if len(parts) < 2 {
1724 return ""
1725 }
1726 for _, name := range remotes {
1727 if strings.Contains(name, "/") {
1728 tracerx.Printf("git: ref remote: cannot determine remote for ref %s since remote %s contains a slash", refname, name)
1729 return ""
1730 }
1731 }
1732 remote := parts[0]
1733 tracerx.Printf("git: working remote %s", remote)
1734 return remote
1735 }
1736
1737 func getValidRemote(refs []string) string {
1738 for _, ref := range refs {
1739 if ref != "" {
1740 return ref
1741 }
1742 }
1743 return ""
1744 }
1745
1746 // FirstRemoteForTreeish returns the first remote found which contains the treeish.
1747 func FirstRemoteForTreeish(treeish string) string {
1748 name := getValidRemote(remotesForTreeish(treeish))
1749 if name == "" {
1750 tracerx.Printf("git: remote treeish: no valid remote refs parsed for %q", treeish)
1751 return ""
1752 }
1753 return remoteForRef(name)
1754 }