13

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.

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
  • Yes. I upvoted it for clarity, and just marked it as answered after verifying functionality as well. Exactly what I was looking for, thank you! – Christopher Ambler Jun 16 '14 at 18:06

2 Answers2

16

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)
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • 3
    Note that if you want to reference the task in a subproject, you must give a scope or the task will not be found in the subproject. Easiest way to write is `removeCacheTask in Global := { ... }` – Dirk Hillbrecht Apr 26 '16 at 07:52
  • 1
    As of sbt `1.1.1`, this approach now works: https://stackoverflow.com/a/44669226/1080804 – ecoe May 24 '18 at 17:25
6

@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.

Community
  • 1
  • 1
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420