Skip to content

Commit 5ffbc29

Browse files
committed
chore: optimize composed ref lookup
1 parent 1ab8b9a commit 5ffbc29

2 files changed

Lines changed: 26 additions & 21 deletions

File tree

bundler/composer_functions.go

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -117,31 +117,36 @@ func composedRefFor(
117117
return "", false
118118
}
119119

120-
longestKey := ""
121-
var longestRef *processRef
122-
for key, pr := range processedNodes.FromOldest() {
123-
if pr == nil || len(pr.location) == 0 {
124-
continue
125-
}
126-
if key == absoluteKey {
127-
continue
128-
}
129-
if !strings.HasPrefix(absoluteKey, key) {
130-
continue
131-
}
132-
suffix := strings.TrimPrefix(absoluteKey, key)
133-
if suffix == "" || !strings.HasPrefix(suffix, "/") {
134-
continue
120+
if ref, ok := composedRefFromProcessRef(processedNodes.GetOrZero(absoluteKey), ""); ok {
121+
return ref, true
122+
}
123+
124+
fragmentStart := strings.Index(absoluteKey, "#/")
125+
if fragmentStart == -1 {
126+
return "", false
127+
}
128+
129+
parentKey := absoluteKey
130+
suffix := ""
131+
for {
132+
slash := strings.LastIndex(parentKey, "/")
133+
if slash <= fragmentStart+1 {
134+
return "", false
135135
}
136-
if len(key) > len(longestKey) {
137-
longestKey = key
138-
longestRef = pr
136+
137+
suffix = parentKey[slash:] + suffix
138+
parentKey = parentKey[:slash]
139+
if ref, ok := composedRefFromProcessRef(processedNodes.GetOrZero(parentKey), suffix); ok {
140+
return ref, true
139141
}
140142
}
141-
if longestRef == nil {
143+
}
144+
145+
func composedRefFromProcessRef(pr *processRef, suffix string) (string, bool) {
146+
if pr == nil || len(pr.location) == 0 {
142147
return "", false
143148
}
144-
return "#/" + joinLocationAsJSONPointer(longestRef.location) + strings.TrimPrefix(absoluteKey, longestKey), true
149+
return "#/" + joinLocationAsJSONPointer(pr.location) + suffix, true
145150
}
146151

147152
func calculateCollisionName(name, pointer, delimiter string, iteration int) string {

bundler/composer_functions_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ func TestComposedRefFor(t *testing.T) {
304304

305305
got, ok = composedRefFor(processedNodes, "/tmp/common.yaml#/components/schemas/Thing/properties/id")
306306
assert.True(t, ok)
307-
assert.Equal(t, "#/components/schemas/ThingProperties/id", got)
307+
assert.Equal(t, "#/components/schemas/ExactMatch", got)
308308

309309
got, ok = composedRefFor(orderedmap.New[string, *processRef](), "/tmp/common.yaml#/components/schemas/Missing")
310310
assert.False(t, ok)

0 commit comments

Comments
 (0)