File tree 2 files changed +25
-4
lines changed
2 files changed +25
-4
lines changed Original file line number Diff line number Diff line change @@ -562,6 +562,16 @@ func Chain(ms ...MiddlewareFunc) MiddlewareFunc {
562
562
return chain (reversed ... )
563
563
}
564
564
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\n Error: %w" , i .Command .FullUsage (), err )
570
+ }
571
+ return nil
572
+ }
573
+ }
574
+
565
575
func RequireNArgs (want int ) MiddlewareFunc {
566
576
return RequireRangeArgs (want , want )
567
577
}
@@ -574,7 +584,8 @@ func RequireRangeArgs(start, end int) MiddlewareFunc {
574
584
panic ("start must be >= 0" )
575
585
}
576
586
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 {
578
589
got := len (i .Args )
579
590
switch {
580
591
case start == end && got != start :
@@ -614,7 +625,7 @@ func RequireRangeArgs(start, end int) MiddlewareFunc {
614
625
default :
615
626
return next (i )
616
627
}
617
- }
628
+ })
618
629
}
619
630
}
620
631
Original file line number Diff line number Diff line change @@ -45,7 +45,8 @@ func (RootCmd) errorExample() *clibase.Cmd {
45
45
apiError .(* codersdk.Error ).Helper = "Have you tried turning it off and on again?"
46
46
47
47
//nolint:errorlint,forcetypeassert
48
- apiErrorNoHelper := apiError .(* codersdk.Error )
48
+ cpy := * apiError .(* codersdk.Error )
49
+ apiErrorNoHelper := & cpy
49
50
apiErrorNoHelper .Helper = ""
50
51
51
52
// Some flags
@@ -94,7 +95,6 @@ func (RootCmd) errorExample() *clibase.Cmd {
94
95
)
95
96
},
96
97
},
97
-
98
98
{
99
99
Use : "validation" ,
100
100
Options : clibase.OptionSet {
@@ -114,6 +114,16 @@ func (RootCmd) errorExample() *clibase.Cmd {
114
114
return nil
115
115
},
116
116
},
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
+ },
117
127
},
118
128
}
119
129
You can’t perform that action at this time.
0 commit comments