forked from abice/go-enum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
251 lines (233 loc) · 6.79 KB
/
main.go
File metadata and controls
251 lines (233 loc) · 6.79 KB
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
package main
import (
"fmt"
"io/ioutil"
"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
Flag bool
Prefix string
Names bool
LeaveSnakeCase bool
SQLNullStr bool
SQLNullInt bool
Ptr bool
TemplateFileNames cli.StringSlice
Aliases cli.StringSlice
}
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"},
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: "flag",
Usage: "Adds golang flag functions.",
Destination: &argv.Flag,
},
&cli.StringFlag{
Name: "prefix",
Usage: "Replaces the prefix with a user one.",
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: "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,
},
},
Action: func(ctx *cli.Context) error {
if err := generator.ParseAliases(argv.Aliases.Value()); 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
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.Flag {
g.WithFlag()
}
if argv.Names {
g.WithNames()
}
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 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
}
for _, fileName := range filenames {
originalName := fileName
out("go-enum started. file: %s\n", color.Cyan(originalName))
fileName, _ = filepath.Abs(fileName)
outFilePath := fmt.Sprintf("%s_enum.go", strings.TrimSuffix(fileName, filepath.Ext(fileName)))
// 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(0644)
err = ioutil.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
}
}