/
git.go
77 lines (64 loc) · 1.84 KB
/
git.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Package git provides an integration with the git command
package git
import (
"bytes"
"context"
"errors"
"os/exec"
"strings"
"github.com/caarlos0/log"
)
// IsRepo returns true if current folder is a git repository.
func IsRepo(ctx context.Context) bool {
out, err := Run(ctx, "rev-parse", "--is-inside-work-tree")
return err == nil && strings.TrimSpace(out) == "true"
}
func RunWithEnv(ctx context.Context, env []string, args ...string) (string, error) {
extraArgs := []string{
"-c", "log.showSignature=false",
}
args = append(extraArgs, args...)
/* #nosec */
cmd := exec.CommandContext(ctx, "git", args...)
stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
cmd.Env = append(cmd.Env, env...)
log.WithField("args", args).Debug("running git")
err := cmd.Run()
log.WithField("stdout", stdout.String()).
WithField("stderr", stderr.String()).
Debug("git result")
if err != nil {
return "", errors.New(stderr.String())
}
return stdout.String(), nil
}
// Run runs a git command and returns its output or errors.
func Run(ctx context.Context, args ...string) (string, error) {
return RunWithEnv(ctx, []string{}, args...)
}
// Clean the output.
func Clean(output string, err error) (string, error) {
output = strings.ReplaceAll(strings.Split(output, "\n")[0], "'", "")
if err != nil {
err = errors.New(strings.TrimSuffix(err.Error(), "\n"))
}
return output, err
}
// CleanAllLines returns all the non empty lines of the output, cleaned up.
func CleanAllLines(output string, err error) ([]string, error) {
var result []string
for _, line := range strings.Split(output, "\n") {
l := strings.TrimSpace(strings.ReplaceAll(line, "'", ""))
if l == "" {
continue
}
result = append(result, l)
}
if err != nil {
err = errors.New(strings.TrimSuffix(err.Error(), "\n"))
}
return result, err
}