-
Notifications
You must be signed in to change notification settings - Fork 120
/
provider_github.go
112 lines (90 loc) · 2.22 KB
/
provider_github.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package git
import (
"context"
"fmt"
"net/http"
"strings"
g "github.com/argoproj-labs/argocd-autopilot/pkg/git/github"
gh "github.com/google/go-github/v35/github"
)
//go:generate mockgen -destination=./github/mocks/repos.go -package=mocks -source=./github/repos.go Repositories
//go:generate mockgen -destination=./github/mocks/users.go -package=mocks -source=./github/users.go Users
type github struct {
opts *ProviderOptions
Repositories g.Repositories
Users g.Users
}
func newGithub(opts *ProviderOptions) (Provider, error) {
var (
c *gh.Client
err error
)
hc := &http.Client{}
if opts.Auth != nil {
hc.Transport = &gh.BasicAuthTransport{
Username: opts.Auth.Username,
Password: opts.Auth.Password,
}
}
if opts.Host != "" && !strings.Contains(opts.Host, "github.com") {
c, err = gh.NewEnterpriseClient(opts.Host, opts.Host, hc)
if err != nil {
return nil, err
}
} else {
c = gh.NewClient(hc)
}
g := &github{
opts: opts,
Repositories: c.Repositories,
Users: c.Users,
}
return g, nil
}
func (g *github) CreateRepository(ctx context.Context, orgRepo string) (string, error) {
opts, err := getDefaultRepoOptions(orgRepo)
if err != nil {
return "", nil
}
authUser, err := g.getAuthenticatedUser(ctx)
if err != nil {
return "", err
}
org := ""
if *authUser.Login != opts.Owner {
org = opts.Owner
}
r, res, err := g.Repositories.Create(ctx, org, &gh.Repository{
Name: gh.String(opts.Name),
Private: gh.Bool(opts.Private),
})
if err != nil {
if res.StatusCode == 404 {
return "", fmt.Errorf("owner %s not found: %w", opts.Owner, err)
}
return "", err
}
if r.CloneURL == nil {
return "", fmt.Errorf("repo clone url is nil")
}
return *r.CloneURL, err
}
func (g *github) GetAuthor(ctx context.Context) (username, email string, err error) {
authUser, err := g.getAuthenticatedUser(ctx)
if err != nil {
return
}
username = *authUser.Login
email = *authUser.Email
return
}
func (g *github) getAuthenticatedUser(ctx context.Context) (*gh.User, error) {
authUser, res, err := g.Users.Get(ctx, "")
if err != nil {
if res.StatusCode == 401 {
return nil, ErrAuthenticationFailed(err)
}
return nil, err
}
return authUser, nil
}