'standardized method for writing an arbitrary typesafe Config to a hocon file?

in a Scala research application, i load a hocon file using PureConfig's ConfigSource.file() method, which represents the default configuration for a research experiment. i use this to build a batch of variations dynamically. after making a few modifications related to a specific experimental variation, i then parse the config into a case class structure using pureconfig's auto parser.

at this point, i would like to save the modified Config to my experiment directory as a hocon file, so i can easily re-create this experiment in the future.

i have been looking around the typesafe config README.md and haven't seen anything on this. clearly, i could write a function to pretty-print the config tree to a hocon format, but, is there a way to do this hidden somewhere in the typesafe config API?



Solution 1:[1]

This is straight forward:

  import pureconfig._
  import pureconfig.generic.auto._

  val configValue = ConfigWriter[YourCaseClass].to(component)
  val configString = configValue.render()

This will create a String of your configuration.

There is one big limitation: It renders JSON.

Here is the according documentation: config-writer

Solution 2:[2]

Here a solution I came up with that only depends on the Typesafe Config library:

val config      = ConfigFactory.parseResources("application.conf")
val otherConfig = ConfigFactory.parseResources("other.conf")

val mergedConf = config.withFallback(otherConfig)

val options = ConfigRenderOptions
  .defaults()
  .setJson(false)           // false: HOCON, true: JSON
  .setOriginComments(false) // true: add comment showing the origin of a value
  .setComments(true)        // true: keep original comment
  .setFormatted(true)       // true: pretty-print result

val result = mergedConf.root().render(options)
println(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pme
Solution 2 Björn Jacobs