-
Notifications
You must be signed in to change notification settings - Fork 149
/
factory.go
81 lines (68 loc) · 2.22 KB
/
factory.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
package gitproviders
import (
"fmt"
"github.com/fluxcd/go-git-providers/github"
"github.com/fluxcd/go-git-providers/gitlab"
"github.com/fluxcd/go-git-providers/gitprovider"
)
// GitProviderName holds a Git provider definition.
type GitProviderName string
const (
GitProviderGitHub GitProviderName = "github"
GitProviderGitLab GitProviderName = "gitlab"
tokenTypeOauth string = "oauth2"
)
// Config defines the configuration for connecting to a GitProvider.
type Config struct {
// Provider defines the GitProvider.
Provider GitProviderName
// Hostname is the HTTP/S hostname of the Provider,
// e.g. github.example.com.
Hostname string
// Token contains the token used to authenticate with the
// Provider.
Token string
}
func buildGitProvider(config Config) (gitprovider.Client, string, error) {
if config.Token == "" {
return nil, "", fmt.Errorf("no git provider token present")
}
switch config.Provider {
case GitProviderGitHub:
opts := []gitprovider.ClientOption{
gitprovider.WithOAuth2Token(config.Token),
}
// Quirk of ggp, if using github.com or gitlab.com and you prepend
// that with https:// you end up with https://https//github.com !!!
hostname := github.DefaultDomain
if config.Hostname != "" && config.Hostname != github.DefaultDomain {
// Quirk of ggp, have to specify scheme with custom domain
hostname = "https://" + config.Hostname
opts = append(opts, gitprovider.WithDomain(hostname))
}
if client, err := github.NewClient(opts...); err != nil {
return nil, "", err
} else {
return client, hostname, nil
}
case GitProviderGitLab:
opts := []gitprovider.ClientOption{
gitprovider.WithOAuth2Token(config.Token),
gitprovider.WithConditionalRequests(true),
}
// Quirk, see above
hostname := gitlab.DefaultDomain
if config.Hostname != "" && config.Hostname != gitlab.DefaultDomain {
// Quirk, see above
hostname = "https://" + config.Hostname
opts = append(opts, gitprovider.WithDomain(hostname))
}
if client, err := gitlab.NewClient(config.Token, tokenTypeOauth, opts...); err != nil {
return nil, "", err
} else {
return client, hostname, nil
}
default:
return nil, "", fmt.Errorf("unsupported Git provider '%s'", config.Provider)
}
}