Debian Codegraph @

convert.go

raw symbols SCIP
1 // Copyright 2012 Jesse van den Kieboom. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package flags
6
7 import (
8 "fmt"
9 "reflect"
10 "strconv"
11 "strings"
12 "time"
13 )
14
15 // Marshaler is the interface implemented by types that can marshal themselves
16 // to a string representation of the flag.
17 type Marshaler interface {
18 MarshalFlag() (string, error)
19 }
20
21 // Unmarshaler is the interface implemented by types that can unmarshal a flag
22 // argument to themselves. The provided value is directly passed from the
23 // command line.
24 type Unmarshaler interface {
25 UnmarshalFlag(value string) error
26 }
27
28 func getBase(options multiTag, base int) (int, error) {
29 sbase := options.Get("base")
30
31 var err error
32 var ivbase int64
33
34 if sbase != "" {
35 ivbase, err = strconv.ParseInt(sbase, 10, 32)
36 base = int(ivbase)
37 }
38
39 return base, err
40 }
41
42 func convertMarshal(val reflect.Value) (bool, string, error) {
43 // Check first for the Marshaler interface
44 if val.Type().NumMethod() > 0 && val.CanInterface() {
45 if marshaler, ok := val.Interface().(Marshaler); ok {
46 ret, err := marshaler.MarshalFlag()
47 return true, ret, err
48 }
49 }
50
51 return false, "", nil
52 }
53
54 func convertToString(val reflect.Value, options multiTag) (string, error) {
55 if ok, ret, err := convertMarshal(val); ok {
56 return ret, err
57 }
58
59 tp := val.Type()
60
61 // Support for time.Duration
62 if tp == reflect.TypeOf((*time.Duration)(nil)).Elem() {
63 stringer := val.Interface().(fmt.Stringer)
64 return stringer.String(), nil
65 }
66
67 switch tp.Kind() {
68 case reflect.String:
69 return val.String(), nil
70 case reflect.Bool:
71 if val.Bool() {
72 return "true", nil
73 } else {
74 return "false", nil
75 }
76 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
77 base, _ := getBase(options, 10)
78 return strconv.FormatInt(val.Int(), base), nil
79 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
80 base, _ := getBase(options, 10)
81 return strconv.FormatUint(val.Uint(), base), nil
82 case reflect.Float32, reflect.Float64:
83 return strconv.FormatFloat(val.Float(), 'g', -1, tp.Bits()), nil
84 case reflect.Slice:
85 if val.Len() == 0 {
86 return "", nil
87 }
88
89 ret := "["
90
91 for i := 0; i < val.Len(); i++ {
92 if i != 0 {
93 ret += ", "
94 }
95
96 item, err := convertToString(val.Index(i), options)
97
98 if err != nil {
99 return "", err
100 }
101
102 ret += item
103 }
104
105 return ret + "]", nil
106 case reflect.Map:
107 ret := "{"
108
109 for i, key := range val.MapKeys() {
110 if i != 0 {
111 ret += ", "
112 }
113
114 item, err := convertToString(val.MapIndex(key), options)
115
116 if err != nil {
117 return "", err
118 }
119
120 ret += item
121 }
122
123 return ret + "}", nil
124 case reflect.Ptr:
125 return convertToString(reflect.Indirect(val), options)
126 case reflect.Interface:
127 if !val.IsNil() {
128 return convertToString(val.Elem(), options)
129 }
130 }
131
132 return "", nil
133 }
134
135 func convertUnmarshal(val string, retval reflect.Value) (bool, error) {
136 if retval.Type().NumMethod() > 0 && retval.CanInterface() {
137 if unmarshaler, ok := retval.Interface().(Unmarshaler); ok {
138 return true, unmarshaler.UnmarshalFlag(val)
139 }
140 }
141
142 if retval.Type().Kind() != reflect.Ptr && retval.CanAddr() {
143 return convertUnmarshal(val, retval.Addr())
144 }
145
146 if retval.Type().Kind() == reflect.Interface && !retval.IsNil() {
147 return convertUnmarshal(val, retval.Elem())
148 }
149
150 return false, nil
151 }
152
153 func convert(val string, retval reflect.Value, options multiTag) error {
154 if ok, err := convertUnmarshal(val, retval); ok {
155 return err
156 }
157
158 tp := retval.Type()
159
160 // Support for time.Duration
161 if tp == reflect.TypeOf((*time.Duration)(nil)).Elem() {
162 parsed, err := time.ParseDuration(val)
163
164 if err != nil {
165 return err
166 }
167
168 retval.SetInt(int64(parsed))
169 return nil
170 }
171
172 switch tp.Kind() {
173 case reflect.String:
174 retval.SetString(val)
175 case reflect.Bool:
176 if val == "" {
177 retval.SetBool(true)
178 } else {
179 b, err := strconv.ParseBool(val)
180
181 if err != nil {
182 return err
183 }
184
185 retval.SetBool(b)
186 }
187 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
188 base, err := getBase(options, 10)
189
190 if err != nil {
191 return err
192 }
193
194 parsed, err := strconv.ParseInt(val, base, tp.Bits())
195
196 if err != nil {
197 return err
198 }
199
200 retval.SetInt(parsed)
201 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
202 base, err := getBase(options, 10)
203
204 if err != nil {
205 return err
206 }
207
208 parsed, err := strconv.ParseUint(val, base, tp.Bits())
209
210 if err != nil {
211 return err
212 }
213
214 retval.SetUint(parsed)
215 case reflect.Float32, reflect.Float64:
216 parsed, err := strconv.ParseFloat(val, tp.Bits())
217
218 if err != nil {
219 return err
220 }
221
222 retval.SetFloat(parsed)
223 case reflect.Slice:
224 elemtp := tp.Elem()
225
226 elemvalptr := reflect.New(elemtp)
227 elemval := reflect.Indirect(elemvalptr)
228
229 if err := convert(val, elemval, options); err != nil {
230 return err
231 }
232
233 retval.Set(reflect.Append(retval, elemval))
234 case reflect.Map:
235 parts := strings.SplitN(val, ":", 2)
236
237 key := parts[0]
238 var value string
239
240 if len(parts) == 2 {
241 value = parts[1]
242 }
243
244 keytp := tp.Key()
245 keyval := reflect.New(keytp)
246
247 if err := convert(key, keyval, options); err != nil {
248 return err
249 }
250
251 valuetp := tp.Elem()
252 valueval := reflect.New(valuetp)
253
254 if err := convert(value, valueval, options); err != nil {
255 return err
256 }
257
258 if retval.IsNil() {
259 retval.Set(reflect.MakeMap(tp))
260 }
261
262 retval.SetMapIndex(reflect.Indirect(keyval), reflect.Indirect(valueval))
263 case reflect.Ptr:
264 if retval.IsNil() {
265 retval.Set(reflect.New(retval.Type().Elem()))
266 }
267
268 return convert(val, reflect.Indirect(retval), options)
269 case reflect.Interface:
270 if !retval.IsNil() {
271 return convert(val, retval.Elem(), options)
272 }
273 }
274
275 return nil
276 }
277
278 func wrapText(s string, l int, prefix string) string {
279 // Basic text wrapping of s at spaces to fit in l
280 var ret string
281
282 s = strings.TrimSpace(s)
283
284 for len(s) > l {
285 // Try to split on space
286 suffix := ""
287
288 pos := strings.LastIndex(s[:l], " ")
289
290 if pos < 0 {
291 pos = l - 1
292 suffix = "-\n"
293 }
294
295 if len(ret) != 0 {
296 ret += "\n" + prefix
297 }
298
299 ret += strings.TrimSpace(s[:pos]) + suffix
300 s = strings.TrimSpace(s[pos:])
301 }
302
303 if len(s) > 0 {
304 if len(ret) != 0 {
305 ret += "\n" + prefix
306 }
307
308 return ret + s
309 }
310
311 return ret
312 }