forked from yudai/gotty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flags.go
101 lines (88 loc) · 2.06 KB
/
flags.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
package main
import (
"errors"
"reflect"
"strings"
"github.com/codegangsta/cli"
"github.com/fatih/structs"
"github.com/yudai/gotty/app"
)
type flag struct {
name string
shortName string
description string
}
func generateFlags(flags []flag, hint map[string]string) ([]cli.Flag, error) {
o := structs.New(app.DefaultOptions)
results := make([]cli.Flag, len(flags))
for i, flag := range flags {
fieldName := fieldName(flag.name, hint)
field, ok := o.FieldOk(fieldName)
if !ok {
return nil, errors.New("No such field: " + fieldName)
}
flagName := flag.name
if flag.shortName != "" {
flagName += ", " + flag.shortName
}
envName := "GOTTY_" + strings.ToUpper(strings.Join(strings.Split(flag.name, "-"), "_"))
switch field.Kind() {
case reflect.String:
results[i] = cli.StringFlag{
Name: flagName,
Value: field.Value().(string),
Usage: flag.description,
EnvVar: envName,
}
case reflect.Bool:
results[i] = cli.BoolFlag{
Name: flagName,
Usage: flag.description,
EnvVar: envName,
}
case reflect.Int:
results[i] = cli.IntFlag{
Name: flagName,
Value: field.Value().(int),
Usage: flag.description,
EnvVar: envName,
}
default:
return nil, errors.New("Unsupported type: " + fieldName)
}
}
return results, nil
}
func applyFlags(
options *app.Options,
flags []flag,
mappingHint map[string]string,
c *cli.Context,
) {
o := structs.New(options)
for _, flag := range flags {
if c.IsSet(flag.name) {
field := o.Field(fieldName(flag.name, mappingHint))
var val interface{}
switch field.Kind() {
case reflect.String:
val = c.String(flag.name)
case reflect.Bool:
val = c.Bool(flag.name)
case reflect.Int:
val = c.Int(flag.name)
}
field.Set(val)
}
}
}
func fieldName(name string, hint map[string]string) string {
if fieldName, ok := hint[name]; ok {
return fieldName
}
nameParts := strings.Split(name, "-")
for i, part := range nameParts {
nameParts[i] = strings.ToUpper(part[0:1]) + part[1:]
}
return strings.Join(nameParts, "")
}