Search code examples
javahocon

Java: How to merge two hocon config block into one?


I have two config

main config: main.conf

join {
  
}

required merge into main: test.conf

mergeMe {
  value = "SomeValue"
}

result:

join {
  test {
    value = "SomeValue"
  }
}

merged block named as same as the merge file`s name

I tried in kotlin:

val main = ConfigFactory.parseFile(File("main.conf")).getConfig("join")
val test = ConfigFactory.parseFile(File("test.conf")).getConfig("mergeMe")
val joined = main.withOnlyPath("test").resolveWith(test, ConfigResolveOptions.defaults()).root().render(ConfigRenderOptions.defaults()
  .setComments(true)
  .setFormatted(true)
  .setJson(false).setOriginComments(true))
val writer = FileWriter(File("main.conf"))
writer.write(joined)
writer.flush()
writer.close()

Update: atPath will wrap config with a new path, should use getConfig("mergeMe") but still doesn't work...

It doesn't work...

How to do it?


Solution

  • First get the merge block and wrap it with the source block name

    Then we can merge this two config by using Config#withFallback

    // get the config block which will contain the merge block
    val main = ConfigFactory.parseFile(File("main.conf"))
    // get merge block and wrap with contain block name
    val test = ConfigFactory.parseFile(File("test.conf")).getConfig("mergeMe").atPath("join.test")
    // merge two block into one and convert to string
    val joined = main.withFallback(test).root().render(ConfigRenderOptions.defaults()
      .setFormatted(true)
      .setJson(false)
      .setComments(true)
      .setOriginComments(false))
    val writer = FileWriter(File("main.conf"))
    writer.write(joined)
    writer.flush()
    writer.close()