forked from hexdigest/gowrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd_generate.go
311 lines (250 loc) · 7.46 KB
/
cmd_generate.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
package gowrap
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"unicode"
"github.com/Masterminds/sprig/v3"
"github.com/hexdigest/gowrap/generator"
"github.com/hexdigest/gowrap/pkg"
"github.com/pkg/errors"
)
// GenerateCommand implements Command interface
type GenerateCommand struct {
BaseCommand
interfaceName string
template string
outputFile string
sourcePkg string
noGenerate bool
vars vars
localPrefix string
loader templateLoader
filepath fs
}
// NewGenerateCommand creates GenerateCommand
func NewGenerateCommand(l remoteTemplateLoader) *GenerateCommand {
gc := &GenerateCommand{
loader: loader{fileReader: os.ReadFile, remoteLoader: l},
filepath: fs{
Rel: filepath.Rel,
Abs: filepath.Abs,
Dir: filepath.Dir,
WriteFile: os.WriteFile,
},
}
//this flagset loads flags values to the command fields
fs := &flag.FlagSet{}
fs.BoolVar(&gc.noGenerate, "g", false, "don't put //go:generate instruction to the generated code")
fs.StringVar(&gc.interfaceName, "i", "", `the source interface name, i.e. "Reader"`)
fs.StringVar(&gc.sourcePkg, "p", "", "the source package import path, i.e. \"io\", \"github.com/hexdigest/gowrap\" or\na relative import path like \"./generator\"")
fs.StringVar(&gc.outputFile, "o", "", "the output file name")
fs.StringVar(&gc.template, "t", "", "the template to use, it can be an HTTPS URL, local file or a\nreference to a template in gowrap repository,\n"+
"run `gowrap template list` for details")
fs.Var(&gc.vars, "v", "a key-value pair to parametrize the template,\narguments without an equal sign are treated as a bool values,\ni.e. -v foo=bar -v disableChecks")
fs.StringVar(&gc.localPrefix, "l", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
gc.BaseCommand = BaseCommand{
Short: "generate decorators",
Usage: "-p package -i interfaceName -t template -o output_file.go",
Flags: fs,
}
return gc
}
// Run implements Command interface
func (gc *GenerateCommand) Run(args []string, stdout io.Writer) error {
if err := gc.FlagSet().Parse(args); err != nil {
return CommandLineError(err.Error())
}
if err := gc.checkFlags(); err != nil {
return err
}
generatorOptions, err := gc.getOptions()
if err != nil {
return err
}
gen, err := generator.NewGenerator(*generatorOptions)
if err != nil {
return err
}
buf := bytes.NewBuffer([]byte{})
if err := gen.Generate(buf); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(gc.outputFile), os.ModePerm); err != nil {
return err
}
return gc.filepath.WriteFile(gc.outputFile, buf.Bytes(), 0664)
}
var (
errNoOutputFile = CommandLineError("output file is not specified")
errNoInterfaceName = CommandLineError("interface name is not specified")
errNoTemplate = CommandLineError("no template specified")
)
func (gc *GenerateCommand) checkFlags() error {
if gc.outputFile == "" {
return errNoOutputFile
}
if gc.interfaceName == "" {
return errNoInterfaceName
}
if gc.template == "" {
return errNoTemplate
}
return nil
}
func (gc *GenerateCommand) getOptions() (*generator.Options, error) {
options := generator.Options{
InterfaceName: gc.interfaceName,
OutputFile: gc.outputFile,
Funcs: helperFuncs,
HeaderTemplate: headerTemplate,
HeaderVars: map[string]interface{}{
"DisableGoGenerate": gc.noGenerate,
"OutputFileName": filepath.Base(gc.outputFile),
"VarsArgs": varsToArgs(gc.vars),
},
Vars: gc.vars.toMap(),
LocalPrefix: gc.localPrefix,
}
outputFileDir, err := gc.filepath.Abs(gc.filepath.Dir(gc.outputFile))
if err != nil {
return nil, err
}
if gc.sourcePkg == "" {
gc.sourcePkg = "./"
}
sourcePackage, err := pkg.Load(gc.sourcePkg)
if err != nil {
return nil, errors.Wrap(err, "failed to load source package")
}
options.SourcePackage = sourcePackage.PkgPath
options.BodyTemplate, options.HeaderVars["Template"], err = gc.loadTemplate(outputFileDir)
return &options, err
}
type readerFunc func(path string) ([]byte, error)
type loader struct {
fileReader readerFunc
remoteLoader templateLoader
}
func (gc *GenerateCommand) loadTemplate(outputFileDir string) (contents, url string, err error) {
body, url, err := gc.loader.Load(gc.template)
if err != nil {
return "", "", errors.Wrap(err, "failed to load template")
}
if !strings.HasPrefix(url, "https://") {
templatePath, err := gc.filepath.Abs(url)
if err != nil {
return "", "", err
}
url, err = gc.filepath.Rel(outputFileDir, templatePath)
if err != nil {
return "", "", err
}
}
return string(body), url, nil
}
// Load implements templateLoader
func (l loader) Load(template string) (tmpl []byte, url string, err error) {
tmpl, err = l.fileReader(template)
if err != nil {
if !os.IsNotExist(err) {
return
}
return l.remoteLoader.Load(template)
}
return tmpl, template, err
}
type templateLoader interface {
Load(path string) (tmpl []byte, url string, err error)
}
type fs struct {
Rel func(string, string) (string, error)
Abs func(string) (string, error)
Dir func(string) string
WriteFile func(string, []byte, os.FileMode) error
}
type varFlag struct {
name string
value interface{}
}
// vars is a helper type that implements flag.Value to read multiple vars from the command line
type vars []varFlag
// String implements flag.Value
func (v vars) String() string {
return fmt.Sprintf("%#v", v)
}
func (v *vars) Set(s string) error {
chunks := strings.SplitN(s, "=", 2)
switch len(chunks) {
case 1:
*v = append(*v, varFlag{name: chunks[0], value: true})
case 2:
*v = append(*v, varFlag{name: chunks[0], value: chunks[1]})
}
return nil
}
func (v vars) toMap() map[string]interface{} {
m := make(map[string]interface{}, len(v))
for _, vf := range v {
m[vf.name] = vf.value
}
return m
}
func varsToArgs(v vars) string {
if len(v) == 0 {
return ""
}
var ss []string
for _, vf := range v {
switch typedValue := vf.value.(type) {
case string:
ss = append(ss, vf.name+"="+typedValue)
case bool:
ss = append(ss, vf.name)
}
}
return " -v " + strings.Join(ss, " -v ")
}
var helperFuncs template.FuncMap
func init() {
helperFuncs = sprig.TxtFuncMap()
helperFuncs["up"] = strings.ToUpper
helperFuncs["down"] = strings.ToLower
helperFuncs["upFirst"] = upFirst
helperFuncs["downFirst"] = downFirst
helperFuncs["replace"] = strings.ReplaceAll
helperFuncs["snake"] = toSnakeCase
}
func upFirst(s string) string {
for _, v := range s {
return string(unicode.ToUpper(v)) + s[len(string(v)):]
}
return ""
}
func downFirst(s string) string {
for _, v := range s {
return string(unicode.ToLower(v)) + s[len(string(v)):]
}
return ""
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func toSnakeCase(str string) string {
result := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
result = matchAllCap.ReplaceAllString(result, "${1}_${2}")
return strings.ToLower(result)
}
const headerTemplate = `// Code generated by gowrap. DO NOT EDIT.
// template: {{.Options.HeaderVars.Template}}
// gowrap: http://github.com/hexdigest/gowrap
package {{.Package.Name}}
{{if (not .Options.HeaderVars.DisableGoGenerate)}}
//{{"go:generate"}} gowrap gen -p {{.SourcePackage.PkgPath}} -i {{.Options.InterfaceName}} -t {{.Options.HeaderVars.Template}} -o {{.Options.HeaderVars.OutputFileName}}{{.Options.HeaderVars.VarsArgs}} -l "{{.Options.LocalPrefix}}"
{{end}}
`