/
api.go
337 lines (293 loc) · 11.1 KB
/
api.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
332
333
334
335
336
337
// Copyright 2017 Istio Authors
//
// 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"
"go/format"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/gogo/protobuf/proto"
"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"github.com/spf13/cobra"
"golang.org/x/tools/imports"
"istio.io/istio/mixer/cmd/shared"
descriptor2 "istio.io/istio/mixer/pkg/protobuf/descriptor"
"istio.io/istio/mixer/tools/codegen/pkg/modelgen"
)
func apiGenCmd(fatalf shared.FormatFn) *cobra.Command {
var templateFile string
var outInterfaceFile string
var oAugmentedTmplFile string
var mappings []string
adapterCmd := &cobra.Command{
Use: "api",
Short: "creates type and service definitions from a given template",
Run: func(cmd *cobra.Command, args []string) {
var err error
outInterfaceFile, err = filepath.Abs(outInterfaceFile)
if err != nil {
fatalf("Invalid path %s: %v", outInterfaceFile, err)
}
oAugmentedTmplFile, err = filepath.Abs(oAugmentedTmplFile)
if err != nil {
fatalf("Invalid path %s: %v", oAugmentedTmplFile, err)
}
importMapping := make(map[string]string)
for _, maps := range mappings {
m := strings.Split(maps, ":")
if len(m) != 2 {
fatalf("Invalid flag -m %v", mappings)
}
importMapping[strings.TrimSpace(m[0])] = strings.TrimSpace(m[1])
}
generator := Generator{OutInterfacePath: outInterfaceFile, OAugmentedTmplPath: oAugmentedTmplFile, ImptMap: importMapping}
if err := generator.Generate(templateFile); err != nil {
fatalf("%v", err)
}
},
}
adapterCmd.PersistentFlags().StringVarP(&templateFile, "template", "t", "", "Input "+
"template file path")
adapterCmd.PersistentFlags().StringVar(&outInterfaceFile, "go_out", "./generated.go", "Output "+
"file path for generated template based go types and interfaces.")
adapterCmd.PersistentFlags().StringVar(&oAugmentedTmplFile, "proto_out", "./generated_template.proto", "Output "+
"file path for generated template based proto messages and services.")
adapterCmd.PersistentFlags().StringArrayVarP(&mappings, "importmapping",
"m", []string{},
"colon separated mapping of proto import to Go package names."+
" -m google/protobuf/descriptor.proto:github.com/golang/protobuf/protoc-gen-go/descriptor")
return adapterCmd
}
const (
resourceMsgSuffix = "Msg"
resourceMsgTypeSuffix = "Type"
resourceMsgInstParamSuffix = "InstanceParam"
fullGoNameOfValueTypeEnum = "istio_policy_v1beta1.ValueType"
fullProtoNameOfValueTypeEnum = "istio.policy.v1beta1.ValueType"
goFileImportFmt = `"%s"`
protoFileImportFmt = `import "%s";`
protoValueTypeImport = "policy/v1beta1/value_type.proto"
)
// Generator generates Go interfaces for adapters to implement for a given Template.
type Generator struct {
OutInterfacePath string
OAugmentedTmplPath string
ImptMap map[string]string
}
func toProtoMap(k string, v string) string {
return fmt.Sprintf("map<%s, %s>", k, v)
}
func containsValueType(ti modelgen.TypeInfo) bool {
return ti.IsValueType || ti.IsMap && ti.MapValue.IsValueType
}
func valueTypeOrResMsg(ti modelgen.TypeInfo) bool {
return ti.IsValueType || ti.IsResourceMessage || ti.IsMap && (ti.MapValue.IsValueType || ti.MapValue.IsResourceMessage)
}
// Generate creates a Go interfaces for adapters to implement for a given Template.
func (g *Generator) Generate(fdsFile string) error {
return g.generateInternal(fdsFile, interfaceTemplate, augmentedProtoTmpl)
}
// Generate creates a Go interfaces for adapters to implement for a given Template.
func (g *Generator) generateInternal(fdsFile string, interfaceTmpl, augmentedProtoTmpl string) error {
fds, err := getFileDescSet(fdsFile)
if err != nil {
return fmt.Errorf("cannot parse file '%s' as a FileDescriptorSetProto: %v", fdsFile, err)
}
parser := descriptor2.CreateFileDescriptorSetParser(fds, g.ImptMap, "")
model, err := modelgen.Create(parser)
if err != nil {
return err
}
interfaceFileData, err := g.getInterfaceGoContent(model, interfaceTmpl)
if err != nil {
return err
}
augProtoData, err := g.getAugmentedProtoContent(model, model.PackageName, augmentedProtoTmpl)
if err != nil {
return err
}
// Everything succeeded, now write to the file.
f1, err := os.Create(g.OutInterfacePath)
if err != nil {
return err
}
defer func() { _ = f1.Close() }() // nolint: gas
if _, err = f1.Write(interfaceFileData); err != nil { // nolint: gas
_ = f1.Close() // nolint: gas
_ = os.Remove(f1.Name()) // nolint: gas
return err
}
f2, err := os.Create(g.OAugmentedTmplPath)
if err != nil {
return err
}
defer func() { _ = f2.Close() }() // nolint: gas
if _, err = f2.Write(augProtoData); err != nil {
_ = f2.Close() // nolint: gas
_ = os.Remove(f2.Name()) // nolint: gas
return err
}
return nil
}
func (g *Generator) getInterfaceGoContent(model *modelgen.Model, interfaceTmpl string) ([]byte, error) {
imprts := make([]string, 0)
intfaceTmpl, err := template.New("ProcInterface").Funcs(
template.FuncMap{
"replaceGoValueTypeToInterface": func(typeInfo modelgen.TypeInfo) string {
return strings.Replace(typeInfo.Name, fullGoNameOfValueTypeEnum, "interface{}", 1)
},
// The text/templates have code logic using which it decides the fields to be printed. Example
// when printing 'Type' we skip fields that have static types. So, this callback method 'reportTypeUsed'
// allows the template code to register which fields and types it actually printed. Based on what was actually
// printed we can decide which imports should be added to the file. Therefore, import adding is a last step
// after all fields and messages / structs are printed.
// The template has a placeholder '$$imports$$' for printing the imports and
// the this generator code will replace it with imports for fields that were recorded via this callback.
"reportTypeUsed": func(ti modelgen.TypeInfo) string {
if len(ti.Import) > 0 {
imprt := fmt.Sprintf(goFileImportFmt, ti.Import)
if !contains(imprts, imprt) {
imprts = append(imprts, imprt)
}
}
// do nothing, just record the import so that we can add them later (only for the types that got printed)
return ""
},
}).Parse(interfaceTmpl)
if err != nil {
return nil, fmt.Errorf("cannot load template: %v", err)
}
intfaceBuf := new(bytes.Buffer)
err = intfaceTmpl.Execute(intfaceBuf, model)
if err != nil {
return nil, fmt.Errorf("cannot execute the template with the given data: %v", err)
}
bytesWithImpts := bytes.Replace(intfaceBuf.Bytes(), []byte("$$additional_imports$$"), []byte(strings.Join(imprts, "\n")), 1)
fmtd, err := format.Source(bytesWithImpts)
if err != nil {
return nil, fmt.Errorf("could not format generated code: %v : %s", err, intfaceBuf.String())
}
imports.LocalPrefix = "istio.io"
// OutFilePath provides context for import path. We rely on the supplied bytes for content.
imptd, err := imports.Process(g.OutInterfacePath, fmtd, nil)
if err != nil {
return nil, fmt.Errorf("could not fix imports for generated code: %v", err)
}
return imptd, nil
}
type stringifyFn func(modelgen.TypeInfo) string
func (g *Generator) getAugmentedProtoContent(model *modelgen.Model, pkgName string, augmentedProtoTmpl string) ([]byte, error) {
imports := make([]string, 0)
re := regexp.MustCompile(`(?i)` + pkgName + "\\.")
var stringify stringifyFn
trimPackageName := func(fullName string) string {
return re.ReplaceAllString(fullName, "")
}
stringify = func(protoType modelgen.TypeInfo) string {
if protoType.IsMap {
return toProtoMap(stringify(*protoType.MapKey), stringify(*protoType.MapValue))
}
if protoType.IsResourceMessage {
return trimPackageName(protoType.Name) + resourceMsgInstParamSuffix
}
return "string"
}
augmentedTemplateTmpl, err := template.New("AugmentedTemplateTmpl").Funcs(
template.FuncMap{
"valueTypeOrResMsg": valueTypeOrResMsg,
"valueTypeOrResMsgFieldTypeName": func(protoTypeInfo modelgen.TypeInfo) string {
if protoTypeInfo.IsResourceMessage {
return trimPackageName(protoTypeInfo.Name) + resourceMsgTypeSuffix
}
if protoTypeInfo.IsMap && protoTypeInfo.MapValue.IsResourceMessage {
return toProtoMap(protoTypeInfo.MapKey.Name, trimPackageName(protoTypeInfo.MapValue.Name)+resourceMsgTypeSuffix)
}
// convert Value msg to ValueType enum for use inside inferred type msg.
if protoTypeInfo.IsValueType {
return fullProtoNameOfValueTypeEnum
}
if protoTypeInfo.IsMap && protoTypeInfo.MapValue.IsValueType {
return toProtoMap(protoTypeInfo.MapKey.Name, fullProtoNameOfValueTypeEnum)
}
return protoTypeInfo.Name
},
"stringify": stringify,
"reportTypeUsed": func(ti modelgen.TypeInfo) string {
if containsValueType(ti) {
imptStm := fmt.Sprintf(protoFileImportFmt, protoValueTypeImport)
if !contains(imports, imptStm) {
imports = append(imports, imptStm)
}
}
if len(ti.Import) > 0 {
imprt := fmt.Sprintf(protoFileImportFmt, ti.Import)
if !contains(imports, imprt) {
imports = append(imports, imprt)
}
}
// do nothing, just record the import so that we can add them later (only for the types that got printed)
return ""
},
"getResourcMessageTypeName": func(s string) string {
return s + resourceMsgTypeSuffix
},
"getResourcMessageInterfaceParamTypeName": func(s string) string {
return s + resourceMsgInstParamSuffix
},
"typeName": func(protoTypeInfo modelgen.TypeInfo) string {
if protoTypeInfo.IsResourceMessage {
return trimPackageName(protoTypeInfo.Name) + resourceMsgSuffix
}
if protoTypeInfo.IsMap && protoTypeInfo.MapValue.IsResourceMessage {
return toProtoMap(protoTypeInfo.MapKey.Name, trimPackageName(protoTypeInfo.MapValue.Name)+resourceMsgSuffix)
}
return protoTypeInfo.Name
},
},
).Parse(augmentedProtoTmpl)
if err != nil {
return nil, fmt.Errorf("cannot load template: %v", err)
}
tmplBuf := new(bytes.Buffer)
err = augmentedTemplateTmpl.Execute(tmplBuf, model)
if err != nil {
return nil, fmt.Errorf("cannot execute the template with the given data: %v", err)
}
return bytes.Replace(tmplBuf.Bytes(), []byte("$$additional_imports$$"), []byte(strings.Join(imports, "\n")), 1), nil
}
func getFileDescSet(path string) (*descriptor.FileDescriptorSet, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
fds := &descriptor.FileDescriptorSet{}
err = proto.Unmarshal(bytes, fds)
if err != nil {
return nil, err
}
return fds, nil
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}