从可能不存在的插件调用任务

时间:2019-05-02 11:06:25

标签: scala sbt

根据设置,我需要调用packageassembly,但是显然组装任务来自sbt-assembly插件,可能没有添加。我的任务看起来像这样

lazy val useAssembly = settingKey[Boolean]("Use assembly")

lazy val myTask = Def.task {
  val file = if (useAssembly.value) {
    // somehow call assembly here
    } else {
      (`package` in Compile).value
    }

  // Do other stuff
}

1 个答案:

答案 0 :(得分:2)

PluginsDebug.autoPluginMap可用于获取可用的自动插件。像这样创建project/AssemblyIsAvailable.scala

package sbt.internal

/** If sbt-assembly is loaded, then it should be listed as sbtassembly.AssemblyPlugin **/
object AssemblyIsAvailable {
  def apply(state: sbt.State): Boolean = {
    PluginsDebug
      .autoPluginMap(state)
      .values
      .toList
      .map(_.label)
      .exists(_.contains("ssembly"))
  }
}

然后定义dynamic task assemblyOrDefaultPackage以便能够在任务中使用条件任务评估:

lazy val assemblyOrDefaultPackage = Def.taskDyn {
  if (AssemblyIsAvailable(state.value))
    Def.task { assembly.value }
  else
    Def.task { (Compile / Keys.`package`).value }
}

现在assemblyOrDefaultPackage可以在像这样的另一个任务中求值

lazy val myTask = Def.task {
  val file = assemblyOrDefaultPackage.value
  // Do other stuff
}

或者,像这样在assemblyOrDefaultPackage中定义自定义命令build.sbt

commands += Command.command("assemblyOrDefaultPackage") { state =>
  (if (AssemblyIsAvailable(state)) "assembly" else "package") :: state
}

现在执行sbt assemblyOrDefaultPackage时应与sbt-assembly一起打包,否则退回到默认打包。