-
Notifications
You must be signed in to change notification settings - Fork 1
/
source_flag.go
230 lines (205 loc) · 5.66 KB
/
source_flag.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
// Copyright 2019 xgfone
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gconf
import (
"encoding/json"
"flag"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/xgfone/go-defaults"
)
// PrintFlagUsage prints the flag usage instead of the default.
func PrintFlagUsage(flagSet *flag.FlagSet) {
flagSet.VisitAll(func(f *flag.Flag) {
// Two spaces before -; see next two comments.
prefix := " -"
if len(f.Name) > 1 {
prefix += "-"
}
s := fmt.Sprintf(prefix+"%s", f.Name)
name, usage := flag.UnquoteUsage(f)
if len(name) > 0 {
s += " " + name
} else {
vf := reflect.ValueOf(f.Value)
if vf.Kind() == reflect.Ptr {
vf = vf.Elem()
}
if vf.Kind() == reflect.Bool {
s += " bool"
}
}
// Boolean flags of one ASCII letter are so common we
// treat them specially, putting their usage on the same line.
if len(s) <= 4 { // space, space, '-', 'x'.
s += "\t"
} else {
// Four spaces before the tab triggers good alignment
// for both 4- and 8-space tab stops.
s += "\n \t"
}
s += strings.Replace(usage, "\n", "\n \t", -1)
s += fmt.Sprintf(" (default: %q)", f.DefValue)
fmt.Fprint(os.Stderr, s, "\n")
})
}
// AddOptFlag adds the option to the flagSet, which is flag.CommandLine
// by default.
//
// Notice: for the slice option, it maybe occur many times, and they are
// combined with the comma as the string representation of slice. For example,
//
// $APP --slice-opt v1 --slice-opt v2 --slice-opt v3
//
// They are equivalent.
func AddOptFlag(c *Config, flagSet ...*flag.FlagSet) {
_ = addAndParseOptFlag(false, c, flagSet...)
}
// AddAndParseOptFlag is the same as AddOptFlag, but parses the CLI arguments.
//
// Notice: if there is the version flag and it is true, it will print the version
// and exit.
func AddAndParseOptFlag(c *Config, flagSet ...*flag.FlagSet) error {
return addAndParseOptFlag(true, c, flagSet...)
}
func addAndParseOptFlag(parse bool, c *Config, flagSet ...*flag.FlagSet) error {
flagset := flag.CommandLine
if len(flagSet) > 0 && flagSet[0] != nil {
flagset = flagSet[0]
}
var vName, value string
if v := c.Version; v.Name != "" && v.Default != nil {
flagset.Bool(v.Name, false, v.Help)
vName = v.Name
value = v.Default.(string)
}
flagset.Usage = func() { PrintFlagUsage(flagset) }
for _, opt := range c.GetAllOpts() {
if !opt.IsCli {
continue
}
name := strings.Replace(opt.Name, "_", "-", -1)
switch v := opt.Default.(type) {
case nil:
flagset.String(name, "", opt.Help)
case string:
flagset.String(name, v, opt.Help)
case bool:
flagset.Bool(name, v, opt.Help)
case int, int8, int16, int32, int64:
flagset.Int64(name, reflect.ValueOf(v).Int(), opt.Help)
case uint, uint8, uint16, uint32, uint64:
flagset.Uint64(name, reflect.ValueOf(v).Uint(), opt.Help)
case float32, float64:
flagset.Float64(name, reflect.ValueOf(v).Float(), opt.Help)
case time.Duration:
flagset.Duration(name, v, opt.Help)
default:
switch vf := reflect.ValueOf(opt.Default); vf.Kind() {
case reflect.Slice, reflect.Array:
sv := &flagSliceValue{values: make([]string, vf.Len())}
for i, _len := 0, vf.Len(); i < _len; i++ {
sv.values[i] = fmt.Sprint(vf.Index(i).Interface())
}
flagset.Var(sv, name, opt.Help)
default:
flagset.String(name, fmt.Sprintf("%v", v), opt.Help)
}
}
}
if parse {
if err := flagset.Parse(os.Args[1:]); err != nil {
return err
}
if vName != "" {
if flag := flagset.Lookup(vName); flag != nil {
if yes, _ := strconv.ParseBool(flag.Value.String()); yes {
fmt.Println(value)
defaults.Exit(0)
}
}
}
}
return nil
}
type flagSliceValue struct {
values []string
isset bool
}
func (v *flagSliceValue) String() string {
if v == nil {
return ""
}
return strings.Join(v.values, ",")
}
func (v *flagSliceValue) Set(s string) error {
if v != nil {
if !v.isset {
v.isset = true
v.values = []string{s}
} else {
v.values = append(v.values, s)
}
}
return nil
}
// NewFlagSource returns a new source based on flag.FlagSet,
// which is flag.CommandLine by default.
func NewFlagSource(flagSet ...*flag.FlagSet) Source {
flagset := flag.CommandLine
if len(flagSet) > 0 && flagSet[0] != nil {
flagset = flagSet[0]
}
return flagSource{flagSet: flagset}
}
type flagSource struct {
flagSet *flag.FlagSet
}
func (f flagSource) String() string { return "flag" }
func (f flagSource) Watch(<-chan struct{}, func(DataSet, error) bool) {}
func (f flagSource) Read() (DataSet, error) {
if !f.flagSet.Parsed() {
if err := f.flagSet.Parse(os.Args[1:]); err != nil {
return DataSet{Source: f.String(), Format: "json"}, err
}
}
vs := make(map[string]interface{}, 32)
f.flagSet.Visit(func(f *flag.Flag) {
var value interface{}
switch v := f.Value.(type) {
case *flagSliceValue:
value = v.values
default:
value = v.String()
}
vs[strings.Replace(f.Name, "-", "_", -1)] = value
})
data, err := json.Marshal(vs)
if err != nil {
return DataSet{Source: f.String(), Format: "json"}, err
}
ds := DataSet{
Args: f.flagSet.Args(),
Data: data,
Format: "json",
Source: "flag",
Timestamp: time.Now(),
}
ds.Checksum = "md5:" + ds.Md5()
return ds, nil
}