-
Notifications
You must be signed in to change notification settings - Fork 7
/
config.go
63 lines (56 loc) · 1.46 KB
/
config.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
package git
import (
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/pkg/errors"
)
// CommitterDetails returns name and email read for a Git configuration file.
//
// Fetching the configuration values are delegated to the git CLI and follows
// precedence rules defined by Git.
func CommitterDetails() (string, string, error) {
name, err := getValue("user.name", "HAMCTL_USER_NAME")
if err != nil {
return "", "", err
}
email, err := getValue("user.email", "HAMCTL_USER_EMAIL")
if err != nil {
return "", "", err
}
return name, email, nil
}
func getValue(gitKey, envKey string) (string, error) {
v, ok := os.LookupEnv(envKey)
if ok {
return v, nil
}
v, err := getGitConfig(gitKey)
if err != nil {
return "", errors.WithMessagef(err, "Failed to get credentials with 'git config --get %s'", gitKey)
}
return v, nil
}
// getGitConfig reads a git configuration field and returns its value as a
// string.
func getGitConfig(field string) (string, error) {
cmd := exec.Command("git", "config", "--get", field)
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", errors.WithMessage(err, "get stdout pipe for command")
}
err = cmd.Start()
if err != nil {
return "", errors.WithMessage(err, "start command")
}
stdoutData, err := ioutil.ReadAll(stdout)
if err != nil {
return "", errors.WithMessage(err, "read stdout data of command")
}
err = cmd.Wait()
if err != nil {
return "", err
}
return strings.TrimSpace(string(stdoutData)), nil
}