将任意类型安全配置写入 hocon 文件的标准化方法?

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

在 Scala 研究应用程序中,我使用 PureConfig 的 ConfigSource.file() 方法加载了一个 hocon 文件,它表示研究实验的默认配置。我用它来动态构建一批变体。在对特定实验变体进行一些修改后,我使用 pureconfig 的自动解析器将配置解析为 case class 结构。

此时,我想将修改后的Config作为hocon文件保存到我的实验目录中,这样我以后可以很容易地重新创建这个实验。

我一直在查看类型安全配置 README.md,但没有看到任何相关信息。显然,我可以编写一个函数来将配置树漂亮地打印成 hocon 格式,但是,有没有一种方法可以隐藏在类型安全配置中的某处 API?

这很简单:

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

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

这将创建您的配置的字符串。

有一个很大的限制:它呈现 JSON

这是相应的文档:config-writer

这是我想出的解决方案,它只依赖于 Typesafe Config 库:

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)