diff --git a/cmd/root.go b/cmd/root.go index 1fbb55bcfe1..ae7c6fa08a5 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -438,7 +438,7 @@ func newRunCommand(ctx context.Context, input *Input) func(*cobra.Command, []str if _, hasGitHubToken := secrets["GITHUB_TOKEN"]; !hasGitHubToken { ctx, cancel := common.EarlyCancelContext(ctx) defer cancel() - secrets["GITHUB_TOKEN"], _ = gh.GetToken(ctx, "") + secrets["GITHUB_TOKEN"], _ = gh.GetToken(ctx, "", input.githubInstance) } log.Debugf("Loading vars from %s", input.Varfile()) diff --git a/pkg/gh/gh.go b/pkg/gh/gh.go index 9ba23eb81e7..ff0a487166f 100644 --- a/pkg/gh/gh.go +++ b/pkg/gh/gh.go @@ -4,12 +4,17 @@ import ( "bufio" "bytes" "context" + "errors" "os/exec" ) -func GetToken(ctx context.Context, workingDirectory string) (string, error) { +func GetToken(ctx context.Context, workingDirectory string, hostname string) (string, error) { var token string + if hostname == "" { + return "", errors.New("hostname must not be empty") + } + // Locate the 'gh' executable path, err := exec.LookPath("gh") if err != nil { @@ -17,7 +22,7 @@ func GetToken(ctx context.Context, workingDirectory string) (string, error) { } // Command setup - cmd := exec.CommandContext(ctx, path, "auth", "token") + cmd := exec.CommandContext(ctx, path, "auth", "token", "--hostname", hostname) cmd.Dir = workingDirectory // Capture the output diff --git a/pkg/gh/gh_test.go b/pkg/gh/gh_test.go index 578f0d34c0f..728fef34f09 100644 --- a/pkg/gh/gh_test.go +++ b/pkg/gh/gh_test.go @@ -3,9 +3,21 @@ package gh import ( "context" "testing" + + "github.com/stretchr/testify/assert" ) func TestGetToken(t *testing.T) { - token, _ := GetToken(context.TODO(), "") + token, _ := GetToken(context.TODO(), "", "github.com") t.Log(token) } + +func TestGetTokenWithUnmatchedHostname(t *testing.T) { + _, err := GetToken(context.TODO(), "", "notgithub.example.com") + assert.Error(t, err) +} + +func TestGetTokenWithNoHostname(t *testing.T) { + _, err := GetToken(context.TODO(), "", "") + assert.EqualError(t, err, "hostname must not be empty") +}