Skip to content

Commit

Permalink
Add method to get the key node for an entry in a YamlMap.
Browse files Browse the repository at this point in the history
  • Loading branch information
charleskorn committed Oct 23, 2020
1 parent 5ea953c commit f4750de
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main/kotlin/com/charleskorn/kaml/YamlNode.kt
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ public data class YamlMap(val entries: Map<YamlScalar, YamlNode>, override val p
else -> throw IncorrectTypeException("Value for '$key' is not a scalar.", node.path)
}

public fun getKey(key: String): YamlScalar? = entries.keys.singleOrNull { it.content == key }

override fun withPath(newPath: YamlPath): YamlMap {
val updatedEntries = entries
.mapKeys { (k, _) -> k.withPath(replacePathOnChild(k, newPath)) }
Expand Down
27 changes: 27 additions & 0 deletions src/test/kotlin/com/charleskorn/kaml/YamlMapTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,33 @@ object YamlMapTest : Spek({
}
}

describe("getting keys of the map") {
val helloKeyPath = YamlPath.root.withMapElementKey("hello", Location(1, 1))
val helloValuePath = helloKeyPath.withMapElementValue(Location(2, 1))
val alsoKeyPath = YamlPath.root.withMapElementKey("also", Location(3, 1))
val alsoValuePath = alsoKeyPath.withMapElementValue(Location(4, 1))

val map = YamlMap(
mapOf(
YamlScalar("hello", helloKeyPath) to YamlScalar("world", helloValuePath),
YamlScalar("also", alsoKeyPath) to YamlScalar("something", alsoValuePath)
),
YamlPath.root
)

context("the key is not in the map") {
it("returns null") {
expect(map.getKey("something else")).toBe(null)
}
}

context("the key is in the map") {
it("returns the node for that key") {
expect(map.getKey("hello")).toBe(YamlScalar("hello", helloKeyPath))
}
}
}

describe("replacing its path") {
val originalPath = YamlPath.root
val originalKey1Path = originalPath.withMapElementKey("key1", Location(4, 1))
Expand Down

0 comments on commit f4750de

Please sign in to comment.