-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathlocalize.go
More file actions
938 lines (829 loc) · 34.1 KB
/
Copy pathlocalize.go
File metadata and controls
938 lines (829 loc) · 34.1 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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
package openapi
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/speakeasy-api/openapi/internal/interfaces"
"github.com/speakeasy-api/openapi/internal/utils"
"github.com/speakeasy-api/openapi/jsonschema/oas3"
"github.com/speakeasy-api/openapi/marshaller"
"github.com/speakeasy-api/openapi/references"
"github.com/speakeasy-api/openapi/sequencedmap"
"github.com/speakeasy-api/openapi/system"
"gopkg.in/yaml.v3"
)
// LocalizeNamingStrategy defines how external reference files should be named when localized.
type LocalizeNamingStrategy int
const (
// LocalizeNamingPathBased uses path-based naming like "schemas-address.yaml" for conflicts
LocalizeNamingPathBased LocalizeNamingStrategy = iota
// LocalizeNamingCounter uses counter-based suffixes like "address_1.yaml" for conflicts
LocalizeNamingCounter
// LocalizeNamingCustom uses a user-provided function for naming
LocalizeNamingCustom
)
// LocalizeOptions represents the options available when localizing an OpenAPI document.
type LocalizeOptions struct {
// DocumentLocation is the location of the document being localized.
DocumentLocation string
// TargetDirectory is the directory where localized files will be written.
TargetDirectory string
// VirtualFS is the file system interface used for reading and writing files.
VirtualFS system.WritableVirtualFS
// HTTPClient is the HTTP client to use for fetching remote references.
HTTPClient system.Client
// NamingStrategy determines how external reference files are named when localized.
NamingStrategy LocalizeNamingStrategy
// CustomNamingFunc is used when NamingStrategy is LocalizeNamingCustom.
// It receives the original reference path and the resolved file content,
// and should return the desired filename for the localized file.
// The caller is responsible for ensuring filenames are unique.
CustomNamingFunc func(originalRef string, content []byte) string
}
// Localize transforms an OpenAPI document by copying all external reference files to a target directory
// and rewriting the references in the document to point to the localized files.
// This operation modifies the document in place.
//
// Why use Localize?
//
// - **Create portable document bundles**: Copy all external dependencies into a single directory
// - **Simplify deployment**: Package all API definition files together for easy distribution
// - **Offline development**: Work with API definitions without external file dependencies
// - **Version control**: Keep all related files in the same repository structure
// - **CI/CD pipelines**: Ensure all dependencies are available in build environments
// - **Documentation generation**: Bundle all files needed for complete API documentation
//
// What you'll get:
//
// Before localization:
//
// main.yaml:
// paths:
// /users:
// get:
// responses:
// '200':
// content:
// application/json:
// schema:
// $ref: "./components.yaml#/components/schemas/User"
//
// components.yaml:
// components:
// schemas:
// User:
// properties:
// address:
// $ref: "./schemas/address.yaml#/Address"
//
// After localization (files copied to target directory):
//
// target/main.yaml:
// paths:
// /users:
// get:
// responses:
// '200':
// content:
// application/json:
// schema:
// $ref: "components.yaml#/components/schemas/User"
//
// target/components.yaml:
// components:
// schemas:
// User:
// properties:
// address:
// $ref: "schemas-address.yaml#/Address"
//
// target/schemas-address.yaml:
// Address:
// type: object
// properties:
// street: {type: string}
//
// Parameters:
// - ctx: Context for cancellation and timeout control
// - doc: The OpenAPI document to localize (modified in place)
// - opts: Configuration options for localization
//
// Returns:
// - error: Any error that occurred during localization
func Localize(ctx context.Context, doc *OpenAPI, opts LocalizeOptions) error {
if doc == nil {
return nil
}
if opts.VirtualFS == nil {
opts.VirtualFS = &system.FileSystem{}
}
if opts.TargetDirectory == "" {
return errors.New("target directory is required")
}
// Storage for tracking external references and their localized names
localizeStorage := &localizeStorage{
externalRefs: sequencedmap.New[string, string](), // original ref -> localized filename
usedFilenames: make(map[string]bool), // track used filenames to avoid conflicts
resolvedContent: make(map[string][]byte), // original ref -> file content
}
// Phase 1: Discover and collect all external references
if err := discoverExternalReferences(ctx, doc, ResolveOptions{
RootDocument: doc,
TargetDocument: doc,
TargetLocation: opts.DocumentLocation,
VirtualFS: opts.VirtualFS,
HTTPClient: opts.HTTPClient,
}, localizeStorage); err != nil {
return fmt.Errorf("failed to discover external references: %w", err)
}
// Phase 2: Generate conflict-free filenames for all external references
generateLocalizedFilenames(localizeStorage, opts.NamingStrategy, opts.CustomNamingFunc)
// Phase 3: Copy external files to target directory
if err := copyExternalFiles(ctx, localizeStorage, opts); err != nil {
return fmt.Errorf("failed to copy external files: %w", err)
}
// Phase 4: Rewrite references in the document
if err := rewriteReferencesToLocalized(ctx, doc, localizeStorage); err != nil {
return fmt.Errorf("failed to rewrite references: %w", err)
}
return nil
}
type localizeStorage struct {
externalRefs *sequencedmap.Map[string, string] // original ref -> localized filename
usedFilenames map[string]bool // track used filenames to avoid conflicts
resolvedContent map[string][]byte // original ref -> file content
}
// discoverExternalReferences walks through the document and collects all external references
func discoverExternalReferences(ctx context.Context, doc *OpenAPI, opts ResolveOptions, storage *localizeStorage) error {
for item := range Walk(ctx, doc) {
err := item.Match(Matcher{
Schema: func(schema *oas3.JSONSchema[oas3.Referenceable]) error {
return discoverSchemaReference(ctx, schema, opts, storage)
},
ReferencedPathItem: func(ref *ReferencedPathItem) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedParameter: func(ref *ReferencedParameter) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedExample: func(ref *ReferencedExample) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedRequestBody: func(ref *ReferencedRequestBody) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedResponse: func(ref *ReferencedResponse) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedHeader: func(ref *ReferencedHeader) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedCallback: func(ref *ReferencedCallback) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedLink: func(ref *ReferencedLink) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
ReferencedSecurityScheme: func(ref *ReferencedSecurityScheme) error {
return discoverGenericReference(ctx, ref, opts, storage)
},
})
if err != nil {
return fmt.Errorf("failed to discover references at %s: %w", item.Location.ToJSONPointer().String(), err)
}
}
return nil
}
// discoverSchemaReference handles discovery of JSON schema references
func discoverSchemaReference(ctx context.Context, schema *oas3.JSONSchema[oas3.Referenceable], opts ResolveOptions, storage *localizeStorage) error {
if !schema.IsReference() {
return nil
}
ref, classification := handleLocalizeReference(schema.GetRef(), "", opts.TargetLocation)
if classification == nil || classification.IsFragment {
return nil // Skip internal references
}
// Get the URI part (file path) from the reference
refObj := references.Reference(ref)
filePath := refObj.GetURI()
// For URLs, use the full reference as the key, for file paths normalize
var normalizedFilePath string
if classification.Type == utils.ReferenceTypeURL {
normalizedFilePath = ref // Use the full URL as the key
} else {
normalizedFilePath = normalizeFilePath(filePath)
}
if _, err := schema.Resolve(ctx, opts); err != nil {
return fmt.Errorf("failed to resolve external schema reference %s: %w", ref, err)
}
// Only store the file content if we haven't processed this file before
if !storage.externalRefs.Has(normalizedFilePath) {
// Get the cached reference document content that was loaded during resolution
resolutionInfo := schema.GetReferenceResolutionInfo()
if resolutionInfo != nil {
storage.externalRefs.Set(normalizedFilePath, "") // Will be filled in filename generation phase
if data, found := opts.RootDocument.GetCachedReferenceDocument(resolutionInfo.AbsoluteDocumentPath); found {
storage.resolvedContent[normalizedFilePath] = data
} else {
return fmt.Errorf("failed to get cached content for reference %s", normalizedFilePath)
}
} else {
return fmt.Errorf("failed to get resolution info for reference %s", normalizedFilePath)
}
}
// Get the resolved schema and recursively discover references within it
resolvedSchema := schema.GetResolvedSchema()
if resolvedSchema != nil {
// Convert back to referenceable schema for recursive discovery
resolvedRefSchema := (*oas3.JSONSchema[oas3.Referenceable])(resolvedSchema)
targetDocInfo := schema.GetReferenceResolutionInfo()
// Recursively discover references within the resolved schema using oas3.Walk
for item := range oas3.Walk(ctx, resolvedRefSchema) {
err := item.Match(oas3.SchemaMatcher{
Schema: func(s *oas3.JSONSchema[oas3.Referenceable]) error {
return discoverSchemaReference(ctx, s, ResolveOptions{
RootDocument: opts.RootDocument,
TargetDocument: targetDocInfo.ResolvedDocument,
TargetLocation: targetDocInfo.AbsoluteDocumentPath,
VirtualFS: opts.VirtualFS,
HTTPClient: opts.HTTPClient,
}, storage)
},
})
if err != nil {
return fmt.Errorf("failed to discover nested schema reference: %w", err)
}
}
}
return nil
}
// discoverGenericReference handles discovery of generic OpenAPI component references
func discoverGenericReference[T any, V interfaces.Validator[T], C marshaller.CoreModeler](ctx context.Context, ref *Reference[T, V, C], opts ResolveOptions, storage *localizeStorage) error {
if ref == nil || !ref.IsReference() {
return nil
}
refStr, classification := handleLocalizeReference(ref.GetReference(), "", opts.TargetLocation)
if classification == nil || classification.IsFragment {
return nil // Skip internal references
}
// Get the URI part (file path) from the reference
refObj := references.Reference(refStr)
filePath := refObj.GetURI()
// For URLs, use the full reference as the key, for file paths normalize
var normalizedFilePath string
if classification.Type == utils.ReferenceTypeURL {
normalizedFilePath = refStr // Use the full URL as the key
} else {
normalizedFilePath = normalizeFilePath(filePath)
}
// Check if we've already processed this file
if storage.externalRefs.Has(normalizedFilePath) {
return nil
}
// Resolve the external reference to ensure it's valid
_, err := ref.Resolve(ctx, opts)
if err != nil {
return fmt.Errorf("failed to resolve external reference %s: %w", refStr, err)
}
// Get the cached reference document content that was loaded during resolution
resolutionInfo := ref.GetReferenceResolutionInfo()
if resolutionInfo != nil {
storage.externalRefs.Set(normalizedFilePath, "") // Will be filled in filename generation phase
if data, found := opts.RootDocument.GetCachedReferenceDocument(resolutionInfo.AbsoluteDocumentPath); found {
storage.resolvedContent[normalizedFilePath] = data
} else {
return fmt.Errorf("failed to get cached content for reference %s", normalizedFilePath)
}
} else {
return fmt.Errorf("failed to get resolution info for reference %s", normalizedFilePath)
}
// Get the resolved object and recursively discover references within it
resolvedValue := ref.GetObject()
if resolvedValue != nil {
targetDocInfo := ref.GetReferenceResolutionInfo()
resolveOpts := ResolveOptions{
RootDocument: opts.RootDocument,
TargetDocument: targetDocInfo.ResolvedDocument,
TargetLocation: targetDocInfo.AbsoluteDocumentPath,
VirtualFS: opts.VirtualFS,
HTTPClient: opts.HTTPClient,
}
// Recursively discover references within the resolved object using Walk
for item := range Walk(ctx, resolvedValue) {
err := item.Match(Matcher{
Schema: func(s *oas3.JSONSchema[oas3.Referenceable]) error {
return discoverSchemaReference(ctx, s, resolveOpts, storage)
},
ReferencedPathItem: func(r *ReferencedPathItem) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedParameter: func(r *ReferencedParameter) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedExample: func(r *ReferencedExample) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedRequestBody: func(r *ReferencedRequestBody) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedResponse: func(r *ReferencedResponse) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedHeader: func(r *ReferencedHeader) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedCallback: func(r *ReferencedCallback) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedLink: func(r *ReferencedLink) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
ReferencedSecurityScheme: func(r *ReferencedSecurityScheme) error {
return discoverGenericReference(ctx, r, resolveOpts, storage)
},
})
if err != nil {
return fmt.Errorf("failed to discover nested reference: %w", err)
}
}
}
return nil
}
// generateLocalizedFilenames creates conflict-free filenames for all external references
func generateLocalizedFilenames(storage *localizeStorage, strategy LocalizeNamingStrategy, customNamingFunc func(string, []byte) string) {
// Custom naming: delegate entirely to the caller's function
if strategy == LocalizeNamingCustom && customNamingFunc != nil {
for ref := range storage.externalRefs.All() {
content := storage.resolvedContent[ref]
filename := customNamingFunc(ref, content)
storage.externalRefs.Set(ref, filename)
storage.usedFilenames[filename] = true
}
return
}
// First pass: collect all base filenames to detect conflicts
baseFilenames := make(map[string][]string) // base filename -> list of full paths
for ref := range storage.externalRefs.All() {
refObj := references.Reference(ref)
filePath := refObj.GetURI()
baseFilename := filepath.Base(filePath)
baseFilenames[baseFilename] = append(baseFilenames[baseFilename], ref)
}
// Second pass: assign filenames based on conflicts (using deterministic order from sequencedmap)
processedBaseNames := make(map[string]bool) // track which base names we've processed
for ref := range storage.externalRefs.All() {
refObj := references.Reference(ref)
filePath := refObj.GetURI()
baseFilename := filepath.Base(filePath)
conflictingRefs := baseFilenames[baseFilename]
var filename string
if len(conflictingRefs) == 1 {
// No conflicts, use simple filename
filename = baseFilename
} else {
// Has conflicts - for path-based naming, first file gets simple name, others get path prefix
if strategy == LocalizeNamingPathBased && !processedBaseNames[baseFilename] {
// First file with this base name gets the simple name
filename = baseFilename
processedBaseNames[baseFilename] = true
} else {
// Subsequent files or counter strategy get modified names
filename = generateLocalizedFilenameWithConflictDetection(ref, strategy, baseFilenames, storage.usedFilenames)
}
}
storage.externalRefs.Set(ref, filename)
storage.usedFilenames[filename] = true
}
}
// generateLocalizedFilenameWithConflictDetection creates a localized filename with proper conflict detection
func generateLocalizedFilenameWithConflictDetection(ref string, strategy LocalizeNamingStrategy, baseFilenames map[string][]string, usedFilenames map[string]bool) string {
// Get the file path from the reference
refObj := references.Reference(ref)
filePath := refObj.GetURI()
baseFilename := filepath.Base(filePath)
// Check if there are conflicts for this base filename
conflictingRefs := baseFilenames[baseFilename]
hasConflicts := len(conflictingRefs) > 1
switch strategy {
case LocalizeNamingPathBased:
return generatePathBasedFilenameWithConflictDetection(filePath, hasConflicts, usedFilenames)
case LocalizeNamingCounter:
return generateCounterBasedFilename(filePath, usedFilenames)
default:
return generatePathBasedFilenameWithConflictDetection(filePath, hasConflicts, usedFilenames)
}
}
// generatePathBasedFilenameWithConflictDetection creates filenames with smart conflict resolution
func generatePathBasedFilenameWithConflictDetection(filePath string, _ bool, usedFilenames map[string]bool) string {
// Check if this is a URL - if so, extract filename from URL path
// Error classifying reference is not fatal - we fall through to file path handling
if classification, err := utils.ClassifyReference(filePath); err == nil && classification.Type == utils.ReferenceTypeURL {
// For URLs, extract the filename from the URL path
if lastSlash := strings.LastIndex(filePath, "/"); lastSlash != -1 {
filename := filePath[lastSlash+1:]
// Remove any query parameters or fragments
if queryIdx := strings.Index(filename, "?"); queryIdx != -1 {
filename = filename[:queryIdx]
}
if fragIdx := strings.Index(filename, "#"); fragIdx != -1 {
filename = filename[:fragIdx]
}
return filename
}
// Fallback to a safe filename if we can't extract from URL
return "remote-schema.yaml"
}
// Clean the path and get the base filename
cleanPath := filepath.Clean(filePath)
// Remove leading "./" if present
cleanPath = strings.TrimPrefix(cleanPath, "./")
// Handle parent directory references by replacing ".." with "parent"
cleanPath = strings.ReplaceAll(cleanPath, "..", "parent")
// Get the directory and filename
dir := filepath.Dir(cleanPath)
filename := filepath.Base(cleanPath)
// For path-based naming, always use directory prefix if there's a directory
// This ensures consistent naming regardless of processing order
var result string
if dir == "." || dir == "" {
// No directory, use simple filename
result = filename
} else {
// Replace path separators with hyphens
dirPart := strings.ReplaceAll(dir, string(filepath.Separator), "-")
dirPart = strings.ReplaceAll(dirPart, "/", "-") // Handle forward slashes on Windows
dirPart = strings.ReplaceAll(dirPart, "\\", "-") // Handle backslashes on Unix
ext := filepath.Ext(filename)
baseName := strings.TrimSuffix(filename, ext)
result = dirPart + "-" + baseName + ext
}
// Ensure uniqueness
originalResult := result
counter := 1
for usedFilenames[result] {
ext := filepath.Ext(originalResult)
baseName := strings.TrimSuffix(originalResult, ext)
result = fmt.Sprintf("%s_%d%s", baseName, counter, ext)
counter++
}
return result
}
// generateCounterBasedFilename creates filenames like "address_1.yaml" for conflicts
func generateCounterBasedFilename(filePath string, usedFilenames map[string]bool) string {
filename := filepath.Base(filePath)
// Ensure uniqueness
result := filename
counter := 1
for usedFilenames[result] {
ext := filepath.Ext(filename)
baseName := strings.TrimSuffix(filename, ext)
result = fmt.Sprintf("%s_%d%s", baseName, counter, ext)
counter++
}
return result
}
// copyExternalFiles copies all external reference files to the target directory
func copyExternalFiles(_ context.Context, storage *localizeStorage, opts LocalizeOptions) error {
for ref, localizedFilename := range storage.externalRefs.All() {
content := storage.resolvedContent[ref]
// Rewrite internal references within the copied file
updatedContent, err := rewriteInternalReferences(content, ref, storage)
if err != nil {
return fmt.Errorf("failed to rewrite internal references in %s: %w", ref, err)
}
targetPath := filepath.Join(opts.TargetDirectory, localizedFilename)
if err := opts.VirtualFS.WriteFile(targetPath, updatedContent, 0o644); err != nil {
return fmt.Errorf("failed to write localized file %s: %w", targetPath, err)
}
}
return nil
}
// rewriteInternalReferences updates references within a copied file to point to other localized files
func rewriteInternalReferences(content []byte, originalRef string, storage *localizeStorage) ([]byte, error) {
// Parse the YAML content
var node yaml.Node
if err := yaml.Unmarshal(content, &node); err != nil {
return nil, fmt.Errorf("failed to parse YAML content: %w", err)
}
// Walk through the YAML and update references
if err := rewriteYAMLReferences(&node, originalRef, storage); err != nil {
return nil, fmt.Errorf("failed to rewrite YAML references: %w", err)
}
// Marshal back to YAML
updatedContent, err := yaml.Marshal(&node)
if err != nil {
return nil, fmt.Errorf("failed to marshal updated YAML: %w", err)
}
return updatedContent, nil
}
// rewriteYAMLReferences recursively walks through YAML nodes and updates $ref values
func rewriteYAMLReferences(node *yaml.Node, originalRef string, storage *localizeStorage) error {
if node == nil {
return nil
}
switch node.Kind {
case yaml.DocumentNode:
for _, child := range node.Content {
if err := rewriteYAMLReferences(child, originalRef, storage); err != nil {
return err
}
}
case yaml.MappingNode:
for i := 0; i < len(node.Content); i += 2 {
keyNode := node.Content[i]
valueNode := node.Content[i+1]
// Check if this is a $ref key
if keyNode.Kind == yaml.ScalarNode && keyNode.Value == "$ref" && valueNode.Kind == yaml.ScalarNode {
// Update the reference value
updatedRef := rewriteReferenceValue(valueNode.Value, originalRef, storage)
valueNode.Value = updatedRef
} else {
// Recursively process the value
if err := rewriteYAMLReferences(valueNode, originalRef, storage); err != nil {
return err
}
}
}
case yaml.SequenceNode:
for _, child := range node.Content {
if err := rewriteYAMLReferences(child, originalRef, storage); err != nil {
return err
}
}
}
return nil
}
// rewriteReferenceValue updates a single reference value to point to localized files
func rewriteReferenceValue(refValue, originalRef string, storage *localizeStorage) string {
// If this is an internal reference (starts with #), leave it as-is
if strings.HasPrefix(refValue, "#") {
return refValue
}
// Resolve the reference relative to the original file
resolvedRef := resolveRelativeReference(refValue, originalRef)
// Extract the file path from the resolved reference
refObj := references.Reference(resolvedRef)
filePath := refObj.GetURI()
// For URLs, use the full reference as the key, for file paths normalize
var normalizedFilePath string
// Error classifying reference is not fatal - we fall through to file path handling
if classification, err := utils.ClassifyReference(resolvedRef); err == nil && classification.Type == utils.ReferenceTypeURL {
normalizedFilePath = resolvedRef // Use the full URL as the key
} else {
normalizedFilePath = normalizeFilePath(filePath)
}
// Check if we have a localized version of this file
if localizedFilename, exists := storage.externalRefs.Get(normalizedFilePath); exists {
// Build new reference with localized filename
if refObj.HasJSONPointer() {
return localizedFilename + "#" + string(refObj.GetJSONPointer())
}
return localizedFilename
}
// If not found by full URL, try to find by just the reference value itself
// This handles cases where the reference value is already a full URL
if localizedFilename, exists := storage.externalRefs.Get(refValue); exists {
// Build new reference with localized filename
refObj := references.Reference(refValue)
if refObj.HasJSONPointer() {
return localizedFilename + "#" + string(refObj.GetJSONPointer())
}
return localizedFilename
}
// If not found in our localized references, return as-is
return refValue
}
// resolveRelativeReference resolves a relative reference against a base reference
func resolveRelativeReference(ref, baseRef string) string {
// Parse base reference to get the directory
baseRefObj := references.Reference(baseRef)
baseURI := baseRefObj.GetURI()
// Parse the reference
refObj := references.Reference(ref)
refPath := refObj.GetURI()
// Check if the base reference is a URL
// Error classifying base reference is not fatal - we fall through to file path handling
if classification, err := utils.ClassifyReference(baseURI); err == nil && classification.Type == utils.ReferenceTypeURL {
// For URLs, use URL path joining instead of file path joining
var resolvedPath string
switch {
case strings.HasPrefix(refPath, "./"):
// Relative reference - resolve against base URL directory
baseDir := baseURI
if lastSlash := strings.LastIndex(baseURI, "/"); lastSlash != -1 {
baseDir = baseURI[:lastSlash+1]
}
resolvedPath = baseDir + strings.TrimPrefix(refPath, "./")
case strings.HasPrefix(refPath, "/"):
// Absolute path reference - use as-is relative to URL root
if idx := strings.Index(baseURI, "://"); idx != -1 {
if hostEnd := strings.Index(baseURI[idx+3:], "/"); hostEnd != -1 {
resolvedPath = baseURI[:idx+3+hostEnd] + refPath
} else {
resolvedPath = baseURI + refPath
}
} else {
resolvedPath = refPath
}
default:
// Simple filename - resolve against base URL directory
baseDir := baseURI
if lastSlash := strings.LastIndex(baseURI, "/"); lastSlash != -1 {
baseDir = baseURI[:lastSlash+1]
}
resolvedPath = baseDir + refPath
}
// Add back the fragment if present
if refObj.HasJSONPointer() {
return resolvedPath + "#" + string(refObj.GetJSONPointer())
}
return resolvedPath
} else {
// For file paths, use the original file path logic
baseDir := filepath.Dir(baseURI)
// Resolve the path
resolvedPath := filepath.Join(baseDir, refPath)
resolvedPath = filepath.Clean(resolvedPath)
// Add back the fragment if present
if refObj.HasJSONPointer() {
return resolvedPath + "#" + string(refObj.GetJSONPointer())
}
return resolvedPath
}
}
// rewriteReferencesToLocalized updates all references in the document to point to localized files
func rewriteReferencesToLocalized(ctx context.Context, doc *OpenAPI, storage *localizeStorage) error {
for item := range Walk(ctx, doc) {
err := item.Match(Matcher{
Schema: func(schema *oas3.JSONSchema[oas3.Referenceable]) error {
if schema.IsReference() {
ref := schema.GetRef()
refObj := ref
filePath := refObj.GetURI()
// For URLs, use the full reference as the key, for file paths normalize
var normalizedFilePath string
// Error classifying reference is not fatal - we fall through to file path handling
if classification, err := utils.ClassifyReference(string(ref)); err == nil && classification.Type == utils.ReferenceTypeURL {
normalizedFilePath = string(ref) // Use the full URL as the key
} else {
normalizedFilePath = normalizeFilePath(filePath)
}
if localizedFilename, exists := storage.externalRefs.Get(normalizedFilePath); exists {
// Build new reference with localized filename
if refObj.HasJSONPointer() {
newRef := localizedFilename + "#" + string(refObj.GetJSONPointer())
*schema.GetLeft().Ref = references.Reference(newRef)
} else {
*schema.GetLeft().Ref = references.Reference(localizedFilename)
}
}
}
return nil
},
ReferencedPathItem: func(ref *ReferencedPathItem) error {
return updateGenericReference(ref, storage)
},
ReferencedParameter: func(ref *ReferencedParameter) error {
return updateGenericReference(ref, storage)
},
ReferencedExample: func(ref *ReferencedExample) error {
return updateGenericReference(ref, storage)
},
ReferencedRequestBody: func(ref *ReferencedRequestBody) error {
return updateGenericReference(ref, storage)
},
ReferencedResponse: func(ref *ReferencedResponse) error {
return updateGenericReference(ref, storage)
},
ReferencedHeader: func(ref *ReferencedHeader) error {
return updateGenericReference(ref, storage)
},
ReferencedCallback: func(ref *ReferencedCallback) error {
return updateGenericReference(ref, storage)
},
ReferencedLink: func(ref *ReferencedLink) error {
return updateGenericReference(ref, storage)
},
ReferencedSecurityScheme: func(ref *ReferencedSecurityScheme) error {
return updateGenericReference(ref, storage)
},
})
if err != nil {
return fmt.Errorf("failed to update reference at %s: %w", item.Location.ToJSONPointer().String(), err)
}
}
return nil
}
// updateGenericReference updates a generic reference to point to the localized filename
func updateGenericReference[T any, V interfaces.Validator[T], C marshaller.CoreModeler](ref *Reference[T, V, C], storage *localizeStorage) error {
if ref == nil || !ref.IsReference() {
return nil
}
refObj := ref.GetReference()
filePath := refObj.GetURI()
// For URLs, use the full reference as the key, for file paths normalize
var normalizedFilePath string
// Error classifying reference is not fatal - we fall through to file path handling
if classification, err := utils.ClassifyReference(string(refObj)); err == nil && classification.Type == utils.ReferenceTypeURL {
normalizedFilePath = string(refObj) // Use the full URL as the key
} else {
normalizedFilePath = normalizeFilePath(filePath)
}
if localizedFilename, exists := storage.externalRefs.Get(normalizedFilePath); exists {
// Build new reference with localized filename
if refObj.HasJSONPointer() {
newRef := localizedFilename + "#" + string(refObj.GetJSONPointer())
*ref.Reference = references.Reference(newRef)
} else {
*ref.Reference = references.Reference(localizedFilename)
}
}
return nil
}
// normalizeFilePath normalizes a file path for consistent handling
func normalizeFilePath(filePath string) string {
// Check if this is a URL - if so, don't apply file path normalization
// Error classifying reference is not fatal - we treat it as a file path
if classification, err := utils.ClassifyReference(filePath); err == nil && classification.Type == utils.ReferenceTypeURL {
return filePath // Return URLs as-is
}
// Clean and normalize the file path
cleanPath := filepath.Clean(filePath)
// Remove leading "./" if present
cleanPath = strings.TrimPrefix(cleanPath, "./")
return cleanPath
}
// handleLocalizeReference processes a reference for localization by preserving relative path structures.
// This function represents the original reference handling behavior and is specifically designed
// for the Localize operation, which needs to:
// - Preserve the original document structure and path relationships during file copying
// - Maintain the original path separators (Windows vs Unix) for generated files
// - Support relative path manipulation when copying nested referenced files
//
// This differs from handleReference (used in Bundle), which:
// - Normalizes all paths to absolute with forward slashes for use as unique map keys
// - Doesn't need to preserve original path structure since everything goes into components
// - Requires consistent path format for deduplication and reference rewriting
//
// Key behavioral differences:
// 1. Path normalization: handleLocalizeReference preserves path style (Windows/Unix),
// while handleReference normalizes to forward slashes
// 2. Path manipulation: handleLocalizeReference supports parentLocation for relative
// path calculations when processing nested references
// 3. Return format: handleLocalizeReference may return relative paths based on context,
// while handleReference always returns absolute paths when targetLocation is provided
//
// Parameters:
// - ref: The reference to process
// - parentLocation: The location of the parent document (for relative path calculations)
// - targetLocation: The location of the current document containing this reference
//
// Returns:
// - string: The processed reference path (may be relative or absolute depending on context)
// - *utils.ReferenceClassification: Classification of the reference type, or nil if invalid
func handleLocalizeReference(ref references.Reference, parentLocation, targetLocation string) (string, *utils.ReferenceClassification) {
r := ref.String()
// Check if this is an external reference using the utility function
classification, err := utils.ClassifyReference(r)
if err != nil {
return "", nil // Invalid reference, skip
}
// For URLs, don't do any path manipulation - return as-is
if classification.Type == utils.ReferenceTypeURL {
return r, classification
}
if parentLocation != "" {
relPath, err := filepath.Rel(filepath.Dir(parentLocation), targetLocation)
if err == nil {
if classification.IsFragment {
r = relPath + r
} else {
if ref.GetURI() != "" {
r = filepath.Join(filepath.Dir(relPath), r)
} else {
r = filepath.Join(relPath, r)
}
}
}
// Error getting relative path is not fatal - fall back to using the original reference
// This can happen when paths are on different drives (Windows) or other path incompatibilities
// convert paths back to original separators
// detect original separators from the original reference
pathStyle := detectPathStyle(ref.String())
switch pathStyle {
case "windows":
r = strings.ReplaceAll(r, "/", "\\")
default:
r = strings.ReplaceAll(r, "\\", "/")
}
cl, err := utils.ClassifyReference(r)
if err == nil {
classification = cl
}
// Error re-classifying is not fatal - we keep using the previous classification
// This maintains backward compatibility and allows processing to continue
}
return r, classification
}