问题
Is it possible to add a Scala compiler plugin only when compiling test sources?
When a compiler plugin is added by calling SBT's addCompilerPlugin
then a library dependency is added. The relevant methods are:
/** Transforms `dependency` to be in the auto-compiler plugin configuration. */
def compilerPlugin(dependency: ModuleID): ModuleID =
dependency.withConfigurations(Some("plugin->default(compile)"))
/** Adds `dependency` to `libraryDependencies` in the auto-compiler plugin configuration. */
def addCompilerPlugin(dependency: ModuleID): Setting[Seq[ModuleID]] =
libraryDependencies += compilerPlugin(dependency)
The question boils down if there is a withConfigurations
that causes the plugin to be on the classpath only when compiling test sources. I tried Some("plugin->default(testCompile)")
without success.
回答1:
To answer my own question: It is possible by setting autoCompilerPlugins
to false and adding the necessary -Xplugin=...
Scalac option manually in the test configuration. This can be done by using the Classpaths.autoPlugins
utility method.
In my case I wanted to activate the SemanticDB compiler plugin during tests only. This can be accomplished by the following SBT settings:
autoCompilerPlugins := false,
ivyConfigurations += Configurations.CompilerPlugin,
scalacOptions in Test ++= Classpaths.autoPlugins(update.value, Seq(), ScalaInstance.isDotty(scalaVersion.value)),
scalacOptions in Test += "-Yrangepos",
scalacOptions in Test += "-P:semanticdb:text:on",
来源:https://stackoverflow.com/questions/62890985/how-to-add-scala-compiler-plugin-only-for-test-sources