Skip to content

Instantly share code, notes, and snippets.

@carlosedp
Last active September 5, 2022 19:52
Scala Mill build file for ScalaScripts

Scala Mill build.sc file for Scala Scripts

This build file defines a ScalaScript trait that can be used to build Scala Scripts.

The trait adds some methods to the build process:

  • run to execute the script
  • test to call a matching script test file in the pattern scriptname.test.scala
  • native to build a native image using GraalVM in the same dir. The binary is compressed with UPX.

Requirements

import mill._
// -------- Create each script module below ----------- //
object template extends ScalaScript
object checkdeps extends ScalaScript
/** A trait defining some default tasks for Scala Scripts
*/
trait ScalaScript extends Module {
def scriptName: String = this.toString
def millSourcePath = super.millSourcePath / os.up
def scriptSource = T.sources(os.pwd / s"$scriptName.sc")
def run(args: String = "") = T.command {
os
.proc(
"scala-cli",
"run",
scriptSource().map(_.path.toString()),
"--",
args.split(" "),
)
.call(stdout = os.Inherit, stderr = os.Inherit)
}
def native = T {
println(s"Building native binary for $scriptName")
os
.proc(
"scala-cli",
"package",
"-f",
"--native-image",
scriptSource().map(_.path.toString()),
"-o",
scriptName,
"--",
"--enable-url-protocols=https",
)
.call(stdout = os.Inherit)
println(s"Compressing binary $scriptName with UPX")
os.proc("upx", "-9", scriptName).call(stdout = os.Inherit, check = false)
PathRef(os.pwd / scriptName)
}
def test() = T.command {
if (os.exists(os.pwd / s"${scriptName}.test.scala")) runTest(scriptName)
def runTest(script: String) = {
val out = os
.proc("scala-cli", "test", s"${script}.test.scala")
.call(stdout = os.Inherit)
}
}
}
// Root level tasks used to run task on all defined scripts
def allBuildNative(ev: eval.Evaluator) = T.command(runOnAll(ev, "native"))
def allTest(ev: eval.Evaluator) = T.command(runOnAll(ev, "test"))
def allRun(ev: eval.Evaluator) = T.command(runOnAll(ev, "run"))
def runOnAll(ev: eval.Evaluator, cmd: String) = T.command {
mill.main.MainModule.evaluateTasks(
ev,
Seq("__." + cmd),
mill.define.SelectMode.Separated,
)(identity)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment