// Package git utilizes the git CLI to retrieve and set information // from the current repository package git import ( "bufio" "bytes" "fmt" "os" "os/exec" "regexp" "strings" ) var ( // ErrRemoteNotFound signalizes there was no remote found ErrRemoteNotFound = fmt.Errorf("no push remote found") pushRemoteRegex = regexp.MustCompile(`origin.*\(push\)`) ) // GetPushRemote gets the remote configured as push-remote and returns // ErrRemoteNotFound in case none is found func GetPushRemote() (remote string, err error) { data, err := runGitCLI([]string{"remote", "-v"}) if err != nil { return "", fmt.Errorf("getting remotes") } scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { if err = scanner.Err(); err != nil { return "", fmt.Errorf("scanning output: %w", err) } if !pushRemoteRegex.Match(scanner.Bytes()) { continue } tokens := strings.Fields(scanner.Text()) if len(tokens) < 2 { //nolint:mnd continue } return tokens[1], nil } return "", ErrRemoteNotFound } // SetLocalConfig applies the param with its value on the local git repo func SetLocalConfig(param, value string) (err error) { if _, err = runGitCLI([]string{"config", "--local", param, value}); err != nil { return fmt.Errorf("setting config: %w", err) } return nil } func runGitCLI(args []string) (output []byte, err error) { cmd := exec.Command("git", args...) cmd.Env = os.Environ() if cmd.Dir, err = os.Getwd(); err != nil { return nil, fmt.Errorf("getting cwd: %w", err) } data, err := cmd.Output() if err != nil { return nil, fmt.Errorf("running command: %w", err) } return data, nil }