move flag validation to RunE

This commit is contained in:
Benjamin Levesque 2025-09-13 21:23:42 +02:00
parent a9cc63b8a3
commit b38e12ef61
No known key found for this signature in database
GPG key ID: 765E3CB147AA4D4A
2 changed files with 25 additions and 22 deletions

View file

@ -159,6 +159,13 @@ func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Co
To change the active account for a host, see %[1]sgh auth switch%[1]s.
`, "`"),
RunE: func(cmd *cobra.Command, args []string) error {
if err := cmdutil.MutuallyExclusive(
"`--json` and `--show-token` cannot be used together. To include the token in the JSON output, use `--json token`.",
opts.Exporter != nil,
opts.ShowToken,
); err != nil {
return err
}
if runF != nil {
return runF(opts)
}
@ -189,10 +196,6 @@ func statusRun(opts *StatusOptions) error {
cs := opts.IO.ColorScheme()
if opts.Exporter != nil {
if opts.ShowToken {
fmt.Fprintf(stderr, "`--json` and `--show-token` cannot be used together. To include the token in the JSON output, use `--json token`.")
return nil
}
opts.ShowToken = true
}

View file

@ -22,9 +22,11 @@ import (
func Test_NewCmdStatus(t *testing.T) {
tests := []struct {
name string
cli string
wants StatusOptions
name string
cli string
wants StatusOptions
wantErr error
wantErrOut string
}{
{
name: "no arguments",
@ -52,6 +54,11 @@ func Test_NewCmdStatus(t *testing.T) {
Active: true,
},
},
{
name: "both --show-token and --json flags",
cli: "--show-token --json state,token",
wantErr: cmdutil.FlagErrorf("`--json` and `--show-token` cannot be used together. To include the token in the JSON output, use `--json token`."),
},
}
for _, tt := range tests {
@ -76,11 +83,15 @@ func Test_NewCmdStatus(t *testing.T) {
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
assert.NoError(t, err)
if tt.wantErr == nil {
assert.NoError(t, err)
assert.Equal(t, tt.wants.Hostname, gotOpts.Hostname)
assert.Equal(t, tt.wants.ShowToken, gotOpts.ShowToken)
assert.Equal(t, tt.wants.Active, gotOpts.Active)
assert.Equal(t, tt.wants.Hostname, gotOpts.Hostname)
assert.Equal(t, tt.wants.ShowToken, gotOpts.ShowToken)
assert.Equal(t, tt.wants.Active, gotOpts.Active)
} else {
assert.Equal(t, tt.wantErr, err)
}
})
}
}
@ -662,17 +673,6 @@ func Test_statusRun(t *testing.T) {
},
wantOut: `{"github.com":[{"active":true,"host":"github.com","login":"monalisa","state":"success","token":"abc123"}]}` + "\n",
},
{
name: "Both show token and json flags",
opts: StatusOptions{
ShowToken: true,
Exporter: defaultJsonExporter(),
},
cfgStubs: func(t *testing.T, c gh.Config) {
login(t, c, "github.com", "monalisa", "abc123", "https")
},
wantErrOut: "`--json` and `--show-token` cannot be used together. To include the token in the JSON output, use `--json token`.",
},
}
for _, tt := range tests {