-
Notifications
You must be signed in to change notification settings - Fork 3
/
tag.go
116 lines (102 loc) · 2.16 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
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
package structflags
import (
"fmt"
"html"
"log"
"reflect"
"strings"
"github.com/urfave/cli/v2"
)
type ParsedTag struct {
Name string
Usage string
Aliases []string
Opts map[string]struct{}
}
func Parse(tag reflect.StructTag, parent *ParsedTag) *ParsedTag {
tagstr, ok := tag.Lookup("flags")
if !ok {
return nil
}
parsed := &ParsedTag{}
ss := strings.Split(tagstr, ",")
if len(ss) > 0 {
parsed.Name = ss[0]
if parent != nil && parent.Name != "" {
parsed.Name = fmt.Sprintf("%s.%s", parent.Name, parsed.Name)
}
}
if len(ss) > 1 {
parsed.Usage = html.UnescapeString(ss[1])
}
if len(ss) > 2 {
aliases := strings.Split(ss[2], ";")
for _, e := range aliases {
if e == "" {
continue
}
parsed.Aliases = append(parsed.Aliases, e)
}
}
if len(ss) > 3 {
parsed.Opts = make(map[string]struct{})
for _, e := range ss[3:] {
parsed.Opts[e] = struct{}{}
}
}
return parsed
}
func (parsed *ParsedTag) ToCliFlag(k reflect.Kind) cli.Flag {
_, required := parsed.Opts["required"]
_, hidden := parsed.Opts["hidden"]
switch k {
case reflect.Bool:
return &cli.BoolFlag{
Name: parsed.Name,
Usage: parsed.Usage,
Aliases: parsed.Aliases,
Required: required,
Hidden: hidden,
}
case reflect.Int:
return &cli.IntFlag{
Name: parsed.Name,
Usage: parsed.Usage,
Aliases: parsed.Aliases,
Required: required,
Hidden: hidden,
}
case reflect.String, reflect.Interface:
if _, ok := parsed.Opts["path"]; ok {
return &cli.PathFlag{
Name: parsed.Name,
Usage: parsed.Usage,
Aliases: parsed.Aliases,
Required: required,
Hidden: hidden,
}
} else {
return &cli.StringFlag{
Name: parsed.Name,
Usage: parsed.Usage,
Aliases: parsed.Aliases,
Required: required,
Hidden: hidden,
}
}
default:
log.Panicf("ToCliFlag: unknown kind %v", k)
return nil
}
}
func (parsed *ParsedTag) ToDurationFlag() cli.Flag {
_, required := parsed.Opts["required"]
_, hidden := parsed.Opts["hidden"]
return &cli.DurationFlag{
Name: parsed.Name,
Usage: parsed.Usage,
Aliases: parsed.Aliases,
Required: required,
Hidden: hidden,
}
}