-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag_valuer.go
74 lines (59 loc) · 1.88 KB
/
flag_valuer.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package cli
import (
"fmt"
"strings"
)
// FlagValuer defines how to set and get the value of a flag.
type FlagValuer interface {
// Destination returns flag's value pointer.
Destination() any
// FromString parses and set the value.
FromString(str string) error
// IsSet returns whether the flag value has been set.
IsSet() bool
// String returns a representation of the value.
String() string
// TypeRepr returns a representation of the underlying type of the value. Example: 'int'.
TypeRepr() string
}
// NewFlagValuer creates a flag valuer from a parse and toString functions. It panics if any parameters are nil.
func NewFlagValuer[T any](destination *T, parse func(string) (T, error), toString func(T) string) FlagValuer {
if destination == nil {
panic("destination is nil")
}
if parse == nil {
panic("parse is nil")
}
if toString == nil {
panic("toString is nil")
}
return &flagValuer[T]{
value: destination,
parse: parse,
toString: toString,
}
}
// NewStringerFlagValuer creates a flag valuer from a parse function returning something that implements stringer.
// See NewFlagValuer for more details.
func NewStringerFlagValuer[T fmt.Stringer](destination *T, parse func(string) (T, error)) FlagValuer {
return NewFlagValuer(destination, parse, func(t T) string { return t.String() })
}
type flagValuer[T any] struct {
value *T
changed bool
parse func(string) (T, error)
toString func(T) string
}
func (v *flagValuer[T]) Destination() any { return v.value }
func (v *flagValuer[T]) FromString(raw string) error {
value, err := v.parse(strings.TrimSpace(raw))
if err != nil {
return err
}
*v.value = value
v.changed = true
return nil
}
func (v *flagValuer[T]) IsSet() bool { return v.changed }
func (v *flagValuer[T]) String() string { return v.toString(*v.value) }
func (v *flagValuer[T]) TypeRepr() string { return fmt.Sprintf("%T", *v.value) }