Rogach
Rogach

Reputation: 27200

How to change setting inside SBT command?

I want to have a command publish-snapshot that would run the publish task with modified version setting (that setting is to be computed at the time of execution of the command).

I figured out how to get the current value of the version inside command, and Project.runTask("task", "scope", ...) seems to be a right call for invoking the publish task.

The only thing that I'm confused with is how to modify the State instance with a new version value. All my attempts seem to do nothing to the original version setting.

My last attempt:

val printVers = TaskKey[Unit]("printvers")
val printVersTask = TaskKey[Unit]("printvers") <<= {version map println}

def publishSnapshot = Command.command("publish-snapshot") { state =>
  val newState = SessionSettings.reapply(state.get(sessionSettings).get.appendRaw(version := "???"), state)
  Project.runTask(printVers in Compile, newState, true)

  state
}

lazy val root = Project("main", file("."),
                        settings =
                          Defaults.defaultSettings ++
                          Seq(printVersTask)).settings(commands += publishSnapshot)

Is there some way to fix that behavior?

Upvotes: 36

Views: 5725

Answers (3)

Gustus
Gustus

Reputation: 111

To update an arbitrary setting from a command, do something like the following:

def updateFoo = Command.command("updateFoo") { state =>
 val extracted = Project extract state
 import extracted._
 println("'foo' set to true")
 //append returns state with updated Foo
 append(Seq(foo := true), state)
}

Upvotes: 5

Samuel Heaney
Samuel Heaney

Reputation: 773

This actually did not work for me. I'm using SBT 0.13.7

Adapting what I had to do to the above example, I had to do something like:

def publishSnapshot = Command.command("publish-snapshot") { state =>
  val extracted = Project extract state
  val newState = extracted.append(Seq(version := "newVersion"), state)
  val (s, _) = Project.extract(newState).runTask(publish in Compile, newState)
  s
}

Or alternatively do:

def publishSnapshot = Command.command("publish-snapshot") { state =>
  val newState =
    Command.process("""set version := "newVersion" """, state)
  val (s, _) = Project.extract(newState).runTask(publish in Compile, newState)
  s
}

Upvotes: 13

Rogach
Rogach

Reputation: 27200

With the help from sbt mailing list, I was able to create a solution as follows:

def publishSnapshot = Command.command("publish-snapshot") { state =>
  val extracted = Project extract state
  import extracted._
  val eVersion = getOpt(version).get // getting current version
  runTask(publish in Compile,
    append(Seq(version := "newVersion"), state),
    true
  )
  state
}

Upvotes: 21

Related Questions