Skip to content
Merged
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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy