-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathmain.go
331 lines (310 loc) · 9.24 KB
/
main.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/abice/go-enum/generator"
"github.com/labstack/gommon/color"
"github.com/urfave/cli/v2"
)
var (
version string
commit string
date string
builtBy string
)
type rootT struct {
FileNames cli.StringSlice
NoPrefix bool
Lowercase bool
NoCase bool
Marshal bool
SQL bool
SQLInt bool
Flag bool
Prefix string
Names bool
Values bool
LeaveSnakeCase bool
SQLNullStr bool
SQLNullInt bool
Ptr bool
TemplateFileNames cli.StringSlice
Aliases cli.StringSlice
BuildTags cli.StringSlice
MustParse bool
ForceLower bool
ForceUpper bool
NoComments bool
OutputSuffix string
}
func main() {
var argv rootT
clr := color.New()
out := func(format string, args ...interface{}) {
_, _ = fmt.Fprintf(clr.Output(), format, args...)
}
app := &cli.App{
Name: "go-enum",
Usage: "An enum generator for go",
HideHelpCommand: true,
Version: version,
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "file",
Aliases: []string{"f"},
EnvVars: []string{"GOFILE"},
Usage: "The file(s) to generate enums. Use more than one flag for more files.",
Required: true,
Destination: &argv.FileNames,
},
&cli.BoolFlag{
Name: "noprefix",
Usage: "Prevents the constants generated from having the Enum as a prefix.",
Destination: &argv.NoPrefix,
},
&cli.BoolFlag{
Name: "lower",
Usage: "Adds lowercase variants of the enum strings for lookup.",
Destination: &argv.Lowercase,
},
&cli.BoolFlag{
Name: "nocase",
Usage: "Adds case insensitive parsing to the enumeration (forces lower flag).",
Destination: &argv.NoCase,
},
&cli.BoolFlag{
Name: "marshal",
Usage: "Adds text (and inherently json) marshalling functions.",
Destination: &argv.Marshal,
},
&cli.BoolFlag{
Name: "sql",
Usage: "Adds SQL database scan and value functions.",
Destination: &argv.SQL,
},
&cli.BoolFlag{
Name: "sqlint",
Usage: "Tells the generator that a string typed enum should be stored in sql as an integer value.",
Destination: &argv.SQLInt,
},
&cli.BoolFlag{
Name: "flag",
Usage: "Adds golang flag functions.",
Destination: &argv.Flag,
},
&cli.StringFlag{
Name: "prefix",
Usage: "Adds a prefix with a user one. If you would like to replace the prefix, then combine this option with --noprefix.",
Destination: &argv.Prefix,
},
&cli.BoolFlag{
Name: "names",
Usage: "Generates a 'Names() []string' function, and adds the possible enum values in the error response during parsing",
Destination: &argv.Names,
},
&cli.BoolFlag{
Name: "values",
Usage: "Generates a 'Values() []{{ENUM}}' function.",
Destination: &argv.Values,
},
&cli.BoolFlag{
Name: "nocamel",
Usage: "Removes the snake_case to CamelCase name changing",
Destination: &argv.LeaveSnakeCase,
},
&cli.BoolFlag{
Name: "ptr",
Usage: "Adds a pointer method to get a pointer from const values",
Destination: &argv.Ptr,
},
&cli.BoolFlag{
Name: "sqlnullint",
Usage: "Adds a Null{{ENUM}} type for marshalling a nullable int value to sql",
Destination: &argv.SQLNullInt,
},
&cli.BoolFlag{
Name: "sqlnullstr",
Usage: "Adds a Null{{ENUM}} type for marshalling a nullable string value to sql. If sqlnullint is specified too, it will be Null{{ENUM}}Str",
Destination: &argv.SQLNullStr,
},
&cli.StringSliceFlag{
Name: "template",
Aliases: []string{"t"},
Usage: "Additional template file(s) to generate enums. Use more than one flag for more files. Templates will be executed in alphabetical order.",
Destination: &argv.TemplateFileNames,
},
&cli.StringSliceFlag{
Name: "alias",
Aliases: []string{"a"},
Usage: "Adds or replaces aliases for a non alphanumeric value that needs to be accounted for. [Format should be \"key:value,key2:value2\", or specify multiple entries, or both!]",
Destination: &argv.Aliases,
},
&cli.BoolFlag{
Name: "mustparse",
Usage: "Adds a Must version of the Parse that will panic on failure.",
Destination: &argv.MustParse,
},
&cli.BoolFlag{
Name: "forcelower",
Usage: "Forces a camel cased comment to generate lowercased names.",
Destination: &argv.ForceLower,
},
&cli.BoolFlag{
Name: "forceupper",
Usage: "Forces a camel cased comment to generate uppercased names.",
Destination: &argv.ForceUpper,
},
&cli.BoolFlag{
Name: "nocomments",
Usage: "Removes auto generated comments. If you add your own comments, these will still be created.",
Destination: &argv.NoComments,
},
&cli.StringSliceFlag{
Name: "buildtag",
Aliases: []string{"b"},
Usage: "Adds build tags to a generated enum file.",
Destination: &argv.BuildTags,
},
&cli.StringFlag{
Name: "output-suffix",
Usage: "Changes the default filename suffix of _enum to something else. `.go` will be appended to the end of the string no matter what, so that `_test.go` cases can be accommodated ",
Destination: &argv.OutputSuffix,
},
},
Action: func(ctx *cli.Context) error {
aliases, err := generator.ParseAliases(argv.Aliases.Value())
if err != nil {
return err
}
for _, fileOption := range argv.FileNames.Value() {
g := generator.NewGenerator()
g.Version = version
g.Revision = commit
g.BuildDate = date
g.BuiltBy = builtBy
g.WithBuildTags(argv.BuildTags.Value()...)
g.WithAliases(aliases)
if argv.NoPrefix {
g.WithNoPrefix()
}
if argv.Lowercase {
g.WithLowercaseVariant()
}
if argv.NoCase {
g.WithCaseInsensitiveParse()
}
if argv.Marshal {
g.WithMarshal()
}
if argv.SQL {
g.WithSQLDriver()
}
if argv.SQLInt {
g.WithSQLInt()
}
if argv.Flag {
g.WithFlag()
}
if argv.Names {
g.WithNames()
}
if argv.Values {
g.WithValues()
}
if argv.LeaveSnakeCase {
g.WithoutSnakeToCamel()
}
if argv.Prefix != "" {
g.WithPrefix(argv.Prefix)
}
if argv.Ptr {
g.WithPtr()
}
if argv.SQLNullInt {
g.WithSQLNullInt()
}
if argv.SQLNullStr {
g.WithSQLNullStr()
}
if argv.MustParse {
g.WithMustParse()
}
if argv.ForceLower {
g.WithForceLower()
}
if argv.ForceUpper {
g.WithForceUpper()
}
if argv.NoComments {
g.WithNoComments()
}
if templates := []string(argv.TemplateFileNames.Value()); len(templates) > 0 {
for _, t := range templates {
if fn, err := globFilenames(t); err != nil {
return err
} else {
g.WithTemplates(fn...)
}
}
}
var filenames []string
if fn, err := globFilenames(fileOption); err != nil {
return err
} else {
filenames = fn
}
outputSuffix := `_enum`
if argv.OutputSuffix != "" {
outputSuffix = argv.OutputSuffix
}
for _, fileName := range filenames {
originalName := fileName
out("go-enum started. file: %s\n", color.Cyan(originalName))
fileName, _ = filepath.Abs(fileName)
outFilePath := fmt.Sprintf("%s%s.go", strings.TrimSuffix(fileName, filepath.Ext(fileName)), outputSuffix)
if strings.HasSuffix(fileName, "_test.go") {
outFilePath = strings.Replace(outFilePath, "_test"+outputSuffix+".go", outputSuffix+"_test.go", 1)
}
// Parse the file given in arguments
raw, err := g.GenerateFromFile(fileName)
if err != nil {
return fmt.Errorf("failed generating enums\nInputFile=%s\nError=%s", color.Cyan(fileName), color.RedBg(err))
}
// Nothing was generated, ignore the output and don't create a file.
if len(raw) < 1 {
out(color.Yellow("go-enum ignored. file: %s\n"), color.Cyan(originalName))
continue
}
mode := int(0o644)
err = os.WriteFile(outFilePath, raw, os.FileMode(mode))
if err != nil {
return fmt.Errorf("failed writing to file %s: %s", color.Cyan(outFilePath), color.Red(err))
}
out("go-enum finished. file: %s\n", color.Cyan(originalName))
}
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
// globFilenames gets a list of filenames matching the provided filename.
// In order to maintain existing capabilities, only glob when a * is in the path.
// Leave execution on par with old method in case there are bad patterns in use that somehow
// work without the Glob method.
func globFilenames(filename string) ([]string, error) {
if strings.Contains(filename, "*") {
matches, err := filepath.Glob(filename)
if err != nil {
return []string{}, fmt.Errorf("failed parsing glob filepath\nInputFile=%s\nError=%s", color.Cyan(filename), color.RedBg(err))
}
return matches, nil
} else {
return []string{filename}, nil
}
}