Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions github/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -497,17 +497,27 @@ func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc {
}
}

// ghCLIHostFromAPIHost maps an API hostname to the corresponding
// gh-CLI --hostname value. For example api.github.com -> github.com
// and api.<slug>.ghe.com -> <slug>.ghe.com.
// for unrecognized hostnames, input is returned unmodified.
func ghCLIHostFromAPIHost(host string) string {
if host == DotComAPIHost {
return DotComHost
} else if GHECAPIHostMatch.MatchString(host) {
return strings.TrimPrefix(host, "api.")
}
return host
}

// See https://github.com/integrations/terraform-provider-github/issues/1822
func tokenFromGHCLI(u *url.URL) string {
ghCliPath := os.Getenv("GH_PATH")
if ghCliPath == "" {
ghCliPath = "gh"
}

host := u.Host
if host == DotComAPIHost {
host = DotComHost
}
host := ghCLIHostFromAPIHost(u.Host)

out, err := exec.Command(ghCliPath, "auth", "token", "--hostname", host).Output()
if err != nil {
Expand Down
43 changes: 43 additions & 0 deletions github/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,3 +259,46 @@ data "github_ip_ranges" "test" {}
})
})
}

func Test_ghCLIHostFromAPIHost(t *testing.T) {
testCases := []struct {
name string
host string
expectedHost string
}{
{
name: "dotcom API host is mapped to dotcom host",
host: "api.github.com",
expectedHost: "github.com",
},
{
name: "ghec API host has api. prefix stripped",
host: "api.my-enterprise.ghe.com",
expectedHost: "my-enterprise.ghe.com",
},
{
name: "ghec API host with numbers has api. prefix stripped",
host: "api.customer-123.ghe.com",
expectedHost: "customer-123.ghe.com",
},
{
name: "ghes host is passed through unchanged",
host: "github.example.com",
expectedHost: "github.example.com",
},
{
name: "ghes host with port is passed through unchanged",
host: "github.example.com:8443",
expectedHost: "github.example.com:8443",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got := ghCLIHostFromAPIHost(tc.host)
if got != tc.expectedHost {
t.Errorf("ghCLIHostFromAPIHost(%q) = %q, want %q", tc.host, got, tc.expectedHost)
}
})
}
}