2

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?

2 Answers2

4

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)
Björn Jacobs
  • 4,033
  • 4
  • 28
  • 47
3

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

pme
  • 14,156
  • 3
  • 52
  • 95
  • ah, missed this. JSON isn't ideal but mostly i need this for reference in case i need to confirm algorithm parameters or re-create an experiment, and it's fine if i have to transform these manually to HOCON for as often as that should happen (hopefully _never_). thanks! – Rob Fitzgerald Jul 11 '20 at 21:22