-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.go
40 lines (35 loc) · 939 Bytes
/
text.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
package flagx
type textValue struct {
value interface {
// See [encoding.TextMarshaler].
MarshalText() (text []byte, err error)
// See [encoding.TextUnmarshaler].
UnmarshalText(text []byte) error
}
}
func (v *textValue) String() string {
b, err := v.value.MarshalText()
if err != nil {
// Panic?
return ""
}
return string(b)
}
func (v *textValue) Set(str string) error {
return v.value.UnmarshalText([]byte(str))
}
func (v *textValue) Get() interface{} {
return v.value
}
// Text wraps an [encoding.TextUnmarshaler] + [encoding.TextMarshaler] as a [flag.Getter]
// which can then be passed to [flag.Var] / [flag.FlagSet.Var].
//
// Note: you might prefer to use [flag.TextVar] which is available since Go 1.19.
func Text(v interface {
// See [encoding.TextMarshaler].
MarshalText() (text []byte, err error)
// See [encoding.TextUnmarshaler].
UnmarshalText(text []byte) error
}) Value {
return &textValue{v}
}