Search code examples
scalasbtsbt-native-packagersbt-release

How to add a custom command in sbt?


I'm trying to add a new command to my sbt.

In my build.sbt I have

lazy val root = (project in file(".")).settings(mySuperDuperCommand)

In a sibling file mySuperDuperCommands.sbt I have

lazy val mySuperDuperTaskKey = TaskKey[Unit]("mySuperDuperCommand")

lazy val mySuperDuperCommand := { ... do *amazing* stuff ... }

It gives me the error cannot resolve symbol "mySuperDuperCommand" inside build.sbt. How to solve this conondrum?


Solution

  • If you like to stay with a single build file then, in your build.sbt you can do:

    lazy val mySuperDuperTask = TaskKey[Unit]("mySuperDuperCommand")
    lazy val root = (project in file(".")).settings(mySuperDuperTask:= { ... })
    

    of course by replacing ... with your own task implementation.

    Alternatively, if you prefer to use two different files you can do something like this:

    In project/Build.scala you can define your Task. For example:

    import sbt._
    import Keys._
    
    object ProjectBuild {
        lazy val mySuperDuperTask = TaskKey[Unit]("mySuperDuperCommand", "Prints hello.")
        def buildSettings = Seq(mySuperDuperTask:={println("Hello")})
    }
    

    Then, in your build.sbt you can write:

    import ProjectBuild._
    lazy val root = (project in file(".")).settings(ProjectBuild.buildSettings : _*)
    

    Then you can invoke your proper sbt mySuperDuperCommand.

    Hope it helps!