forked from go-swagger/go-swagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared.go
289 lines (253 loc) · 6.67 KB
/
shared.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
// Copyright 2015 go-swagger maintainers
//
// 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 generator
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/go-swagger/go-swagger/spec"
"github.com/go-swagger/go-swagger/swag"
"golang.org/x/tools/imports"
)
// TODO: actually use this in some of the naming methods (eg. camelize and snakize)
var reservedGoWords = []string{
"break", "default", "func", "interface", "select",
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var",
}
var defaultGoImports = []string{
"bool", "int", "int8", "int16", "int32", "int64",
"uint", "uint8", "uint16", "uint32", "uint64",
"float32", "float64", "interface{}", "string",
"byte", "rune",
}
var reservedGoWordSet map[string]struct{}
func init() {
reservedGoWordSet = make(map[string]struct{})
for _, gw := range reservedGoWords {
reservedGoWordSet[gw] = struct{}{}
}
}
func mangleName(name, suffix string) string {
if _, ok := reservedGoWordSet[swag.ToFileName(name)]; !ok {
return name
}
return strings.Join([]string{name, suffix}, "_")
}
func findSwaggerSpec(name string) (string, error) {
f, err := os.Stat(name)
if err != nil {
return "", err
}
if f.IsDir() {
return "", fmt.Errorf("%s is a directory", name)
}
return name, nil
}
// GenOpts the options for the generator
type GenOpts struct {
Spec string
APIPackage string
ModelPackage string
ServerPackage string
ClientPackage string
Principal string
Target string
TypeMapping map[string]string
Imports map[string]string
DumpData bool
DefaultScheme string
}
type generatorOptions struct {
ModelPackage string
TargetDirectory string
}
// on its way out
type propertyDescriptor struct {
PropertyName string
ParamName string
Path string
ValueExpression string
IndexVar string
IsPrimitive bool
IsCustomFormatter bool
IsContainer bool
IsMap bool
}
// on its way out
type commonValidations struct {
propertyDescriptor
sharedValidations
Type string
Format string
Items *spec.Items
Default interface{}
}
// on its way out
type genValidations struct {
Type string
Required bool
DefaultValue string
MaxLength int64
MinLength int64
Pattern string
MultipleOf float64
Minimum float64
Maximum float64
ExclusiveMinimum bool
ExclusiveMaximum bool
Enum string
HasValidations bool
Format string
MinItems int64
MaxItems int64
UniqueItems bool
HasSliceValidations bool
NeedsSize bool
}
func loadSpec(specFile string) (string, *spec.Document, error) {
// find swagger spec document, verify it exists
specPath := specFile
var err error
if !strings.HasPrefix(specPath, "http") {
specPath, err = findSwaggerSpec(specFile)
if err != nil {
return "", nil, err
}
}
// load swagger spec
specDoc, err := spec.Load(specPath)
if err != nil {
return "", nil, err
}
return specPath, specDoc, nil
}
func fileExists(target, name string) bool {
ffn := swag.ToFileName(name) + ".go"
_, err := os.Stat(filepath.Join(target, ffn))
return !os.IsNotExist(err)
}
func writeToFileIfNotExist(target, name string, content []byte) error {
if fileExists(target, name) {
return nil
}
return writeToFile(target, name, content)
}
func formatGoFile(ffn string, content []byte) ([]byte, error) {
opts := new(imports.Options)
opts.TabIndent = true
opts.TabWidth = 2
opts.Fragment = true
opts.Comments = true
return imports.Process(ffn, content, opts)
}
func writeToFile(target, name string, content []byte) error {
ffn := swag.ToFileName(name) + ".go"
res, err := formatGoFile(ffn, content)
if err != nil {
log.Println(err)
return writeFile(target, ffn, content)
}
return writeFile(target, ffn, res)
}
func writeFile(target, ffn string, content []byte) error {
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
return ioutil.WriteFile(filepath.Join(target, ffn), content, 0644)
}
func commentedLines(str string) string {
lines := strings.Split(str, "\n")
var commented []string
for _, line := range lines {
if strings.TrimSpace(line) != "" {
if !strings.HasPrefix(strings.TrimSpace(line), "//") {
commented = append(commented, "// "+line)
} else {
commented = append(commented, line)
}
}
}
return strings.Join(commented, "\n")
}
func gatherModels(specDoc *spec.Document, modelNames []string) map[string]spec.Schema {
models, mnc := make(map[string]spec.Schema), len(modelNames)
for k, v := range specDoc.Spec().Definitions {
for _, nm := range modelNames {
if mnc == 0 || k == nm {
models[k] = v
}
}
}
return models
}
func appNameOrDefault(specDoc *spec.Document, name, defaultName string) string {
if name == "" {
if specDoc.Spec().Info != nil && specDoc.Spec().Info.Title != "" {
name = specDoc.Spec().Info.Title
} else {
name = defaultName
}
}
return strings.TrimSuffix(swag.ToGoName(name), "API")
}
var namesCounter int64
func ensureUniqueName(key, method, path string, operations map[string]opRef) string {
nm := key
if nm == "" {
nm = swag.ToGoName(strings.ToLower(method) + " " + path)
}
_, found := operations[nm]
if found {
namesCounter++
return fmt.Sprintf("%s%d", nm, namesCounter)
}
return nm
}
func containsString(names []string, name string) bool {
for _, nm := range names {
if nm == name {
return true
}
}
return false
}
type opRef struct {
Method string
Path string
Op spec.Operation
}
func gatherOperations(specDoc *spec.Document, operationIDs []string) map[string]opRef {
operations := make(map[string]opRef)
for method, pathItem := range specDoc.Operations() {
for path, operation := range pathItem {
if len(operationIDs) == 0 || containsString(operationIDs, operation.ID) {
nm := ensureUniqueName(operation.ID, method, path, operations)
vv := *operation
vv.ID = nm
operations[nm] = opRef{
Method: method,
Path: path,
Op: vv,
}
}
}
}
return operations
}