I am trying to add a library dependency through an sbt plugin. The dependency should be added to each sub-project per its binary scala version, so I iterate through each subproject.
private def inject(): State => State = { state =>
val extracted: Extracted = Project.extract(state)
val enrichedLibDepSettings = extracted.structure.allProjectRefs map { projRef =>
val projectScalaVersion = (scalaBinaryVersion in projRef)
libraryDependencies in projRef +=
compilerPluginOrg % (compilerPluginArtifact + "_" + projectScalaVersion.value) % compilerPluginVersion % "provided"
}
val newState = extracted.append(enrichedLibDepSettings, state)
val updateAfterLibAppend = extracted.structure.allProjectRefs map { projRef =>
println("running update: " + EvaluateTask(extracted.structure, update, newState, projRef)) }
state
}
However this is not working - the printed output shows no trace of a library dependency being appended through libraryDependencies in projRef +=
, nor is any error issued, leaving subsequent steps to fail over the missing dependency. What might be wrong with this technique?
You will ask why is this needed in the first place? why add a library dependency through an sbt plugin like that?
Although we have in sbt addCompilerPlugin
, it cannot be used for compiler plugins that have arguments (-Xplugin
with a path to a jar must be specified to scalac, for it to accept compiler plugin arguments, as far as experimentation shows). Hence we need to inject the compiler plugin via -Xplugin
after having it resolved as a library dependency (then fiddle its file path location inspecting the result of update
). Hence we do need to add a library dependency via an sbt plugin. And we further need to do this per sub-project, as a multi-project build may house sub-projects of varying scala versions - each one must have a binary compatible compiler plugin injected, in order to maintain binary compatibility.
By the way, and this might illuminate something I'm in the dark over:
When adding the library dependency in a projectSettings
override for the root project - as below - the dependency seems to resolve, but that is useless, as it will apply the same binary version to all sub-projects, which is against the nature of the task at hand (some sub-projects will naturally crash over binary incompatibility). Also I think it will override the root's settings whereas the goal here is to append a setting not to override existing settings.
object Plugin extends AutoPlugin {
override lazy val projectSettings = Seq(
...
}
A pair of clues?
Appending scalacOptions per sub-project - using the same technique - simply works.
Applying
+=
tolibraryDepenencies
above, does not even affect the output ofinspect libraryDependencies
, unlike when using the same idiom inside a anoverride lazy val projectSettings
block of anAutoPlugin
.