scalasbtsbt-plugin

How can I conditionally add an sbt plugin, depending on the active sbt version?


Use case: I like to be able to show the dependency tree for my sbt projects, so I have added addDependencyTreePlugin to my ~/.sbt/1.0/plugins.sbt, to make it globally available on my machine.

However, that plugin is only available since sbt 1.4.x (not sure about the exact version).

Problem: whenever I try to build a project that has an sbt.version=1.3.x or lower in the build.properties, it will fail.

Is there a way to conditionally do the addDependencyTreePlugin, based on the 'current' version of sbt that is being used by the build process?

This does not work:

addDependencyTreePlugin.filter(es => sbtVersion.value.startsWith("1.5")

sbt will complain about:

.../plugins.sbt:4: error: `value` can only be used within a task or setting macro, such as :=, +=, ++=, Def.task, or Def.setting.
addDependencyTreePlugin.filter(es => sbtVersion.value.startsWith("1.5"))
^

Solution

  • With the help of @Gaël, I have come up with:

    libraryDependencies ++= (if (VersionNumber(sbtVersion.value).matchesSemVer(SemanticSelector(">=1.4"))) {
                               println(s"Adding dependency tree plugin, sbt version is ${sbtVersion.value}")
                               Seq(
                                 sbtPluginExtra(
                                   ModuleID("org.scala-sbt", "sbt-dependency-tree", sbtVersion.value),
                                   sbtBinaryVersion.value,
                                   scalaBinaryVersion.value
                                 )
                               )
                             } else Seq[ModuleID]())
    }
    
    

    Which will work as long as the sbt version is 1.2 or later (since that is the version that introduced the VersionNumber and SemanticSelector accoding to https://stackoverflow.com/a/56587048/2037054