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