Return an error on unrecognized arguments when running default commands in Prysm (#9129)

* Return an error on unrecognized arguments when running default commands in Prysm

* fix cases for subcommands

* Deepsource suggestion
This commit is contained in:
Preston Van Loon
2021-06-30 11:24:04 -05:00
committed by GitHub
parent b23f63a064
commit 24d17a536c
6 changed files with 62 additions and 4 deletions

View File

@@ -177,7 +177,10 @@ func main() {
runtimeDebug.SetGCPercent(ctx.Int(flags.SetGCPercent.Name))
}
runtime.GOMAXPROCS(runtime.NumCPU())
return debug.Setup(ctx)
if err := debug.Setup(ctx); err != nil {
return err
}
return cmd.ValidateNoArgs(ctx)
}
defer func() {

View File

@@ -84,7 +84,7 @@ func main() {
log.WithError(err).Error("Failed to configuring logging to disk.")
}
}
return nil
return cmd.ValidateNoArgs(ctx)
}
defer func() {

View File

@@ -132,7 +132,10 @@ func main() {
}
runtime.GOMAXPROCS(runtime.NumCPU())
return debug.Setup(ctx)
if err := debug.Setup(ctx); err != nil {
return err
}
return cmd.ValidateNoArgs(ctx)
}
app.After = func(ctx *cli.Context) error {

View File

@@ -168,7 +168,10 @@ func main() {
}
runtime.GOMAXPROCS(runtime.NumCPU())
return debug.Setup(ctx)
if err := debug.Setup(ctx); err != nil {
return err
}
return cmd.ValidateNoArgs(ctx)
}
app.After = func(ctx *cli.Context) error {

View File

@@ -2,6 +2,9 @@
package cmd
import (
"fmt"
"strings"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
@@ -250,3 +253,17 @@ func LoadFlagsFromConfig(cliCtx *cli.Context, flags []cli.Flag) error {
}
return nil
}
// ValidateNoArgs insures that the application is not run with erroneous arguments or flags.
// This function should be used in the app.Before, whenever the application supports a default command.
func ValidateNoArgs(ctx *cli.Context) error {
for _, a := range ctx.Args().Slice() {
if strings.HasPrefix(a, "-") {
continue
}
if c := ctx.App.Command(a); c == nil {
return fmt.Errorf("unrecognized argument: %s", a)
}
}
return nil
}

View File

@@ -40,3 +40,35 @@ func TestLoadFlagsFromConfig(t *testing.T) {
require.NoError(t, command.Run(context))
require.NoError(t, os.Remove("flags_test.yaml"))
}
func TestValidateNoArgs(t *testing.T) {
app := &cli.App{
Before: ValidateNoArgs,
Action: func(c *cli.Context) error {
return nil
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "foo",
},
},
Commands: []*cli.Command{
{
Name: "bar",
},
},
}
// It should not work with a bogus argument
err := app.Run([]string{"command", "foo"})
require.ErrorContains(t, "unrecognized argument: foo", err)
// It should work with registered flags
err = app.Run([]string{"command", "--foo=bar"})
require.NoError(t, err)
// It should work with subcommands.
err = app.Run([]string{"command", "bar"})
require.NoError(t, err)
// It should fail on unregistered flag (default logic in urfave/cli).
err = app.Run([]string{"command", "bar", "--baz"})
require.ErrorContains(t, "flag provided but not defined", err)
}