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