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

Time:01-12

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"))
^

CodePudding user response:

SBT addDependencyTreePlugin is defined as follow:

def addDependencyTreePlugin: Setting[Seq[ModuleID]] =
    libraryDependencies  = sbtPluginExtra(
      ModuleID("org.scala-sbt", "sbt-dependency-tree", sbtVersion.value),
      sbtBinaryVersion.value,
      scalaBinaryVersion.value
    )

To apply the conditional logic, you'll have to use something like this:

def addDependencyTreePluginCustom: Setting[Seq[ModuleID]] =
    libraryDependencies   = if (condition) Seq(sbtPluginExtra(
      ModuleID("org.scala-sbt", "sbt-dependency-tree", sbtVersion.value),
      sbtBinaryVersion.value,
      scalaBinaryVersion.value
    )) else Seq()

Note: there might exist a simpler way

CodePudding user response:

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

def conditionallyAddDependencyTreePlugin: Setting[Seq[ModuleID]] = {
  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]())
}
conditionallyAddDependencyTreePlugin

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

  •  Tags:  
  • Related