Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access object both from build.sbt and application code

Tags:

scala

sbt

I need to access a build.sbt variable from application code, or define some class/object accessible both from the build.sbt and the application code. How to do this?

For example, build.sbt:

propName := "hello"

MyApp.scala:

buildSbtProvider.getVariable("propName")

Or build.sbt:

propName := CommonObject.hello

MyApp.scala:

propName = CommonObject.hello
like image 880
Igorock Avatar asked Dec 24 '22 10:12

Igorock


2 Answers

You may want to use the sbt-buildinfo plugin for this.

As stated in the documentation, you just have to add a few definition to your build

lazy val root = (project in file(".")).
  enablePlugins(BuildInfoPlugin).
  settings(
    buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion),
    buildInfoPackage := "hello"
  )

And this would generate the following class that you can use after reload:

package hello

import java.io.File
import java.lang._
import java.net.URL
import scala._; import Predef._

/** This object was generated by sbt-buildinfo. */
case object BuildInfo {
  /** The value is "helloworld". */
  val name: String = "helloworld"
  /** The value is "0.1-SNAPSHOT". */
  val version: String = "0.1-SNAPSHOT"
  /** The value is "2.10.3". */
  val scalaVersion: String = "2.10.3"
  /** The value is "0.13.2". */
  val sbtVersion: String = "0.13.2"
  override val toString: String = "name: %s, version: %s, scalaVersion: %s, sbtVersion: %s" format (name, version, scalaVersion, sbtVersion)
}

You can refer to the README file of the project for more details.

like image 190
stefanobaghino Avatar answered Dec 25 '22 22:12

stefanobaghino


A possibility would be to use the default src/main/resources/application.conf file. This file is often used to set properties for the application at run time. And just discovered you can read it from build.sbt (see this answer)

So let's say this application.conf has this content:

{ name=my_app_name }

Then you can get the name from within build.sbt:

import java.util.Properties

val appProperties = settingKey[Properties]("The application properties")

appProperties := {
  val prop = new Properties()
  IO.load(prop, new File("src/main/resources/application.conf"))
  prop
}

name := appProperties.value.getProperty("name")

On the application side, this is very classic:

import com.typesafe.config.ConfigFactory

var conf = ConfigFactory.load

println(conf.getString("name"))
like image 23
Xavier Guihot Avatar answered Dec 26 '22 00:12

Xavier Guihot