Skip to content

Commit

Permalink
KTOR-7008 Fix toMap() to correctly handle nested values in MergedAppl…
Browse files Browse the repository at this point in the history
…icationConfig (#4453)
  • Loading branch information
marcgr9 authored Nov 5, 2024
1 parent bc412ad commit de26b15
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,20 @@ internal class MergedApplicationConfig(

override fun keys(): Set<String> = firstKeys + secondKeys

override fun toMap(): Map<String, Any?> = second.toMap() + first.toMap()
override fun toMap(): Map<String, Any?> = second.toMap().merge(first.toMap())

@Suppress("UNCHECKED_CAST")
private fun Map<String, Any?>.merge(other: Map<String, Any?>): Map<String, Any?> =
(this.keys + other.keys).associateWith { key ->
val value1 = this[key]
val value2 = other[key]

when {
value1 is Map<*, *> && value2 is Map<*, *> -> {
(value1 as Map<String, Any?>).merge(value2 as Map<String, Any?>)
}

else -> value2 ?: value1
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,22 @@ class MergedApplicationConfigTest {
assertEquals(mapOf("first" to "value1", "second" to "value3"), config.toMap())
}

@Test
fun testDeepToMap() {
val first = MapApplicationConfig(
"nested.nested-value-1" to "value1",
"nested.nested-value-2" to "value1",
)
val second = MapApplicationConfig(
"nested.nested-value-2" to "value2",
"nested.nested-value-3" to "value2",
)
val merged = first.mergeWith(second).toMap()["nested"] as Map<*, *>
assertEquals("value1", merged["nested-value-1"])
assertEquals("value2", merged["nested-value-2"])
assertEquals("value2", merged["nested-value-3"])
}

@Test
fun testMergeWith() {
val first = MapApplicationConfig(
Expand Down

0 comments on commit de26b15

Please sign in to comment.