forked from aws/aws-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shape.go
448 lines (394 loc) · 11.7 KB
/
shape.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package api
import (
"bytes"
"fmt"
"path"
"regexp"
"sort"
"strings"
"text/template"
"github.com/aws/aws-sdk-go/private/util"
)
// A ShapeRef defines the usage of a shape within the API.
type ShapeRef struct {
API *API `json:"-"`
Shape *Shape `json:"-"`
Documentation string
ShapeName string `json:"shape"`
Location string
LocationName string
QueryName string
Flattened bool
Streaming bool
XMLAttribute bool
XMLNamespace XMLInfo
Payload string
IdempotencyToken bool `json:"idempotencyToken"`
Deprecated bool `json:"deprecated"`
}
// A XMLInfo defines URL and prefix for Shapes when rendered as XML
type XMLInfo struct {
Prefix string
URI string
}
// A Shape defines the definition of a shape type
type Shape struct {
API *API `json:"-"`
ShapeName string
Documentation string
MemberRefs map[string]*ShapeRef `json:"members"`
MemberRef ShapeRef `json:"member"`
KeyRef ShapeRef `json:"key"`
ValueRef ShapeRef `json:"value"`
Required []string
Payload string
Type string
Exception bool
Enum []string
EnumConsts []string
Flattened bool
Streaming bool
Location string
LocationName string
IdempotencyToken bool `json:"idempotencyToken"`
XMLNamespace XMLInfo
Min int // optional Minimum length (string, list) or value (number)
Max int // optional Minimum length (string, list) or value (number)
refs []*ShapeRef // References to this shape
resolvePkg string // use this package in the goType() if present
// Defines if the shape is a placeholder and should not be used directly
Placeholder bool
Deprecated bool `json:"deprecated"`
}
// Rename changes the name of the Shape to newName. Also updates
// the associated API's reference to use newName.
func (s *Shape) Rename(newName string) {
for _, r := range s.refs {
r.ShapeName = newName
}
delete(s.API.Shapes, s.ShapeName)
s.API.Shapes[newName] = s
s.ShapeName = newName
}
// MemberNames returns a slice of struct member names.
func (s *Shape) MemberNames() []string {
i, names := 0, make([]string, len(s.MemberRefs))
for n := range s.MemberRefs {
names[i] = n
i++
}
sort.Strings(names)
return names
}
// GoTypeWithPkgName returns a shape's type as a string with the package name in
// <packageName>.<type> format. Package naming only applies to structures.
func (s *Shape) GoTypeWithPkgName() string {
return goType(s, true)
}
// GoType returns a shape's Go type
func (s *Shape) GoType() string {
return goType(s, false)
}
// GoType returns a shape ref's Go type.
func (ref *ShapeRef) GoType() string {
if ref.Shape == nil {
panic(fmt.Errorf("missing shape definition on reference for %#v", ref))
}
return ref.Shape.GoType()
}
// GoTypeWithPkgName returns a shape's type as a string with the package name in
// <packageName>.<type> format. Package naming only applies to structures.
func (ref *ShapeRef) GoTypeWithPkgName() string {
if ref.Shape == nil {
panic(fmt.Errorf("missing shape definition on reference for %#v", ref))
}
return ref.Shape.GoTypeWithPkgName()
}
// Returns a string version of the Shape's type.
// If withPkgName is true, the package name will be added as a prefix
func goType(s *Shape, withPkgName bool) string {
switch s.Type {
case "structure":
if withPkgName || s.resolvePkg != "" {
pkg := s.resolvePkg
if pkg != "" {
s.API.imports[pkg] = true
pkg = path.Base(pkg)
} else {
pkg = s.API.PackageName()
}
return fmt.Sprintf("*%s.%s", pkg, s.ShapeName)
}
return "*" + s.ShapeName
case "map":
return "map[string]" + s.ValueRef.GoType()
case "list":
return "[]" + s.MemberRef.GoType()
case "boolean":
return "*bool"
case "string", "character":
return "*string"
case "blob":
return "[]byte"
case "integer", "long":
return "*int64"
case "float", "double":
return "*float64"
case "timestamp":
s.API.imports["time"] = true
return "*time.Time"
default:
panic("Unsupported shape type: " + s.Type)
}
}
// GoTypeElem returns the Go type for the Shape. If the shape type is a pointer just
// the type will be returned minus the pointer *.
func (s *Shape) GoTypeElem() string {
t := s.GoType()
if strings.HasPrefix(t, "*") {
return t[1:]
}
return t
}
// GoTypeElem returns the Go type for the Shape. If the shape type is a pointer just
// the type will be returned minus the pointer *.
func (ref *ShapeRef) GoTypeElem() string {
if ref.Shape == nil {
panic(fmt.Errorf("missing shape definition on reference for %#v", ref))
}
return ref.Shape.GoTypeElem()
}
// ShapeTag is a struct tag that will be applied to a shape's generated code
type ShapeTag struct {
Key, Val string
}
// String returns the string representation of the shape tag
func (s ShapeTag) String() string {
return fmt.Sprintf(`%s:"%s"`, s.Key, s.Val)
}
// ShapeTags is a collection of shape tags and provides serialization of the
// tags in an ordered list.
type ShapeTags []ShapeTag
// Join returns an ordered serialization of the shape tags with the provided
// seperator.
func (s ShapeTags) Join(sep string) string {
o := &bytes.Buffer{}
for i, t := range s {
o.WriteString(t.String())
if i < len(s)-1 {
o.WriteString(sep)
}
}
return o.String()
}
// String is an alias for Join with the empty space seperator.
func (s ShapeTags) String() string {
return s.Join(" ")
}
// GoTags returns the rendered tags string for the ShapeRef
func (ref *ShapeRef) GoTags(toplevel bool, isRequired bool) string {
tags := ShapeTags{}
if ref.Location != "" {
tags = append(tags, ShapeTag{"location", ref.Location})
} else if ref.Shape.Location != "" {
tags = append(tags, ShapeTag{"location", ref.Shape.Location})
}
if ref.LocationName != "" {
tags = append(tags, ShapeTag{"locationName", ref.LocationName})
} else if ref.Shape.LocationName != "" {
tags = append(tags, ShapeTag{"locationName", ref.Shape.LocationName})
}
if ref.QueryName != "" {
tags = append(tags, ShapeTag{"queryName", ref.QueryName})
}
if ref.Shape.MemberRef.LocationName != "" {
tags = append(tags, ShapeTag{"locationNameList", ref.Shape.MemberRef.LocationName})
}
if ref.Shape.KeyRef.LocationName != "" {
tags = append(tags, ShapeTag{"locationNameKey", ref.Shape.KeyRef.LocationName})
}
if ref.Shape.ValueRef.LocationName != "" {
tags = append(tags, ShapeTag{"locationNameValue", ref.Shape.ValueRef.LocationName})
}
if ref.Shape.Min > 0 {
tags = append(tags, ShapeTag{"min", fmt.Sprintf("%d", ref.Shape.Min)})
}
if ref.Deprecated || ref.Shape.Deprecated {
tags = append(tags, ShapeTag{"deprecated", "true"})
}
// All shapes have a type
tags = append(tags, ShapeTag{"type", ref.Shape.Type})
// embed the timestamp type for easier lookups
if ref.Shape.Type == "timestamp" {
t := ShapeTag{Key: "timestampFormat"}
if ref.Location == "header" {
t.Val = "rfc822"
} else {
switch ref.API.Metadata.Protocol {
case "json", "rest-json":
t.Val = "unix"
case "rest-xml", "ec2", "query":
t.Val = "iso8601"
}
}
tags = append(tags, t)
}
if ref.Shape.Flattened || ref.Flattened {
tags = append(tags, ShapeTag{"flattened", "true"})
}
if ref.XMLAttribute {
tags = append(tags, ShapeTag{"xmlAttribute", "true"})
}
if isRequired {
tags = append(tags, ShapeTag{"required", "true"})
}
if ref.Shape.IsEnum() {
tags = append(tags, ShapeTag{"enum", ref.ShapeName})
}
if toplevel {
if ref.Shape.Payload != "" {
tags = append(tags, ShapeTag{"payload", ref.Shape.Payload})
}
if ref.XMLNamespace.Prefix != "" {
tags = append(tags, ShapeTag{"xmlPrefix", ref.XMLNamespace.Prefix})
} else if ref.Shape.XMLNamespace.Prefix != "" {
tags = append(tags, ShapeTag{"xmlPrefix", ref.Shape.XMLNamespace.Prefix})
}
if ref.XMLNamespace.URI != "" {
tags = append(tags, ShapeTag{"xmlURI", ref.XMLNamespace.URI})
} else if ref.Shape.XMLNamespace.URI != "" {
tags = append(tags, ShapeTag{"xmlURI", ref.Shape.XMLNamespace.URI})
}
}
if ref.IdempotencyToken || ref.Shape.IdempotencyToken {
tags = append(tags, ShapeTag{"idempotencyToken", "true"})
}
return fmt.Sprintf("`%s`", tags)
}
// Docstring returns the godocs formated documentation
func (ref *ShapeRef) Docstring() string {
if ref.Documentation != "" {
return ref.Documentation
}
return ref.Shape.Docstring()
}
// Docstring returns the godocs formated documentation
func (s *Shape) Docstring() string {
return s.Documentation
}
var goCodeStringerTmpl = template.Must(template.New("goCodeStringerTmpl").Parse(`
// String returns the string representation
func (s {{ .ShapeName }}) String() string {
return awsutil.Prettify(s)
}
// GoString returns the string representation
func (s {{ .ShapeName }}) GoString() string {
return s.String()
}
`))
func (s *Shape) goCodeStringers() string {
w := bytes.Buffer{}
if err := goCodeStringerTmpl.Execute(&w, s); err != nil {
panic(fmt.Sprintln("Unexpected error executing goCodeStringers template", err))
}
return w.String()
}
var enumStrip = regexp.MustCompile(`[^a-zA-Z0-9_:\./-]`)
var enumDelims = regexp.MustCompile(`[-_:\./]+`)
var enumCamelCase = regexp.MustCompile(`([a-z])([A-Z])`)
// EnumName returns the Nth enum in the shapes Enum list
func (s *Shape) EnumName(n int) string {
enum := s.Enum[n]
enum = enumStrip.ReplaceAllLiteralString(enum, "")
enum = enumCamelCase.ReplaceAllString(enum, "$1-$2")
parts := enumDelims.Split(enum, -1)
for i, v := range parts {
v = strings.ToLower(v)
parts[i] = ""
if len(v) > 0 {
parts[i] = strings.ToUpper(v[0:1])
}
if len(v) > 1 {
parts[i] += v[1:]
}
}
enum = strings.Join(parts, "")
enum = strings.ToUpper(enum[0:1]) + enum[1:]
return enum
}
// GoCode returns the rendered Go code for the Shape.
func (s *Shape) GoCode() string {
code := s.Docstring()
if !s.IsEnum() {
code += "type " + s.ShapeName + " "
}
switch {
case s.Type == "structure":
ref := &ShapeRef{ShapeName: s.ShapeName, API: s.API, Shape: s}
code += "struct {\n"
code += "_ struct{} " + ref.GoTags(true, false) + "\n\n"
for _, n := range s.MemberNames() {
m := s.MemberRefs[n]
code += m.Docstring()
if (m.Streaming || m.Shape.Streaming) && s.Payload == n {
rtype := "io.ReadSeeker"
if len(s.refs) > 1 {
rtype = "aws.ReaderSeekCloser"
} else if strings.HasSuffix(s.ShapeName, "Output") {
rtype = "io.ReadCloser"
}
s.API.imports["io"] = true
code += n + " " + rtype + " " + m.GoTags(false, s.IsRequired(n)) + "\n\n"
} else {
code += n + " " + m.GoType() + " " + m.GoTags(false, s.IsRequired(n)) + "\n\n"
}
}
code += "}"
if !s.API.NoStringerMethods {
code += s.goCodeStringers()
}
case s.IsEnum():
code += "const (\n"
for n, e := range s.Enum {
code += fmt.Sprintf("\t// @enum %s\n\t%s = %q\n",
s.ShapeName, s.EnumConsts[n], e)
}
code += ")"
default:
panic("Cannot generate toplevel shape for " + s.Type)
}
return util.GoFmt(code)
}
// IsEnum returns whether this shape is an enum list
func (s *Shape) IsEnum() bool {
return s.Type == "string" && len(s.Enum) > 0
}
// IsRequired returns if member is a required field.
func (s *Shape) IsRequired(member string) bool {
for _, n := range s.Required {
if n == member {
return true
}
}
return false
}
// IsInternal returns whether the shape was defined in this package
func (s *Shape) IsInternal() bool {
return s.resolvePkg == ""
}
// removeRef removes a shape reference from the list of references this
// shape is used in.
func (s *Shape) removeRef(ref *ShapeRef) {
r := s.refs
for i := 0; i < len(r); i++ {
if r[i] == ref {
j := i + 1
copy(r[i:], r[j:])
for k, n := len(r)-j+i, len(r); k < n; k++ {
r[k] = nil // free up the end of the list
} // for k
s.refs = r[:len(r)-j+i]
break
}
}
}