navige
navige

Reputation: 2517

Rename file using sbt-assembly

I have a scala project that uses the ConfigFactory to set up the application configurations. For building I use sbt (together with sbt-assembly).

Depending on whether I create an assembly with sbt-assembly or whether I just run the project, I would like to use different config files (application.conf when running the project, assembly.conf when running the assembly of the project).

I thought of using the assemblyMergeStrategy for this purpose: When assembling the jar, I would discard the application.conf and rename assembly.conf. My idea was something like:

assemblyMergeStrategy in assembly := {
  case PathList("application.conf") => MergeStrategy.discard
  case PathList("assembly.conf") => MergeStrategy.rename
  ...
}

By this I would like to achieve is that when assembling the jar, the file assembly.conf is renamed to application.conf and is therefore used by ConfigFactory, whereas the original application.conf is discarded.

The code above obviously does not work, as I cannot specify to what filename assembly.conf should be renamed to. How can I achieve this?

Upvotes: 3

Views: 1398

Answers (1)

himos
himos

Reputation: 56

You need to define your own MergeStrategy(in project directory) that will rename files to application.conf and then redefine assemblyMergeStrategy in assembly to discard original application.conf and apply MyMergeStrategy to assembly.conf:

import java.io.File   
import sbtassembly.MergeStrategy

class MyMergeStrategy extends MergeStrategy{
  override def name: String = "Rename to application.conf"

  override def apply(tempDir: File, path: String, files: Seq[File]): Either[String, Seq[(File, String)]] = {
    Right(files.map(_ -> "application.conf"))
  }
}

And then use in build.sbt:

val root = (project in file(".")).settings(Seq(
  assemblyMergeStrategy in assembly := {
    case PathList("application.conf") => MergeStrategy.discard
    case PathList("assembly.conf") => new MyMergeStrategy()
    case x =>
      val oldStrategy = (assemblyMergeStrategy in assembly).value
      oldStrategy(x)
  }
))

This will do just for your case but for more complicated cases I would read how they do it in sbt-native-packager: https://www.scala-sbt.org/sbt-native-packager/recipes/package_configuration.html

Upvotes: 2

Related Questions