From 588af4b1162479f502a17c76d56bbf128ad13f22 Mon Sep 17 00:00:00 2001 From: Jack Koenig Date: Wed, 18 Nov 2026 15:21:23 -0800 Subject: [PATCH] Remove Coursier and fetching from Maven --- README.md | 7 ++-- build.mill | 27 ++------------- src/Main.scala | 67 +++--------------------------------- test/src/HttpTests.scala | 2 +- test/src/JarTests.scala | 10 ++++-- test/src/LiveTests.scala | 66 +++++------------------------------ test/src/ResolverTests.scala | 38 ++++---------------- test/src/Sandbox.scala | 25 +++----------- test/src/TestFixtures.scala | 5 ++- 9 files changed, 37 insertions(+), 210 deletions(-) diff --git a/README.md b/README.md index 367c70a..e2ddaab 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,6 @@ cs launch --scala 2.13 org.chipsalliance::firtool-resolver:2.2.0 \ 3. If no explicit version is set, honor `llvm-firtool` on the classpath. This legacy mechanism logs a deprecation message at info level. 4. Reuse the cached binary at `//bin/firtool`. 5. Download the effective version from GitHub, verify its checksum, and atomically install just the executable in the cache. Downloads are locked per version across processes. -6. As a last resort, fetch `llvm-firtool` with Coursier from Maven. This supports older versions and environments that can reach a Maven proxy but cannot reach GitHub; it only works for already-published artifacts. ### Configuration @@ -59,15 +58,15 @@ To use an internal web server (HTTP or HTTPS), an Artifactory generic remote, or | `macos-aarch64` | `firrtl-bin-macos-arm64.tar.gz` | | `windows-x64` | `firrtl-bin-windows-x64.zip` | -GitHub fetching supports versions starting at **1.45.0**. Native macOS arm64 assets start at **1.144.0**; earlier versions fall back to macOS x64 through Rosetta. Older releases remain available through the legacy Maven path. +GitHub fetching supports versions starting at **1.45.0**. Native macOS arm64 assets start at **1.144.0**; earlier versions fall back to macOS x64 through Rosetta. For versions older than **1.45.0**, provide a local binary or a legacy jar on the classpath. ### Development and release Run `./mill -i 'firtool-resolver[_].test'` for the tests on both Scala versions, or `./mill -i 'firtool-resolver[2.13].test'` for just Scala 2.13. -The tests are MUnit tests that run the resolver in real JVMs against local fixtures (a fake release mirror, a fake Maven repository, and local HTTP servers), once from the unshaded classes and once from the shaded jar as published. They also check the contents of the published jar. +The tests are MUnit tests that run the resolver in real JVMs against local fixtures (a fake release mirror, classpath resources, and local HTTP servers), once from the unshaded classes and once from the shaded jar as published. They also check the contents of the published jar. -`LiveTests` additionally exercise the real GitHub releases, Maven Central, and real firtool binaries. They need network access, are tagged `live`, and run by default. Use MUnit's tag filters to select which tests to run: +`LiveTests` downloads and runs a real firtool release from GitHub. It needs network access, is tagged `live`, and runs by default. Use MUnit's tag filters to select which tests to run: ```bash # Hermetic tests only diff --git a/build.mill b/build.mill index bc0e11b..ff58f95 100644 --- a/build.mill +++ b/build.mill @@ -112,13 +112,6 @@ trait FirtoolResolver extends CrossScalaModule with ChipsAlliancePublishModule { Agg(PathRef(dir)) } - // TODO These are the things stripped from upstreamAssemblyClasspath (in addition to scala-library). - // Is it possible to derive these automatically? - def ivyDeps = Agg( - ivy"org.scala-lang.modules::scala-xml:2.2.0", - ivy"org.scala-lang.modules::scala-collection-compat:2.11.0" - ) - object core extends ScalaModule { def scalaVersion = root.scalaVersion @@ -132,14 +125,13 @@ trait FirtoolResolver extends CrossScalaModule with ChipsAlliancePublishModule { // getting System property os.name def ivyDeps = Agg( ivy"dev.dirs:directories:26", - ivy"io.get-coursier::coursier:2.1.8", ivy"org.apache.commons:commons-compress:1.24.0", ) // Modify the classpath to remove things we want to dynamically link (Scala jars). override def upstreamIvyAssemblyClasspath: T[Agg[PathRef]] = T { val all = super.upstreamIvyAssemblyClasspath() - // Remove Scala jars (scala-library, scala-collection-compat, scala-xml, etc.) + // The published assembly links against Scala rather than bundling it. val regex = """scala.*\.jar""".r all.filterNot(p => regex.matches(p.path.last)) } @@ -148,24 +140,9 @@ trait FirtoolResolver extends CrossScalaModule with ChipsAlliancePublishModule { // Including the launcher causes unzip to fail. override def prependShellScript: T[String] = T { "" } - // It would be nice if this could be derived from dependencies. def packagesToShade = Seq( "dev.dirs", - "coursier", - "com.github.plokhotnyuk", - "concurrentrefhashmap", - "org.codehaus", - "scala.cli", - "io.github.alexarchambault", - "javax.inject", - "org.apache.commons", - "org.slf4j", - "org.iq80.snappy", - "org.tukaani.xz", - "com.github.luben.zstd", - "org.apache.xbean", - "org.fusesource.jansi", - "org.fusesource.hawtjni", + "org.apache.commons.compress", ) override def assemblyRules = diff --git a/src/Main.scala b/src/Main.scala index 63010a8..6e70742 100644 --- a/src/Main.scala +++ b/src/Main.scala @@ -8,12 +8,9 @@ import scala.io.Source import java.io.File import java.nio.file.{Path, Paths, Files, StandardCopyOption, StandardOpenOption} import java.nio.channels.FileChannel -import java.net.URLClassLoader import scala.sys.process._ import dev.dirs.ProjectDirectories -import coursier._ -import coursier.core.Extension final case class FirtoolBinary(path: File, version: String) @@ -23,7 +20,6 @@ final case class FirtoolBinary(path: File, version: String) * - Check for firtool on the CHISEL_FIRTOOL_PATH, note any version mismatch * - Honor an explicit version override, otherwise check classpath resources * - Reuse the version's cache, or download and verify a GitHub release - * - Use Coursier to fetch legacy Maven artifacts as a last resort */ object Resolve { @@ -163,7 +159,7 @@ object Resolve { } } - private def checkResources(classloader: Option[URLClassLoader], logger: Logger): Either[String, FirtoolBinary] = { + private def checkResources(logger: Logger): Either[String, FirtoolBinary] = { val platform = determinePlatform(logger) logger.debug("Checking resources for firtool") if (platform.isLeft) { @@ -171,7 +167,7 @@ object Resolve { return Left(platform.merge) // Help out the type system } val primaryPlatform = platform.toOption.get - val resourceLoader = classloader.getOrElse(this.getClass.getClassLoader) + val resourceLoader = this.getClass.getClassLoader val baseDir = s"$groupId/$artId" val versionFile = resourceLoader.getResource(s"$baseDir/project.version") @@ -308,60 +304,6 @@ object Resolve { } } - private def fetchArtifact(logger: Logger, defaultVersion: String): Either[String, FirtoolBinary] = { - val platform = - determinePlatform(logger) match { - case Left(msg) => - logger.debug(msg) - return Left(msg) - case Right(name) => name - } - - // Try fetching for a specific platform classifier; returns Left on any failure. - def tryFetch(p: String): Either[String, FirtoolBinary] = { - // See coursier.parse.DependencyParser to understand how the classifier is added via Publication - val org = Organization(groupId) - val module = Module(org, ModuleName(s"$artId"), Map()) - val dep = - Dependency(module, defaultVersion) - .withPublication("", Type.empty, Extension.empty, Classifier(p)) - // One would think there'd be a built-in pretty print like this but there isn't - // (coursier.util.Print doesn't include the classifier) - logger.debug(s"Attempting to fetch ${dep.module}:${dep.version},classifier=${p}") - - val resolution = Try { - coursier.Fetch() - .addDependencies(dep) - .run() - } - if (resolution.isFailure) { - val msg = resolution.failed.get.toString + "\n" // Coursier's message is already pretty good - logger.debug(msg) - return Left(msg) - } - // Head here is dangerous, without the classifier, multiple jars are fetched - val jar = resolution.get.head - logger.debug(s"Successfully fetched $jar") - - logger.debug(s"Loading $jar to search its resources") - // A version override must not be shadowed by resources in the parent classloader. - val classloader = new URLClassLoader(Array(jar.toURI.toURL), null) - try checkResources(Some(classloader), logger) - finally classloader.close() - } - - tryFetch(platform) match { - case right @ Right(_) => right - case left @ Left(_) => - fallbackPlatform(platform) match { - case Some(fallback) => - logger.debug(s"Falling back to platform $fallback") - tryFetch(fallback) - case None => left - } - } - } - /** Lookup firtool binary * * @param defaultVersion fallback version to fetch if not found in CHISEL_FIRTOOL_PATH nor on classpath @@ -386,7 +328,7 @@ object Resolve { logger.warn(s"Firtool version override $v takes precedence over llvm-firtool $classpathVersion on the classpath") } Left("Classpath lookup skipped because an explicit firtool version is set") - case None => checkResources(None, logger).map { binary => + case None => checkResources(logger).map { binary => logger.info(s"using llvm-firtool ${binary.version} from classpath; this mechanism is deprecated, set chisel.firtool.version instead") binary } @@ -400,8 +342,7 @@ object Resolve { for { cacheError <- checkInstalled(logger, version).left githubError <- fetchFromGitHub(logger, version).left - mavenError <- fetchArtifact(logger, version).left - } yield List("Failed to fetch firtool:", pathError, resourceError, cacheError, githubError, mavenError).mkString("\n") + } yield List("Failed to fetch firtool:", pathError, resourceError, cacheError, githubError).mkString("\n") } } } diff --git a/test/src/HttpTests.scala b/test/src/HttpTests.scala index 71d95cb..fd0361a 100644 --- a/test/src/HttpTests.scala +++ b/test/src/HttpTests.scala @@ -36,7 +36,7 @@ class HttpTests extends TemporaryDirectorySuite with LogAssertions { server.start() try { val url = s"http://${server.getAddress.getAddress.getHostAddress}:${server.getAddress.getPort}" - import scala.jdk.CollectionConverters._ + import scala.collection.JavaConverters._ body(url, () => requests.asScala.toVector) } finally server.stop(0) } diff --git a/test/src/JarTests.scala b/test/src/JarTests.scala index 6f9cc4a..e5484a6 100644 --- a/test/src/JarTests.scala +++ b/test/src/JarTests.scala @@ -26,9 +26,13 @@ class JarTests extends munit.FunSuite { } test("dependencies are shaded and not left at their original packages") { - val unshaded = Seq("coursier/", "dev/dirs/", "org/apache/commons/") - val leaked = entries.filter(e => unshaded.exists(e.startsWith)) + // Check every class, including any introduced by new transitive dependencies. + val leaked = entries.filter(e => e.endsWith(".class") && !e.startsWith("firtoolresolver/")) assert(leaked.isEmpty, s"unshaded entries:\n${leaked.take(10).mkString("\n")}") - assert(entries.exists(_.startsWith("firtoolresolver/shaded/coursier/")), "coursier was not shaded") + Seq("dev/dirs/", "org/apache/commons/compress/").foreach { pkg => + assert(entries.exists(e => e.startsWith(s"firtoolresolver/shaded/$pkg") && e.endsWith(".class")), + s"missing shaded classes for $pkg") + } + assert(!entries.exists(_.contains("coursier/")), "jar contains Coursier classes") } } diff --git a/test/src/LiveTests.scala b/test/src/LiveTests.scala index e9b4a9f..9581620 100644 --- a/test/src/LiveTests.scala +++ b/test/src/LiveTests.scala @@ -2,70 +2,20 @@ package firtoolresolver -import coursier._ -import coursier.core.Extension -import java.nio.file.{Files, Path, Paths} +import java.nio.file.Paths import Check._ -/** Tests of what hermetic fixtures cannot prove: the real GitHub releases, Maven Central, and real firtool binaries. - * - * These are tagged "live" and need network access (and download a few hundred MB). - * They run the resolver as published, i.e. from the shaded classpath. - * - * llvm-firtool is no longer published, so use a version already on Maven Central that is also a GitHub release. - */ class LiveTests extends TemporaryDirectorySuite with LogAssertions { - private val firtoolVersion = "1.162.0" private val Live = new munit.Tag("live") - private def live(name: String)(body: Sandbox => Unit): Unit = - directory.test(name.tag(Live)) { root => - body(new Sandbox(root, "firtoolresolver.test.shaded.classpath")) - } - - private def resolved(result: Result): Path = { + directory.test("downloads and runs a real GitHub release".tag(Live)) { root => + val version = "1.162.0" + val sandbox = new Sandbox(root, "firtoolresolver.test.shaded.classpath") + val result = sandbox.launch(arg = version, envVersion = None, envURL = None).await() assertEquals(result.exit, 0, result.output) - Paths.get(result.out.trim) - } - - // Real firtool prints an LLVM banner before its CIRCT version line, and some releases append a git describe suffix. - private def assertRealFirtool(s: Sandbox, binary: Path): Unit = { - val output = s.runFirtool(binary) - assert(output.linesIterator.exists(_.matches(s"CIRCT firtool-${java.util.regex.Pattern.quote(firtoolVersion)}(-.*)?")), - output) - } - - live("downloads a real release from GitHub") { s => - val result = s.launch(arg = firtoolVersion, envVersion = None, envURL = None, envRepos = None).await() - val binary = resolved(result) checkLog(result.err, has("Verified SHA-256 checksum:")) - assertAbsent(result.err, "Attempting to fetch org.chipsalliance:llvm-firtool:") - assertRealFirtool(s, binary) - - } - - live("falls back to the real llvm-firtool on Maven Central when GitHub fails") { s => - val result = s.launch( - arg = firtoolVersion, envVersion = None, envURL = Some("file:///nonexistent"), envRepos = Some("central")).await() - val binary = resolved(result) - checkLog(result.err, - has(s"Attempting to fetch org.chipsalliance:llvm-firtool:$firtoolVersion"), - has("Successfully fetched")) - assertRealFirtool(s, binary) - } - - live("copies firtool from the real llvm-firtool jar on the classpath") { s => - def fetch(platform: String): Seq[java.io.File] = { - val dep = Dependency(Module(Organization("org.chipsalliance"), ModuleName("llvm-firtool")), firtoolVersion) - .withPublication("", Type.empty, Extension.empty, Classifier(platform)) - Fetch().addDependencies(dep).run() - } - val jar = scala.util.Try(fetch(Host.platform)).getOrElse(fetch("macos-x64")) - val result = s.launch( - arg = firtoolVersion, envVersion = None, envURL = Some("file:///nonexistent"), envRepos = None, - extraClasspath = jar.map(_.toPath).take(1)).await() - val binary = resolved(result) - checkLog(result.err, has(s"using llvm-firtool $firtoolVersion from classpath")) - assertRealFirtool(s, binary) + val output = sandbox.runFirtool(Paths.get(result.out.trim)) + assert(output.linesIterator.exists(_.matches(s"CIRCT firtool-${java.util.regex.Pattern.quote(version)}(-.*)?")), + output) } } diff --git a/test/src/ResolverTests.scala b/test/src/ResolverTests.scala index cc286cc..08c59c1 100644 --- a/test/src/ResolverTests.scala +++ b/test/src/ResolverTests.scala @@ -3,11 +3,11 @@ package firtoolresolver import java.nio.file.{Files, Path} -import scala.jdk.CollectionConverters._ +import scala.collection.JavaConverters._ import Check._ import TestFixtures._ -/** Hermetic resolver tests run real JVMs against local release and Maven fixtures. +/** Hermetic resolver tests run real JVMs against local release and classpath fixtures. * * This covers what used to be the FileCheck scripts; the only things left out are those requiring real servers * (see [[LiveTests]]). @@ -90,7 +90,7 @@ abstract class ResolverSuite(classpathProperty: String) extends TemporaryDirecto write(s.asset.checksum, bytes("0" * 64)) val result = failed(s.launch()) assert(result.err.contains(s"expected ${"0" * 64}, actual ${digest(s.asset.archive)}"), result.output) - assert(result.err.contains("Attempting to fetch org.chipsalliance:llvm-firtool:"), result.output) + assertAbsent(result.err, "Attempting to fetch org.chipsalliance:llvm-firtool:") assert(result.err.contains("Failed to fetch firtool:"), result.output) assert(!Files.exists(s.binary())) assertEquals(walk(s.cache.resolve(s.version)).count(Files.isRegularFile(_)), 0) @@ -169,29 +169,6 @@ abstract class ResolverSuite(classpathProperty: String) extends TemporaryDirecto assert(!Files.exists(s.binary(s.classpathVersion))) } - // ---- Maven fallback (coursier_fallback.sh) ---- - - directory.test("falls back to Maven when GitHub fails") { root => - val s = sandbox(root) - s.publishMaven() - val result = succeeded(s.launch(arg = s.version, envVersion = None, envURL = Some("file:///nonexistent"))) - checkLog(result.err, - has(s"Fetching firtool ${s.version} from GitHub failed:"), - has(s"Attempting to fetch org.chipsalliance:llvm-firtool:${s.version}"), - has(s"Firtool version ${s.version} found in resources")) - assertEquals(java.nio.file.Paths.get(result.out.trim), s.binary()) - assertEquals(Files.readAllBytes(s.binary()).toSeq, s.executable.toSeq) - } - - directory.test("Maven fallback honors the override despite a different classpath version") { root => - val s = sandbox(root) - s.publishMaven() - val result = succeeded(s.launch(extraClasspath = Seq(s.classpathResources()), envURL = Some("file:///nonexistent"))) - assert(result.err.contains(s"Firtool version ${s.version} found in resources"), result.output) - assertEquals(Files.readAllBytes(s.binary()).toSeq, s.executable.toSeq) - assert(!Files.exists(s.cache.resolve(s.classpathVersion))) - } - // ---- Platform fallback (platform_fallback.sh) ---- directory.test("macOS arm64 falls back to the x64 release asset when no arm64 asset is published") { root => @@ -220,15 +197,12 @@ abstract class ResolverSuite(classpathProperty: String) extends TemporaryDirecto result.output) } - directory.test("macOS arm64 falls back to x64 resources in Maven artifacts") { root => + directory.test("macOS arm64 falls back to x64 resources on the classpath") { root => val s = sandbox(root, Nil) - s.publishMaven(forPlatforms = Seq("macos-x64")) - val result = succeeded(s.launch(arg = s.version, envVersion = None, javaOpts = Host.macArm64)) + val result = succeeded(s.launch(arg = s.version, envVersion = None, javaOpts = Host.macArm64, + extraClasspath = Seq(s.classpathResources(platform = "macos-x64")))) checkLog(result.err, - has("Falling back to platform macos-x64"), - has(s"Firtool version ${s.version} found in resources"), has("Falling back to macos-x64 resources")) - assertEquals(Files.readAllBytes(s.binary()).toSeq, s.executable.toSeq) } // ---- CHISEL_FIRTOOL_PATH (firtool_path.sh) ---- diff --git a/test/src/Sandbox.scala b/test/src/Sandbox.scala index 0aad914..9f36f9e 100644 --- a/test/src/Sandbox.scala +++ b/test/src/Sandbox.scala @@ -40,7 +40,7 @@ private[firtoolresolver] final class Child(process: Process, outFile: Path, errF } } -/** A hermetic world for one test: a fake GitHub release mirror, a fake Maven repository, a firtool cache, and +/** A hermetic world for one test: a fake GitHub release mirror, a firtool cache, and * the ability to launch the resolver's `Main` in a fresh JVM against all of them. * * @param classpathProperty system property holding the classpath to launch the resolver with @@ -55,7 +55,6 @@ private[firtoolresolver] class Sandbox( val classpathVersion = "1.0.0-classpath" val base: Path = root.resolve("mirror") val cache: Path = root.resolve("cache") - val maven: Path = root.resolve("maven") def script(output: String, exitCode: Int = 0): Array[Byte] = bytes(s"#!/bin/sh\necho $output\nexit $exitCode\n") val executable: Array[Byte] = script(s"CIRCT firtool-$version") @@ -81,25 +80,12 @@ private[firtoolresolver] class Sandbox( /** The asset of the first platform, for tests which tamper with it. */ def asset: Asset = assets.head - /** Publish the legacy llvm-firtool jars (one per platform classifier) into the fake Maven repository. */ - def publishMaven(forVersion: String = version, forPlatforms: Seq[String] = Seq(Host.platform)): Unit = { - val dir = maven.resolve(s"org/chipsalliance/llvm-firtool/$forVersion") - write(dir.resolve(s"llvm-firtool-$forVersion.pom"), bytes( - s"4.0.0org.chipsalliance" + - s"llvm-firtool$forVersion")) - forPlatforms.foreach { platform => - zip(dir.resolve(s"llvm-firtool-$forVersion-$platform.jar"), Seq( - Entry("org.chipsalliance/llvm-firtool/project.version", bytes(forVersion)), - Entry(s"org.chipsalliance/llvm-firtool/$platform/bin/firtool", executable))) - } - } - /** Resources as llvm-firtool puts them on the classpath, as a directory to add to the classpath. */ - def classpathResources(forVersion: String = classpathVersion): Path = { + def classpathResources(forVersion: String = classpathVersion, platform: String = Host.platform): Path = { val resources = root.resolve("resources") val dir = "org.chipsalliance/llvm-firtool" write(resources.resolve(s"$dir/project.version"), bytes(forVersion)) - write(resources.resolve(s"$dir/${Host.platform}/bin/firtool"), executable) + write(resources.resolve(s"$dir/$platform/bin/firtool"), executable) resources } @@ -124,7 +110,6 @@ private[firtoolresolver] class Sandbox( envURL: Option[String] = Some(base.toUri.toString), envCache: Option[String] = Some(cache.toString), envPath: Option[String] = None, - envRepos: Option[String] = Some(maven.toUri.toString), javaOpts: Seq[String] = Nil, extraClasspath: Seq[Path] = Nil ): Child = { @@ -141,13 +126,11 @@ private[firtoolresolver] class Sandbox( .redirectError(err.toFile) val env = builder.environment() Seq("CHISEL_FIRTOOL_PATH", "CHISEL_FIRTOOL_VERSION", "CHISEL_FIRTOOL_CACHE", "CHISEL_FIRTOOL_URL", - "COURSIER_REPOSITORIES", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS").foreach(env.remove(_)) + "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS").foreach(env.remove(_)) envPath.foreach(env.put("CHISEL_FIRTOOL_PATH", _)) envVersion.foreach(env.put("CHISEL_FIRTOOL_VERSION", _)) envCache.foreach(env.put("CHISEL_FIRTOOL_CACHE", _)) envURL.foreach(env.put("CHISEL_FIRTOOL_URL", _)) - envRepos.foreach(env.put("COURSIER_REPOSITORIES", _)) - env.put("COURSIER_CACHE", root.resolve("coursier").toString) new Child(builder.start(), out, err) } diff --git a/test/src/TestFixtures.scala b/test/src/TestFixtures.scala index fd3c16b..806fc13 100644 --- a/test/src/TestFixtures.scala +++ b/test/src/TestFixtures.scala @@ -7,9 +7,9 @@ import java.nio.file.{Files, Path} import java.security.MessageDigest import java.util.zip.{GZIPOutputStream, ZipEntry, ZipOutputStream} import org.apache.commons.compress.archivers.tar.{TarArchiveEntry, TarArchiveOutputStream} -import scala.jdk.CollectionConverters._ +import scala.collection.JavaConverters._ -/** Builders for local release mirrors and Maven fixtures. */ +/** Builders for local release mirrors. */ private[firtoolresolver] object TestFixtures { def bytes(value: String): Array[Byte] = value.getBytes(UTF_8) @@ -31,7 +31,6 @@ private[firtoolresolver] object TestFixtures { } finally output.close() } - // ZIP is also used to build the legacy Maven jar fixture. def zip(path: Path, entries: Seq[Entry]): Unit = { val output = new ZipOutputStream(Files.newOutputStream(path)) try entries.foreach { entry =>