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