github.com/amane3/goreleaser@v0.182.0/internal/git/git.go (about) 1 // Package git provides an integration with the git command 2 package git 3 4 import ( 5 "bytes" 6 "errors" 7 "os/exec" 8 "strings" 9 10 "github.com/apex/log" 11 ) 12 13 // IsRepo returns true if current folder is a git repository. 14 func IsRepo() bool { 15 out, err := Run("rev-parse", "--is-inside-work-tree") 16 return err == nil && strings.TrimSpace(out) == "true" 17 } 18 19 // RunEnv runs a git command with the specified env vars and returns its output or errors. 20 func RunEnv(env map[string]string, args ...string) (string, error) { 21 // TODO: use exex.CommandContext here and refactor. 22 var extraArgs = []string{ 23 "-c", "log.showSignature=false", 24 } 25 args = append(extraArgs, args...) 26 /* #nosec */ 27 var cmd = exec.Command("git", args...) 28 29 if env != nil { 30 cmd.Env = []string{} 31 for k, v := range env { 32 cmd.Env = append(cmd.Env, k+"="+v) 33 } 34 } 35 36 stdout := bytes.Buffer{} 37 stderr := bytes.Buffer{} 38 39 cmd.Stdout = &stdout 40 cmd.Stderr = &stderr 41 42 log.WithField("args", args).Debug("running git") 43 err := cmd.Run() 44 45 log.WithField("stdout", stdout.String()). 46 WithField("stderr", stderr.String()). 47 Debug("git result") 48 49 if err != nil { 50 return "", errors.New(stderr.String()) 51 } 52 53 return stdout.String(), nil 54 } 55 56 // Run runs a git command and returns its output or errors. 57 func Run(args ...string) (string, error) { 58 return RunEnv(nil, args...) 59 } 60 61 // Clean the output. 62 func Clean(output string, err error) (string, error) { 63 output = strings.ReplaceAll(strings.Split(output, "\n")[0], "'", "") 64 if err != nil { 65 err = errors.New(strings.TrimSuffix(err.Error(), "\n")) 66 } 67 return output, err 68 }