Skip to content

Commit 7191311

Browse files
committed
extract/improve name from ref creation (#291)
1 parent 7a95afc commit 7191311

3 files changed

Lines changed: 63 additions & 0 deletions

File tree

openapi-processor-core-parser-api/build.gradle.kts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
plugins {
2+
id("openapiprocessor.test")
23
id("openapiprocessor.library")
34
id("openapiprocessor.publish")
45
}
@@ -12,3 +13,10 @@ publishing {
1213
}
1314
}
1415
}
16+
17+
dependencies {
18+
testImplementation (platform(libs.kotest.bom))
19+
testImplementation (libs.kotest.runner)
20+
testImplementation (libs.kotest.datatest)
21+
testImplementation (libs.mockk)
22+
}

openapi-processor-core-parser-api/src/main/kotlin/io/openapiprocessor/core/parser/RefResolver.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,27 @@ class NamedSchema(val name: String?, val schema: Schema) {
1616
val hasName = name != null
1717
val hasNoName = name == null
1818
}
19+
20+
/**
21+
* Extract a name from the $ref that can be used to name classes.
22+
*
23+
* @param ref the $ref path
24+
*/
25+
fun getRefName(ref: String): String? {
26+
val split = ref.split('#')
27+
28+
if (split.size == 1) {
29+
val fileName = ref.substring(ref.lastIndexOf('/') + 1)
30+
val lastDot = fileName.lastIndexOf('.')
31+
if (lastDot == -1) {
32+
return fileName
33+
}
34+
return fileName.take(lastDot)
35+
36+
} else if (split.size > 1) {
37+
val hash = split[1]
38+
return hash.substring(hash.lastIndexOf('/') + 1)
39+
}
40+
41+
return null
42+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright 2025 https://github.com/openapi-processor/openapi-processor-base
3+
* PDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package io.openapiprocessor.core.parser
7+
8+
import io.kotest.core.spec.style.FreeSpec
9+
import io.kotest.datatest.withData
10+
import io.kotest.matchers.shouldBe
11+
12+
class RefNameSpec : FreeSpec({
13+
14+
data class TestCase(val ref: String, val expected: String)
15+
16+
withData(
17+
nameFn = { "${it.ref} -> ${it.expected}" },
18+
listOf(
19+
TestCase("foo.yaml#/Foo", "Foo"),
20+
TestCase("components/schemas/foo.yaml#/Foo", "Foo"),
21+
TestCase("Foo.yaml", "Foo"),
22+
TestCase("components/schemas/Foo.yaml", "Foo"),
23+
TestCase("Foo.yml", "Foo"),
24+
TestCase("components/schemas/Foo.yml", "Foo"),
25+
TestCase("Foo", "Foo"),
26+
TestCase("components/schemas/Foo", "Foo")
27+
)
28+
) { (ref, expected) ->
29+
getRefName(ref) shouldBe expected
30+
}
31+
})

0 commit comments

Comments
 (0)