Sergey Gornostaev
Sergey Gornostaev

Reputation: 7777

Default arguments for run task

My project needs several arguments to start. Something like this

sbt run -DONE_ARG.0=some_big_string -DANOTHER_ARG=another_big_string -DONE_MORE_ARG=with_big_value

In most cases, these args have typical values. Can I define default values for these arguments in build.sbt if they are not set in command line?

Upvotes: 1

Views: 296

Answers (2)

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7777

I don't yet know how correct this is, but I did this and it works as expected:

lazy val defaultProperties = settingKey[Map[String, String]]("Default JVM properties")
lazy val setDefaultProps = taskKey[Unit]("Sets the default properties")

defaultProperties := Map(
  "ONE_ARG.0" -> "some_big_string",
  "ANOTHER_ARG" -> "another_big_string",
  "ONE_MORE_ARG" -> "with_big_value"
)

setDefaultProps := {
  val willFork = fork.value
  val defaults = defaultProperties.value
  val options = defaults ++ sys.props.filterKeys(defaults.keySet)

  if (!willFork) {
    options.foreach { case (k, v) => sys.props(k) = v }
  } else {
    javaOptions ++= options.map { case (k, v) => s"-D$k=$v" }.toSeq
  }
}

Compile / run := (Compile / run).dependsOn(setDefaultProps).evaluated

Thanks a lot to @cbley for the tip.

Upvotes: 2

cbley
cbley

Reputation: 4608

Since you are setting system properties, you can also check those properties inside the build and configure them if they are not there yet.

You need to set the javaOptions if fork is true. Otherwise you can simply change the system properties of the currently running JVM.

val defaultOptions = Map(
  "ONE_ARG.0" -> "some_big_string",
  "ANOTHER_ARG" -> "another_big_string",
  "ONE_MORE_ARG" -> "with_big_value"
)

// use default options, if not overriden
val options = (defaultOptions ++ sys.props.filterKeys(defaultOptions.keySet)).toMap

Compile / run := {
  val willFork = fork.value

  if (!willFork) {
    options.foreach { case (k, v) => sys.props(k) = v }
  }
  (Compile / run).inputTaskValue
}

javaOptions ++= {
  val willFork = fork.value

  if (willFork) {
    options
      .map { case (k, v) => s"-D$k=$v" }
      .toSeq
  } else {
    Seq.empty[String]
  }
}

Upvotes: 2

Related Questions