gunk-dev/the-valley

git.go

source83b8fc332220main's published tip history
7.8 KiB
1package rebase
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "io"
8 "os/exec"
9 "strconv"
10 "strings"
11 "time"
12)
13
14// Git runs git in one repository. Every command runs under the context it
15// is given, so a cancelled context ends the git it is running, and what
16// that git started.
17//
18// The engine never changes the environment it is given. A caller that
19// must not run the repository's hooks or filters says so in Env, as git
20// configuration.
21type Git struct {
22 Dir string // the repository's directory; "" for the current one
23 Env []string // git's environment; nil for this process's own
24 Stdout io.Writer // where a rebase prints as it goes; nil discards it
25 Stderr io.Writer // where git's own diagnostics go, unless quiet; nil discards them
26
27 // Unattended is git that nobody is at a terminal for, as a service's
28 // is. Every command runs in a process group of its own, a command that
29 // reaches origin included, so a cancelled context kills what that
30 // command started too, such as ssh. A caller that sets it never lets git
31 // or ssh ask a question: see command.
32 Unattended bool
33
34 // Phase, when set, is told as a read enters one of its parts, and the
35 // func it returns as that part ends: "fetch" (ls-remote and fetch),
36 // "records" (reading what the listing names) and "transfers"
37 // (verifying transfer statements). Started, when set, is told of each
38 // process started. Both only measure, for the caller's telemetry.
39 Phase func(name string) (end func())
40 Started func()
41}
42
43// phase enters a part of a read, for Phase.
44func (g Git) phase(name string) (end func()) {
45 if g.Phase == nil {
46 return func() {}
47 }
48 return g.Phase(name)
49}
50
51// started counts a process, for Started.
52func (g Git) started() {
53 if g.Started != nil {
54 g.Started()
55 }
56}
57
58// waitDelay is how long a wait for git's output may go on after git has
59// exited, or after a cancelled context has killed it. Something git
60// started may still hold the output open.
61const waitDelay = 5 * time.Second
62
63// reachesOrigin is the git commands that talk to origin.
64var reachesOrigin = map[string]bool{"ls-remote": true, "fetch": true, "push": true}
65
66// command is git with the arguments given, run in g's repository and
67// environment under ctx.
68//
69// A cancelled context kills git and everything git started, such as a
70// hook or a filter. Killing git alone is not enough: a hook it started
71// can keep git's output open, and a wait for that output would not
72// return. So git runs in a process group of its own, and the whole group
73// is killed. A wait for git's output is also bounded by waitDelay, for a
74// process that has left the group.
75//
76// A command that reaches origin stays in the caller's process group, and
77// is killed alone, unless g is Unattended. A process group of its own is
78// not the terminal's foreground group, and a process outside that group
79// that reads the terminal is stopped. ssh reads the terminal to ask for a
80// passphrase, and git reads it to ask for credentials.
81func (g Git) command(ctx context.Context, args ...string) *exec.Cmd {
82 g.started()
83 cmd := exec.CommandContext(ctx, "git", args...)
84 cmd.Env, cmd.Dir, cmd.WaitDelay = g.Env, g.Dir, waitDelay
85 if g.Unattended || len(args) == 0 || !reachesOrigin[args[0]] {
86 ownGroup(cmd)
87 }
88 return cmd
89}
90
91// Command is git with the arguments given, run as the engine runs its
92// own: in g's repository and environment, killed with what it started
93// once ctx is done, and with the wait for its output bounded. A caller
94// that runs git beside the engine runs it this way, so its git is bounded
95// as the engine's is.
96func (g Git) Command(ctx context.Context, args ...string) *exec.Cmd {
97 return g.command(ctx, args...)
98}
99
100// tool is a program other than git, such as attest, run in g's
101// environment. It never reads the terminal, so it always runs in a
102// process group of its own, killed whole once ctx is done, and the wait
103// for its output is bounded as git's is.
104func (g Git) tool(ctx context.Context, name string, args ...string) *exec.Cmd {
105 g.started()
106 cmd := exec.CommandContext(ctx, name, args...)
107 cmd.Env, cmd.WaitDelay = g.Env, waitDelay
108 ownGroup(cmd)
109 return cmd
110}
111
112// cleanupBound is the longest cleanup may run: removing a worktree,
113// aborting its rebase, and deleting the refs that kept a prepared family.
114var cleanupBound = time.Minute
115
116// cleanupContext is the context cleanup runs under. It is not cancelled
117// with ctx, since cleanup has to run once the caller's work is cancelled
118// or past its deadline. It is done after cleanupBound, so cleanup cannot
119// hang on a hook or a filter that never returns.
120func cleanupContext(ctx context.Context) (context.Context, context.CancelFunc) {
121 return context.WithTimeout(context.WithoutCancel(ctx), cleanupBound)
122}
123
124// finished is the error of git that has ended. git that exits zero has
125// succeeded even when the wait for its output was cut short: only
126// something git started can still hold the output then.
127func finished(err error) error {
128 if errors.Is(err, exec.ErrWaitDelay) {
129 return nil
130 }
131 return err
132}
133
134// output runs git and returns what it printed, less trailing newlines, as
135// a shell's command substitution reads it. A quiet run discards git's
136// diagnostics; any other passes them on.
137func (g Git) output(ctx context.Context, quiet bool, args ...string) (string, error) {
138 return g.input(ctx, quiet, nil, args...)
139}
140
141// input is output with stdin.
142func (g Git) input(ctx context.Context, quiet bool, stdin io.Reader, args ...string) (string, error) {
143 cmd := g.command(ctx, args...)
144 cmd.Stdin = stdin
145 if !quiet {
146 cmd.Stderr = g.Stderr
147 }
148 out, err := cmd.Output()
149 return strings.TrimRight(string(out), "\n"), finished(err)
150}
151
152// blobs reads blobs with one `git cat-file --batch`: for each name, what
153// output would return for `git cat-file blob <name>`. A name the batch does
154// not show as a blob is left out, and the caller reads it alone: one that
155// names nothing, or names a tag of a blob, which `cat-file blob` follows.
156func (g Git) blobs(ctx context.Context, names []string) map[string]string {
157 found := map[string]string{}
158 var asked []string
159 var stdin bytes.Buffer
160 for _, name := range names {
161 if name != "" && !strings.ContainsAny(name, " \t\n") {
162 asked = append(asked, name)
163 stdin.WriteString(name + "\n")
164 }
165 }
166 if len(asked) == 0 {
167 return found
168 }
169 cmd := g.command(ctx, "cat-file", "--batch")
170 cmd.Stdin = &stdin
171 out, err := cmd.Output()
172 if finished(err) != nil {
173 return found
174 }
175 for _, name := range asked {
176 header, rest, ok := bytes.Cut(out, []byte("\n"))
177 if !ok {
178 break
179 }
180 out = rest
181 fields := strings.Fields(string(header))
182 if len(fields) != 3 {
183 continue
184 }
185 size, err := strconv.Atoi(fields[2])
186 if err != nil || size < 0 || size >= len(out) {
187 break
188 }
189 if fields[1] == "blob" {
190 found[name] = strings.TrimRight(string(out[:size]), "\n")
191 }
192 out = out[size+1:]
193 }
194 return found
195}
196
197// succeeds reports whether git exits zero. A failure to run git at all is
198// a no as well, as it is to a shell condition.
199func (g Git) succeeds(ctx context.Context, quiet bool, args ...string) bool {
200 _, err := g.output(ctx, quiet, args...)
201 return err == nil
202}
203
204// passing runs git with its output on Stdout and its diagnostics on
205// Stderr.
206func (g Git) passing(ctx context.Context, args ...string) error {
207 cmd := g.command(ctx, args...)
208 cmd.Stdout, cmd.Stderr = g.Stdout, g.Stderr
209 return finished(cmd.Run())
210}
211
212// in is g run in another directory.
213func (g Git) in(dir string) Git {
214 g.Dir = dir
215 return g
216}
217
218// short is an object ID cut to seven digits, as messages name a commit.
219func short(oid string) string {
220 if len(oid) > 7 {
221 return oid[:7]
222 }
223 return oid
224}
225
226// IsObjectID reports whether s is a full SHA-1 or SHA-256 object ID,
227// lowercase.
228func IsObjectID(s string) bool {
229 return isHex(s, 40) || isHex(s, 64)
230}
231
232func isHex(s string, n int) bool {
233 if len(s) != n {
234 return false
235 }
236 for _, c := range []byte(s) {
237 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
238 return false
239 }
240 }
241 return true
242}