joslinm
joslinm

Reputation: 8105

How to run different main classed based upon setting?

While building a build.sbt file, say I have two main objects:

object A {
    def main(args: Array[String]) = { println("I'm A!") }
}
object B {
    def main(args: Array[String]) = { println("I'm B!") }
}

I want to call B when environment variable RUN_B is set otherwise just run the default -- A. Two questions:

Upvotes: 1

Views: 49

Answers (2)

marios
marios

Reputation: 8996

You can directly read the environment variable using Scala code inside the mainClass task.

mainClass in run := {
    Option(System.getenv("RUN_B")) match {
        case Some(_) => Some("com.myproject.main.B")
        case None  => Some("com.myproject.main.A")
    }
}

You can inspect the setting to see if everything works:

> show run::mainClass
[info] Some(com.myproject.main.A)

Upvotes: 0

Biswanath
Biswanath

Reputation: 9185

I kind of did something similar to this with the following code

lazy val stage = sys.props.getOrElse("stage", default = "dev")
lazy val selectedMain = stage match {
    case "dev" => Some("A")
    case _  => Some("B")
}

mainClass in (Compile, run) := selectedMain

You need to set sbt -Dstage=production and then sbt run for to kick the either main A or main B.

Upvotes: 1

Related Questions