Skip to content

Commit 4449af6

Browse files
committed
fix error missing in json output
1 parent 5bb76e8 commit 4449af6

2 files changed

Lines changed: 59 additions & 31 deletions

File tree

pkg/cmd/auth/status/status.go

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ var authFields = []string{
4545

4646
func (e authEntry) String(cs *iostreams.ColorScheme, showToken bool) string {
4747
var sb strings.Builder
48-
switch e.State {
49-
case authStateSuccess:
48+
if e.State == authStateSuccess {
5049
sb.WriteString(
5150
fmt.Sprintf(" %s Logged in to %s account %s (%s)\n", cs.SuccessIcon(), e.Host, cs.Bold(e.Login), e.TokenSource),
5251
)
@@ -69,32 +68,25 @@ func (e authEntry) String(cs *iostreams.ColorScheme, showToken bool) string {
6968
}
7069
}
7170
}
71+
return sb.String()
72+
}
7273

73-
case authStateTimeout:
74-
if e.Login != "" {
75-
sb.WriteString(fmt.Sprintf(" %s Timeout trying to log in to %s account %s (%s)\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
76-
} else {
77-
sb.WriteString(fmt.Sprintf(" %s Timeout trying to log in to %s using token (%s)\n", cs.Red("X"), e.Host, e.TokenSource))
78-
}
79-
activeStr := fmt.Sprintf("%v", e.Active)
80-
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
74+
if e.Login != "" {
75+
sb.WriteString(fmt.Sprintf(" %s %s to %s account %s (%s)\n", cs.Red("X"), e.Error, e.Host, cs.Bold(e.Login), e.TokenSource))
76+
} else {
77+
sb.WriteString(fmt.Sprintf(" %s %s to %s using token (%s)\n", cs.Red("X"), e.Error, e.Host, e.TokenSource))
78+
}
79+
activeStr := fmt.Sprintf("%v", e.Active)
80+
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
8181

82-
case authStateError:
83-
if e.Login != "" {
84-
sb.WriteString(fmt.Sprintf(" %s Failed to log in to %s account %s (%s)\n", cs.Red("X"), e.Host, cs.Bold(e.Login), e.TokenSource))
85-
} else {
86-
sb.WriteString(fmt.Sprintf(" %s Failed to log in to %s using token (%s)\n", cs.Red("X"), e.Host, e.TokenSource))
87-
}
88-
activeStr := fmt.Sprintf("%v", e.Active)
89-
sb.WriteString(fmt.Sprintf(" - Active account: %s\n", cs.Bold(activeStr)))
82+
if e.State == authStateError {
9083
sb.WriteString(fmt.Sprintf(" - The token in %s is invalid.\n", e.TokenSource))
9184
if authTokenWriteable(e.TokenSource) {
9285
loginInstructions := fmt.Sprintf("gh auth login -h %s", e.Host)
9386
logoutInstructions := fmt.Sprintf("gh auth logout -h %s -u %s", e.Host, e.Login)
9487
sb.WriteString(fmt.Sprintf(" - To re-authenticate, run: %s\n", cs.Bold(loginInstructions)))
9588
sb.WriteString(fmt.Sprintf(" - To forget about this account, run: %s\n", cs.Bold(logoutInstructions)))
9689
}
97-
9890
}
9991
return sb.String()
10092
}
@@ -351,31 +343,32 @@ type buildEntryOptions struct {
351343
}
352344

353345
func buildEntry(httpClient *http.Client, opts buildEntryOptions) authEntry {
346+
tokenSource := opts.tokenSource
347+
if tokenSource == "oauth_token" {
348+
// The go-gh function TokenForHost returns this value as source for tokens read from the
349+
// config file, but we want the file path instead. This attempts to reconstruct it.
350+
tokenSource = filepath.Join(config.ConfigDir(), "hosts.yml")
351+
}
354352
entry := authEntry{
355353
Active: opts.active,
356354
Host: opts.hostname,
357355
Login: opts.username,
358-
TokenSource: opts.tokenSource,
356+
TokenSource: tokenSource,
359357
Token: opts.token,
360358
GitProtocol: opts.gitProtocol,
361359
}
362360

363-
if opts.tokenSource == "oauth_token" {
364-
// The go-gh function TokenForHost returns this value as source for tokens read from the
365-
// config file, but we want the file path instead. This attempts to reconstruct it.
366-
entry.TokenSource = filepath.Join(config.ConfigDir(), "hosts.yml")
367-
}
368-
369361
// If token is not writeable, then it came from an environment variable and
370362
// we need to fetch the username as it won't be stored in the config.
371-
if !authTokenWriteable(opts.tokenSource) {
363+
if !authTokenWriteable(tokenSource) {
372364
// The httpClient will automatically use the correct token here as
373365
// the token from the environment variable take highest precedence.
374366
apiClient := api.NewClientFromHTTP(httpClient)
375367
var err error
376368
entry.Login, err = api.CurrentLoginName(apiClient, opts.hostname)
377369
if err != nil {
378370
entry.State = authStateError
371+
entry.Error = "Failed to log in"
379372
return entry
380373
}
381374
}
@@ -386,10 +379,12 @@ func buildEntry(httpClient *http.Client, opts buildEntryOptions) authEntry {
386379
var networkError net.Error
387380
if errors.As(err, &networkError) && networkError.Timeout() {
388381
entry.State = authStateTimeout
382+
entry.Error = "Timeout trying to log in"
389383
return entry
390384
}
391385

392386
entry.State = authStateError
387+
entry.Error = "Failed to log in"
393388
return entry
394389
}
395390
entry.Scopes = scopesHeader

pkg/cmd/auth/status/status_test.go

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -663,10 +663,29 @@ func Test_statusRun(t *testing.T) {
663663
`{"active":true,"host":"github.com","login":"monalisa2","state":"success"}` +
664664
"]}\n",
665665
},
666+
{
667+
name: "token from env with json flag",
668+
opts: StatusOptions{
669+
Exporter: defaultJsonExporter(),
670+
},
671+
env: map[string]string{"GH_TOKEN": "gho_abc123"},
672+
httpStubs: func(reg *httpmock.Registry) {
673+
reg.Register(
674+
httpmock.REST("GET", ""),
675+
httpmock.ScopesResponder(""))
676+
reg.Register(
677+
httpmock.GraphQL(`query UserCurrent\b`),
678+
httpmock.StringResponse(`{"data":{"viewer":{"login":"monalisa"}}}`))
679+
},
680+
wantOut: `{` +
681+
`"github.com":[` +
682+
`{"active":true,"host":"github.com","login":"monalisa","state":"success"}` +
683+
"]}\n",
684+
},
666685
{
667686
name: "bad token with json flag",
668687
opts: StatusOptions{
669-
Exporter: addFieldsToExporter(defaultJsonExporter(), []string{"scopes"}),
688+
Exporter: addFieldsToExporter(defaultJsonExporter(), []string{"error"}),
670689
},
671690
cfgStubs: func(t *testing.T, c gh.Config) {
672691
login(t, c, "ghe.io", "monalisa-ghe", "gho_abc123", "https")
@@ -675,13 +694,27 @@ func Test_statusRun(t *testing.T) {
675694
// mock for HeaderHasMinimumScopes api requests to a non-github.com host
676695
reg.Register(httpmock.REST("GET", "api/v3/"), httpmock.StatusStringResponse(400, "no bueno"))
677696
},
678-
wantOut: `{"ghe.io":[{"active":true,"host":"ghe.io","login":"monalisa-ghe","scopes":"","state":"error"}]}` + "\n",
697+
wantOut: `{"ghe.io":[{"active":true,"error":"Failed to log in","host":"ghe.io","login":"monalisa-ghe","state":"error"}]}` + "\n",
698+
},
699+
{
700+
name: "bad token from env with json flag",
701+
opts: StatusOptions{
702+
Exporter: addFieldsToExporter(defaultJsonExporter(), []string{"error"}),
703+
},
704+
env: map[string]string{"GH_TOKEN": "gho_abc123"},
705+
httpStubs: func(reg *httpmock.Registry) {
706+
// mock for HeaderHasMinimumScopes api requests to a non-github.com host
707+
reg.Register(
708+
httpmock.GraphQL(`query UserCurrent\b`),
709+
httpmock.StatusStringResponse(400, "no bueno"))
710+
},
711+
wantOut: `{"github.com":[{"active":true,"error":"Failed to log in","host":"github.com","login":"","state":"error"}]}` + "\n",
679712
},
680713
{
681714
name: "timeout error with json flag",
682715
opts: StatusOptions{
683716
Hostname: "github.com",
684-
Exporter: addFieldsToExporter(defaultJsonExporter(), []string{"scopes"}),
717+
Exporter: addFieldsToExporter(defaultJsonExporter(), []string{"error"}),
685718
},
686719
cfgStubs: func(t *testing.T, c gh.Config) {
687720
login(t, c, "github.com", "monalisa", "abc123", "https")
@@ -692,7 +725,7 @@ func Test_statusRun(t *testing.T) {
692725
return nil, context.DeadlineExceeded
693726
})
694727
},
695-
wantOut: `{"github.com":[{"active":true,"host":"github.com","login":"monalisa","scopes":"","state":"timeout"}]}` + "\n",
728+
wantOut: `{"github.com":[{"active":true,"error":"Timeout trying to log in","host":"github.com","login":"monalisa","state":"timeout"}]}` + "\n",
696729
},
697730
{
698731
name: "token is not masked with json flag",

0 commit comments

Comments
 (0)