Refactor fishAddFileFlag for better flexibility [#1156]

Performing reflection on the given flag ensures that fishAddFileFlag
will behave correctly if any flag types get a TakesFile field in the
future.
This commit is contained in:
Erin Call 2020-10-13 12:55:44 -07:00
parent 0d11bd55f5
commit fcce511478
No known key found for this signature in database
GPG Key ID: 4071FF6C15B8DAD1

24
fish.go
View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"reflect"
"strings" "strings"
"text/template" "text/template"
) )
@ -158,24 +159,17 @@ func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string
} }
func fishAddFileFlag(flag Flag, completion *strings.Builder) { func fishAddFileFlag(flag Flag, completion *strings.Builder) {
switch f := flag.(type) { val := reflect.ValueOf(flag)
case *GenericFlag: // if flag is a non-nil pointer to a struct...
if f.TakesFile { if val.Kind() != reflect.Invalid && val.Elem().Kind() == reflect.Struct {
return field := val.Elem().FieldByName("TakesFile")
} // if flag's underlying type has a bool field called TakesFile, whose value is true...
case *StringFlag: if field.Kind() == reflect.Bool && field.Bool() {
if f.TakesFile { // don't append '-f'
return
}
case *StringSliceFlag:
if f.TakesFile {
return
}
case *PathFlag:
if f.TakesFile {
return return
} }
} }
// append '-f', indicating that arguments to this flag are *not* meant to be file paths
completion.WriteString(" -f") completion.WriteString(" -f")
} }