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