Skip to content

Commit 97f0838

Browse files
authored
chore: provide usage instruction for CLI argument failures (#12309)
* chore: add usage to # cli arg failures
1 parent 30d9d84 commit 97f0838

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

cli/clibase/cmd.go

+13-2
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,16 @@ func Chain(ms ...MiddlewareFunc) MiddlewareFunc {
562562
return chain(reversed...)
563563
}
564564

565+
func ShowUsageOnError(next HandlerFunc) HandlerFunc {
566+
return func(i *Invocation) error {
567+
err := next(i)
568+
if err != nil {
569+
return xerrors.Errorf("Usage: %s\nError: %w", i.Command.FullUsage(), err)
570+
}
571+
return nil
572+
}
573+
}
574+
565575
func RequireNArgs(want int) MiddlewareFunc {
566576
return RequireRangeArgs(want, want)
567577
}
@@ -574,7 +584,8 @@ func RequireRangeArgs(start, end int) MiddlewareFunc {
574584
panic("start must be >= 0")
575585
}
576586
return func(next HandlerFunc) HandlerFunc {
577-
return func(i *Invocation) error {
587+
// ShowUsageOnError will add the command usage before the error message.
588+
return ShowUsageOnError(func(i *Invocation) error {
578589
got := len(i.Args)
579590
switch {
580591
case start == end && got != start:
@@ -614,7 +625,7 @@ func RequireRangeArgs(start, end int) MiddlewareFunc {
614625
default:
615626
return next(i)
616627
}
617-
}
628+
})
618629
}
619630
}
620631

cli/errors.go

+12-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ func (RootCmd) errorExample() *clibase.Cmd {
4545
apiError.(*codersdk.Error).Helper = "Have you tried turning it off and on again?"
4646

4747
//nolint:errorlint,forcetypeassert
48-
apiErrorNoHelper := apiError.(*codersdk.Error)
48+
cpy := *apiError.(*codersdk.Error)
49+
apiErrorNoHelper := &cpy
4950
apiErrorNoHelper.Helper = ""
5051

5152
// Some flags
@@ -94,7 +95,6 @@ func (RootCmd) errorExample() *clibase.Cmd {
9495
)
9596
},
9697
},
97-
9898
{
9999
Use: "validation",
100100
Options: clibase.OptionSet{
@@ -114,6 +114,16 @@ func (RootCmd) errorExample() *clibase.Cmd {
114114
return nil
115115
},
116116
},
117+
{
118+
Use: "arg-required <required>",
119+
Middleware: clibase.Chain(
120+
clibase.RequireNArgs(1),
121+
),
122+
Handler: func(i *clibase.Invocation) error {
123+
_, _ = fmt.Fprint(i.Stdout, "Try running this without an argument\n")
124+
return nil
125+
},
126+
},
117127
},
118128
}
119129

0 commit comments

Comments
 (0)