-
Notifications
You must be signed in to change notification settings - Fork 0
/
parameter.go
65 lines (56 loc) · 1.57 KB
/
parameter.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
package klash
import (
"reflect"
"strings"
)
// A Parameter is a convenient representation of an expected parameter.
// Since parameters can have aliases (e.g -v and --version), a Parameter
// can store multiple (expected to be around 2) names.
// The Value field is the reflection representation of the
// value of the parameters structure field.
type Parameter struct {
Name string
Alias string
Value reflect.Value
Help string
}
// A capacity of 2 seems to be a good guess for the number of aliases.
func NewParameter(name string, value reflect.Value) *Parameter {
parameter := Parameter{
Name: name,
Value: value,
}
return ¶meter
}
// List through all Tag-related (i.e starting with Tag) method of the Parameter type
// and execute them.
func (p *Parameter) DiscoverProperties(tag reflect.StructTag) error {
if len(tag) > 0 {
paramtype := reflect.TypeOf((*Parameter)(nil))
prefix := "Tag"
paramvalue := reflect.ValueOf(p)
for idx := 0; idx < paramtype.NumMethod(); idx++ {
method := paramtype.Method(idx)
if !strings.HasPrefix(method.Name, prefix) {
continue
}
tagname := "klash-" + strings.ToLower(method.Name[len(prefix):])
if tagval := tag.Get(tagname); tagval != "" {
methodValue := paramvalue.MethodByName(method.Name)
err := methodValue.Call([]reflect.Value{reflect.ValueOf(tagval)})[0].Interface()
if err != nil {
return (err).(error)
}
}
}
}
return nil
}
func (p *Parameter) TagHelp(tag string) error {
p.Help = tag
return nil
}
func (p *Parameter) TagAlias(tag string) error {
p.Alias = tag
return nil
}