Cobra: Allow combination of PositionalArgs validation functions

Created on 15 Mar 2018  路  2Comments  路  Source: spf13/cobra

Would be nice to be able to easily combine (ie AND, OR, NOT) validation functions, because otherwise the builtin provided functions quickly fall short.

As an example, let's say I want to implement cmd completion <zsh|bash>. I tried using

Args:      cobra.OnlyValidArgs,
ValidArgs: []string{"bash", "zsh"},

but then it passes through (and crashes later) if the user did not provide any arg!

I believe this feature request can be implemented by adding the composition methods on the PositionalArgs type

kinstale

Most helpful comment

I hit this one too.

[UPDATE] This project does a good job solving this: https://github.com/lbryio/reflector.go/blob/280cd22922edd6d70cb795c53aa492f771f64be1/cmd/cluster.go#L21

Args: argFuncs(cobra.ExactArgs(1), cobra.OnlyValidArgs),
func argFuncs(funcs ...cobra.PositionalArgs) cobra.PositionalArgs {
    return func(cmd *cobra.Command, args []string) error {
        for _, f := range funcs {
            err := f(cmd, args)
            if err != nil {
                return err
            }
        }
        return nil
    }
}

All 2 comments

I hit this one too.

[UPDATE] This project does a good job solving this: https://github.com/lbryio/reflector.go/blob/280cd22922edd6d70cb795c53aa492f771f64be1/cmd/cluster.go#L21

Args: argFuncs(cobra.ExactArgs(1), cobra.OnlyValidArgs),
func argFuncs(funcs ...cobra.PositionalArgs) cobra.PositionalArgs {
    return func(cmd *cobra.Command, args []string) error {
        for _, f := range funcs {
            err := f(cmd, args)
            if err != nil {
                return err
            }
        }
        return nil
    }
}

This issue is being marked as stale due to a long period of inactivity

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mdaymard picture mdaymard  路  5Comments

anuraaga picture anuraaga  路  5Comments

lukasmalkmus picture lukasmalkmus  路  4Comments

diwakergupta picture diwakergupta  路  5Comments

groenborg picture groenborg  路  5Comments