Search code examples
scalasbtscalatest

How do you delete a directory before running in ScalaTest/sbt/Intellij?


I am currently using ScalaTest 3.0.1 for my Scala 2.11.8 project, with sbt 0.13.18 as the build tool. The IDE is Intellij.

The project is a Spark project, and I'm using a temp directory at root/temp/ for checkpoints and warehousing. When I run the tests multiple times the checkpoints keep getting added to, eventually reaching a very large size. I want to keep the checkpoints around after the test runs so they can be used for verification, but I would like to delete them before the next run.

How can you accomplish this using sbt and ScalaTest in Intellij?

I've been looking into setting up an sbt clean with my temp directory in build.sbt but I can't seem to get it to delete the directory, and reading the documentary hints it will only delete the files sbt has created, so I abandoned that idea.

I'm currently looking into setting up my ScalaTest set up to have a BeforeAll event which will delete the directory, but I'm not sure this is the correct approach and I've been having issues getting it to work.


Solution

  • Based on https://stackoverflow.com/a/48659771/5205022 clean can include temp directory

    cleanFiles += baseDirectory.value / "temp"
    

    Another option is to create a custom task that cleans temp, for example using better-files

    lazy val deleteTestTemp = taskKey[Unit]("Delete test temp directory")
    deleteTestTemp := {
      import better.files._
      val temp = (baseDirectory.value / "temp").toScala
      if (temp.exists) temp.delete()
    }
    

    where project/plugins.sbt contains

    libraryDependencies += "com.github.pathikrit" %% "better-files" % "3.9.1"
    

    we could clean and then test like so

    deleteTestTemp;test