gunk-dev/the-valley

git.go

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