internal/gitutil/read.go
217 lines · 6364 bytes
18 symbols in this file
1package gitutil
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os/exec"
10 "strconv"
11 "strings"
12 "time"
13
14 "gitbay.org/gitbay/internal/toolpath"
15)
16
17type TreeEntry struct {
18 Mode string
19 Type string // blob | tree
20 SHA string
21 Size int64 // -1 for trees
22 Name string
23}
24
25// ListTree lists one level of the tree at ref:path.
26func ListTree(dir, ref, path string) ([]TreeEntry, error) {
27 return lsTree(dir, ref, path, false)
28}
29
30// ListTreeRecursive lists every blob under ref:path, named by its path
31// relative to that tree.
32func ListTreeRecursive(dir, ref, path string) ([]TreeEntry, error) {
33 return lsTree(dir, ref, path, true)
34}
35
36func lsTree(dir, ref, path string, recursive bool) ([]TreeEntry, error) {
37 spec := ref
38 if path != "" {
39 spec = ref + ":" + path
40 }
41 args := []string{"-C", dir, "ls-tree", "-l"}
42 if recursive {
43 args = append(args, "-r")
44 }
45 cmd := exec.Command(toolpath.Look("git"), append(args, "--end-of-options", spec)...)
46 out, err := cmd.Output()
47 if err != nil {
48 return nil, fmt.Errorf("ls-tree %s: %w", spec, err)
49 }
50 var entries []TreeEntry
51 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
52 if line == "" {
53 continue
54 }
55 // <mode> <type> <sha> <size>\t<name>
56 meta, name, ok := strings.Cut(line, "\t")
57 if !ok {
58 continue
59 }
60 f := strings.Fields(meta)
61 if len(f) != 4 {
62 continue
63 }
64 size := int64(-1)
65 if f[3] != "-" {
66 size, _ = strconv.ParseInt(f[3], 10, 64)
67 }
68 entries = append(entries, TreeEntry{Mode: f[0], Type: f[1], SHA: f[2], Size: size, Name: name})
69 }
70 return entries, nil
71}
72
73// ReadBlob returns the contents of ref:path, capped at limit bytes.
74func ReadBlob(dir, ref, path string, limit int64) ([]byte, error) {
75 cmd := exec.Command(toolpath.Look("git"), "-C", dir, "cat-file", "blob", "--end-of-options", ref+":"+path)
76 stdout, err := cmd.StdoutPipe()
77 if err != nil {
78 return nil, err
79 }
80 if err := cmd.Start(); err != nil {
81 return nil, err
82 }
83 data, err := io.ReadAll(io.LimitReader(stdout, limit))
84 io.Copy(io.Discard, stdout) // drain so git exits cleanly
85 if werr := cmd.Wait(); werr != nil {
86 return nil, fmt.Errorf("cat-file blob %s:%s: %w", ref, path, werr)
87 }
88 return data, err
89}
90
91// BlobID returns the object id of the blob at ref:path; errors if the path
92// is absent or not a blob.
93func BlobID(dir, ref, path string) (string, error) {
94 spec := ref + ":" + path
95 if strings.ContainsAny(spec, "\n\r") {
96 return "", fmt.Errorf("no blob %s", spec)
97 }
98 cmd := exec.Command(toolpath.Look("git"), "-C", dir, "cat-file", "--batch-check=%(objecttype) %(objectname)")
99 cmd.Stdin = strings.NewReader(spec + "\n")
100 out, err := cmd.Output()
101 if err != nil {
102 return "", fmt.Errorf("cat-file %s: %w", spec, err)
103 }
104 f := strings.Fields(string(out))
105 if len(f) != 2 || f[0] != "blob" {
106 return "", fmt.Errorf("no blob %s", spec)
107 }
108 return f[1], nil
109}
110
111// ResolveRef resolves a ref or sha to a full commit sha; errors if absent.
112func ResolveRef(dir, ref string) (string, error) {
113 cmd := exec.Command(toolpath.Look("git"), "-C", dir, "rev-parse", "--verify", "--quiet", "--end-of-options", ref+"^{commit}")
114 out, err := cmd.Output()
115 if err != nil {
116 return "", fmt.Errorf("unknown ref %q", ref)
117 }
118 return strings.TrimSpace(string(out)), nil
119}
120
121type Ref struct {
122 Name string
123 SHA string
124}
125
126// Refs lists branches or tags; kind is "heads" or "tags".
127func Refs(dir, kind string) ([]Ref, error) {
128 cmd := exec.Command(toolpath.Look("git"), "-C", dir, "for-each-ref",
129 "--format=%(refname:short) %(objectname)", "refs/"+kind)
130 out, err := cmd.Output()
131 if err != nil {
132 return nil, err
133 }
134 var refs []Ref
135 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
136 if name, sha, ok := strings.Cut(line, " "); ok {
137 refs = append(refs, Ref{Name: name, SHA: sha})
138 }
139 }
140 return refs, nil
141}
142
143// Bounds on one archive: a request cannot hold git and a goroutine for
144// longer than this, or stream more than this, however large the
145// repository or however slowly the client reads (#124).
146const archiveTimeout = 2 * time.Minute
147
148var MaxArchiveBytes int64 = 512 << 20
149
150var ErrArchiveTooLarge = errors.New("archive exceeds the size limit")
151
152// Archive streams a tar.gz of ref to w, within archiveTimeout and
153// MaxArchiveBytes. Past either, git is killed and the error says which.
154func Archive(dir, ref, prefix string, w io.Writer) error {
155 return ArchiveUntil(dir, ref, prefix, w, nil)
156}
157
158// ArchiveUntil is Archive, killing git when stop closes.
159func ArchiveUntil(dir, ref, prefix string, w io.Writer, stop <-chan struct{}) error {
160 ctx, cancel := context.WithTimeout(context.Background(), archiveTimeout)
161 defer cancel()
162 cmd := exec.CommandContext(ctx, toolpath.Look("git"), "-C", dir, "archive", "--format=tar.gz", "--prefix="+prefix+"/", "--end-of-options", ref)
163 lw := &cappedWriter{w: w, left: MaxArchiveBytes, stop: cancel}
164 cmd.Stdout = lw
165 err := RunUntil(cmd, stop)
166 switch {
167 case lw.exceeded:
168 return ErrArchiveTooLarge
169 case errors.Is(ctx.Err(), context.DeadlineExceeded):
170 return fmt.Errorf("git archive: timed out after %s", archiveTimeout)
171 }
172 return err
173}
174
175// cappedWriter passes bytes through until the cap, then stops the
176// producer instead of writing a truncated tail.
177type cappedWriter struct {
178 w io.Writer
179 left int64
180 stop func()
181 exceeded bool
182}
183
184func (c *cappedWriter) Write(p []byte) (int, error) {
185 if int64(len(p)) > c.left {
186 c.exceeded = true
187 c.stop()
188 return 0, ErrArchiveTooLarge
189 }
190 c.left -= int64(len(p))
191 return c.w.Write(p)
192}
193
194// ShowPatch returns the stat+patch text for one commit.
195func ShowPatch(dir, sha string, limit int64) (patch string, truncated bool, err error) {
196 cmd := exec.Command(toolpath.Look("git"), "-C", dir, "show", "--stat", "--patch", "--format=", "--end-of-options", sha)
197 stdout, err := cmd.StdoutPipe()
198 if err != nil {
199 return "", false, err
200 }
201 if err := cmd.Start(); err != nil {
202 return "", false, err
203 }
204 // One byte past the limit says whether there was more.
205 data, _ := io.ReadAll(io.LimitReader(stdout, limit+1))
206 io.Copy(io.Discard, stdout)
207 if err := cmd.Wait(); err != nil {
208 return "", false, fmt.Errorf("show %s: %w", sha, err)
209 }
210 data, truncated = cutAtLine(data, limit)
211 return string(data), truncated, nil
212}
213
214// IsBinary reports whether data looks like binary content.
215func IsBinary(data []byte) bool {
216 return bytes.IndexByte(data, 0) >= 0
217}