Debian Codegraph @

vendor/github.com/urfave/cli/v2/flag_duration.go

raw
1 package cli
2
3 import (
4 "flag"
5 "fmt"
6 "time"
7 )
8
9 // TakesValue returns true of the flag takes a value, otherwise false
10 func (f *DurationFlag) TakesValue() bool {
11 return true
12 }
13
14 // GetUsage returns the usage string for the flag
15 func (f *DurationFlag) GetUsage() string {
16 return f.Usage
17 }
18
19 // GetCategory returns the category for the flag
20 func (f *DurationFlag) GetCategory() string {
21 return f.Category
22 }
23
24 // GetValue returns the flags value as string representation and an empty
25 // string if the flag takes no value at all.
26 func (f *DurationFlag) GetValue() string {
27 return f.Value.String()
28 }
29
30 // GetDefaultText returns the default text for this flag
31 func (f *DurationFlag) GetDefaultText() string {
32 if f.DefaultText != "" {
33 return f.DefaultText
34 }
35 if f.defaultValueSet {
36 return f.defaultValue.String()
37 }
38 return f.Value.String()
39 }
40
41 // GetEnvVars returns the env vars for this flag
42 func (f *DurationFlag) GetEnvVars() []string {
43 return f.EnvVars
44 }
45
46 // Apply populates the flag given the flag set and environment
47 func (f *DurationFlag) Apply(set *flag.FlagSet) error {
48 // set default value so that environment wont be able to overwrite it
49 f.defaultValue = f.Value
50 f.defaultValueSet = true
51
52 if val, source, found := flagFromEnvOrFile(f.EnvVars, f.FilePath); found {
53 if val != "" {
54 valDuration, err := time.ParseDuration(val)
55
56 if err != nil {
57 return fmt.Errorf("could not parse %q as duration value from %s for flag %s: %s", val, source, f.Name, err)
58 }
59
60 f.Value = valDuration
61 f.HasBeenSet = true
62 }
63 }
64
65 for _, name := range f.Names() {
66 if f.Destination != nil {
67 set.DurationVar(f.Destination, name, f.Value, f.Usage)
68 continue
69 }
70 set.Duration(name, f.Value, f.Usage)
71 }
72 return nil
73 }
74
75 // Get returns the flag’s value in the given Context.
76 func (f *DurationFlag) Get(ctx *Context) time.Duration {
77 return ctx.Duration(f.Name)
78 }
79
80 // RunAction executes flag action if set
81 func (f *DurationFlag) RunAction(c *Context) error {
82 if f.Action != nil {
83 return f.Action(c, c.Duration(f.Name))
84 }
85
86 return nil
87 }
88
89 // Duration looks up the value of a local DurationFlag, returns
90 // 0 if not found
91 func (cCtx *Context) Duration(name string) time.Duration {
92 if fs := cCtx.lookupFlagSet(name); fs != nil {
93 return lookupDuration(name, fs)
94 }
95 return 0
96 }
97
98 func lookupDuration(name string, set *flag.FlagSet) time.Duration {
99 f := set.Lookup(name)
100 if f != nil {
101 parsed, err := time.ParseDuration(f.Value.String())
102 if err != nil {
103 return 0
104 }
105 return parsed
106 }
107 return 0
108 }