Ditti
Ditti

Reputation: 47

sbt run a resource generator conditionally

I have a project in which I need to generate my ui from sources to resources using a third party cli. To achieve that i did the following:

Compile / resourceGenerators += {
  // do my stuff here
}.taskValue

This works just fine, but since it is a long running task, I only want it to be executed, when I specifically say so (e.g. by a command with arguments). Thus, I'm trying to create such a command that calls run with different Compile settings. I read a lot about sbt/settings/tasks/commands etc. but im kind of lost.

Edit: As Luis Miguel Mejía Suárez has commented, there is a way to cache files and only run a task when said files have changed. Unfortunatelly this does not solve my problem, since i might have changes to the respective files, but still do not want to build them. This is due to the fact, that I have a development server running, that live reloads my ui whenever I change it. Thus, while developing, I do not need to execute the costly build-task for my ui, but rather only want recompile my scala classes and restart the application.

Upvotes: 1

Views: 186

Answers (1)

Ditti
Ditti

Reputation: 47

I finally solved my (I admit it, very specific) problem using Def.TaskDyn and a settingKey. In case someone with a similar problem comes here:

 lazy val buildUi = Def.settingKey[Boolean]("to build or not to build")

 Compile / resourceGenerators += Def.taskDyn {
      if (buildUi.value) {
        // build here and return the files
      } else {
        Def.task[Seq[File]]{Seq.empty}
      }
    }

For ease of use I also added to command aliases:

addCommandAlias("buildUiOff", "set buildUi := false")
addCommandAlias("buildUiOn", "set buildUi := true")

Edit: the project definition:

lazy val root = (project in file("."))
  .settings(
    name := "ProjectName",
    // default behaviour: building on
    buildUi := true,
...

and for running without building in sbt shell

>buildUiOff
>run

Upvotes: 1

Related Questions