cloudflare/pint
Publicmirrored fromhttps://github.com/cloudflare/pintAvailable
internal/git/git.go
57lines · modecode
| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "log/slog" |
| 8 | "os/exec" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | type CommandRunner func(args ...string) ([]byte, error) |
| 13 | |
| 14 | func RunGit(args ...string) (content []byte, err error) { |
| 15 | slog.LogAttrs(context.Background(), slog.LevelDebug, "Running git command", slog.Any("args", args)) |
| 16 | cmd := exec.Command("git", args...) |
| 17 | var stdout, stderr bytes.Buffer |
| 18 | cmd.Stdout = &stdout |
| 19 | cmd.Stderr = &stderr |
| 20 | if err = cmd.Run(); err != nil { |
| 21 | if stderr.Len() > 0 { |
| 22 | return nil, errors.New(stderr.String()) |
| 23 | } |
| 24 | return nil, err |
| 25 | } |
| 26 | return stdout.Bytes(), nil |
| 27 | } |
| 28 | |
| 29 | type Info struct { |
| 30 | HeadCommit string |
| 31 | CurrentBranch string |
| 32 | } |
| 33 | |
| 34 | func Describe(cmd CommandRunner) (Info, error) { |
| 35 | commit, err := cmd("rev-parse", "--verify", "HEAD") |
| 36 | if err != nil { |
| 37 | return Info{}, err |
| 38 | } |
| 39 | |
| 40 | branch, err := cmd("rev-parse", "--abbrev-ref", "HEAD") |
| 41 | if err != nil { |
| 42 | return Info{}, err |
| 43 | } |
| 44 | |
| 45 | return Info{ |
| 46 | HeadCommit: strings.Trim(string(commit), "\n"), |
| 47 | CurrentBranch: strings.Trim(string(branch), "\n"), |
| 48 | }, nil |
| 49 | } |
| 50 | |
| 51 | func CommitMessage(cmd CommandRunner, sha string) (string, error) { |
| 52 | msg, err := cmd("show", "-s", "--format=%B", sha) |
| 53 | if err != nil { |
| 54 | return "", err |
| 55 | } |
| 56 | return string(msg), err |
| 57 | } |
| 58 | |