Skip to content

Commit

Permalink
compat: added cobra bridge
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed Nov 27, 2023
1 parent 8b897f0 commit 410233f
Show file tree
Hide file tree
Showing 14 changed files with 402 additions and 16 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ caraparse/caraparse
docs/book
example/cmd/_test_files/*.txt
example/example
example-nonposix/example-nonposix
integration.cov
unit.cov
.vscode
4 changes: 2 additions & 2 deletions carapace.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
73 changes: 71 additions & 2 deletions compat.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package carapace

import (
"fmt"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand All @@ -10,17 +11,27 @@ 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})
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)
}
}
}

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.GetFlagCompletionFunc(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})
action := a.Invoke(Context{Args: args, Value: toComplete}) // TODO cmd might differ for persistentflags and either way args or cmd will be wrong
return cobraValuesFor(action), cobraDirectiveFor(action)
})
if err != nil {
Expand Down Expand Up @@ -51,3 +62,61 @@ func cobraDirectiveFor(action InvokedAction) cobra.ShellCompDirective {
}
return directive
}

func ActionCobra(f func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)) Action {
return ActionCallback(func(c Context) Action {
switch {
case f == nil:
return ActionValues()
case c.cmd == nil:
return ActionMessage("TODO: cmd is nil [ActionCobra]") // TODO test
}
values, directive := f(c.cmd, c.cmd.Flags().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
}
4 changes: 2 additions & 2 deletions compat_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package carapace

import (
"io/ioutil"
"io"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -54,7 +54,7 @@ func TestRegisterFlagCompletion(t *testing.T) {
_ = cmd.Execute()

w.Close()
out, _ := ioutil.ReadAll(r)
out, _ := io.ReadAll(r)
os.Stdout = rescueStdout

if lines := strings.Split(string(out), "\n"); lines[0] != "1\tone" {
Expand Down
2 changes: 2 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/rsteube/carapace/pkg/util"
"github.com/rsteube/carapace/third_party/github.com/drone/envsubst"
"github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs"
"github.com/spf13/cobra"
)

// Context provides information during completion.
Expand All @@ -28,6 +29,7 @@ type Context struct {
Dir string

mockedReplies map[string]string
cmd *cobra.Command
}

// NewContext creates a new context for given arguments.
Expand Down
6 changes: 5 additions & 1 deletion defaultActions.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,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)]
}
Expand Down
88 changes: 88 additions & 0 deletions example/cmd/compat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package cmd

import (
"fmt"

"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")
compatCmd.PersistentFlags().String("persistent-compat", "", "persistent flag defined with cobra")

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.RegisterFlagCompletionFunc("persistent-compat", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{
fmt.Sprintf("args: %#v toComplete: %#v", args, toComplete),
"alternative",
}, cobra.ShellCompDirectiveNoFileComp
})

compatCmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {

Check failure on line 72 in example/cmd/compat.go

View workflow job for this annotation

GitHub Actions / lint

SA4009: argument args is overwritten before first use (staticcheck)
args = cmd.Flags().Args()

Check failure on line 73 in example/cmd/compat.go

View workflow job for this annotation

GitHub Actions / lint

SA4009(related information): assignment to args (staticcheck)
switch len(args) {
case 0:
return []string{"p1", "positional1"}, cobra.ShellCompDirectiveDefault
case 1:
return nil, cobra.ShellCompDirectiveDefault
case 2:
return []string{
fmt.Sprintf("args: %#v toComplete: %#v", args, toComplete),
"alternative",
}, cobra.ShellCompDirectiveNoFileComp
default:
return nil, cobra.ShellCompDirectiveNoFileComp
}
}
}
18 changes: 18 additions & 0 deletions example/cmd/compat_sub.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cmd

import (
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
)

var compat_subCmd = &cobra.Command{
Use: "sub",
Short: "",
Run: func(cmd *cobra.Command, args []string) {},
}

func init() {
carapace.Gen(compat_subCmd).Standalone()

compatCmd.AddCommand(compat_subCmd)
}
30 changes: 30 additions & 0 deletions example/cmd/compat_sub_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cmd

import (
"testing"

"github.com/rsteube/carapace"
"github.com/rsteube/carapace/pkg/sandbox"
)

func TestCompatPersistent(t *testing.T) {
sandbox.Package(t, "github.com/rsteube/carapace/example")(func(s *sandbox.Sandbox) {
s.Run("compat", "sub", "--persistent-compat", "").
Expect(carapace.ActionValues(
`args: []string(nil) toComplete: ""`,
"alternative",
).Usage("persistent flag defined with cobra"))

s.Run("compat", "sub", "one", "--persistent-compat", "").
Expect(carapace.ActionValues(
`args: []string{"one"} toComplete: ""`,
"alternative",
).Usage("persistent flag defined with cobra"))

s.Run("compat", "sub", "one", "two", "--persistent-compat", "a").
Expect(carapace.ActionValues(
`args: []string{"one", "two"} toComplete: "a"`,
"alternative",
).Usage("persistent flag defined with cobra"))
})
}
Loading

0 comments on commit 410233f

Please sign in to comment.