Add GH_HOST to hosts list if it has corresponding auth token (#5087)

* Add GH_HOST to hosts list if it has coresponding auth token

* Keep default host at front of hosts list

* Always add GH_HOST to hosts list
This commit is contained in:
Sam Coe 2022-01-29 09:37:24 +02:00 committed by GitHub
parent 3be4b9951d
commit ba8c41a6ed
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 10 deletions

View file

@ -3,9 +3,11 @@ package config
import (
"fmt"
"os"
"sort"
"strconv"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/set"
)
const (
@ -34,19 +36,29 @@ type envConfig struct {
}
func (c *envConfig) Hosts() ([]string, error) {
hasDefault := false
hosts, err := c.Config.Hosts()
for _, h := range hosts {
if h == ghinstance.Default() {
hasDefault = true
}
if err != nil {
return nil, err
}
token, _ := AuthTokenFromEnv(ghinstance.Default())
if (err != nil || !hasDefault) && token != "" {
hosts = append([]string{ghinstance.Default()}, hosts...)
return hosts, nil
hostSet := set.NewStringSet()
hostSet.AddValues(hosts)
// If GH_HOST is set then add it to list.
if host := os.Getenv(GH_HOST); host != "" {
hostSet.Add(host)
}
return hosts, err
// If there is a valid environment variable token for the
// default host then add default host to list.
if token, _ := AuthTokenFromEnv(ghinstance.Default()); token != "" {
hostSet.Add(ghinstance.Default())
}
s := hostSet.ToSlice()
// If default host is in list then move it to the front.
sort.SliceStable(s, func(i, j int) bool { return s[i] == ghinstance.Default() })
return s, nil
}
func (c *envConfig) DefaultHost() (string, error) {

View file

@ -44,6 +44,7 @@ func TestInheritEnv(t *testing.T) {
tests := []struct {
name string
baseConfig string
GH_HOST string
GITHUB_TOKEN string
GITHUB_ENTERPRISE_TOKEN string
GH_TOKEN string
@ -285,9 +286,23 @@ func TestInheritEnv(t *testing.T) {
writeable: false,
},
},
{
name: "GH_HOST adds host entry when paired with environment token",
baseConfig: ``,
GH_HOST: "example.org",
GH_ENTERPRISE_TOKEN: "GH_ENTERPRISE_TOKEN",
hostname: "example.org",
wants: wants{
hosts: []string{"example.org"},
token: "GH_ENTERPRISE_TOKEN",
source: "GH_ENTERPRISE_TOKEN",
writeable: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setenv(t, "GH_HOST", tt.GH_HOST)
setenv(t, "GITHUB_TOKEN", tt.GITHUB_TOKEN)
setenv(t, "GITHUB_ENTERPRISE_TOKEN", tt.GITHUB_ENTERPRISE_TOKEN)
setenv(t, "GH_TOKEN", tt.GH_TOKEN)

View file

@ -10,6 +10,7 @@ type stringSet struct {
func NewStringSet() *stringSet {
s := &stringSet{}
s.m = make(map[string]struct{})
s.v = []string{}
return s
}