-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_auth.go
More file actions
65 lines (58 loc) · 2.11 KB
/
Copy pathgit_auth.go
File metadata and controls
65 lines (58 loc) · 2.11 KB
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
package main
import (
"fmt"
"os/exec"
"runtime"
"strings"
)
// configureGitCredentials ensures the system credential helper is set, then
// stores the provided credentials so that git clone/push work without prompting.
func configureGitCredentials(host, username, token string, log func(string)) error {
log("Configuring git credential helper…")
if err := ensureCredentialHelper(log); err != nil {
// Non-fatal: log the warning and try to store credentials anyway.
log(fmt.Sprintf("Warning: could not configure credential helper: %v", err))
}
log(fmt.Sprintf("Storing credentials for %s…", host))
return storeGitCredential(host, username, token)
}
// ensureCredentialHelper sets a platform-appropriate credential helper if none
// is already configured globally.
func ensureCredentialHelper(log func(string)) error {
out, err := exec.Command("git", "config", "--global", "credential.helper").Output()
if err == nil && strings.TrimSpace(string(out)) != "" {
log("Credential helper already configured.")
return nil
}
var helper string
switch runtime.GOOS {
case "windows":
// Git Credential Manager is bundled with Git for Windows.
helper = "manager"
case "darwin":
helper = "osxkeychain"
default:
// Plaintext file fallback on Linux — better than nothing.
helper = "store"
}
log(fmt.Sprintf("Setting credential helper to %q…", helper))
cmd := exec.Command("git", "config", "--global", "credential.helper", helper)
if combined, runErr := cmd.CombinedOutput(); runErr != nil {
return fmt.Errorf("git config --global credential.helper %s: %w\n%s", helper, runErr, combined)
}
return nil
}
// storeGitCredential passes credentials to the configured git credential helper
// via "git credential approve".
func storeGitCredential(host, username, password string) error {
input := fmt.Sprintf(
"protocol=https\nhost=%s\nusername=%s\npassword=%s\n\n",
host, username, password,
)
cmd := exec.Command("git", "credential", "approve")
cmd.Stdin = strings.NewReader(input)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("git credential approve: %w\n%s", err, out)
}
return nil
}