Unable to run custom sbt task from AutoPlugin'

2019-06-06 19:46发布

问题:

I tried everything I could think of but running taskB still ends up with the error message that task is not defined either in */*:taskB or in */cmd:taskB if I put it in custom configuration.

Command.command("doStuff", Help.more("doStuff", "whatever")) {
      (state: State) =>
        val e = Project.extract(state)

        val taskA = taskKey[Seq[String]]("A")
        val taskB = taskKey[Seq[File]]("B")

        val cmdConfig = config("cmd")

        val newState = e.append(
          inConfig(cmdConfig)(Seq(
              taskA := {
                // do stuff
              },
              taskB := {
                // do stuff
              }
            )
          )
          , state
        )

        val result: (State, Seq[File]) = e.runTask(taskB in cmdConfig, newState)
)

When debugging it, it seems like the task are not present in structure.data where it is searched for.

回答1:

First of all, I assume you just want to call the tasks from your command, and you don't really care if they are added by modifying state in that command.

If so I'd do it more standard way, as it is done by the AutoPlugins.

import sbt._
import Keys._

object MyPlugin extends AutoPlugin {

  object autoImport {
    val taskA = taskKey[Seq[String]]("Task A")
    val taskB = taskKey[Seq[File]]("Task B")
  }

  import autoImport._

  val cmdConfig = config("cmd")

  override def projectConfigurations = Seq(cmdConfig)

  // this is optional of course, you can also enable plugin manually
  override def trigger = allRequirements

  override def projectSettings = 
    Seq(commands += doStuffCommand) ++
    inConfig(cmdConfig)(Seq(
      taskA := {
        println("TASK A")
        Seq("A", "B")
      },
      taskB := {
        println("TASK B")
        Seq(file("."))
      }
    ))


  lazy val doStuffCommand =
   Command.command("doStuff", Help.more("doStuff", "whatever")) {
     (state: State) =>
     val e = Project.extract(state)
     val (newState, bResult) = e.runTask(taskB in cmdConfig, state)
     newState
   }

}

Besides maybe you don't need a command at all, and just having some tasks calling another tasks would be simpler.