-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtag.go
89 lines (74 loc) · 2.05 KB
/
tag.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
package opt
import (
"reflect"
"regexp"
"strings"
)
var (
shortRgx = regexp.MustCompile(`^(\?|\[\]|[A-Za-z]{1})$`)
longRgx = regexp.MustCompile(`^[a-z]{1}[a-z\-1-9]{1,}$`)
)
// The tagSample is struct of the fields of the tag for env's package.
// Tag example: "env:[kye,[value,[sep]]]" where:
//
// key key name in the environment;
// value default value for this key;
// sep list separator (default ":").
type tagSample struct {
Short string
Long string
Value string
Help string
}
type fieldSample struct {
TagSample *tagSample
Item *reflect.Value
}
// The isValid returns true if key name is valid.
func (args tagSample) IsValid() bool {
return (len(args.Short) != 0 && shortRgx.Match([]byte(args.Short))) ||
(len(args.Long) != 0 && longRgx.Match([]byte(args.Long)))
}
// The isIgnored returns true if key name is "-" or incorrect.
func (args tagSample) IsIgnored() bool {
return !args.IsValid() || args.Short == "-"
}
// The getTagValues returns field valueas as array: [flag, cmd, value, help].
func getTagValues(tag string) (r [4]string) {
var chunks = splitN(tag, ",", 4)
for i, c := range chunks {
// Save the last piece without changed.
if i == len(r)-1 {
if v := strings.Join(chunks[i:], ","); v != "" {
r[i] = v
}
break
}
r[i] = c
}
return
}
// The getTagArgs returns tagSample object for tag.
// If key isn't sets in the tag, it will be assigned from the second argument.
//
// Examples
//
// getTagArgs("a,b,c,d", "default") // [a b c d]
// getTagArgs(",b,c,d", "default") // [ b c d]
// getTagArgs("a", "default") // [a]
// getTagArgs(",,c,d", "default") // [ defaulr c d]
func getTagSample(tag, cmd string) *tagSample {
var args, v = &tagSample{}, getTagValues(tag)
// Short.
args.Short = strings.Trim(v[0], " ")
// Long.
args.Long = strings.Trim(v[1], " ")
if len(args.Short) == 0 && len(args.Long) == 0 {
args.Long = cmd
}
// Value.
args.Value = strings.TrimRight(strings.TrimLeft(v[2], "({[\"'`"), ")}]\"'`")
// Help.
args.Help = strings.Trim(v[3], " ")
return args
}