Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a Command in Task

Tags:

sbt

Is it possible to execute a Command in Sbt Task? If so, how? as Command requires a State, how could I obtain one?

I am trying to override a default task, here's what I've tried

dist := {
  println("Turning coverage off")
  Command.process("coverageOff")
  dist.value
}

The signature of Command.process is (string, state) => _

I havent figure out where to get the State

like image 358
Qingwei Avatar asked Oct 28 '25 14:10

Qingwei


1 Answers

Yes, you can run a command within a task. Here is what I'm currently doing to achieve it. First, define the following method in your build:

/**
  * Convert the given command string to a release step action, preserving and      invoking remaining commands
  * Note: This was copied from https://github.com/sbt/sbt-release/blob/663cfd426361484228a21a1244b2e6b0f7656bdf/src/main/scala/ReleasePlugin.scala#L99-L115
  */
def runCommandAndRemaining(command: String): State => State = { st: State =>
  import sbt.complete.Parser
  @annotation.tailrec
  def runCommand(command: String, state: State): State = {
    val nextState = Parser.parse(command, state.combinedParser) match {
      case Right(cmd) => cmd()
      case Left(msg) => throw sys.error(s"Invalid programmatic input:\n$msg")
    }
    nextState.remainingCommands.toList match {
      case Nil => nextState
      case head :: tail => runCommand(head.commandLine, nextState.copy(remainingCommands = tail))
    }
  }
  runCommand(command, st.copy(remainingCommands = Nil)).copy(remainingCommands = st.remainingCommands)
}

Then, just call any command from within a task using the above defined utility, e.g., runCommandAndRemaining("+myProject/publishLocal")(state.value).

In your specific case, it should boil down to

dist := {
  val log = streams.value.log
  log.debug("Turning coverage off")
  runCommandAndRemaining("coverageOff")(state.value)
  dist.value
}

Hope this helps!

like image 156
Mirco Dotta Avatar answered Oct 30 '25 13:10

Mirco Dotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!