-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconfig.go
More file actions
109 lines (84 loc) · 2.32 KB
/
config.go
File metadata and controls
109 lines (84 loc) · 2.32 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
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
package scaleset
import (
"fmt"
"net/url"
"os"
"strings"
)
var ErrInvalidGitHubConfigURL = fmt.Errorf("invalid config URL, should point to an enterprise, org, or repository")
type gitHubScope int
const (
gitHubScopeUnknown gitHubScope = iota
gitHubScopeEnterprise
gitHubScopeOrganization
gitHubScopeRepository
)
type gitHubConfig struct {
configURL *url.URL
scope gitHubScope
enterprise string
organization string
repository string
isHosted bool
}
func parseGitHubConfigFromURL(in string) (*gitHubConfig, error) {
u, err := url.Parse(strings.Trim(in, "/"))
if err != nil {
return nil, fmt.Errorf("failed to parse URL: %w", err)
}
isHosted := isHostedGitHubURL(u)
configURL := &gitHubConfig{
configURL: u,
isHosted: isHosted,
}
invalidURLError := fmt.Errorf("%q: %w", u.String(), ErrInvalidGitHubConfigURL)
pathParts := strings.Split(strings.Trim(u.Path, "/"), "/")
switch len(pathParts) {
case 1: // Organization
if pathParts[0] == "" {
return nil, invalidURLError
}
configURL.scope = gitHubScopeOrganization
configURL.organization = pathParts[0]
case 2: // Repository or enterprise
if strings.ToLower(pathParts[0]) == "enterprises" {
configURL.scope = gitHubScopeEnterprise
configURL.enterprise = pathParts[1]
break
}
configURL.scope = gitHubScopeRepository
configURL.organization = pathParts[0]
configURL.repository = pathParts[1]
default:
return nil, invalidURLError
}
return configURL, nil
}
func (c *gitHubConfig) gitHubAPIURL(path string) *url.URL {
result := &url.URL{
Scheme: c.configURL.Scheme,
Host: c.configURL.Host, // default for Enterprise mode
Path: "/api/v3", // default for Enterprise mode
}
isHosted := isHostedGitHubURL(c.configURL)
if isHosted {
result.Host = fmt.Sprintf("api.%s", c.configURL.Host)
result.Path = ""
if strings.EqualFold("www.github.com", c.configURL.Host) {
// re-routing www.github.com to api.github.com
result.Host = "api.github.com"
}
}
result.Path += path
return result
}
func isHostedGitHubURL(u *url.URL) bool {
_, forceGhes := os.LookupEnv("GITHUB_ACTIONS_FORCE_GHES")
if forceGhes {
return false
}
return strings.EqualFold(u.Host, "github.com") ||
strings.EqualFold(u.Host, "www.github.com") ||
strings.EqualFold(u.Host, "github.localhost") ||
strings.HasSuffix(u.Host, ".ghe.com")
}