-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypes.go
120 lines (96 loc) · 1.79 KB
/
types.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package cli
import (
"encoding"
"errors"
"fmt"
"time"
)
// setters
func tryGetSetter(i interface{}) Setter {
switch v := i.(type) {
case Setter:
return v
case encoding.TextUnmarshaler:
return textSetter{v}
case encoding.BinaryUnmarshaler:
return binarySetter{v}
case *time.Duration:
return durationSetter{v}
case *string:
return stringSetter{v}
case
*bool,
*int, *int8, *int16, *int32, *int64,
*uint, *uint8, *uint16, *uint32, *uint64,
*float32, *float64:
return scanfSetter{v}
default:
return nil
}
}
// string
type stringSetter struct {
v *string
}
func (ss stringSetter) Set(s string) error {
*ss.v = s
return nil
}
// TextUnmarshaler
type textSetter struct {
encoding.TextUnmarshaler
}
func (ts textSetter) Set(s string) error {
return ts.UnmarshalText([]byte(s))
}
// BinaryUnmarshaler
type binarySetter struct {
encoding.BinaryUnmarshaler
}
func (bs binarySetter) Set(s string) error {
return bs.UnmarshalBinary([]byte(s))
}
// Primitives (scanf)
type scanfSetter struct {
v interface{}
}
func (ss scanfSetter) Set(s string) error {
n, err := fmt.Sscanf(s, "%v", ss.v)
if err != nil {
return err
} else if n == 0 {
return errors.New("scanf did not scan any items")
}
return nil
}
// time.Duration
type durationSetter struct {
duration *time.Duration
}
func (ds durationSetter) Set(s string) error {
v, err := time.ParseDuration(s)
if err != nil {
return err
}
*ds.duration = v
return nil
}
// stringers
func tryGetStringer(i interface{}) stringer {
switch v := i.(type) {
case stringer:
return v
default:
return nil
}
}
type staticStringer string
func (ss staticStringer) String() string {
return string(ss)
}
type sprintfStringer struct {
v interface{}
}
func (ss sprintfStringer) String() string {
return fmt.Sprintf("%v", ss.v)
}