Noel Yap
Noel Yap

Reputation: 19768

How to execute Scala script from Gradle?

I have a Scala script that looks something like:

#!/bin/sh
PATH=${SCALA_HOME}:${PATH}

exec scala "$0" "$@"
!#

Console.println("Hello, world!")

Is there some way in Gradle to set the version of Scala to be used, have it implicitly set SCALA_HOME, and execute the script?

Upvotes: 1

Views: 655

Answers (3)

F. P. Freely
F. P. Freely

Reputation: 1124

Gradle has an Exec task in which you can set the environment to be passed to the new process. You could pass SCALA_HOME through that.

Upvotes: 0

F. P. Freely
F. P. Freely

Reputation: 1124

Here is an example of executing Scala from Gradle. It is a nascent attempt to build a plugin using Scalafmt. Of note is how nasty it is to use static values.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.geirsson:scalafmt-core_2.11:0.4.2'
    }
}

task scalafmt << {
    String target = "object FormatMe { List(Split(Space, 0).withPolicy(SingleLineBlock(close)), Split(Newline, 1).withPolicy{ case Decision(t@FormatToken(_, `close`, _), s) => Decision(t, List(Split(Newline, 0)))}.withIndent(2, close, Right)) }"
    def config = org.scalafmt.config.ScalafmtConfig$.MODULE$.default
    def range = scala.collection.immutable.Set$EmptySet$.MODULE$
    println org.scalafmt.Scalafmt.format(target, config, range).formattedCode()
}

I know this is not quite on topic but I couldn't find anywhere else to put this and I hope it is of some value to people who ended up here for the same reason I did.

Upvotes: 1

Peter Niederwieser
Peter Niederwieser

Reputation: 123910

There is no built-in feature for this. The way to tackle this is to declare two tasks: A Copy task that downloads the Scala distribution and unpacks it to a local directory, and an Exec task that sets the SCALA_HOME environment variable to the copy task's output directory and executes your script.

Upvotes: 1

Related Questions