diff --git a/carapace.go b/carapace.go index 714139f69..9d03feac8 100644 --- a/carapace.go +++ b/carapace.go @@ -57,7 +57,7 @@ func (c Carapace) PositionalCompletion(action ...Action) { // PositionalAnyCompletion defines completion for any positional arguments not already defined. func (c Carapace) PositionalAnyCompletion(action Action) { - storage.get(c.cmd).positionalAny = action + storage.get(c.cmd).positionalAny = &action } // DashCompletion defines completion for positional arguments after dash (`--`) using a list of Actions. @@ -67,7 +67,7 @@ func (c Carapace) DashCompletion(action ...Action) { // DashAnyCompletion defines completion for any positional arguments after dash (`--`) not already defined. func (c Carapace) DashAnyCompletion(action Action) { - storage.get(c.cmd).dashAny = action + storage.get(c.cmd).dashAny = &action } // FlagCompletion defines completion for flags using a map consisting of name and Action. diff --git a/compat.go b/compat.go index 800116f23..2035fefe2 100644 --- a/compat.go +++ b/compat.go @@ -2,6 +2,7 @@ package carapace import ( "fmt" + "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -10,7 +11,11 @@ import ( func registerValidArgsFunction(cmd *cobra.Command) { if cmd.ValidArgsFunction == nil { cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - action := storage.getPositional(cmd, len(args)).Invoke(Context{Args: args, Value: toComplete}) + // TODO check storage.hasPositional to prevent loop + action := Action{}.Invoke(Context{Args: args, Value: toComplete}) // TODO just IvokedAction{} ok? + if storage.hasPositional(cmd, len(args)) { + action = storage.getPositional(cmd, len(args)).Invoke(Context{Args: args, Value: toComplete}) + } return cobraValuesFor(action), cobraDirectiveFor(action) } } @@ -18,6 +23,13 @@ func registerValidArgsFunction(cmd *cobra.Command) { func registerFlagCompletion(cmd *cobra.Command) { cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if !storage.hasFlag(cmd, f.Name) { + return // skip if not defined in carapace + } + if _, ok := cmd.GetFlagCompletionByName(f.Name); ok { + return // skip if already defined in cobra + } + err := cmd.RegisterFlagCompletionFunc(f.Name, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { a := storage.getFlag(cmd, f.Name) action := a.Invoke(Context{Args: args, Value: toComplete}) @@ -51,3 +63,60 @@ func cobraDirectiveFor(action InvokedAction) cobra.ShellCompDirective { } return directive } + +func actionCobra(cmd *cobra.Command, f func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)) Action { + return ActionCallback(func(c Context) Action { + if f == nil { + return ActionValues() + } + + c.Args = cmd.Flags().Args() // TODO verify - ensure it contains all args, this might not be correct at all times (e.g. changed Context.Args) + values, directive := f(cmd, c.Args, c.Value) + return compDirective(directive).ToA(values...) + }) +} + +type compDirective cobra.ShellCompDirective + +func (d compDirective) matches(cobraDirective cobra.ShellCompDirective) bool { + return d&compDirective(cobraDirective) != 0 +} + +func (d compDirective) ToA(values ...string) Action { + var action Action + switch { + case d.matches(cobra.ShellCompDirectiveError): + return ActionMessage("an error occured") + case d.matches(cobra.ShellCompDirectiveFilterDirs): + switch len(values) { + case 0: + action = ActionDirectories() + default: + action = ActionDirectories().Chdir(values[0]) + } + case d.matches(cobra.ShellCompDirectiveFilterFileExt): + extensions := make([]string, 0) + for _, v := range values { + extensions = append(extensions, "."+v) + } + return ActionFiles(extensions...) + case len(values) == 0 && !d.matches(cobra.ShellCompDirectiveNoFileComp): + action = ActionFiles() + default: + vals := make([]string, 0) + for _, v := range values { + if splitted := strings.SplitN(v, "\t", 2); len(splitted) == 2 { + vals = append(vals, splitted[0], splitted[1]) + } else { + vals = append(vals, splitted[0], "") + } + } + action = ActionValuesDescribed(vals...) + } + + if d.matches(cobra.ShellCompDirectiveNoSpace) { + action = action.NoSpace() + } + + return action +} diff --git a/defaultActions.go b/defaultActions.go index 75799e386..c17166878 100644 --- a/defaultActions.go +++ b/defaultActions.go @@ -473,7 +473,11 @@ func ActionPositional(cmd *cobra.Command) Action { c.Args = cmd.Flags().Args() entry := storage.get(cmd) - a := entry.positionalAny + var a Action + if entry.positionalAny != nil { + a = *entry.positionalAny + } + if index := len(c.Args); index < len(entry.positional) { a = entry.positional[len(c.Args)] } diff --git a/example/cmd/compat.go b/example/cmd/compat.go new file mode 100644 index 000000000..9cc853f25 --- /dev/null +++ b/example/cmd/compat.go @@ -0,0 +1,72 @@ +package cmd + +import ( + "github.com/rsteube/carapace" + "github.com/spf13/cobra" +) + +var compatCmd = &cobra.Command{ + Use: "compat", + Short: "", + Run: func(cmd *cobra.Command, args []string) {}, +} + +func init() { + carapace.Gen(compatCmd).Standalone() + + compatCmd.Flags() + + compatCmd.Flags().String("error", "", "ShellCompDirectiveError") + compatCmd.Flags().String("nospace", "", "ShellCompDirectiveNoSpace") + compatCmd.Flags().String("nofilecomp", "", "ShellCompDirectiveNoFileComp") + compatCmd.Flags().String("filterfileext", "", "ShellCompDirectiveFilterFileExt") + compatCmd.Flags().String("filterdirs", "", "ShellCompDirectiveFilterDirs") + compatCmd.Flags().String("filterdirs-chdir", "", "ShellCompDirectiveFilterDirs") + compatCmd.Flags().String("keeporder", "", "ShellCompDirectiveKeepOrder") + compatCmd.Flags().String("default", "", "ShellCompDirectiveDefault") + + compatCmd.Flags().String("unset", "", "no completions defined") + + rootCmd.AddCommand(compatCmd) + + compatCmd.RegisterFlagCompletionFunc("error", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return nil, cobra.ShellCompDirectiveError + }) + compatCmd.RegisterFlagCompletionFunc("nospace", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"one", "two"}, cobra.ShellCompDirectiveNoSpace + }) + compatCmd.RegisterFlagCompletionFunc("nofilecomp", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return nil, cobra.ShellCompDirectiveNoFileComp + }) + + compatCmd.RegisterFlagCompletionFunc("filterfileext", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"mod", "sum"}, cobra.ShellCompDirectiveFilterFileExt + }) + + compatCmd.RegisterFlagCompletionFunc("filterdirs", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return nil, cobra.ShellCompDirectiveFilterDirs + }) + + compatCmd.RegisterFlagCompletionFunc("filterdirs-chdir", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"subdir"}, cobra.ShellCompDirectiveFilterDirs + }) + + compatCmd.RegisterFlagCompletionFunc("keeporder", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"one", "three", "two"}, cobra.ShellCompDirectiveKeepOrder + }) + + compatCmd.RegisterFlagCompletionFunc("default", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return nil, cobra.ShellCompDirectiveDefault + }) + + compatCmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + switch len(args) { + case 0: + return []string{"p1", "positional1"}, cobra.ShellCompDirectiveDefault + case 1: + return nil, cobra.ShellCompDirectiveDefault + default: + return nil, cobra.ShellCompDirectiveNoFileComp + } + } +} diff --git a/example/cmd/compat_test.go b/example/cmd/compat_test.go new file mode 100644 index 000000000..bf0777b68 --- /dev/null +++ b/example/cmd/compat_test.go @@ -0,0 +1,84 @@ +package cmd + +import ( + "testing" + + "github.com/rsteube/carapace" + "github.com/rsteube/carapace/pkg/sandbox" + "github.com/rsteube/carapace/pkg/style" +) + +func TestCompat(t *testing.T) { + sandbox.Package(t, "github.com/rsteube/carapace/example")(func(s *sandbox.Sandbox) { + s.Files( + "subdir/file1.txt", "", + "subdir/subdir2/file2.txt", "", + "go.mod", "", + "go.sum", "", + "README.md", "", + ) + + s.Run("compat", "--error", ""). + Expect(carapace.ActionMessage("an error occured"). + Usage("ShellCompDirectiveError")) + + s.Run("compat", "--nospace", ""). + Expect(carapace.ActionValues( + "one", + "two", + ).NoSpace(). + Usage("ShellCompDirectiveNoSpace")) + + s.Run("compat", "--nofilecomp", ""). + Expect(carapace.ActionValues(). + Usage("ShellCompDirectiveNoFileComp")) + + s.Run("compat", "--filterfileext", ""). + Expect(carapace.ActionValues( + "subdir/", + "go.mod", + "go.sum", + ).NoSpace('/'). + Tag("files"). + StyleF(style.ForPath). + Usage("ShellCompDirectiveFilterFileExt")) + + s.Run("compat", "--filterdirs", ""). + Expect(carapace.ActionValues( + "subdir/", + ).NoSpace('/'). + Tag("directories"). + StyleF(style.ForPath). + Usage("ShellCompDirectiveFilterDirs")) + + s.Run("compat", "--filterdirs-chdir", ""). + Expect(carapace.ActionValues( + "subdir2/", + ).NoSpace('/'). + Tag("directories"). + StyleF(style.ForPathExt). + Usage("ShellCompDirectiveFilterDirs")) + + s.Run("compat", "--keeporder", ""). + Expect(carapace.ActionValues( + "one", + "two", + "three", + ).Usage("ShellCompDirectiveKeepOrder")) + + s.Run("compat", "--default", ""). + Expect(carapace.ActionValues( + "subdir/", + "go.mod", + "go.sum", + "README.md", + ).NoSpace('/'). + Tag("files"). + StyleF(style.ForPath). + Usage("ShellCompDirectiveDefault")) + + s.Run("compat", "--unset", ""). + Expect(carapace.ActionValues(). + Usage("no completions defined")) + }) +} diff --git a/example/cmd/root_test.go b/example/cmd/root_test.go index 214f68037..8c4f95256 100644 --- a/example/cmd/root_test.go +++ b/example/cmd/root_test.go @@ -73,6 +73,7 @@ func TestRoot(t *testing.T) { ).Style(style.Magenta).Tag("plugin commands"), carapace.ActionValuesDescribed( "chain", "shorthand chain", + "compat", "", "completion", "Generate the autocompletion script for the specified shell", "group", "group example", "help", "Help about any command", diff --git a/go.mod b/go.mod index 4caa2d402..2c6a2a7ec 100644 --- a/go.mod +++ b/go.mod @@ -8,3 +8,5 @@ require ( github.com/spf13/pflag v1.0.5 gopkg.in/yaml.v3 v3.0.1 ) + +replace github.com/spf13/cobra => github.com/avirtopeanu-ionos/cobra v0.0.0-20230330100513-ad4838bd46b0 diff --git a/go.sum b/go.sum index f5f55b3bc..84ed88624 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,11 @@ +github.com/avirtopeanu-ionos/cobra v0.0.0-20230330100513-ad4838bd46b0 h1:rZ2JtTLPDPTwQVMbU+VYpG8Tz2JfWFS3NW/YdV8vqXs= +github.com/avirtopeanu-ionos/cobra v0.0.0-20230330100513-ad4838bd46b0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/rsteube/carapace-shlex v0.0.4 h1:3GVn8PaM2RCxPTAiwVy9vDQI8Mi7DqrbdpDgf5ZzQmY= github.com/rsteube/carapace-shlex v0.0.4/go.mod h1:zPw1dOFwvLPKStUy9g2BYKanI6bsQMATzDMYQQybo3o= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= diff --git a/storage.go b/storage.go index 082d986bf..ace2cd9b8 100644 --- a/storage.go +++ b/storage.go @@ -17,9 +17,9 @@ type entry struct { flag ActionMap flagMutex sync.RWMutex positional []Action - positionalAny Action + positionalAny *Action dash []Action - dashAny Action + dashAny *Action preinvoke func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action prerun func(cmd *cobra.Command, args []string) bridged bool @@ -72,6 +72,18 @@ func (s _storage) bridge(cmd *cobra.Command) { } } +func (s _storage) hasFlag(cmd *cobra.Command, name string) bool { + if flag := cmd.LocalFlags().Lookup(name); flag == nil && cmd.HasParent() { + return s.hasFlag(cmd.Parent(), name) + } else { + entry := s.get(cmd) + entry.flagMutex.RLock() + defer entry.flagMutex.RUnlock() + _, ok := entry.flag[name] + return ok + } +} + func (s _storage) getFlag(cmd *cobra.Command, name string) Action { if flag := cmd.LocalFlags().Lookup(name); flag == nil && cmd.HasParent() { return s.getFlag(cmd.Parent(), name) @@ -79,7 +91,15 @@ func (s _storage) getFlag(cmd *cobra.Command, name string) Action { entry := s.get(cmd) entry.flagMutex.RLock() defer entry.flagMutex.RUnlock() - a := s.preinvoke(cmd, flag, entry.flag[name]) + + flagAction, ok := entry.flag[name] + if !ok { + if f, ok := cmd.GetFlagCompletionByName(name); ok { + flagAction = actionCobra(cmd, f) + } + } + + a := s.preinvoke(cmd, flag, flagAction) return ActionCallback(func(c Context) Action { // TODO verify order of execution is correct invoked := a.Invoke(c) @@ -112,6 +132,24 @@ func (s _storage) preinvoke(cmd *cobra.Command, flag *pflag.Flag, action Action) return a } +func (s _storage) hasPositional(cmd *cobra.Command, index int) bool { + entry := s.get(cmd) + isDash := common.IsDash(cmd) + + // TODO fallback to cobra defined completion if exists + + switch { + case !isDash && len(entry.positional) > index: + return true + case !isDash: + return entry.positionalAny != nil + case len(entry.dash) > index: + return true + default: + return entry.dashAny != nil + } +} + func (s _storage) getPositional(cmd *cobra.Command, index int) Action { entry := s.get(cmd) isDash := common.IsDash(cmd) @@ -119,14 +157,23 @@ func (s _storage) getPositional(cmd *cobra.Command, index int) Action { var a Action switch { case !isDash && len(entry.positional) > index: - a = s.preinvoke(cmd, nil, entry.positional[index]) + a = entry.positional[index] case !isDash: - a = s.preinvoke(cmd, nil, entry.positionalAny) + if entry.positionalAny != nil { + a = *entry.positionalAny + } else { + a = actionCobra(cmd, cmd.ValidArgsFunction) + } case len(entry.dash) > index: - a = s.preinvoke(cmd, nil, entry.dash[index]) + a = entry.dash[index] default: - a = s.preinvoke(cmd, nil, entry.dashAny) + if entry.dashAny != nil { + a = *entry.dashAny + } else { + a = actionCobra(cmd, cmd.ValidArgsFunction) + } } + a = s.preinvoke(cmd, nil, a) return ActionCallback(func(c Context) Action { invoked := a.Invoke(c)