Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions fish.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,9 @@ func prepareFishFlags(binary string, owner *Command) []string {
}

func fishAddFileFlag(flag Flag, completion *strings.Builder) {
switch f := flag.(type) {
case *StringFlag:
if f.TakesFile {
return
}
case *StringSliceFlag:
if f.TakesFile {
return
}
// TakesFile is a field of every flag type, not only StringFlag and StringSliceFlag
if f, ok := flag.(interface{ takesFile() bool }); ok && f.takesFile() {
return
}
completion.WriteString(" -f")
}
Expand Down
23 changes: 23 additions & 0 deletions fish_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,29 @@ func TestFishCompletionShellComplete(t *testing.T) {
assert.Contains(t, res, fmt.Sprintf("complete -c greet -n '__fish_seen_subcommand_from config c; and __fish_seen_subcommand_from sub-config s ss' -xa '(greet config sub-config %s 2>/dev/null)'", completionFlag))
}

func TestFishCompletionTakesFileForAllFlagTypes(t *testing.T) {
cmd := &Command{
Name: "greet",
Flags: []Flag{
&StringFlag{Name: "config", TakesFile: true},
&GenericFlag{Name: "input", Value: &Parser{}, TakesFile: true},
&StringMapFlag{Name: "env-file", TakesFile: true},
&StringFlag{Name: "name"},
// a boolean takes no value, so there is no file to complete
&BoolFlag{Name: "dry-run", TakesFile: true},
},
}

res, err := cmd.ToFishCompletion()
require.NoError(t, err)

assert.Contains(t, res, "'__fish_greet_no_subcommand' -l config -r")
assert.Contains(t, res, "'__fish_greet_no_subcommand' -l input -r")
assert.Contains(t, res, "'__fish_greet_no_subcommand' -l env-file -r")
assert.Contains(t, res, "'__fish_greet_no_subcommand' -f -l name -r")
assert.Contains(t, res, "'__fish_greet_no_subcommand' -f -l dry-run")
}

func TestFishCompletionUsesFirstLineOfUsage(t *testing.T) {
cmd := &Command{
Name: "greet",
Expand Down
5 changes: 5 additions & 0 deletions flag_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,11 @@ func (f *FlagBase[T, C, V]) TakesValue() bool {
return reflect.TypeOf(t) == nil || reflect.TypeOf(t).Kind() != reflect.Bool
}

// takesFile returns true if the flag's value is a file path, for shell completion
func (f *FlagBase[T, C, V]) takesFile() bool {
return f.TakesFile && f.TakesValue()
}

// GetDefaultText returns the default text for this flag
func (f *FlagBase[T, C, V]) GetDefaultText() string {
return f.DefaultText
Expand Down
Loading