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