-
Notifications
You must be signed in to change notification settings - Fork 787
/
gitcredentials_auth.go
70 lines (62 loc) · 1.85 KB
/
gitcredentials_auth.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
64
65
66
67
68
69
70
package auth
import (
"io/ioutil"
"net/url"
"strings"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/pkg/errors"
)
// loadGitCredentialsAuth loads the git credentials from the `git/credentials` file
// in `$XDG_CONFIG_HOME/git/credentials` or in the `~/git/credentials` directory
func loadGitCredentialsAuth() (*AuthConfig, error) {
fileName := util.GitCredentialsFile()
return loadGitCredentialsAuthFile(fileName)
}
// loadGitCredentialsAuthFile loads the git credentials file
func loadGitCredentialsAuthFile(fileName string) (*AuthConfig, error) {
exists, err := util.FileExists(fileName)
if err != nil {
return nil, errors.Wrapf(err, "failed to check if git credentials file exists %s", fileName)
}
if !exists {
return nil, nil
}
data, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, errors.Wrapf(err, "failed to load git credentials file %s", fileName)
}
config := &AuthConfig{}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
u, err := url.Parse(line)
if err != nil {
log.Logger().Warnf("ignoring invalid line in git credentials file: %s error: %s", fileName, err.Error())
continue
}
user := u.User
username := user.Username()
password, _ := user.Password()
if username == "" {
log.Logger().Warnf("ignoring missing user name in git credentials file: %s URL: %s", fileName, line)
continue
}
if password == "" {
log.Logger().Warnf("ignoring missing password in git credentials file: %s URL: %s", fileName, line)
continue
}
u.User = nil
serverURL := u.String()
server := config.GetOrCreateServer(serverURL)
server.CurrentUser = username
server.Users = append(server.Users, &UserAuth{
Username: username,
Password: password,
ApiToken: password,
})
}
return config, nil
}