gunk-dev/the-valley

git.go

source111eb193e549main's published tip history
2.5 KiB
1package rebase
2
3import (
4 "context"
5 "io"
6 "os/exec"
7 "strings"
8)
9
10// Git runs git in one repository. Every command runs under the context it
11// is given, so a cancelled context ends the git it is running.
12//
13// The engine never changes the environment it is given. A caller that
14// must not run the repository's hooks or filters says so in Env, as git
15// configuration.
16type Git struct {
17 Dir string // the repository's directory; "" for the current one
18 Env []string // git's environment; nil for this process's own
19 Stdout io.Writer // where a rebase prints as it goes; nil discards it
20 Stderr io.Writer // where git's own diagnostics go, unless quiet; nil discards them
21}
22
23// output runs git and returns what it printed, less trailing newlines, as
24// a shell's command substitution reads it. A quiet run discards git's
25// diagnostics; any other passes them on.
26func (g Git) output(ctx context.Context, quiet bool, args ...string) (string, error) {
27 return g.input(ctx, quiet, nil, args...)
28}
29
30// input is output with stdin.
31func (g Git) input(ctx context.Context, quiet bool, stdin io.Reader, args ...string) (string, error) {
32 cmd := exec.CommandContext(ctx, "git", args...)
33 cmd.Env, cmd.Dir, cmd.Stdin = g.Env, g.Dir, stdin
34 if !quiet {
35 cmd.Stderr = g.Stderr
36 }
37 out, err := cmd.Output()
38 return strings.TrimRight(string(out), "\n"), err
39}
40
41// succeeds reports whether git exits zero. A failure to run git at all is
42// a no as well, as it is to a shell condition.
43func (g Git) succeeds(ctx context.Context, quiet bool, args ...string) bool {
44 _, err := g.output(ctx, quiet, args...)
45 return err == nil
46}
47
48// passing runs git with its output on Stdout and its diagnostics on
49// Stderr.
50func (g Git) passing(ctx context.Context, args ...string) error {
51 cmd := exec.CommandContext(ctx, "git", args...)
52 cmd.Env, cmd.Dir, cmd.Stdout, cmd.Stderr = g.Env, g.Dir, g.Stdout, g.Stderr
53 return cmd.Run()
54}
55
56// in is g run in another directory.
57func (g Git) in(dir string) Git {
58 g.Dir = dir
59 return g
60}
61
62// short is an object ID cut to seven digits, as messages name a commit.
63func short(oid string) string {
64 if len(oid) > 7 {
65 return oid[:7]
66 }
67 return oid
68}
69
70// IsObjectID reports whether s is a full SHA-1 or SHA-256 object ID,
71// lowercase.
72func IsObjectID(s string) bool {
73 return isHex(s, 40) || isHex(s, 64)
74}
75
76func isHex(s string, n int) bool {
77 if len(s) != n {
78 return false
79 }
80 for _, c := range []byte(s) {
81 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
82 return false
83 }
84 }
85 return true
86}