Skip to content

Commit fc0458e

Browse files
refactor: cleanup creeds functions (#8)
1 parent 0247b66 commit fc0458e

File tree

1 file changed

+55
-19
lines changed

1 file changed

+55
-19
lines changed

internal/app/git/creds.go

Lines changed: 55 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,61 @@ type Credentials struct {
1414
SSHPrivKey string
1515
}
1616

17-
// NewCreds returns the credentials for the given repo url.
18-
func (g Credentials) NewGitCreds(repoURL string) (git.Creds, error) {
19-
if ok, _ := git.IsSSHURL(repoURL); ok {
20-
if g.SSHPrivKey != "" {
21-
return git.NewSSHCreds(g.SSHPrivKey, "", true), nil
22-
}
23-
return nil, fmt.Errorf(
24-
"sshPrivKey not provided for authenticatication to repository %s",
25-
repoURL,
26-
)
27-
} else if git.IsHTTPSURL(repoURL) {
28-
if g.Username != "" && g.Password != "" {
29-
return git.NewHTTPSCreds(g.Username, g.Password, "", "", true, ""), nil
30-
}
31-
return nil, fmt.Errorf(
32-
"no value provided for username and password for authentication to repository %s",
33-
repoURL,
34-
)
17+
// NewGitCreds returns the credentials for the given repo url.
18+
func (c Credentials) NewGitCreds(repoURL string) (git.Creds, error) {
19+
if isSshUrl(repoURL) {
20+
return c.fromSsh(repoURL)
3521
}
3622

37-
return nil, fmt.Errorf("unknown repository type for git repository URL %s", repoURL)
23+
if isHttpsUrl(repoURL) {
24+
return c.fromHttps(repoURL)
25+
}
26+
27+
return nil, unknownRepositoryType(repoURL)
28+
}
29+
30+
func isSshUrl(repoUrl string) bool {
31+
ok, _ := git.IsSSHURL(repoUrl)
32+
33+
return ok
34+
}
35+
36+
func isHttpsUrl(repoUrl string) bool {
37+
return git.IsHTTPSURL(repoUrl)
38+
}
39+
40+
func (c Credentials) fromSsh(repoUrl string) (git.Creds, error) {
41+
if c.allowsSshAuth() {
42+
return git.NewSSHCreds(c.SSHPrivKey, "", true), nil
43+
}
44+
45+
return nil, sshPrivateKeyNotProvided(repoUrl)
46+
}
47+
48+
func (c Credentials) fromHttps(repoURL string) (git.Creds, error) {
49+
if c.allowsHttpsAuth() {
50+
return git.NewHTTPSCreds(c.Username, c.Password, "", "", true, ""), nil
51+
}
52+
53+
return nil, httpsUserAndPasswordNotProvided(repoURL)
54+
}
55+
56+
func (c Credentials) allowsSshAuth() bool {
57+
return c.SSHPrivKey != ""
58+
}
59+
60+
func (c Credentials) allowsHttpsAuth() bool {
61+
return c.Username != "" && c.Password != ""
62+
}
63+
64+
func sshPrivateKeyNotProvided(repoUrl string) error {
65+
return fmt.Errorf("sshPrivKey not provided for authenticatication to repository %s", repoUrl)
66+
}
67+
68+
func httpsUserAndPasswordNotProvided(repoUrl string) error {
69+
return fmt.Errorf("no value provided for username and password for authentication to repository %s", repoUrl)
70+
}
71+
72+
func unknownRepositoryType(repoUrl string) error {
73+
return fmt.Errorf("unknown repository type for git repository URL %s", repoUrl)
3874
}

0 commit comments

Comments
 (0)