1package cli 2 3import "flag" 4 5// StringFlag is a flag with type string 6type StringFlag struct { 7 Name string 8 Aliases []string 9 Usage string 10 EnvVars []string 11 FilePath string 12 Required bool 13 Hidden bool 14 TakesFile bool 15 Value string 16 DefaultText string 17 Destination *string 18 HasBeenSet bool 19} 20 21// IsSet returns whether or not the flag has been set through env or file 22func (f *StringFlag) IsSet() bool { 23 return f.HasBeenSet 24} 25 26// String returns a readable representation of this value 27// (for usage defaults) 28func (f *StringFlag) String() string { 29 return FlagStringer(f) 30} 31 32// Names returns the names of the flag 33func (f *StringFlag) Names() []string { 34 return flagNames(f.Name, f.Aliases) 35} 36 37// IsRequired returns whether or not the flag is required 38func (f *StringFlag) IsRequired() bool { 39 return f.Required 40} 41 42// TakesValue returns true of the flag takes a value, otherwise false 43func (f *StringFlag) TakesValue() bool { 44 return true 45} 46 47// GetUsage returns the usage string for the flag 48func (f *StringFlag) GetUsage() string { 49 return f.Usage 50} 51 52// GetValue returns the flags value as string representation and an empty 53// string if the flag takes no value at all. 54func (f *StringFlag) GetValue() string { 55 return f.Value 56} 57 58// Apply populates the flag given the flag set and environment 59func (f *StringFlag) Apply(set *flag.FlagSet) error { 60 if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok { 61 f.Value = val 62 f.HasBeenSet = true 63 } 64 65 for _, name := range f.Names() { 66 if f.Destination != nil { 67 set.StringVar(f.Destination, name, f.Value, f.Usage) 68 continue 69 } 70 set.String(name, f.Value, f.Usage) 71 } 72 73 return nil 74} 75 76// String looks up the value of a local StringFlag, returns 77// "" if not found 78func (c *Context) String(name string) string { 79 if fs := lookupFlagSet(name, c); fs != nil { 80 return lookupString(name, fs) 81 } 82 return "" 83} 84 85func lookupString(name string, set *flag.FlagSet) string { 86 f := set.Lookup(name) 87 if f != nil { 88 parsed, err := f.Value.String(), error(nil) 89 if err != nil { 90 return "" 91 } 92 return parsed 93 } 94 return "" 95} 96