-
Notifications
You must be signed in to change notification settings - Fork 9
/
txtunmarshaler.go
60 lines (53 loc) · 1.53 KB
/
txtunmarshaler.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
// This file implements support for all types that support interface encoding.TextUnmarshaler
package flagsfiller
import (
"encoding"
"flag"
"fmt"
"reflect"
"strings"
)
// RegisterTextUnmarshaler use is optional, since flagsfiller will automatically register the types implement encoding.TextUnmarshaler it encounters
func RegisterTextUnmarshaler(in any) {
base := textUnmarshalerType{}
extendedTypes[getTypeName(reflect.TypeOf(in).Elem())] = base.process
}
type textUnmarshalerType struct {
val encoding.TextUnmarshaler
}
// String implements flag.Value interface
func (tv *textUnmarshalerType) String() string {
if tv.val == nil {
return fmt.Sprint(nil)
}
return fmt.Sprint(tv.val)
}
// Set implements flag.Value interface
func (tv *textUnmarshalerType) Set(s string) error {
return tv.val.UnmarshalText([]byte(s))
}
func (tv *textUnmarshalerType) process(tag reflect.StructTag, fieldRef interface{},
hasDefaultTag bool, tagDefault string,
flagSet *flag.FlagSet, renamed string,
usage string, aliases string) error {
v, ok := fieldRef.(encoding.TextUnmarshaler)
if !ok {
return fmt.Errorf("can't cast %v into encoding.TextUnmarshaler", fieldRef)
}
newval := textUnmarshalerType{
val: v,
}
if hasDefaultTag {
err := newval.Set(tagDefault)
if err != nil {
return fmt.Errorf("failed to parse default value into %v: %w", reflect.TypeOf(fieldRef), err)
}
}
flagSet.Var(&newval, renamed, usage)
if aliases != "" {
for _, alias := range strings.Split(aliases, ",") {
flagSet.Var(&newval, alias, usage)
}
}
return nil
}