Skip to content

chore: provide instructions for handling CLI argument failures #12355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions cli/clibase/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,16 @@ func Chain(ms ...MiddlewareFunc) MiddlewareFunc {
return chain(reversed...)
}

func ShowUsageOnError(next HandlerFunc) HandlerFunc {
return func(i *Invocation) error {
err := next(i)
if err != nil {
return xerrors.Errorf("Usage: %s\nError: %w", i.Command.FullUsage(), err)
}
return nil
}
}

func RequireNArgs(want int) MiddlewareFunc {
return RequireRangeArgs(want, want)
}
Expand All @@ -574,7 +584,8 @@ func RequireRangeArgs(start, end int) MiddlewareFunc {
panic("start must be >= 0")
}
return func(next HandlerFunc) HandlerFunc {
return func(i *Invocation) error {
// ShowUsageOnError will add the command usage before the error message.
return ShowUsageOnError(func(i *Invocation) error {
got := len(i.Args)
switch {
case start == end && got != start:
Expand Down Expand Up @@ -614,7 +625,7 @@ func RequireRangeArgs(start, end int) MiddlewareFunc {
default:
return next(i)
}
}
})
}
}

Expand Down
14 changes: 12 additions & 2 deletions cli/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ func (RootCmd) errorExample() *clibase.Cmd {
apiError.(*codersdk.Error).Helper = "Have you tried turning it off and on again?"

//nolint:errorlint,forcetypeassert
apiErrorNoHelper := apiError.(*codersdk.Error)
cpy := *apiError.(*codersdk.Error)
apiErrorNoHelper := &cpy
apiErrorNoHelper.Helper = ""

// Some flags
Expand Down Expand Up @@ -94,7 +95,6 @@ func (RootCmd) errorExample() *clibase.Cmd {
)
},
},

{
Use: "validation",
Options: clibase.OptionSet{
Expand All @@ -114,6 +114,16 @@ func (RootCmd) errorExample() *clibase.Cmd {
return nil
},
},
{
Use: "arg-required <required>",
Middleware: clibase.Chain(
clibase.RequireNArgs(1),
),
Handler: func(i *clibase.Invocation) error {
_, _ = fmt.Fprint(i.Stdout, "Try running this without an argument\n")
return nil
},
},
},
}

Expand Down