-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathduration.go
56 lines (49 loc) · 1.39 KB
/
duration.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package dynflags
import (
"fmt"
"time"
)
type DurationValue struct {
Bound *time.Duration
}
func (d *DurationValue) GetBound() interface{} {
if d.Bound == nil {
return nil
}
return *d.Bound
}
func (d *DurationValue) Parse(value string) (interface{}, error) {
return time.ParseDuration(value)
}
func (d *DurationValue) Set(value interface{}) error {
if dur, ok := value.(time.Duration); ok {
*d.Bound = dur
return nil
}
return fmt.Errorf("invalid value type: expected duration")
}
// Duration defines a duration flag with the specified name, default value, and usage description.
// The flag is added to the group's flag list and returned as a *Flag instance.
func (g *ConfigGroup) Duration(name string, value time.Duration, usage string) *Flag {
bound := &value
flag := &Flag{
Type: FlagTypeDuration,
Default: value,
Usage: usage,
value: &DurationValue{Bound: bound},
}
g.Flags[name] = flag
g.flagOrder = append(g.flagOrder, name)
return flag
}
// GetDuration returns the time.Duration value of a flag with the given name
func (pg *ParsedGroup) GetDuration(flagName string) (time.Duration, error) {
vaue, exists := pg.Values[flagName]
if !exists {
return 0, fmt.Errorf("flag '%s' not found in group '%s'", flagName, pg.Name)
}
if durationVal, ok := vaue.(time.Duration); ok {
return durationVal, nil
}
return 0, fmt.Errorf("flag '%s' is not a time.Duration", flagName)
}