Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute shell command before compile task?

Tags:

scala

sbt

I'd like to execute a shell command - rm -r a directory - whenever my sbt project builds. This would be before compile.

Reasoning: There's a cache file that never gets updated. If I delete it before each compile, it forces the update.

Please advise.

like image 838
Christopher Ambler Avatar asked Jun 11 '14 23:06

Christopher Ambler


2 Answers

You can create a task that deletes the file:

val removeCacheTask = TaskKey[Unit]("removeCacheFile", "Deletes a cache file")
val removeCacheSettings = removeCacheTask := {
    import sys.process._
    Seq("rm", "/path/to/file") !
}

Then require that the task be run before compilation by adding these settings to your project:

Project(...).settings(
    removeCacheSettings,
    compile in Compile <<= (compile in Compile).dependsOn(removeCacheTask)
)

Source: https://groups.google.com/forum/#!topic/play-framework/4DMWSTNM4kQ


In build.sbt it would look like this:

lazy val removeCacheTask = TaskKey[Unit]("removeCacheFile", "Deletes a cache file")

removeCacheTask := {
    import sys.process._
    Seq("rm", "/path/to/file")!
}

compile in Compile <<= (compile in Compile).dependsOn(removeCacheTask)
like image 99
Michael Zajac Avatar answered Nov 18 '22 21:11

Michael Zajac


@LimbSoup answer is fine, but there're some improvements to consider.

The command to execute rm might not be available on other non-rm OSes, like Windows, so it's much safer to use sbt.IO.delete method.

Since it's about deleting files, there's the clean task that relies on def doClean(clean: Seq[File], preserve: Seq[File]): Unit method (from sbt.Defaults) and with proper changes it could also be of some help. I think it would require a new config, though.

See How to exclude files in a custom clean task? for some guidance regarding a custom clean task.

like image 38
Jacek Laskowski Avatar answered Nov 18 '22 20:11

Jacek Laskowski