-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathflag_text.go
More file actions
86 lines (73 loc) · 2.18 KB
/
Copy pathflag_text.go
File metadata and controls
86 lines (73 loc) · 2.18 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
package cli
import (
"encoding"
"strings"
)
// TextMarshalUnmarshaler is the interface implemented by types that can marshal
// themselves to and from a textual form. It is the value type used by TextFlag,
// mirroring the standard library's flag.TextVar, and is satisfied by types such
// as *slog.LevelVar, *net/netip.Addr, and *time.Time.
type TextMarshalUnmarshaler interface {
encoding.TextMarshaler
encoding.TextUnmarshaler
}
type TextFlag = FlagBase[TextMarshalUnmarshaler, StringConfig, textValue]
// -- TextMarshalUnmarshaler Value
type textValue struct {
destination TextMarshalUnmarshaler
trimSpace bool
}
// Below functions are to satisfy the ValueCreator interface
func (t textValue) Create(val TextMarshalUnmarshaler, p *TextMarshalUnmarshaler, c StringConfig) Value {
// Only overwrite the target when a non-nil default value is given, so that
// a Destination pointing at an existing target is preserved (unlike the
// concrete flag types, T here is an interface whose nil default would
// otherwise clobber the destination).
if val != nil {
*p = val
}
return &textValue{
destination: *p,
trimSpace: c.TrimSpace,
}
}
func (t textValue) ToString(val TextMarshalUnmarshaler) string {
if val == nil {
return ""
}
text, err := val.MarshalText()
if err != nil {
return ""
}
return string(text)
}
// Below functions are to satisfy the flag.Value interface
func (t *textValue) Set(val string) error {
if t.destination == nil {
return nil
}
if t.trimSpace {
val = strings.TrimSpace(val)
}
return t.destination.UnmarshalText([]byte(val))
}
func (t *textValue) Get() any { return t.destination }
func (t *textValue) String() string {
if t.destination == nil {
return ""
}
text, err := t.destination.MarshalText()
if err != nil {
return ""
}
return string(text)
}
// Text looks up the value of a local TextFlag, returns nil if not found
func (cmd *Command) Text(name string) TextMarshalUnmarshaler {
if v, ok := cmd.Value(name).(TextMarshalUnmarshaler); ok {
tracef("text available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name)
return v
}
tracef("text NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name)
return nil
}