Yevhenii Popadiuk
Yevhenii Popadiuk

Reputation: 1054

SBT plugin to forbid use of auto-imported dependencies

I have this line of code in my build.sbt file:

libraryDependencies ++= Seq("com.foo" %% "lib" % "1.2.3")

Imagine that this library depends on "com.bar.lib" lib. Now in my code I can import com.bar.lib._ and it'll work. But I don't want this to compile, so maybe there is SBT plugin out there just for this purpose?

One of libraries I'm using depends on old cats version. I spent really long time to understand why mapN method not works... I just never imported a newer version of cats in the subproject.

Upvotes: 1

Views: 221

Answers (1)

Rich
Rich

Reputation: 15457

SBT offers the intransitive and exclude features to deal with issues like this, as @earldouglas points out. See: https://www.scala-sbt.org/1.x/docs/Library-Management.html

You replied:

I tried to do so, but intransitive() don't import transitive dependencies (so I need to import all of them by hand to make it compile).

Yes, that is what it is for

What I want is something that will warn me about using libraries not directly imported in SBT file.

So you want transitive dependencies on your classpath, but you want the compiler to reject uses of transitive classes in your project code while allowing them in library code?

That is not a sensible approach: at runtime, these transitive dependencies will be on the classpath. The JVM classpath does not distinguish between different kinds of dependencies; such distinction only exists in SBT at build time.

You would be much better served by either

  • including a newer version of the cats library, overriding the transitive dep or

  • excluding the transitively included cats library, if it is broken.

However, I think you probably could achieve what you want by setting different dependencies at different build stages:

  1. at Compile stage, include the dependency with intransitive. Your code should compile against your direct dependencies, but fail if you referenced any transitive dependencies
  2. at Runtime stage, include the dependency with its transitive deps

the SBT code might look like this (untested):

(libraryDependencies in Compile) ++= Seq("com.foo" %% "lib" % "1.2.3" intransitive())
(libraryDependencies in Runtime) ++= Seq("com.foo" %% "lib" % "1.2.3")

Upvotes: 1

Related Questions