Skip to content

Commit 7846f80

Browse files
authored
Fix dependency main class detection throwing an NPE when JAR manifest doesn't list the main class correctly (#3319)
1 parent 1e23e17 commit 7846f80

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

modules/build/src/main/scala/scala/build/internal/MainClass.scala

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,11 @@ object MainClass {
7171
def findInDependency(jar: os.Path): Option[String] =
7272
jar match {
7373
case jar if os.isFile(jar) && jar.last.endsWith(".jar") =>
74-
val jarFile = new JarFile(jar.toIO)
75-
val manifest = jarFile.getManifest()
76-
val mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS)
77-
Option(mainClass).map(_.asInstanceOf[String])
74+
for {
75+
manifest <- Option(new JarFile(jar.toIO).getManifest)
76+
mainAttributes <- Option(manifest.getMainAttributes)
77+
mainClass: String <- Option(mainAttributes.getValue(Attributes.Name.MAIN_CLASS))
78+
} yield mainClass
7879
case _ => None
7980
}
8081

modules/integration/src/test/scala/scala/cli/integration/RunTestDefinitions.scala

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2270,4 +2270,25 @@ abstract class RunTestDefinitions
22702270
}
22712271
}
22722272
}
2273+
2274+
if (actualScalaVersion.startsWith("3")) test(
2275+
"fail with a valid error when multiple main classes are present and a dependency doesn't define main classes in the manifest"
2276+
) {
2277+
val (main1, main2) = "main1" -> "main2"
2278+
val input = "example.scala"
2279+
TestInputs(
2280+
os.rel / input ->
2281+
s"""//> using dep io.get-coursier:coursier_2.13:2.1.18
2282+
|@main def $main1() = println("$main1")
2283+
|@main def $main2() = println("$main2")
2284+
|""".stripMargin
2285+
).fromRoot { root =>
2286+
val res = os.proc(TestUtil.cli, "run", input, extraOptions)
2287+
.call(cwd = root, stderr = os.Pipe, check = false)
2288+
val err = res.err.trim()
2289+
expect(err.contains("Found several main classes"))
2290+
expect(err.contains(main1))
2291+
expect(err.contains(main2))
2292+
}
2293+
}
22732294
}

0 commit comments

Comments
 (0)