Files
Francesco Renzi e4a017ce06 Initial commit for open source release 🚀
Co-authored-by: Francesco Renzi <rentziass@github.com>
Co-authored-by: Nikola Jokic <jokicnikola07@gmail.com>
2026-02-03 16:41:15 +01:00

110 lines
2.3 KiB
Go

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")
}