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 4, 2023
1 parent 7af4c10 commit 67029db
Show file tree
Hide file tree
Showing 13 changed files with 398 additions and 16 deletions.
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
74 changes: 72 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,28 @@ 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)
}
}
}

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 {

Check failure on line 29 in compat.go

View workflow job for this annotation

GitHub Actions / build

cmd.GetFlagCompletionByName undefined (type *cobra.Command has no field or method GetFlagCompletionByName)

Check failure on line 29 in compat.go

View workflow job for this annotation

GitHub Actions / lint

cmd.GetFlagCompletionByName undefined (type *cobra.Command has no field or method GetFlagCompletionByName) (typecheck)

Check failure on line 29 in compat.go

View workflow job for this annotation

GitHub Actions / build

cmd.GetFlagCompletionByName undefined (type *cobra.Command has no field or method GetFlagCompletionByName)
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 +63,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) {
args = cmd.Flags().Args()
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
}
}
}
19 changes: 19 additions & 0 deletions example/cmd/compat_sub.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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 67029db

Please sign in to comment.