forked from caicloud/nirvana
/
flags.go
314 lines (271 loc) · 8.26 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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
Copyright 2017 Caicloud Authors
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 generators
import (
"io"
flagNamer "github.com/caicloud/nirvana/cmd/flag-gen/namer"
"github.com/golang/glog"
"k8s.io/gengo/args"
"k8s.io/gengo/generator"
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
)
// NameSystems returns the name system used by the generators in this package.
func NameSystems() namer.NameSystems {
return namer.NameSystems{
"public": flagNamer.NewPublicNamer(0),
"private": flagNamer.NewPrivateNamer(0),
"raw": namer.NewRawNamer("", nil),
}
}
// DefaultNameSystem returns the default name system for ordering the types to be
// processed by the generators in this package.
func DefaultNameSystem() string {
return "public"
}
// Packages makes the sets package definition.
func Packages(_ *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
boilerplate, err := arguments.LoadGoBoilerplate()
if err != nil {
glog.Fatalf("Failed loading boilerplate: %v", err)
}
return generator.Packages{&generator.DefaultPackage{
PackageName: "cli",
PackagePath: arguments.OutputPackagePath,
HeaderText: append(boilerplate, []byte(
`
// This file was autogenerated by set-gen. Do not edit it manually!
`)...),
GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {
glog.Info("generator func")
generators = []generator.Generator{}
for _, t := range c.Order {
generators = append(generators,
&flagsGenerator{
DefaultGen: generator.DefaultGen{
OptionalName: "flags_generated",
},
outputPackage: arguments.OutputPackagePath,
typeToMatch: t,
imports: generator.NewImportTracker(),
},
&flagsTestGenerator{
DefaultGen: generator.DefaultGen{
OptionalName: "flags_generated_test",
},
outputPackage: arguments.OutputPackagePath,
typeToMatch: t,
imports: generator.NewImportTracker(),
},
)
}
return generators
},
FilterFunc: func(c *generator.Context, t *types.Type) bool {
switch t.Kind {
case types.Builtin, types.Alias:
if t.Name == types.Byte.Name {
return false
}
return true
case types.Slice:
if t.Elem.Name == types.Byte.Name {
return false
}
return true
case types.Struct:
if t.Name.String() == "net.IPNet" {
return true
}
return false
}
return false
},
}}
}
var _ generator.Generator = &flagsGenerator{}
type flagsGenerator struct {
generator.DefaultGen
outputPackage string
imports namer.ImportTracker
typeToMatch *types.Type
}
func (g *flagsGenerator) Filter(c *generator.Context, t *types.Type) bool {
return t == g.typeToMatch
}
func (g *flagsGenerator) Namers(c *generator.Context) namer.NameSystems {
return namer.NameSystems{
"raw": namer.NewRawNamer(g.outputPackage, g.imports),
}
}
func (g *flagsGenerator) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
imports = append(imports, "github.com/spf13/pflag")
imports = append(imports, "github.com/spf13/cast")
return
}
func (g *flagsGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "$", "$")
glog.V(5).Infof("processing type %v", t)
m := map[string]interface{}{
"type": t,
}
sw.Do(flagCode, m)
return sw.Error()
}
var flagCode = `
var _ Flag = $.type|public$Flag{}
// $.type|public$Flag is a flag of type $.type|raw$
type $.type|public$Flag struct {
// Name as it appears on command line
Name string
// one-letter abbreviated flag
Shorthand string
// help message
Usage string
// specify whether the flag is persistent
Persistent bool
// used by cobra.Command bash autocomple code
Annotations map[string][]string
// If this flag is deprecated, this string is the new or now thing to use
Deprecated string
// If the shorthand of this flag is deprecated, this string is the new or now thing to use
ShorthandDeprecated string
// used by cobra.Command to allow flags to be hidden from help/usage text
Hidden bool
// bind the flag to env key, you can use AutomaticEnv to bind all flags to env automatically
// if EnvKey is set, it will override the automatic generated env key
EnvKey string
// the default value
DefValue $.type|raw$
// points to a variable in which to store the value of the flag
Destination *$.type|raw$
}
// IsPersistent specify whether the flag is persistent
func (f $.type|public$Flag) IsPersistent() bool {
return f.Persistent
}
// GetName returns the flag's name
func (f $.type|public$Flag) GetName() string {
return f.Name
}
// ApplyTo adds the flag to given FlagSet
func (f $.type|public$Flag) ApplyTo(fs *pflag.FlagSet) error {
if f.Destination == nil {
f.Destination = new($.type|raw$)
}
defValue := cast.To$.type|public$(getEnv(f.Name, f.EnvKey, f.DefValue))
fs.$.type|public$VarP(f.Destination, f.Name, f.Shorthand, defValue, f.Usage)
var err error
if f.Deprecated != "" {
err = fs.MarkDeprecated(f.Name, f.Deprecated)
if err != nil {
return err
}
}
if f.ShorthandDeprecated != "" {
err = fs.MarkShorthandDeprecated(f.Name, f.ShorthandDeprecated)
if err != nil {
return err
}
}
if f.Hidden {
err = fs.MarkHidden(f.Name)
if err != nil {
return err
}
}
for key, values := range f.Annotations {
err = fs.SetAnnotation(f.Name, key, values)
if err != nil {
return err
}
}
return Viper.BindPFlag(f.Name, fs.Lookup(f.Name))
}
`
type flagsTestGenerator struct {
generator.DefaultGen
outputPackage string
imports namer.ImportTracker
typeToMatch *types.Type
}
func (g *flagsTestGenerator) Filter(c *generator.Context, t *types.Type) bool {
return t == g.typeToMatch
}
func (g *flagsTestGenerator) Namers(c *generator.Context) namer.NameSystems {
return namer.NameSystems{
"raw": namer.NewRawNamer(g.outputPackage, g.imports),
}
}
func (g *flagsTestGenerator) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
imports = append(imports, "github.com/spf13/cast")
imports = append(imports, "github.com/spf13/pflag")
imports = append(imports, "github.com/spf13/viper")
imports = append(imports, "testing")
imports = append(imports, "reflect")
return
}
func (g *flagsTestGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "$", "$")
glog.V(5).Infof("processing type %v", t)
m := map[string]interface{}{
"type": t,
}
sw.Do(flagTestCode, m)
return sw.Error()
}
var flagTestCode = `
func Test$.type|public$Flag(t *testing.T) {
testcase := getTestCase("$.type|public$")
dest := new($.type|raw$)
f := $.type|public$Flag{
Name: "test",
Shorthand: "t",
Usage: "help",
Persistent: true,
Annotations: map[string][]string{"key": []string{"value"}},
Deprecated: "for test",
ShorthandDeprecated: "for test",
Hidden: true,
EnvKey: "TEST",
DefValue: *dest,
Destination: dest,
}
f.IsPersistent()
f.GetName()
fs := pflag.NewFlagSet("dev", pflag.ContinueOnError)
f.ApplyTo(fs)
// test flag
fs.Parse([]string{"-t=" + testcase.flag})
want, err := cast.To$.type|public$E(testcase.want)
if err != nil {
t.Fatalf("Test$.type|public$Flag(): can't convert %v to $.type|raw$, %v", testcase.want, err)
}
if !reflect.DeepEqual(*dest, want) {
t.Fatalf("Test$.type|public$Flag() = %v, want %v", *dest, want)
}
// test viper
v := Viper.Get(f.Name)
got, err := cast.To$.type|public$E(v)
if err != nil {
t.Fatalf("Test$.type|public$Flag(): can't convert %v to $.type|raw$, %v", v, err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("Test$.type|public$Flag().Viper = %v, want %v", got, want)
}
// reset viper
Viper = viper.New()
}
`