-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.go
373 lines (340 loc) · 8.61 KB
/
array.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package flagx
import (
"flag"
"fmt"
"strconv"
"strings"
"time"
)
// NewArrayString returns new ArrayString with the given name and description.
func NewArrayString(name, description string) *ArrayString {
description += "\nSupports an `array` of values separated by comma or specified via multiple flags." + envHelp(name)
var a ArrayString
flag.Var(&a, name, description)
return &a
}
// NewArrayDuration returns new ArrayDuration with the given name and description.
func NewArrayDuration(name, description string) *ArrayDuration {
description += "\nSupports `array` of values separated by comma or specified via multiple flags." + envHelp(name)
var a ArrayDuration
flag.Var(&a, name, description)
return &a
}
// NewArrayBool returns new ArrayBool with the given name and description.
func NewArrayBool(name, description string) *ArrayBool {
description += "\nSupports `array` of values separated by comma or specified via multiple flags." + envHelp(name)
var a ArrayBool
flag.Var(&a, name, description)
return &a
}
// NewArrayInt returns new ArrayInt with the given name and description.
func NewArrayInt(name, description string) *ArrayInt {
description += "\nSupports `array` of values separated by comma or specified via multiple flags." + envHelp(name)
var a ArrayInt
flag.Var(&a, name, description)
return &a
}
// NewArrayBytes returns new ArrayBytes with the given name and description.
func NewArrayBytes(name, description string) *ArrayBytes {
description += "\nSupports the following optional suffixes for size values: KB, MB, GB, TB, KiB, MiB, GiB, TiB."
description += "\nSupports `array` of values separated by comma or specified via multiple flags." + envHelp(name)
var a ArrayBytes
flag.Var(&a, name, description)
return &a
}
// ArrayString is a flag that holds an array of strings.
//
// It may be set either by specifying multiple flags with the given name
// passed to NewArray or by joining flag values by comma.
//
// The following example sets equivalent flag array with two items (value1, value2):
//
// -foo=value1 -foo=value2
// -foo=value1,value2
//
// Each flag value may contain commas inside single quotes, double quotes, [], () or {} braces.
// For example, -foo=[a,b,c] defines a single command-line flag with `[a,b,c]` value.
//
// Flag values may be quoted. For instance, the following arg creates an array of ("a", "b,c") items:
//
// -foo='a,"b,c"'
type ArrayString []string
// String implements flag.Value interface
func (a *ArrayString) String() string {
aEscaped := make([]string, len(*a))
for i, v := range *a {
if strings.ContainsAny(v, `,'"{[(`+"\n") {
v = fmt.Sprintf("%q", v)
}
aEscaped[i] = v
}
return strings.Join(aEscaped, ",")
}
// Set implements flag.Value interface
func (a *ArrayString) Set(value string) error {
values := parseArrayValues(value)
*a = append(*a, values...)
return nil
}
func parseArrayValues(s string) []string {
if len(s) == 0 {
return nil
}
var values []string
for {
v, tail := getNextArrayValue(s)
values = append(values, v)
if len(tail) == 0 {
return values
}
s = tail
if s[0] == ',' {
s = s[1:]
}
}
}
var closeQuotes = map[byte]byte{
'"': '"',
'\'': '\'',
'[': ']',
'{': '}',
'(': ')',
}
func getNextArrayValue(s string) (string, string) {
v, tail := getNextArrayValueMaybeQuoted(s)
if strings.HasPrefix(v, `"`) && strings.HasSuffix(v, `"`) {
vUnquoted, err := strconv.Unquote(v)
if err == nil {
return vUnquoted, tail
}
v = v[1 : len(v)-1]
v = strings.ReplaceAll(v, `\"`, `"`)
v = strings.ReplaceAll(v, `\\`, `\`)
return v, tail
}
if strings.HasPrefix(v, `'`) && strings.HasSuffix(v, `'`) {
v = v[1 : len(v)-1]
v = strings.ReplaceAll(v, `\'`, "'")
v = strings.ReplaceAll(v, `\\`, `\`)
return v, tail
}
return v, tail
}
func getNextArrayValueMaybeQuoted(s string) (string, string) {
idx := 0
for {
n := strings.IndexAny(s[idx:], `,"'[{(`)
if n < 0 {
// The last item
return s, ""
}
idx += n
ch := s[idx]
if ch == ',' {
// The next item
return s[:idx], s[idx:]
}
idx++
m := indexCloseQuote(s[idx:], closeQuotes[ch])
idx += m
}
}
func indexCloseQuote(s string, closeQuote byte) int {
if closeQuote == '"' || closeQuote == '\'' {
idx := 0
for {
n := strings.IndexByte(s[idx:], closeQuote)
if n < 0 {
return 0
}
idx += n
if n := getTrailingBackslashesCount(s[:idx]); n%2 == 1 {
// The quote is escaped with backslash. Skip it
idx++
continue
}
return idx + 1
}
}
idx := 0
for {
n := strings.IndexAny(s[idx:], `"'[{()}]`)
if n < 0 {
return 0
}
idx += n
ch := s[idx]
if ch == closeQuote {
return idx + 1
}
idx++
m := indexCloseQuote(s[idx:], closeQuotes[ch])
if m == 0 {
return 0
}
idx += m
}
}
func getTrailingBackslashesCount(s string) int {
n := len(s)
for n > 0 && s[n-1] == '\\' {
n--
}
return len(s) - n
}
// GetOptionalArg returns optional arg under the given argIdx.
func (a *ArrayString) GetOptionalArg(argIdx int) string {
x := *a
if argIdx >= len(x) {
if len(x) == 1 {
return x[0]
}
return ""
}
return x[argIdx]
}
// ArrayBool is a flag that holds an array of booleans values.
//
// Has the same api as ArrayString.
type ArrayBool []bool
// IsBoolFlag implements flag.IsBoolFlag interface
func (a *ArrayBool) IsBoolFlag() bool { return true }
// String implements flag.Value interface
func (a *ArrayBool) String() string {
formattedBools := make([]string, len(*a))
for i, v := range *a {
formattedBools[i] = strconv.FormatBool(v)
}
return strings.Join(formattedBools, ",")
}
// Set implements flag.Value interface
func (a *ArrayBool) Set(value string) error {
values := parseArrayValues(value)
for _, v := range values {
b, err := strconv.ParseBool(v)
if err != nil {
return err
}
*a = append(*a, b)
}
return nil
}
// GetOptionalArg returns optional arg under the given argIdx.
func (a *ArrayBool) GetOptionalArg(argIdx int) bool {
x := *a
if argIdx >= len(x) {
if len(x) == 1 {
return x[0]
}
return false
}
return x[argIdx]
}
// ArrayDuration is a flag that holds an array of time.Duration values.
//
// Has the same api as ArrayString.
type ArrayDuration []time.Duration
// String implements flag.Value interface
func (a *ArrayDuration) String() string {
formattedBools := make([]string, len(*a))
for i, v := range *a {
formattedBools[i] = v.String()
}
return strings.Join(formattedBools, ",")
}
// Set implements flag.Value interface
func (a *ArrayDuration) Set(value string) error {
values := parseArrayValues(value)
for _, v := range values {
b, err := time.ParseDuration(v)
if err != nil {
return err
}
*a = append(*a, b)
}
return nil
}
// GetOptionalArgOrDefault returns optional arg under the given argIdx,
// or default value, if argIdx not found.
func (a *ArrayDuration) GetOptionalArgOrDefault(argIdx int, defaultValue time.Duration) time.Duration {
x := *a
if argIdx >= len(x) {
if len(x) == 1 {
return x[0]
}
return defaultValue
}
return x[argIdx]
}
// ArrayInt is flag that holds an array of ints.
//
// Has the same api as ArrayString.
type ArrayInt []int
// String implements flag.Value interface
func (a *ArrayInt) String() string {
x := *a
formattedInts := make([]string, len(x))
for i, v := range x {
formattedInts[i] = strconv.Itoa(v)
}
return strings.Join(formattedInts, ",")
}
// Set implements flag.Value interface
func (a *ArrayInt) Set(value string) error {
values := parseArrayValues(value)
for _, v := range values {
n, err := strconv.Atoi(v)
if err != nil {
return err
}
*a = append(*a, n)
}
return nil
}
// GetOptionalArgOrDefault returns optional arg under the given argIdx.
func (a *ArrayInt) GetOptionalArgOrDefault(argIdx, defaultValue int) int {
x := *a
if argIdx < len(x) {
return x[argIdx]
}
if len(x) == 1 {
return x[0]
}
return defaultValue
}
// ArrayBytes is flag that holds an array of Bytes.
//
// Has the same api as ArrayString.
type ArrayBytes []*Bytes
// String implements flag.Value interface
func (a *ArrayBytes) String() string {
x := *a
formattedBytes := make([]string, len(x))
for i, v := range x {
formattedBytes[i] = v.String()
}
return strings.Join(formattedBytes, ",")
}
// Set implemented flag.Value interface
func (a *ArrayBytes) Set(value string) error {
values := parseArrayValues(value)
for _, v := range values {
var b Bytes
if err := b.Set(v); err != nil {
return err
}
*a = append(*a, &b)
}
return nil
}
// GetOptionalArgOrDefault returns optional arg under the given argIdx.
func (a *ArrayBytes) GetOptionalArgOrDefault(argIdx int, defaultValue int64) int64 {
x := *a
if argIdx < len(x) {
return x[argIdx].N
}
if len(x) == 1 {
return x[0].N
}
return defaultValue
}