/
model-methods.go
176 lines (154 loc) · 5.16 KB
/
model-methods.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
/*
Copyright © 2020 Jacek Kucharczyk kucjac@gmail.com
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 cmd
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/neuronlabs/strcase"
"github.com/spf13/cobra"
"github.com/neuronlabs/neuron-extensions/neurogonesis/input"
"github.com/neuronlabs/neuron-extensions/neurogonesis/internal/ast"
)
// modelMethodsCmd represents the model methods command
var modelMethodsCmd = &cobra.Command{
Use: "methods",
Short: "Generates neuron models mapping.Model methods.",
Long: `This generator allows to create model interfaces used by other neuron components.
By default it creates github.com/neuronlabs/neuron/mapping model interfaces implementation
for provided input model type. A model type is provided with flag '-type' i.e.:
neurogonesis models methods methods -type=MyModel .
Model methods must exists in the same namespace package. Due to the fact that the generator
creates these files in the same directory as input.
By default generator takes current working directory as an input.`,
PreRun: modelsPreRun,
Run: generateModelMethods,
}
func init() {
modelsCmd.AddCommand(modelMethodsCmd)
// Here you will define your flags and configuration settings.
modelMethodsCmd.Flags().StringP("naming-convention", "n", "snake", `set the naming convention for the output models.
Possible values: 'snake', 'kebab', 'lower_camel', 'camel'`)
modelMethodsCmd.Flags().BoolP("single-file", "s", false, "creates the methods within single file")
}
func generateModelMethods(cmd *cobra.Command, args []string) {
namingConvention, err := cmd.Flags().GetString("naming-convention")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
cmd.Usage()
os.Exit(2)
}
singleFile, err := cmd.Flags().GetBool("single-file")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
cmd.Usage()
os.Exit(2)
}
switch namingConvention {
case "kebab", "snake", "lower_camel", "camel":
default:
fmt.Fprintf(os.Stderr, "Error: provided unsupported naming convention: '%v'", namingConvention)
cmd.Usage()
os.Exit(2)
}
// Get the optional type names flag.
typeNames, err := cmd.Flags().GetStringSlice("type")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: loading flags failed: '%v\n", err)
os.Exit(2)
}
// Get the optional type names flag.
excludeTypes, err := cmd.Flags().GetStringSlice("exclude")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: loading flags failed: '%v\n", err)
os.Exit(2)
}
g := ast.NewModelGenerator(namingConvention, typeNames, tags, excludeTypes)
// Get the directory from the arguments.
dir := directory(args)
// Clear previous model methods files.
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() && path != dir {
return filepath.SkipDir
}
if strings.HasSuffix(path, ".gen.go") && !strings.HasSuffix(path, "db.gen.go") {
if err := os.Remove(path); err != nil {
return err
}
}
return nil
})
if err != nil {
os.Exit(1)
}
// Parse provided argument packages.
g.ParsePackages(args...)
// Extract all models from given packages.
if err := g.ExtractPackages(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
buf := &bytes.Buffer{}
// Generate model files.
var modelNames []string
if !singleFile {
for _, model := range g.Models() {
fileName := filepath.Join(dir, strcase.ToSnake(model.Name)+".gen")
if model.TestFile {
fileName += "_test"
}
fileName += ".go"
generateFile(fileName, "model", buf, model)
modelNames = append(modelNames, model.Name)
}
} else {
var testModels, models []*input.Model
for _, model := range g.Models() {
modelNames = append(modelNames, model.Name)
if model.TestFile {
testModels = append(testModels, model)
} else {
models = append(models, model)
}
}
if len(models) > 0 {
generateSingleFileMethods(models, dir, false, buf)
}
if len(testModels) > 0 {
generateSingleFileMethods(testModels, dir, true, buf)
}
}
fmt.Fprintf(os.Stdout, "Success. Generated methods for: %s models.\n", strings.Join(modelNames, ","))
}
func generateSingleFileMethods(models []*input.Model, dir string, isTesting bool, buf *bytes.Buffer) {
multiModels := &input.MultiModel{}
imports := map[string]struct{}{}
for _, model := range models {
for _, imp := range model.Imports {
imports[imp] = struct{}{}
}
multiModels.PackageName = model.PackageName
multiModels.Models = append(multiModels.Models, model)
}
for imp := range imports {
multiModels.Imports = append(multiModels.Imports, imp)
}
fileName := filepath.Join(dir, "models.gen")
if isTesting {
fileName += "_test"
}
fileName += ".go"
generateFile(fileName, "single-file-models", buf, multiModels)
}