javascalatypesafe-configpureconfig

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

  • 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)