1package repository
2
3import (
4 "bytes"
5 "fmt"
6 "io"
7 "strings"
8
9 "golang.org/x/sys/execabs"
10)
11
12// gitCli is a helper to launch CLI git commands
13type gitCli struct {
14 path string
15}
16
17// Run the given git command with the given I/O reader/writers, returning an error if it fails.
18func (cli gitCli) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
19 // make sure that the working directory for the command
20 // always exist, in particular when running "git init".
21 path := strings.TrimSuffix(cli.path, ".git")
22
23 // fmt.Printf("[%s] Running git %s\n", path, strings.Join(args, " "))
24
25 cmd := execabs.Command("git", args...)
26 cmd.Dir = path
27 cmd.Stdin = stdin
28 cmd.Stdout = stdout
29 cmd.Stderr = stderr
30
31 return cmd.Run()
32}
33
34// Run the given git command and return its stdout, or an error if the command fails.
35func (cli gitCli) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
36 var stdout bytes.Buffer
37 var stderr bytes.Buffer
38 err := cli.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
39 return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
40}
41
42// Run the given git command and return its stdout, or an error if the command fails.
43func (cli gitCli) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
44 stdout, stderr, err := cli.runGitCommandRaw(stdin, args...)
45 if err != nil {
46 if stderr == "" {
47 stderr = "Error running git command: " + strings.Join(args, " ")
48 }
49 err = fmt.Errorf(stderr)
50 }
51 return stdout, err
52}
53
54// Run the given git command and return its stdout, or an error if the command fails.
55func (cli gitCli) runGitCommand(args ...string) (string, error) {
56 return cli.runGitCommandWithStdin(nil, args...)
57}