-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathnaming.go
More file actions
690 lines (604 loc) · 18.6 KB
/
Copy pathnaming.go
File metadata and controls
690 lines (604 loc) · 18.6 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
// Copyright 2025 DoorDash, Inc.
//
// 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.
// Copyright 2019 DeepMap, Inc.
//
// 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 codegen
import (
"bytes"
"fmt"
"go/token"
"mime"
"net/url"
"regexp"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/pb33f/libopenapi/datamodel/high/base"
v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
)
var (
pathParamRE *regexp.Regexp
predeclaredSet map[string]struct{}
separatorSet map[rune]struct{}
nameNormalizer = toCamelCaseWithInitialism
initialismMap = makeInitialismMap(initialismList)
camelCaseMatchParts = regexp.MustCompile(`[\p{Lu}\d]+([\p{Ll}\d]+|$)`)
numericPattern = regexp.MustCompile(`^\d+$`)
)
var initialismList = []string{
"ACH",
"ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON",
"QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID",
"URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", "SIP", "RTP", "AMQP", "DB", "TS", "PSP",
}
// targetWordRegex is a regex that matches all initialisms.
var targetWordRegex *regexp.Regexp
func init() {
pathParamRE = regexp.MustCompile(`{[.;?]?([^{}*]+)\*?}`)
predeclaredIdentifiers := []string{
// Types
"bool",
"byte",
"complex64",
"complex128",
"error",
"float32",
"float64",
"int",
"int8",
"int16",
"int32",
"int64",
"rune",
"string",
"uint",
"uint8",
"uint16",
"uint32",
"uint64",
"uintptr",
// Constants
"true",
"false",
"iota",
// Zero value
"nil",
// Functions
"append",
"cap",
"close",
"complex",
"copy",
"delete",
"imag",
"len",
"make",
"new",
"panic",
"print",
"println",
"real",
"recover",
}
// for _, acr := range initialismList {
// strcase.ConfigureAcronym(acr, strings.ToLower(acr))
// }
predeclaredSet = map[string]struct{}{}
for _, id := range predeclaredIdentifiers {
predeclaredSet[id] = struct{}{}
}
separators := "-#@!$&=.+:;_~ (){}[]"
separatorSet = map[rune]struct{}{}
for _, r := range separators {
separatorSet[r] = struct{}{}
}
}
// UppercaseFirstCharacter Uppercases the first character in a string. This assumes UTF-8, so we have
// to be careful with unicode, don't treat it as a byte array.
func UppercaseFirstCharacter(str string) string {
if str == "" {
return ""
}
runes := []rune(str)
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}
// toCamelCase will convert query-arg style strings to CamelCase.
func toCamelCase(str string) string {
res := bytes.NewBuffer(nil)
capNext := true
for _, v := range str {
if unicode.IsUpper(v) {
res.WriteRune(v)
capNext = false
continue
}
if unicode.IsDigit(v) {
res.WriteRune(v)
capNext = true
continue
}
if unicode.IsLower(v) {
if capNext {
res.WriteRune(unicode.ToUpper(v))
} else {
res.WriteRune(v)
}
capNext = false
continue
}
capNext = true
}
return res.String()
}
// toCamelCaseWithInitialism function will convert query-arg style strings to CamelCase with initialisms in uppercase.
// So, httpOperationId would be converted to HTTPOperationID
func toCamelCaseWithInitialism(s string) string {
parts := camelCaseMatchParts.FindAllString(toCamelCase(s), -1)
for i := range parts {
if v, ok := initialismMap[strings.ToLower(parts[i])]; ok {
parts[i] = v
}
}
return strings.Join(parts, "")
}
func makeInitialismMap(additionalInitialisms []string) map[string]string {
l := append(initialismList, additionalInitialisms...)
m := make(map[string]string, len(l))
for i := range l {
m[strings.ToLower(l[i])] = l[i]
}
// Create a regex to match the initialisms
targetWordRegex = regexp.MustCompile(`(?i)(` + strings.Join(l, "|") + `)`)
return m
}
func replaceInitialism(s string) string {
// These strings do not apply CamelCase
// Do not do CamelCase when these characters match when the preceding character is lowercase
return targetWordRegex.ReplaceAllStringFunc(s, func(s string) string {
// If the preceding character is lowercase, do not do CamelCase
if unicode.IsLower(rune(s[0])) {
return s
}
return strings.ToUpper(s)
})
}
// mediaTypeToCamelCase converts a media type to a PascalCase representation
func mediaTypeToCamelCase(s string) string {
// toCamelCase doesn't - and won't - add `/` to the characters it'll allow word boundary
s = strings.Replace(s, "/", "_", 1)
// including a _ to make sure that these are treated as word boundaries by `toCamelCase`
s = strings.Replace(s, "*", "Wildcard_", 1)
s = strings.Replace(s, "+", "Plus_", 1)
return toCamelCaseWithInitialism(s)
}
// sortedMapKeys takes a map with keys of type string and returns a slice of those
// keys sorted lexicographically.
func sortedMapKeys[T any](m map[string]T) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// refPathToObjName returns the name of referenced object without changes.
//
// #/components/schemas/Foo -> Foo
// #/components/parameters/Bar -> Bar
// #/components/responses/baz_baz -> baz_baz
//
// Does not check refPath correctness.
func refPathToObjName(refPath string) string {
parts := strings.Split(refPath, "/")
if len(parts) > 0 {
return parts[len(parts)-1]
}
return ""
}
// refPathToGoType takes a $ref value and converts it to a Go typename.
// #/components/schemas/Foo -> Foo
// #/components/parameters/Bar -> Bar
// #/components/responses/Baz -> Baz
// #/paths/~1api~1v1~1foo/get/responses/200/content/application~1json/schema/properties/time -> GetApiV1FooResponse200_Schema_Properties_Time
// Remote components (document.json#/Foo) are not supported
func refPathToGoType(refPath string) (string, error) {
if refPath == "" {
return "", ErrEmptyReferencePath
}
pathParts := strings.Split(refPath, "/")
depth := len(pathParts)
if depth < 2 {
return "", fmt.Errorf("unexpected reference depth: %d for ref: %s", depth, refPath)
}
// Standard component references: #/components/schemas/Foo
if depth == 4 && pathParts[1] == "components" {
lastPart := pathParts[len(pathParts)-1]
return schemaNameToTypeName(lastPart), nil
}
// Deep path references (e.g., inline schemas in paths/responses/properties)
// Generate a meaningful name from the path structure
return generateTypeNameFromPath(pathParts), nil
}
// generateTypeNameFromPath creates a type name from a deep JSON pointer path.
// Examples:
//
// #/paths/~1api~1v1~1foo/get/responses/200/content/application~1json/schema -> GetApiV1FooResponse200Schema
// #/paths/~1api~1v1~1foo/get/responses/200/content/application~1json/schema/properties/time -> GetApiV1FooResponse200Schema_Time
func generateTypeNameFromPath(pathParts []string) string {
if len(pathParts) < 2 {
return "Schema"
}
var nameParts []string
// Skip the leading "#" part
for i := 1; i < len(pathParts); i++ {
part := pathParts[i]
// Skip generic/noise parts that don't add meaning
if part == "content" || part == "schema" {
continue
}
// Decode JSON Pointer escapes: ~1 -> /, ~0 -> ~
part = strings.ReplaceAll(part, "~1", "/")
part = strings.ReplaceAll(part, "~0", "~")
// URL decode (e.g., %7B -> {, %7D -> })
if decoded, err := url.QueryUnescape(part); err == nil {
part = decoded
}
// Clean up path parameters: /api/v1/foo/{id} -> /api/v1/foo
// Remove parameter placeholders like {id}, {name}, etc.
part = regexp.MustCompile(`\{[^}]+\}`).ReplaceAllString(part, "")
// For path segments, extract meaningful parts
if part == "paths" {
continue // Skip the "paths" keyword itself
}
// Handle path URLs: /api/v1/company/search -> ApiV1CompanySearch
if strings.HasPrefix(part, "/") {
// Split by / and filter out empty parts
segments := strings.Split(strings.Trim(part, "/"), "/")
for _, seg := range segments {
if seg != "" && seg != "api" {
nameParts = append(nameParts, seg)
}
}
continue
}
// Handle HTTP methods
if part == "get" || part == "post" || part == "put" || part == "delete" || part == "patch" {
nameParts = append(nameParts, part)
continue
}
// Handle response codes
if part == "responses" {
continue
}
if numericPattern.MatchString(part) {
nameParts = append(nameParts, "response"+part)
continue
}
if part == "default" {
nameParts = append(nameParts, "defaultResponse")
continue
}
// Handle media types: application/json -> Json
if strings.Contains(part, "/") {
// Likely a media type
if strings.HasSuffix(part, "/json") || part == "application/json" {
nameParts = append(nameParts, "json")
} else {
// Use the part after the slash
parts := strings.Split(part, "/")
if len(parts) > 1 {
nameParts = append(nameParts, parts[len(parts)-1])
}
}
continue
}
// Regular parts (properties, items, etc.)
nameParts = append(nameParts, part)
}
// If we ended up with no meaningful parts, use a generic name
if len(nameParts) == 0 {
return "Schema"
}
// Convert to a valid Go type name using pathToTypeName
return pathToTypeName(nameParts)
}
// orderedParamsFromUri returns the argument names, in order, in a given URI string, so for
// /path/{param1}/{.param2*}/{?param3}, it would return param1, param2, param3
func orderedParamsFromUri(uri string) []string {
matches := pathParamRE.FindAllStringSubmatch(uri, -1)
result := make([]string, len(matches))
for i, m := range matches {
result[i] = m[1]
}
return result
}
// replacePathParamsWithStr replaces path parameters of the form {param} with %s
func replacePathParamsWithStr(uri string) string {
return pathParamRE.ReplaceAllString(uri, "%s")
}
// isGoKeyword returns whether the given string is a go keyword
func isGoKeyword(str string) bool {
return token.IsKeyword(str)
}
// isPredeclaredGoIdentifier returns whether the given string
// is a predefined go identifier.
//
// See https://golang.org/ref/spec#Predeclared_identifiers
func isPredeclaredGoIdentifier(str string) bool {
_, exists := predeclaredSet[str]
return exists
}
// isGoIdentity checks if the given string can be used as an identity
// in the generated code like a type name or constant name.
//
// See https://golang.org/ref/spec#Identifiers
func isGoIdentity(str string) bool {
for i, c := range str {
if !isValidRuneForGoID(i, c) {
return false
}
}
return isGoKeyword(str)
}
func isValidRuneForGoID(index int, char rune) bool {
if index == 0 && unicode.IsNumber(char) {
return false
}
return unicode.IsLetter(char) || char == '_' || unicode.IsNumber(char)
}
// isValidGoIdentity checks if the given string can be used as a
// name of variable, constant, or type.
func isValidGoIdentity(str string) bool {
if isGoIdentity(str) {
return false
}
return !isPredeclaredGoIdentifier(str)
}
// sanitizeGoIdentity deletes and replaces the illegal runes in the given
// string to use the string as a valid identity.
func sanitizeGoIdentity(str string) string {
sanitized := []rune(str)
for i, c := range sanitized {
if !isValidRuneForGoID(i, c) {
sanitized[i] = '_'
} else {
sanitized[i] = c
}
}
str = string(sanitized)
if isGoKeyword(str) || isPredeclaredGoIdentifier(str) {
str = "_" + str
}
if !isValidGoIdentity(str) {
panic("here is a bug")
}
return str
}
func typeNamePrefix(name string) (prefix string) {
return typeNamePrefixInternal(name, true)
}
// typeNamePrefixNonDigit is like typeNamePrefix but doesn't add "N" prefix for leading digits
// This is used for path segments that are not the first segment
func typeNamePrefixNonDigit(name string) (prefix string) {
return typeNamePrefixInternal(name, false)
}
func typeNamePrefixInternal(name string, handleDigits bool) (prefix string) {
if len(name) == 0 {
return "Empty"
}
for _, r := range name {
switch r {
case '$':
if utf8.RuneCountInString(name) == 1 {
return "DollarSign"
}
case '£':
if utf8.RuneCountInString(name) == 1 {
return "PoundSign"
}
case '€':
if utf8.RuneCountInString(name) == 1 {
return "EuroSign"
}
case '-':
prefix += "Minus"
case '+':
prefix += "Plus"
case '&':
prefix += "And"
case '|':
prefix += "Or"
case '~':
prefix += "Tilde"
case '=':
prefix += "Equal"
case '>':
prefix += "GreaterThan"
case '<':
prefix += "LessThan"
case '#':
prefix += "Hash"
case '.':
prefix += "Dot"
case '*':
prefix += "Asterisk"
case '^':
prefix += "Caret"
case '%':
prefix += "Percent"
case '_':
prefix += "Underscore"
case '@':
prefix += "At"
default:
// Prepend "N" to schemas starting with a number (only if handleDigits is true)
if handleDigits && prefix == "" && unicode.IsDigit(r) {
return "N"
}
// break the loop, done parsing prefix
return
}
}
return
}
// schemaNameToTypeName converts a GoSchema name to a valid Go type name.
// It converts to camel case, and makes sure the name is valid in Go
func schemaNameToTypeName(name string) string {
// Handle parameter names ending with [] (e.g., "dataSegmentCode[]")
// These are typically array parameters in query strings
// We append "Array" suffix to distinguish them from the singular version
arraySuffix := ""
if strings.HasSuffix(name, "[]") {
name = strings.TrimSuffix(name, "[]")
arraySuffix = "Array"
}
return typeNamePrefix(name) + nameNormalizer(name) + arraySuffix
}
// pathToTypeName converts a path, like Object/field1/nestedField into a go
// type name.
func pathToTypeName(path []string) string {
for i, p := range path {
// Only add prefix for special characters and digits at the start of the first segment
// For subsequent segments, only handle special characters, not leading digits
if i == 0 {
path[i] = typeNamePrefix(p) + nameNormalizer(p)
} else {
path[i] = typeNamePrefixNonDigit(p) + nameNormalizer(p)
}
}
return strings.Join(path, "_")
}
// stringToGoComment renders a possible multi-line string as a valid Go-Comment.
// Each line is prefixed as a comment.
func stringToGoComment(in string) string {
return stringToGoCommentWithPrefix(in, "")
}
// stringWithTypeNameToGoComment renders a possible multi-line string as a
// valid Go-Comment, including the name of the type being referenced. Each line
// is prefixed as a comment.
func stringWithTypeNameToGoComment(in, typeName string) string {
return stringToGoCommentWithPrefix(in, typeName)
}
func deprecationComment(reason string) string {
content := "Deprecated:" // The colon is required at the end even without reason
if reason != "" {
content += fmt.Sprintf(" %s", reason)
}
return stringToGoCommentWithPrefix(content, "")
}
func stringToGoCommentWithPrefix(in, prefix string) string {
if len(in) == 0 || len(strings.TrimSpace(in)) == 0 { // ignore empty comment
return ""
}
// Normalize newlines from Windows/Mac to Linux
in = strings.ReplaceAll(in, "\r\n", "\n")
in = strings.ReplaceAll(in, "\r", "\n")
// Add comment to each line
var lines []string
for i, line := range strings.Split(in, "\n") {
s := "//"
if i == 0 && len(prefix) > 0 {
s += " " + prefix
}
lines = append(lines, fmt.Sprintf("%s %s", s, line))
}
in = strings.Join(lines, "\n")
// in case we have a multiline string which ends with \n, we would generate
// empty-line-comments, like `// `. Therefore remove this line comment.
in = strings.TrimSuffix(in, "\n// ")
return in
}
// escapePathElements breaks apart a path, and looks at each element. If it's
// not a path parameter, eg, {param}, it will URL-escape the element.
func escapePathElements(path string) string {
elems := strings.Split(path, "/")
for i, e := range elems {
if strings.HasPrefix(e, "{") && strings.HasSuffix(e, "}") {
// This is a path parameter, we don't want to mess with its value
continue
}
elems[i] = url.QueryEscape(e)
}
return strings.Join(elems, "/")
}
// renameComponent takes as input the name of a schema as provided in the spec,
// and the definition of the schema. If the schema overrides the name via
// x-go-name, the new name is returned, otherwise, the original name is
// returned.
func renameComponent(schemaName string, schemaRef *base.SchemaProxy) (string, error) {
if schemaRef == nil {
return schemaName, nil
}
// References will not change type names.
if schemaRef.IsReference() {
return schemaNameToTypeName(schemaName), nil
}
// Try to get x-go-name from low-level schema extensions without triggering full schema parsing.
// This is a performance optimization - we only need the extension value.
lowProxy := schemaRef.GoLow()
if lowProxy != nil {
lowSchema := lowProxy.Schema()
if lowSchema != nil && lowSchema.Extensions != nil {
for k, v := range lowSchema.Extensions.FromOldest() {
if k.Value == extGoName && v.Value != nil {
var name string
if err := v.Value.Decode(&name); err == nil && name != "" {
return name, nil
}
}
}
}
}
return schemaName, nil
}
// renameParameter generates the name for a parameter, taking x-go-name into account
func renameParameter(parameterName string, parameterRef *v3.Parameter) (string, error) {
if parameterRef.Schema != nil && parameterRef.Schema.IsReference() {
return schemaNameToTypeName(parameterName), nil
}
parameter := parameterRef
exts := extractExtensions(parameter.Extensions)
if extension, ok := exts[extGoName]; ok {
typeName, err := parseString(extension)
if err != nil {
return "", fmt.Errorf("invalid value for %q: %w", extPropGoType, err)
}
return typeName, nil
}
return schemaNameToTypeName(parameterName), nil
}
func isMediaTypeJson(mediaType string) bool {
parsed, _, err := mime.ParseMediaType(mediaType)
if err != nil {
return false
}
if parsed == "application/json" || strings.HasSuffix(parsed, "+json") {
return true
}
switch parsed {
case "application/x-ndjson", "application/ndjson",
"application/jsonl", "application/x-jsonlines":
return true
}
return false
}