Search code examples
scalasbtsbt-assemblyjson4s

Error when shading json4s-native in simple Scala project: "Symbol 'term org.json4s' is missing from the classpath."


I have a simple Scala project where I'd like to shade json4s-native before compiling my fat JAR using sbt-assembly. The idea is that in my own code, I would then import the shaded Java classes as follows.

import acme.shade.org.json4s.native.Json
...

I tried using the following simplified build.sbt (inspired by this). The idea is to create an empty project which depends on json4s-native, shade the classes, then have my actual project depend on that JAR containing shaded classes.

val commonSettings = Seq(
  organization := "com.acme",
  version := "1.0.0",
  scalaVersion := "2.11.12",
  test in assembly := {}
)

// Inspiration for shading JARs taken from:
// https://github.com/wsargent/shade-with-sbt-assembly/
lazy val shaded = (project in file("shaded/libs"))
  .settings(commonSettings)
  .settings(
    name := "my-shaded-lib",
    libraryDependencies ++= Seq(
      "org.json4s" %% "json4s-native" % "3.7.0-M2"
    )
  )
  .settings(
    assemblyOption in assembly ~= { _.copy(includeScala = false) },
    assemblyJarName in assembly := s"my-shaded-lib-${version.value}.jar",
    assemblyShadeRules in assembly := Seq(
      ShadeRule.rename("org.json4s.**" -> "acme.shade.@0").inAll
    )
  )

lazy val root = (project in file ("."))
  .settings(commonSettings)
  .settings(
    name := "shadejson4s",
    mainClass in assembly := Some("com.acme.test.Main"),
    unmanagedJars in Compile ++= Seq(
      shaded.base / "target" / s"scala-${scalaBinaryVersion.value}" / s"my-shaded-lib-${version.value}.jar"
    ),
    update := (update dependsOn (shaded / assembly)).value
  )

The JAR containing the shaded classes was assembled successfully, but when I try to compile my source code, I get the following error:

[info] Compiling 1 Scala source to /private/tmp/shade-json4s/target/scala-2.11/classes ...
[error] /private/tmp/shade-json4s/src/main/scala/com/acme/shadejson4s/Main.scala:3:8: Symbol 'term org.json4s' is missing from the classpath.
[error] This symbol is required by ' <none>'.
[error] Make sure that term json4s is in your classpath and check for conflicting dependencies with `-Ylog-classpath`.
[error] A full rebuild may help if 'package.class' was compiled against an incompatible version of org.
[error] import acme.shade.org.json4s.native.Json
[error]        ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 2 s, completed Feb 11, 2020 2:51:01 PM

What am I missing here?


Solution

  • Scala lib cannot be shaded as far as I know: https://contributors.scala-lang.org/t/scala-signature-layout/3327