From 2f06e19095388e66951530f91912dc3325958532 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 13 Nov 2026 14:17:41 +0100 Subject: [PATCH 01/23] Generate Socket facts with Coana instead of socket-cli's build-tool scripts socket-cli keeps discovering build roots, resolving each root's options from the socket.json cascade, walking them depth-first and aborting a tool's walk on a failure. It now hands each root to `coana generate-socket-facts --request`, takes coverage from the result's coveredBuildFiles and a dotnet solution's members from `--list-members`. Reachability and `socket fix --dynamic-sbom-inference` give Coana a work dir owned by socket-cli (with `--with-files` for reachability), collect each root's sidecarEntry and pass them back with `--socket-facts-sidecar` in place of `--compute-artifacts-sidecar`. The work dir is removed after Coana's run, and both phases run the same Coana version. Removed: the Gradle facts init script, the sbt facts plugin, the Maven extension's facts participant, the sidecar builder, the resolution-report classifiers and renderer, and their tests and compat suites. The setup wizard still lists workspaces with socket-cli's own scripts, Maven extension and dotnet tool, so those stay, trimmed to that use. --- .config/rollup.dist.config.mjs | 22 +- .gitignore | 99 -- CHANGELOG.md | 1 + .../coana-fix-dynamic-sbom-inference.test.mts | 6 +- src/commands/fix/coana-fix.mts | 9 +- src/commands/fix/generated-socket-facts.mts | 35 +- .../fix/generated-socket-facts.test.mts | 29 +- src/commands/manifest/cmd-manifest-auto.mts | 18 +- src/commands/manifest/cmd-manifest-scala.mts | 26 +- .../manifest/convert-dotnet-to-facts.mts | 17 +- .../manifest/convert-gradle-to-facts.mts | 20 +- .../manifest/convert-maven-to-facts.mts | 19 +- .../manifest/convert-sbt-to-facts.mts | 23 +- .../manifest/discover-manifest-roots.mts | 44 +- .../manifest/enumerate-workspaces.mts | 13 +- .../manifest/generate-recursive-manifests.mts | 166 +-- .../generate-recursive-manifests.test.mts | 721 ++++-------- .../manifest/generate_auto_manifest.mts | 54 +- src/commands/manifest/run-manifest-facts.mts | 543 +++++---- .../manifest/run-manifest-facts.test.mts | 433 +++---- .../manifest/scripts/assemble.test.mts | 256 +---- .../manifest/scripts/maven-extension/pom.xml | 32 +- .../tech/coana/ext/CoanaFactsEventSpy.java | 31 - .../ext/CoanaFactsLifecycleParticipant.java | 92 -- .../CoanaWorkspacesLifecycleParticipant.java | 3 +- .../tech/coana/socket/CollectionObserver.java | 125 -- .../socket/SocketFactsRecordsEngine.java | 1018 ----------------- .../java/tech/coana/socket/SocketSupport.java | 71 +- .../socket/SocketWorkspacesRecordsEngine.java | 7 +- .../scripts/resolution-report-gradle.mts | 123 -- .../scripts/resolution-report-ivy.mts | 61 - .../scripts/resolution-report-maven.mts | 85 -- .../scripts/resolution-report-nuget.mts | 63 - .../scripts/resolution-report-nuget.test.mts | 39 - .../scripts/resolution-report-render.mts | 507 -------- .../scripts/resolution-report-render.test.mts | 605 ---------- src/commands/manifest/scripts/run.mts | 349 +----- src/commands/manifest/scripts/run.test.mts | 119 +- src/commands/manifest/scripts/sidecar.mts | 158 --- .../manifest/scripts/sidecar.test.mts | 423 ------- .../manifest/scripts/socket-facts.init.gradle | 832 -------------- .../scripts/socket-facts.plugin.scala | 1018 ----------------- .../scripts/socket-workspaces.init.gradle | 8 +- .../scripts/socket-workspaces.plugin.scala | 12 +- src/commands/manifest/scripts/test/README.md | 107 +- .../scripts/test/assemble-records.mts | 22 - .../manifest/scripts/test/compat-cache.sh | 10 +- .../scripts/test/dotnet-compat/.gitignore | 4 - .../test/dotnet-compat/assert-dotnet-list.py | 117 -- .../test/dotnet-compat/assert-facts.py | 227 ---- .../scripts/test/dotnet-compat/cpm/Cpm.slnx | 4 - .../dotnet-compat/cpm/Directory.Build.props | 5 - .../cpm/Directory.Packages.props | 14 - .../test/dotnet-compat/cpm/src/Api/A.cs | 1 - .../test/dotnet-compat/cpm/src/Api/Api.csproj | 8 - .../test/dotnet-compat/cpm/src/Core/C.cs | 1 - .../dotnet-compat/cpm/src/Core/Core.csproj | 7 - .../scripts/test/dotnet-compat/dev/Dev.csproj | 14 - .../scripts/test/dotnet-compat/dev/Program.cs | 1 - .../dotnet-compat/evaluation/Build.csproj | 9 - .../dotnet-compat/evaluation/Lib/Class.cs | 3 - .../dotnet-compat/evaluation/Lib/Lib.csproj | 8 - .../failures/broken/Broken.csproj | 5 - .../failures/missing/Missing.csproj | 7 - .../test/dotnet-compat/langs/Fs/First.fs | 3 - .../test/dotnet-compat/langs/Fs/Fs.fsproj | 8 - .../test/dotnet-compat/langs/Fs/Library.fs | 2 - .../scripts/test/dotnet-compat/langs/Vb/V.vb | 2 - .../test/dotnet-compat/langs/Vb/Vb.vbproj | 7 - .../test/dotnet-compat/make-stub-feed.py | 96 -- .../scripts/test/dotnet-compat/multi/One.sln | 34 - .../scripts/test/dotnet-compat/multi/One.slnx | 3 - .../test/dotnet-compat/multi/One/One.csproj | 4 - .../test/dotnet-compat/multi/Stray.csproj | 4 - .../scripts/test/dotnet-compat/multi/Two.sln | 48 - .../test/dotnet-compat/multi/Two/Two.csproj | 4 - .../scripts/test/dotnet-compat/nuget.config | 19 - .../packages-config/Legacy/Class1.cs | 1 - .../packages-config/Legacy/Legacy.csproj | 37 - .../Legacy/Properties/AssemblyInfo.cs | 1 - .../packages-config/Legacy/packages.config | 6 - .../dotnet-compat/packages-config/Mixed.sln | 48 - .../dotnet-compat/packages-config/Modern/M.cs | 1 - .../packages-config/Modern/Modern.csproj | 9 - .../scripts/test/dotnet-compat/pair/A.csproj | 4 - .../scripts/test/dotnet-compat/pair/B.csproj | 4 - .../scripts/test/dotnet-compat/rid/R.cs | 1 - .../scripts/test/dotnet-compat/rid/Rid.csproj | 4 - .../test/dotnet-compat/sibling/sln/All.sln | 34 - .../test/dotnet-compat/sibling/src/A/A.cs | 1 - .../test/dotnet-compat/sibling/src/A/A.csproj | 4 - .../scripts/test/dotnet-compat/smoke-test.sh | 129 --- .../scripts/test/gradle-compat/.gitignore | 13 +- .../scripts/test/gradle-compat/README.md | 31 - .../gradle-compat/failures/app/build.gradle | 8 - .../test/gradle-compat/failures/build.gradle | 64 -- .../failures/gradle/verification-metadata.xml | 18 - .../gradle-compat/failures/lib/build.gradle | 3 - .../gradle-compat/failures/settings.gradle | 2 - .../gradle-compat/failures/transforms.gradle | 25 - .../test/gradle-compat/project/build.gradle | 20 +- .../test/gradle-compat/smoke-test-failures.sh | 127 -- .../gradle-compat/smoke-test-workspaces.sh | 8 +- .../scripts/test/gradle-compat/smoke-test.sh | 126 -- .../manifest/scripts/test/make-stub-repo.sh | 123 -- .../scripts/test/maven-compat/.gitignore | 26 +- .../test/maven-compat/assert-fail-closed.py | 31 - .../assert-no-invented-failures.py | 27 - .../test/maven-compat/assert-records.py | 126 -- .../maven-compat/descriptor-failure/a/pom.xml | 107 -- .../maven-compat/descriptor-failure/b/pom.xml | 28 - .../maven-compat/descriptor-failure/pom.xml | 13 - .../maven-compat/duplicate-failure/m1/pom.xml | 10 - .../maven-compat/duplicate-failure/m2/pom.xml | 10 - .../maven-compat/duplicate-failure/pom.xml | 26 - .../test/maven-compat/extension-type/pom.xml | 55 - .../test/maven-compat/graph-failure/pom.xml | 43 - .../test/maven-compat/maven4-scopes/pom.xml | 55 - .../test/maven-compat/project/app/pom.xml | 86 -- .../project/app/src/main/java/demo/App.java | 7 - .../test/maven-compat/project/lib/pom.xml | 21 - .../project/lib/src/main/java/demo/Lib.java | 7 - .../test/maven-compat/project/mid/pom.xml | 24 - .../project/mid/src/main/java/demo/Mid.java | 4 - .../scripts/test/maven-compat/project/pom.xml | 22 - .../repo-inheritance/liba/pom.xml | 32 - .../repo-inheritance/libb/pom.xml | 18 - .../maven-compat/repo-inheritance/pom.xml | 21 - .../smoke-test-descriptor-failure.sh | 179 --- .../smoke-test-duplicate-failure.sh | 36 - .../maven-compat/smoke-test-extension-type.sh | 76 -- .../maven-compat/smoke-test-graph-failure.sh | 138 --- .../smoke-test-repo-inheritance.sh | 128 --- .../test/maven-compat/smoke-test-scopes.sh | 77 -- .../smoke-test-unsolvable-conflict.sh | 56 - .../maven-compat/smoke-test-workspaces.sh | 8 +- .../scripts/test/maven-compat/smoke-test.sh | 132 --- .../test/maven-compat/unknown-scopes/pom.xml | 38 - .../maven-compat/unsolvable-conflict/pom.xml | 42 - .../manifest/scripts/test/run-compat.sh | 43 +- .../scripts/test/sbt-compat/.gitignore | 18 +- .../sbt-compat/artifact-failure/build.sbt | 20 - .../scripts/test/sbt-compat/failure/build.sbt | 26 - .../test/sbt-compat/project/Base.scala | 1 - .../scripts/test/sbt-compat/project/build.sbt | 21 +- .../project/src/main/scala/App.scala | 1 - .../test/sbt-compat/relocation/build.sbt | 21 - .../test/sbt-compat/smoke-test-failure.sh | 266 ----- .../test/sbt-compat/smoke-test-relocation.sh | 79 -- .../test/sbt-compat/smoke-test-workspaces.sh | 10 +- .../scripts/test/sbt-compat/smoke-test.sh | 96 -- .../setup-recursive-manifest-config.mts | 2 +- src/commands/scan/handle-create-new-scan.mts | 44 +- .../scan/handle-create-new-scan.test.mts | 42 +- src/commands/scan/handle-scan-reach.mts | 19 +- src/commands/scan/handle-scan-reach.test.mts | 55 +- .../scan/perform-reachability-analysis.mts | 24 +- .../perform-reachability-analysis.test.mts | 23 +- .../scan/run-dynamic-sbom-inference.mts | 40 +- .../scan/run-dynamic-sbom-inference.test.mts | 79 +- .../scan/warn-socket-json-only-flags.mts | 2 +- test/maven-compat-smoke-assertions.test.mts | 366 ------ 162 files changed, 1235 insertions(+), 11767 deletions(-) delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsEventSpy.java delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsLifecycleParticipant.java delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/CollectionObserver.java delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketFactsRecordsEngine.java delete mode 100644 src/commands/manifest/scripts/resolution-report-gradle.mts delete mode 100644 src/commands/manifest/scripts/resolution-report-ivy.mts delete mode 100644 src/commands/manifest/scripts/resolution-report-maven.mts delete mode 100644 src/commands/manifest/scripts/resolution-report-nuget.mts delete mode 100644 src/commands/manifest/scripts/resolution-report-nuget.test.mts delete mode 100644 src/commands/manifest/scripts/resolution-report-render.mts delete mode 100644 src/commands/manifest/scripts/resolution-report-render.test.mts delete mode 100644 src/commands/manifest/scripts/sidecar.mts delete mode 100644 src/commands/manifest/scripts/sidecar.test.mts delete mode 100644 src/commands/manifest/scripts/socket-facts.init.gradle delete mode 100644 src/commands/manifest/scripts/socket-facts.plugin.scala delete mode 100644 src/commands/manifest/scripts/test/assemble-records.mts delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/assert-dotnet-list.py delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/assert-facts.py delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/Cpm.slnx delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Build.props delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Packages.props delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/A.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/Api.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/C.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/Core.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/dev/Dev.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/dev/Program.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/evaluation/Build.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Class.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Lib.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/failures/broken/Broken.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/failures/missing/Missing.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/First.fs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Fs.fsproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Library.fs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/V.vb delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/Vb.vbproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/make-stub-feed.py delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/multi/One.sln delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/multi/One.slnx delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/multi/One/One.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/multi/Stray.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/multi/Two.sln delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/multi/Two/Two.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/nuget.config delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Class1.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Legacy.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Properties/AssemblyInfo.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/packages.config delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Mixed.sln delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/M.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/Modern.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/pair/A.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/pair/B.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/rid/R.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/rid/Rid.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/sibling/sln/All.sln delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.csproj delete mode 100755 src/commands/manifest/scripts/test/dotnet-compat/smoke-test.sh delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/README.md delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/failures/app/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/failures/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/failures/gradle/verification-metadata.xml delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/failures/lib/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/failures/settings.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/failures/transforms.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/smoke-test-failures.sh delete mode 100755 src/commands/manifest/scripts/test/gradle-compat/smoke-test.sh delete mode 100755 src/commands/manifest/scripts/test/make-stub-repo.sh delete mode 100644 src/commands/manifest/scripts/test/maven-compat/assert-fail-closed.py delete mode 100644 src/commands/manifest/scripts/test/maven-compat/assert-no-invented-failures.py delete mode 100755 src/commands/manifest/scripts/test/maven-compat/assert-records.py delete mode 100644 src/commands/manifest/scripts/test/maven-compat/descriptor-failure/a/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/descriptor-failure/b/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/descriptor-failure/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m1/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m2/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/duplicate-failure/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/extension-type/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/graph-failure/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/maven4-scopes/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/demo/App.java delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/demo/Lib.java delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/demo/Mid.java delete mode 100644 src/commands/manifest/scripts/test/maven-compat/repo-inheritance/liba/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/repo-inheritance/libb/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/repo-inheritance/pom.xml delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-descriptor-failure.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-duplicate-failure.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-extension-type.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-graph-failure.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-repo-inheritance.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-scopes.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-unsolvable-conflict.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test.sh delete mode 100644 src/commands/manifest/scripts/test/maven-compat/unknown-scopes/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/unsolvable-conflict/pom.xml delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/artifact-failure/build.sbt delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/failure/build.sbt delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/project/Base.scala delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/project/src/main/scala/App.scala delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/relocation/build.sbt delete mode 100755 src/commands/manifest/scripts/test/sbt-compat/smoke-test-failure.sh delete mode 100755 src/commands/manifest/scripts/test/sbt-compat/smoke-test-relocation.sh delete mode 100755 src/commands/manifest/scripts/test/sbt-compat/smoke-test.sh delete mode 100644 test/maven-compat-smoke-assertions.test.mts diff --git a/.config/rollup.dist.config.mjs b/.config/rollup.dist.config.mjs index 14abdf87b1..7ef22943f0 100644 --- a/.config/rollup.dist.config.mjs +++ b/.config/rollup.dist.config.mjs @@ -109,8 +109,8 @@ async function copyInitGradle() { await fs.copyFile(filepath, destPath) } -// Copy the build-tool resolution assets (Gradle init script, sbt plugin, -// Maven extension jar, dotnet tool) into dist/manifest-scripts, where run.mts resolves them +// Copy the workspace-enumeration assets (Gradle init script, sbt plugin, Maven +// extension jar, dotnet tool) into dist/manifest-scripts, where run.mts resolves them // at runtime. The Maven jar is compiled by maven-extension/build-jar.sh. Local // dev builds may omit it; published builds fail here if it is missing. async function copyManifestScripts() { @@ -118,14 +118,6 @@ async function copyManifestScripts() { const destDir = path.join(constants.distPath, 'manifest-scripts') await fs.mkdir(path.join(destDir, 'maven-extension'), { recursive: true }) await Promise.all([ - fs.copyFile( - path.join(srcDir, 'socket-facts.init.gradle'), - path.join(destDir, 'socket-facts.init.gradle'), - ), - fs.copyFile( - path.join(srcDir, 'socket-facts.plugin.scala'), - path.join(destDir, 'socket-facts.plugin.scala'), - ), fs.copyFile( path.join(srcDir, 'socket-workspaces.init.gradle'), path.join(destDir, 'socket-workspaces.init.gradle'), @@ -159,13 +151,11 @@ async function copyManifestScripts() { jarPath, path.join(destDir, 'maven-extension', 'coana-maven-extension.jar'), ) - } else if ( - constants.ENV[INLINED_SOCKET_CLI_PUBLISHED_BUILD] - ) { + } else if (constants.ENV[INLINED_SOCKET_CLI_PUBLISHED_BUILD]) { // Fail closed: a published build without the jar would ship a package whose - // `socket manifest maven` / Maven reachability silently produces an empty - // SBOM. Run `pnpm run build:maven-extension` before `build:dist`. (A local - // dev build tolerates a missing jar; run.mts surfaces a hint at runtime.) + // `socket manifest setup` cannot list Maven projects. Run + // `pnpm run build:maven-extension` before `build:dist`. (A local dev build + // tolerates a missing jar; run.mts surfaces a hint at runtime.) throw new Error( 'Maven manifest extension jar not found at ' + jarPath + diff --git a/.gitignore b/.gitignore index 93d4b0b001..2c1bda539a 100644 --- a/.gitignore +++ b/.gitignore @@ -642,36 +642,19 @@ !/src/commands/manifest/scripts/maven-extension/mvnw !/src/commands/manifest/scripts/maven-extension/mvnw.cmd !/src/commands/manifest/scripts/maven-extension/pom.xml -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsEventSpy.java -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsLifecycleParticipant.java !/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/CollectionObserver.java -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketFactsRecordsEngine.java !/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java !/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java !/src/commands/manifest/scripts/records.mts -!/src/commands/manifest/scripts/resolution-report-gradle.mts -!/src/commands/manifest/scripts/resolution-report-ivy.mts -!/src/commands/manifest/scripts/resolution-report-maven.mts -!/src/commands/manifest/scripts/resolution-report-nuget.mts -!/src/commands/manifest/scripts/resolution-report-nuget.test.mts -!/src/commands/manifest/scripts/resolution-report-render.mts -!/src/commands/manifest/scripts/resolution-report-render.test.mts !/src/commands/manifest/scripts/resolution-report.mts !/src/commands/manifest/scripts/run.mts !/src/commands/manifest/scripts/run.test.mts -!/src/commands/manifest/scripts/sidecar.mts -!/src/commands/manifest/scripts/sidecar.test.mts -!/src/commands/manifest/scripts/socket-facts.init.gradle -!/src/commands/manifest/scripts/socket-facts.plugin.scala !/src/commands/manifest/scripts/socket-workspaces.init.gradle !/src/commands/manifest/scripts/socket-workspaces.plugin.scala !/src/commands/manifest/scripts/test/README.md !/src/commands/manifest/scripts/test/assert-reachability.py !/src/commands/manifest/scripts/test/compat-cache.sh !/src/commands/manifest/scripts/test/dotnet-compat/.gitignore -!/src/commands/manifest/scripts/test/dotnet-compat/assert-dotnet-list.py -!/src/commands/manifest/scripts/test/dotnet-compat/assert-facts.py !/src/commands/manifest/scripts/test/dotnet-compat/basic/Basic.sln !/src/commands/manifest/scripts/test/dotnet-compat/basic/shared/Linked.cs !/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/App.csproj @@ -683,119 +666,38 @@ !/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/App.Tests.csproj !/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/T.cs !/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/Nuke.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/Cpm.slnx -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Build.props -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Packages.props -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/A.cs -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/Api.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/C.cs -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/Core.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/dev/Dev.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/dev/Program.cs -!/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Build.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Class.cs -!/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Lib.csproj !/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.csproj !/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.sln !/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/Core.csproj !/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/Shared.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/failures/broken/Broken.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/failures/missing/Missing.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/First.fs -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Fs.fsproj -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Library.fs -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/V.vb -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/Vb.vbproj !/src/commands/manifest/scripts/test/dotnet-compat/lib.sh -!/src/commands/manifest/scripts/test/dotnet-compat/make-stub-feed.py -!/src/commands/manifest/scripts/test/dotnet-compat/multi/One.sln -!/src/commands/manifest/scripts/test/dotnet-compat/multi/One.slnx -!/src/commands/manifest/scripts/test/dotnet-compat/multi/One/One.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/multi/Stray.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/multi/Two.sln -!/src/commands/manifest/scripts/test/dotnet-compat/multi/Two/Two.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/nuget.config -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Class1.cs -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Legacy.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Properties/AssemblyInfo.cs -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/packages.config -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Mixed.sln -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/M.cs -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/Modern.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/pair/A.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/pair/B.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/rid/R.cs -!/src/commands/manifest/scripts/test/dotnet-compat/rid/Rid.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/sln/All.sln -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.cs -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.csproj !/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-exclude-base.sh !/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/dotnet-compat/smoke-test.sh !/src/commands/manifest/scripts/test/gradle-compat/.gitignore -!/src/commands/manifest/scripts/test/gradle-compat/README.md !/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/build.gradle !/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/build.gradle !/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/settings.gradle !/src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/failures/app/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/failures/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/failures/gradle/verification-metadata.xml -!/src/commands/manifest/scripts/test/gradle-compat/failures/lib/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/failures/settings.gradle -!/src/commands/manifest/scripts/test/gradle-compat/failures/transforms.gradle !/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle !/src/commands/manifest/scripts/test/gradle-compat/project/settings.gradle !/src/commands/manifest/scripts/test/gradle-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/gradle-compat/smoke-test-failures.sh !/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/gradle-compat/smoke-test.sh -!/src/commands/manifest/scripts/test/make-stub-repo.sh !/src/commands/manifest/scripts/test/maven-compat/.gitignore -!/src/commands/manifest/scripts/test/maven-compat/assert-fail-closed.py -!/src/commands/manifest/scripts/test/maven-compat/assert-no-invented-failures.py -!/src/commands/manifest/scripts/test/maven-compat/assert-records.py -!/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/a/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/b/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m1/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m2/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/pom.xml !/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/pom.xml !/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/pom.xml !/src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/graph-failure/pom.xml !/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/demo/App.java !/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/demo/Lib.java !/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/demo/Mid.java !/src/commands/manifest/scripts/test/maven-compat/project/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/liba/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/libb/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/smoke-test-descriptor-failure.sh -!/src/commands/manifest/scripts/test/maven-compat/smoke-test-duplicate-failure.sh !/src/commands/manifest/scripts/test/maven-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/maven-compat/smoke-test-graph-failure.sh -!/src/commands/manifest/scripts/test/maven-compat/smoke-test-repo-inheritance.sh !/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/maven-compat/smoke-test.sh !/src/commands/manifest/scripts/test/run-compat.sh !/src/commands/manifest/scripts/test/sbt-compat/.gitignore -!/src/commands/manifest/scripts/test/sbt-compat/artifact-failure/build.sbt !/src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/build.sbt -!/src/commands/manifest/scripts/test/sbt-compat/failure/build.sbt -!/src/commands/manifest/scripts/test/sbt-compat/project/Base.scala !/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt -!/src/commands/manifest/scripts/test/sbt-compat/project/src/main/scala/App.scala -!/src/commands/manifest/scripts/test/sbt-compat/relocation/build.sbt !/src/commands/manifest/scripts/test/sbt-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/sbt-compat/smoke-test-failure.sh -!/src/commands/manifest/scripts/test/sbt-compat/smoke-test-relocation.sh !/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/sbt-compat/smoke-test.sh !/src/commands/manifest/setup-manifest-config.mts !/src/commands/manifest/setup-manifest-config.test.mts !/src/commands/manifest/setup-recursive-manifest-config.mts @@ -1327,7 +1229,6 @@ !/test/glob.test.mts !/test/json-output-validation.mts !/test/manifest-reachability-assertions.test.mts -!/test/maven-compat-smoke-assertions.test.mts !/test/mock-auth.mts !/test/mock-auth.test.mts !/test/mock-malware-api.mts diff --git a/CHANGELOG.md b/CHANGELOG.md index 07b54ebbb4..44c2ce63c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - Configure or skip one build of a directory on its own, with `socket.json` settings under `defaults.manifest.builds` keyed by its build file name. ### Changed +- Gradle, Maven, sbt and .NET Socket facts SBOM files are now generated by the Coana CLI. Downloading it the first time needs a login (`socket login`) or an API token. - `socket.json` settings apply from every directory above a scan's starting point, not only from that directory down. - `--dynamic-sbom-inference` builds a module that lives outside its reactor's directory (such as Maven's `../core`) only inside that reactor, instead of also building it on its own. - A build that fails to generate Socket facts now stops only the builds in and beneath its directory, and its failure is ignored when another build that includes it succeeds. diff --git a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts index b62add74b1..c5b550c143 100644 --- a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts +++ b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts @@ -157,8 +157,8 @@ describe('socket fix --dynamic-sbom-inference', () => { ) const args = coanaCalls('compute-fixes-and-upgrade-purls')[0]! expect(args).toContain('--maven-use-only-socket-facts') - expect(args).toContain('--compute-artifacts-sidecar') - expect(args[args.indexOf('--compute-artifacts-sidecar') + 1]).toBe( + expect(args).toContain('--socket-facts-sidecar') + expect(args[args.indexOf('--socket-facts-sidecar') + 1]).toBe( generated.sidecarFile, ) expect(generated.remove).toHaveBeenCalledTimes(1) @@ -179,7 +179,7 @@ describe('socket fix --dynamic-sbom-inference', () => { const args = coanaCalls('find-vulnerabilities')[0] expect(args).toContain('--maven-use-only-socket-facts') - expect(args).not.toContain('--compute-artifacts-sidecar') + expect(args).not.toContain('--socket-facts-sidecar') }) it('regenerates facts files that were already present, uploading each once', async () => { diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index df44729781..9d6ec66385 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -398,11 +398,13 @@ async function coanaFixWithFacts( logger.info('Generating Socket facts for each build ...') } factsSlot.generated = await generateSocketFactsForFix({ + coanaVersion, cwd, excludePaths, purlTypes: factsSlot.purlTypes, findFactsPaths: async () => (await findScanFilepaths()).filter(isSocketFactsFile), + orgSlug, tmpDir: factsSlot.tmpDir, }) scanFilepaths = await withoutDiscardedFacts( @@ -416,13 +418,12 @@ async function coanaFixWithFacts( } } const sidecarFile = factsSlot?.generated?.sidecarFile - // Discovery only needs which artifacts the facts files resolve. Applying - // fixes reads each project's tree; a Coana predating facts trees can only - // tell from the sidecar's classpaths which projects resolve an artifact. + // Discovery only needs which artifacts the facts files resolve; applying + // fixes also reads what facts generation kept of each build root. const discoveryFlags = factsSlot?.generated?.artifactsFlags ?? [] const factsFlags = [ ...discoveryFlags, - ...(sidecarFile ? ['--compute-artifacts-sidecar', sidecarFile] : []), + ...(sidecarFile ? ['--socket-facts-sidecar', sidecarFile] : []), ] const uploadCResult = await handleApiCall( sockSdk.uploadManifestFiles(orgSlug, scanFilepaths, { diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index a6654b9685..a1a49f5f3f 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -5,6 +5,7 @@ import { useOnlySocketFactsArtifactsFlags } from '../../utils/coana.mts' import { runDynamicSbomInference } from '../scan/run-dynamic-sbom-inference.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' +import type { SocketFactsWorkDir } from '../manifest/run-manifest-facts.mts' export type GeneratedSocketFacts = { // Coana's flags selecting what the facts files resolve. @@ -12,7 +13,8 @@ export type GeneratedSocketFacts = { // Facts files of dropped runs, which Coana must not read. discardedPaths: string[] paths: string[] - // The facts files' per-project classpaths, written outside the repository. + // What Coana kept of each build root, for `--socket-facts-sidecar`; written + // outside the repository. sidecarFile: string remove: () => Promise restore: () => Promise @@ -40,15 +42,19 @@ async function restoreAll(backups: Backup[]): Promise { // Backed up so each fix attempt sees the pre-fix build after `git clean`, and // facts files already present are left as they were found. export async function generateSocketFactsForFix({ + coanaVersion, cwd, excludePaths, findFactsPaths, + orgSlug, purlTypes, tmpDir, }: { + coanaVersion?: string | undefined cwd: string excludePaths: string[] findFactsPaths: () => Promise + orgSlug?: string | undefined purlTypes: readonly PURL_Type[] tmpDir: string }): Promise { @@ -65,25 +71,26 @@ export async function generateSocketFactsForFix({ let discardedPaths: string[] let paths: string[] const sidecarFile = path.join(tmpDir, 'sidecar.json') + const workDir: SocketFactsWorkDir = { + dir: path.join(tmpDir, 'work'), + entries: [], + withFiles: false, + } try { - const { - discardedFactsPaths, - factsOnlyTypes, - factsPaths, - resolvedPathsSidecar, - } = await runDynamicSbomInference({ - consumer: 'fix', - cwd, - excludePaths, - purlTypes, - sbtTmpDir: undefined, - }) + const { discardedFactsPaths, factsOnlyTypes, factsPaths } = + await runDynamicSbomInference({ + consumer: 'fix', + context: { coanaVersion, orgSlug, workDir }, + cwd, + excludePaths, + purlTypes, + }) artifactsFlags = useOnlySocketFactsArtifactsFlags(factsOnlyTypes) discardedPaths = discardedFactsPaths paths = factsPaths.map(p => path.resolve(cwd, p)) // Written even when empty, as for reach; applying fixes looks each facts // file up in it, so an empty one is the same as none. - await writeFile(sidecarFile, JSON.stringify(resolvedPathsSidecar ?? {})) + await writeFile(sidecarFile, JSON.stringify(workDir.entries)) } catch (e) { // A failed build root aborts inference after others wrote their facts. await reset(await findFactsPaths()) diff --git a/src/commands/fix/generated-socket-facts.test.mts b/src/commands/fix/generated-socket-facts.test.mts index f395c62ae0..4f501dbe4e 100644 --- a/src/commands/fix/generated-socket-facts.test.mts +++ b/src/commands/fix/generated-socket-facts.test.mts @@ -85,33 +85,44 @@ describe('generateSocketFactsForFix', () => { expect(await fs.readFile(existing, 'utf8')).toBe('original') }) - it('writes the sidecar outside the repository', async () => { - mockRunDynamicSbomInference.mockImplementation(async () => { + it('keeps what Coana kept of each build root outside the repository', async () => { + const entry = { factsFile: fresh, stateDir: path.join(tmpDir, 'work', 'x') } + mockRunDynamicSbomInference.mockImplementation(async ({ context }) => { await fs.writeFile(fresh, 'generated') + context.workDir.entries.push(entry) return { discardedFactsPaths: [], factsOnlyTypes: ['maven', 'nuget'], factsPaths: [fresh], - resolvedPathsSidecar: { [fresh]: { components: [], projects: [] } }, } }) const { artifactsFlags, sidecarFile } = await generate() expect(mockRunDynamicSbomInference).toHaveBeenCalledWith( - expect.objectContaining({ consumer: 'fix', purlTypes: ['maven'] }), + expect.objectContaining({ + consumer: 'fix', + context: { + coanaVersion: undefined, + orgSlug: undefined, + workDir: { + dir: path.join(tmpDir, 'work'), + entries: [entry], + withFiles: false, + }, + }, + purlTypes: ['maven'], + }), ) expect(artifactsFlags).toEqual([ '--use-only-socket-facts-artifacts', 'maven,nuget', ]) expect(path.dirname(sidecarFile)).toBe(tmpDir) - expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual({ - [fresh]: { components: [], projects: [] }, - }) + expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual([entry]) }) - it('writes an empty sidecar when no build root resolved any paths', async () => { + it('writes an empty sidecar when no build root generated facts', async () => { mockRunDynamicSbomInference.mockResolvedValue({ discardedFactsPaths: [], factsOnlyTypes: ['maven'], @@ -121,7 +132,7 @@ describe('generateSocketFactsForFix', () => { const { artifactsFlags, sidecarFile } = await generate() expect(artifactsFlags).toEqual(['--maven-use-only-socket-facts']) - expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual({}) + expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual([]) }) it('restores an existing facts file that generation does not rewrite', async () => { diff --git a/src/commands/manifest/cmd-manifest-auto.mts b/src/commands/manifest/cmd-manifest-auto.mts index e8451ba575..cf4021a361 100644 --- a/src/commands/manifest/cmd-manifest-auto.mts +++ b/src/commands/manifest/cmd-manifest-auto.mts @@ -9,7 +9,6 @@ import { excludePathsFlag } from './manifest-flags.mts' import constants from '../../constants.mts' import { commonFlags } from '../../flags.mts' import { cmdFlagValueToArray } from '../../utils/cmd.mts' -import { withTmpDir } from '../../utils/fs.mts' import { getOutputKind } from '../../utils/get-output-kind.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' import { getFlagListOutput } from '../../utils/output-formatting.mts' @@ -125,16 +124,13 @@ async function run( const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths']) assertValidExcludePaths(excludePaths) - await withTmpDir('socket-manifest-auto-', tmpDir => - generateAutoManifest({ - detected, - cwd, - excludePaths, - outputKind, - tmpDir, - verbose, - }), - ) + await generateAutoManifest({ + detected, + cwd, + excludePaths, + outputKind, + verbose, + }) logger.success( `Finished. Should have attempted to generate manifest files for ${detected.count} targets.`, diff --git a/src/commands/manifest/cmd-manifest-scala.mts b/src/commands/manifest/cmd-manifest-scala.mts index c9b2152dbd..19f887dfb4 100644 --- a/src/commands/manifest/cmd-manifest-scala.mts +++ b/src/commands/manifest/cmd-manifest-scala.mts @@ -11,7 +11,6 @@ import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' import { checkCommandInput } from '../../utils/check-input.mts' import { cmdFlagValueToArray } from '../../utils/cmd.mts' -import { withTmpDir } from '../../utils/fs.mts' import { getOutputKind } from '../../utils/get-output-kind.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' import { getFlagListOutput } from '../../utils/output-formatting.mts' @@ -352,20 +351,17 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await withTmpDir('socket-manifest-scala-', tmpDir => - convertSbtToFacts({ - bin: String(bin), - cwd, - excludeConfigs: String(excludeConfigs || ''), - excludePaths, - ignoreUnresolved: Boolean(ignoreUnresolved), - includeConfigs: String(includeConfigs || ''), - javaHome, - sbtOpts: parsedSbtOpts, - tmpDir, - verbose: Boolean(verbose), - }), - ) + await convertSbtToFacts({ + bin: String(bin), + cwd, + excludeConfigs: String(excludeConfigs || ''), + excludePaths, + ignoreUnresolved: Boolean(ignoreUnresolved), + includeConfigs: String(includeConfigs || ''), + javaHome, + sbtOpts: parsedSbtOpts, + verbose: Boolean(verbose), + }) return } diff --git a/src/commands/manifest/convert-dotnet-to-facts.mts b/src/commands/manifest/convert-dotnet-to-facts.mts index d4fcd5a774..e14ce3aa06 100644 --- a/src/commands/manifest/convert-dotnet-to-facts.mts +++ b/src/commands/manifest/convert-dotnet-to-facts.mts @@ -8,30 +8,30 @@ import { import { buildUncoveredRoot } from './generate-recursive-manifests.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' // Generates `.socket.facts.json` for the given solution or project // file, or for every solution and project at the top of `cwd`. A project a // solution there already covers is not built again. export async function convertDotnetToFacts({ config, + context, cwd, entryFile, excludePaths, hints, - sidecarAcc, - withFiles, }: { config: EcosystemBuildConfig + context?: SocketFactsContext | undefined cwd: string // Builds only this file (relative to cwd) when set. entryFile?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined - sidecarAcc?: SidecarAccumulator | undefined - withFiles?: boolean | undefined }): Promise { const entries = entryFile ? [entryFile] : findDotnetEntries(cwd) if (!entries.length) { @@ -48,14 +48,13 @@ export async function convertDotnetToFacts({ // eslint-disable-next-line no-await-in-loop const outcome = await buildUncoveredRoot({ config, + context, covered, cwd, ecosystem: 'dotnet', excludePaths, hints, root: { dir, entryFile: entry }, - sidecarAcc, - withFiles, }) if (outcome === 'covered') { if (config.verbose) { diff --git a/src/commands/manifest/convert-gradle-to-facts.mts b/src/commands/manifest/convert-gradle-to-facts.mts index 3ed9a63292..b00782a60a 100644 --- a/src/commands/manifest/convert-gradle-to-facts.mts +++ b/src/commands/manifest/convert-gradle-to-facts.mts @@ -1,13 +1,15 @@ import { runManifestFacts } from './run-manifest-facts.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' -// Generates `gradle.socket.facts.json` for a Gradle project via the bundled -// init script. +// Generates `gradle.socket.facts.json` for a Gradle project with Coana. export async function convertGradleToFacts({ bin, + context, cwd, excludeConfigs, excludePaths, @@ -16,11 +18,10 @@ export async function convertGradleToFacts({ ignoreUnresolved, includeConfigs, javaHome, - sidecarAcc, verbose, - withFiles, }: { bin: string + context?: SocketFactsContext | undefined cwd: string excludeConfigs: string excludePaths?: string[] | undefined @@ -29,13 +30,12 @@ export async function convertGradleToFacts({ ignoreUnresolved: boolean includeConfigs: string javaHome?: string | undefined - sidecarAcc?: SidecarAccumulator | undefined verbose: boolean - withFiles?: boolean | undefined }): Promise { return await runManifestFacts({ bin, buildOpts: gradleOpts, + context, cwd, ecosystem: 'gradle', excludeConfigs, @@ -44,8 +44,6 @@ export async function convertGradleToFacts({ ignoreUnresolved, includeConfigs, javaHome, - sidecarAcc, verbose, - withFiles, }) } diff --git a/src/commands/manifest/convert-maven-to-facts.mts b/src/commands/manifest/convert-maven-to-facts.mts index ad436e6bc4..e51aefeafe 100644 --- a/src/commands/manifest/convert-maven-to-facts.mts +++ b/src/commands/manifest/convert-maven-to-facts.mts @@ -1,13 +1,16 @@ import { runManifestFacts } from './run-manifest-facts.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' // Generates `pom.xml.socket.facts.json` (named after the POM Maven runs on) -// for a Maven project via the bundled extension. +// for a Maven project with Coana. export async function convertMavenToFacts({ bin, + context, cwd, excludeConfigs, excludePaths, @@ -16,11 +19,10 @@ export async function convertMavenToFacts({ includeConfigs, javaHome, mavenOpts, - sidecarAcc, verbose, - withFiles, }: { bin: string + context?: SocketFactsContext | undefined cwd: string excludeConfigs: string excludePaths?: string[] | undefined @@ -29,13 +31,12 @@ export async function convertMavenToFacts({ includeConfigs: string javaHome?: string | undefined mavenOpts: string[] - sidecarAcc?: SidecarAccumulator | undefined verbose: boolean - withFiles?: boolean | undefined }): Promise { return await runManifestFacts({ bin, buildOpts: mavenOpts, + context, cwd, ecosystem: 'maven', excludeConfigs, @@ -44,8 +45,6 @@ export async function convertMavenToFacts({ ignoreUnresolved, includeConfigs, javaHome, - sidecarAcc, verbose, - withFiles, }) } diff --git a/src/commands/manifest/convert-sbt-to-facts.mts b/src/commands/manifest/convert-sbt-to-facts.mts index b1a1d35e25..5d209c8895 100644 --- a/src/commands/manifest/convert-sbt-to-facts.mts +++ b/src/commands/manifest/convert-sbt-to-facts.mts @@ -1,14 +1,17 @@ import { runManifestFacts } from './run-manifest-facts.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' -// Generates `sbt.socket.facts.json` for an sbt project via the bundled sbt plugin. +// Generates `sbt.socket.facts.json` for an sbt project with Coana. // sbt 0.13/early 1.x can't run on modern JDKs — pass a compatible JDK via // `--sbt-opts "--java-home "` or `JAVA_HOME`. export async function convertSbtToFacts({ bin, + context, cwd, excludeConfigs, excludePaths, @@ -17,12 +20,10 @@ export async function convertSbtToFacts({ includeConfigs, javaHome, sbtOpts, - sidecarAcc, - tmpDir, verbose, - withFiles, }: { bin: string + context?: SocketFactsContext | undefined cwd: string excludeConfigs: string excludePaths?: string[] | undefined @@ -31,15 +32,12 @@ export async function convertSbtToFacts({ includeConfigs: string javaHome?: string | undefined sbtOpts: string[] - sidecarAcc?: SidecarAccumulator | undefined - // Caller-owned; see ManifestScriptOptions.tmpDir. - tmpDir: string verbose: boolean - withFiles?: boolean | undefined }): Promise { return await runManifestFacts({ bin, buildOpts: sbtOpts, + context, cwd, ecosystem: 'sbt', excludeConfigs, @@ -48,9 +46,6 @@ export async function convertSbtToFacts({ ignoreUnresolved, includeConfigs, javaHome, - sidecarAcc, - tmpDir, verbose, - withFiles, }) } diff --git a/src/commands/manifest/discover-manifest-roots.mts b/src/commands/manifest/discover-manifest-roots.mts index 73636c0fc8..3e3660d263 100644 --- a/src/commands/manifest/discover-manifest-roots.mts +++ b/src/commands/manifest/discover-manifest-roots.mts @@ -5,6 +5,7 @@ import micromatch from 'micromatch' import { logger } from '@socketsecurity/registry/lib/logger' +import { listDotnetSolutionMembers } from './run-manifest-facts.mts' import { BUILD_FILES, BUILD_TOOLS, @@ -12,15 +13,14 @@ import { buildToolsFor, isDotnetSolution, } from './scripts/build-tool.mts' -import { listDotnetEntryProjects } from './scripts/run.mts' import { realpathOrResolved } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { globWithGitIgnore } from '../../utils/glob.mts' import { excludePathToScanIgnores } from '../scan/exclude-paths.mts' +import type { SocketFactsContext } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { SocketFactsSbomProject } from './scripts/facts.mts' -import type { ManifestScriptOptions } from './scripts/run.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { SocketJson } from '../../utils/socket-json.mts' import type { SocketYml } from '@socketsecurity/config' @@ -166,6 +166,22 @@ export async function membershipOf( return membership } +// Coana reports the realpath-resolved build files a build covers. +export async function membershipOfBuildFiles( + files: readonly string[], + scanRoot?: string | undefined, +): Promise { + const realScanRoot = scanRoot ? await realpathOrResolved(scanRoot) : undefined + return { + dirs: new Set(), + files: new Set( + realScanRoot + ? files.filter(file => isPathInside(realScanRoot, file)) + : files, + ), + } +} + const rootMarkerByDir = new Map() export function hasRootMarker(tool: BuildTool, root: BuildRoot): boolean { @@ -196,17 +212,22 @@ export function isBuildRootCovered( ) } +export type RootBuildOptions = { + bin?: string | undefined + buildOpts: string[] + context?: SocketFactsContext | undefined + excludeBase?: string | undefined + excludePaths?: string[] | undefined +} + // A dotnet solution is covered once every project it builds is, or, when the // SDK cannot read it, by a same-named solution in the other format beside it // (`dotnet sln migrate` writes App.slnx next to App.sln) that it can read. async function isSolutionCovered( covered: Membership, root: BuildRoot, - opts: Pick< - ManifestScriptOptions, - 'bin' | 'excludeBase' | 'excludePaths' | 'toolOpts' - >, - listMembers: typeof listDotnetEntryProjects = listDotnetEntryProjects, + opts: RootBuildOptions, + listMembers: typeof listDotnetSolutionMembers = listDotnetSolutionMembers, ): Promise { const { entryFile } = root if (!entryFile || !isDotnetSolution(entryFile)) { @@ -220,7 +241,7 @@ async function isSolutionCovered( return false } const list = (file: string) => - listMembers({ ...opts, entryFile: file, projectDir: root.dir }) + listMembers({ ...opts, dir: root.dir, entryFile: file }) const listed = await list(entryFile) if (!listed) { // Unless the twin is readable, this one is built and its failure shows. @@ -254,11 +275,8 @@ export async function isRootCovered( covered: Membership, tool: BuildTool, root: BuildRoot, - opts: Pick< - ManifestScriptOptions, - 'bin' | 'excludeBase' | 'excludePaths' | 'toolOpts' - >, - listMembers: typeof listDotnetEntryProjects = listDotnetEntryProjects, + opts: RootBuildOptions, + listMembers: typeof listDotnetSolutionMembers = listDotnetSolutionMembers, ): Promise { return ( isBuildRootCovered(covered, tool, root) || diff --git a/src/commands/manifest/enumerate-workspaces.mts b/src/commands/manifest/enumerate-workspaces.mts index 87f838befe..120b1998e5 100644 --- a/src/commands/manifest/enumerate-workspaces.mts +++ b/src/commands/manifest/enumerate-workspaces.mts @@ -4,13 +4,24 @@ import { expandEnvVarRefs, formatMissingEnvVarRefs, } from './expand-env-var-refs.mts' -import { tailBuildOutput } from './run-manifest-facts.mts' import { enumerateWorkspaces as enumerateWorkspacesScript } from './scripts/run.mts' import { getErrorMessageOr } from '../../utils/errors.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { SocketFactsSbomProject } from './scripts/facts.mts' +const MAX_FAILURE_OUTPUT_LINES = 40 + +// Last N non-empty lines of the captured build output, for diagnosing a crash +// without forcing a --verbose rebuild. +function tailBuildOutput(stdout: string, stderr: string): string { + const combined = [stdout, stderr] + .map(s => s.trimEnd()) + .filter(Boolean) + .join('\n') + return combined.split('\n').slice(-MAX_FAILURE_OUTPUT_LINES).join('\n') +} + export type EnumerateWorkspacesResult = { buildRoot: string projects: SocketFactsSbomProject[] diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 6bebf01b0f..4ad8be7d8a 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -21,41 +21,45 @@ import { isBuildRootCovered, isPathInside, isRootCovered, - membershipOf, + membershipOfBuildFiles, realpathOrResolved, unionMemberships, withoutDisabledFlags, } from './discover-manifest-roots.mts' import { loadBuild, withModules } from './load-build.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' -import { runManifestFacts } from './run-manifest-facts.mts' +import { + DSI_SETUP_COMMAND, + REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, + runManifestFacts, + setSidecarEntry, + sidecarEntryOf, +} from './run-manifest-facts.mts' import { BUILD_FILES, resolveBuildToolBin, socketFactsFileName, } from './scripts/build-tool.mts' -import { - DSI_SETUP_COMMAND, - REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, -} from './scripts/resolution-report-render.mts' import { loadSocketConfig } from '../../utils/config.mts' -import { withTmpDir } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' import type { ResolvedBuildRootSettings } from './build-root-config.mts' -import type { BuildRoot, Membership } from './discover-manifest-roots.mts' +import type { + BuildRoot, + Membership, + RootBuildOptions, +} from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { + BuildOption, + BuildOptionHints, RunManifestFactsOutcome, RunManifestFactsResult, + SocketFactsContext, + SocketFactsSidecarEntry, } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { - BuildOption, - BuildOptionHints, -} from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { SocketJson } from '../../utils/socket-json.mts' @@ -151,12 +155,10 @@ type Candidate = { root: BuildRoot } -type SidecarEntry = NonNullable> - // A copy of a facts file, if there was one, and its sidecar entry. type FactsState = { facts: string | undefined - sidecar: SidecarEntry | undefined + sidecar: SocketFactsSidecarEntry | undefined } type Run = Candidate & { @@ -174,6 +176,7 @@ type Load = Candidate & LoadedBuild type WalkContext = { backupDir: () => Promise + context: SocketFactsContext excludePaths: string[] | undefined // What each facts file held before the walk, by real path; undefined when a // run wrote it away from its own directory (Gradle's `-p`) before it was @@ -186,10 +189,7 @@ type WalkContext = { tool: BuildTool, root: BuildRoot, ) => ResolvedBuildRootSettings - sbtTmpDir: string | undefined - sidecarAcc: SidecarAccumulator | undefined verbose: boolean - withFiles: boolean | undefined } type Loader = { path: string; skipped: boolean } @@ -205,17 +205,19 @@ function statusOf(loader: Loader | undefined): RecursiveManifestOutcomeStatus { return loader?.skipped ? 'skippedDisabled' : 'skippedCovered' } -// The options the build-tool scripts take besides the build itself. +// The options a build's listings take besides the build itself. export function buildToolScriptOptions( config: Pick, excludeBase: string | undefined, excludePaths: string[] | undefined, -) { + context?: SocketFactsContext | undefined, +): RootBuildOptions { return { bin: config.bin, + buildOpts: config.buildOpts, + context, excludeBase, excludePaths, - toolOpts: config.buildOpts, } } @@ -314,7 +316,12 @@ async function walkTool( }) const scriptOpts = (candidate: Candidate) => - buildToolScriptOptions(configFor(candidate), ctx.realCwd, ctx.excludePaths) + buildToolScriptOptions( + configFor(candidate), + ctx.realCwd, + ctx.excludePaths, + ctx.context, + ) // A solution the SDK cannot read, built through its twin instead. const superseded = new Map>() @@ -677,6 +684,7 @@ async function runCandidate( const result = await runManifestFacts({ bin: dirConfig.bin, buildOpts: dirConfig.buildOpts, + context: ctx.context, cwd: root.dir, ecosystem, entryFile: root.entryFile, @@ -686,7 +694,7 @@ async function runCandidate( excludeConfigs: dirConfig.excludeConfigs, excludePaths: ctx.excludePaths, hints: { - continueOnInstallErrorsFlag: ctx.withFiles + continueOnInstallErrorsFlag: ctx.context.workDir?.withFiles ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG : undefined, flags: ctx.optionFlags, @@ -696,10 +704,7 @@ async function runCandidate( ignoreUnresolved: ctx.ignoreUnresolved ?? dirConfig.ignoreUnresolved, includeConfigs: dirConfig.includeConfigs, javaHome: dirConfig.javaHome, - sidecarAcc: ctx.sidecarAcc, - tmpDir: ecosystem === 'sbt' ? ctx.sbtTmpDir : undefined, verbose: ctx.verbose || dirConfig.verbose, - withFiles: ctx.withFiles, }) if (result === null) { return undefined @@ -722,13 +727,8 @@ async function runCandidate( return { ...candidate, factsKey, - // Gradle's `-p` can root the build away from `root.dir`. membership: result - ? await membershipOf( - path.dirname(result.factsPath), - result.projects, - ctx.realCwd, - ) + ? await membershipOfBuildFiles(result.coveredBuildFiles, ctx.realCwd) : emptyMembership(), output, result: result ?? undefined, @@ -743,10 +743,9 @@ async function putFacts( key: string, state: FactsState | undefined, ): Promise { - if (state?.sidecar) { - ctx.sidecarAcc?.set(key, state.sidecar) - } else { - ctx.sidecarAcc?.delete(key) + const { workDir } = ctx.context + if (workDir) { + setSidecarEntry(workDir, key, state?.sidecar) } if (!state) { return @@ -769,13 +768,15 @@ async function saveFacts( facts = path.join(await ctx.backupDir(), name) await fs.copyFile(file, facts) } - return { facts, sidecar: ctx.sidecarAcc?.get(key) } + const { workDir } = ctx.context + return { facts, sidecar: workDir && sidecarEntryOf(workDir, key) } } // Builds `root` unless earlier builds cover it, then adds what it loaded to // `covered`. export async function buildUncoveredRoot({ config, + context, covered, cwd, ecosystem, @@ -783,11 +784,9 @@ export async function buildUncoveredRoot({ excludePaths, hints, root, - sidecarAcc, - tmpDir, - withFiles, }: { config: EcosystemBuildConfig + context?: SocketFactsContext | undefined covered: Membership // Where the build runs, as the user named it; `root.dir` by default. cwd?: string | undefined @@ -796,9 +795,6 @@ export async function buildUncoveredRoot({ excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined root: BuildRoot - sidecarAcc?: SidecarAccumulator | undefined - tmpDir?: string | undefined - withFiles?: boolean | undefined }): Promise { const { bin, buildOpts } = config if ( @@ -806,7 +802,7 @@ export async function buildUncoveredRoot({ covered, ecosystem, root, - buildToolScriptOptions(config, excludeBase, excludePaths), + buildToolScriptOptions(config, excludeBase, excludePaths, context), ) ) { return 'covered' @@ -814,6 +810,7 @@ export async function buildUncoveredRoot({ const result = await runManifestFacts({ bin, buildOpts, + context, cwd: cwd ?? root.dir, ecosystem, entryFile: root.entryFile, @@ -824,15 +821,12 @@ export async function buildUncoveredRoot({ ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, - sidecarAcc, - tmpDir, verbose: config.verbose, - withFiles, }) if (result) { addMembership( covered, - await membershipOf(path.dirname(result.factsPath), result.projects), + await membershipOfBuildFiles(result.coveredBuildFiles), ) } return result @@ -840,16 +834,15 @@ export async function buildUncoveredRoot({ // A failure fails the walk only when no kept or skipped build loads it. export async function generateRecursiveManifests({ + context = {}, cwd, excludePaths, ignoreUnresolved, optionFlags = new Set(), purlTypes, - sbtTmpDir, - sidecarAcc, verbose, - withFiles, }: { + context?: SocketFactsContext | undefined cwd: string excludePaths?: string[] | undefined // When set, overrides every build root's own socket.json setting. @@ -858,21 +851,7 @@ export async function generateRecursiveManifests({ // build root's socket.json. optionFlags?: ReadonlySet | undefined purlTypes?: readonly PURL_Type[] | undefined - // Reachability path only: caller-supplied directory to use as sbt's shared - // global base across every sbt root in this run. sbt provisions the Scala - // toolchain under `/boot`, which withFiles' artifactPaths point into, - // so when the caller intends to consume those paths after this call - // returns (e.g. reachability analysis), it must supply a directory that - // outlives this call and delete it once it's done - mirrors - // ManifestScriptOptions.tmpDir one level up. Unset ⇒ an ephemeral shared - // dir is allocated and cleaned up before this call returns, matching - // runManifestFacts' own withFiles-less default. - sbtTmpDir?: string | undefined - // Reachability path only: run build tools with files and fold resolved - // artifact paths into sidecarAcc, keyed by each root's own factsPath. - sidecarAcc?: SidecarAccumulator | undefined verbose: boolean - withFiles?: boolean | undefined }): Promise { const rootSockJson = readOrDefaultSocketJson(cwd) // Candidate dirs come back realpath-resolved (findBuildToolCandidates); cwd @@ -899,47 +878,28 @@ export async function generateRecursiveManifests({ const exitCodeBefore = process.exitCode let backupDir: string | undefined - const runAll = async (resolvedSbtTmpDir: string | undefined) => { - const ctx: WalkContext = { - backupDir: async () => { - backupDir ??= await fs.mkdtemp( - path.join(tmpdir(), 'socket-facts-backup-'), - ) - return backupDir - }, - excludePaths, - ignoreUnresolved, - optionFlags, - originals: new Map(), - realCwd, - resolveSettings, - sbtTmpDir: resolvedSbtTmpDir, - sidecarAcc, - verbose, - withFiles, - } - const outcomes: RecursiveManifestOutcome[] = [] + const ctx: WalkContext = { + backupDir: async () => { + backupDir ??= await fs.mkdtemp( + path.join(tmpdir(), 'socket-facts-backup-'), + ) + return backupDir + }, + context, + excludePaths, + ignoreUnresolved, + optionFlags, + originals: new Map(), + realCwd, + resolveSettings, + verbose, + } + const outcomes: RecursiveManifestOutcome[] = [] + try { for (const { 0: ecosystem, 1: roots } of candidatesByTool) { // eslint-disable-next-line no-await-in-loop outcomes.push(...(await walkTool(ctx, ecosystem, roots))) } - return outcomes - } - - // A shared global base across every sbt root in this run lets sbt's own - // Scala-toolchain cache under /boot survive between invocations - // instead of being reprovisioned per root (the plugin file is rewritten and - // records.tsv is removed before every invocation, so reuse is safe). A - // caller-supplied sbtTmpDir is reused as-is (the caller owns its lifetime); - // otherwise one is allocated and cleaned up here, but only when there's an - // sbt root to benefit from sharing it at all. - let outcomes: RecursiveManifestOutcome[] - try { - outcomes = sbtTmpDir - ? await runAll(sbtTmpDir) - : candidatesByTool.get('sbt')?.length - ? await withTmpDir('socket-sbt-facts-shared-', runAll) - : await runAll(undefined) } finally { if (backupDir) { await fs.rm(backupDir, { recursive: true, force: true }) diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 3bb4031be5..c150a6ec1b 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -12,30 +12,73 @@ vi.mock('../../utils/socket-json.mts', async importOriginal => ({ // Default: no nested socket.json anywhere in the fixture tree. readSocketJsonChain: vi.fn(() => []), })) -vi.mock('./run-manifest-facts.mts', () => ({ +vi.mock('./run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal()), + listDotnetSolutionMembers: vi.fn(async () => undefined), runManifestFacts: vi.fn(), })) vi.mock('./enumerate-workspaces.mts', () => ({ enumerateWorkspaces: vi.fn(), })) -vi.mock('./scripts/run.mts', async importOriginal => ({ - ...(await importOriginal()), - listDotnetEntryProjects: vi.fn(async () => undefined), -})) import { buildRootPath } from './discover-manifest-roots.mts' import { enumerateWorkspaces } from './enumerate-workspaces.mts' import { generateRecursiveManifests } from './generate-recursive-manifests.mts' -import { runManifestFacts } from './run-manifest-facts.mts' -import { listDotnetEntryProjects } from './scripts/run.mts' +import { + listDotnetSolutionMembers, + runManifestFacts, + setSidecarEntry, +} from './run-manifest-facts.mts' import { testPath } from '../../../test/utils.mts' import { readOrDefaultSocketJson, readSocketJsonChain, } from '../../utils/socket-json.mts' +import type { + RunManifestFactsOutcome, + SocketFactsWorkDir, +} from './run-manifest-facts.mts' import type { SocketJson } from '../../utils/socket-json.mts' +type TestProject = { + manifestFiles?: Array<{ file: string }> | undefined + subprojectDir: string + [field: string]: unknown +} + +type TestFacts = { factsPath: string; projects: TestProject[] } + +// What Coana reports of a build whose tool lists `projects`, relative to the +// facts file's directory. +function reported({ factsPath, projects }: TestFacts) { + const buildRoot = path.dirname(factsPath) + return { + coveredBuildFiles: projects + .flatMap(project => project.manifestFiles ?? []) + .map(({ file }) => path.resolve(buildRoot, file)) + .filter(file => existsSync(file)), + factsPath, + } +} + +function newWorkDir(): SocketFactsWorkDir { + return { dir: '/work', entries: [], withFiles: true } +} + +function mockFacts( + impl: ( + options: Parameters[0], + ) => Promise, +): void { + vi.mocked(runManifestFacts).mockImplementation( + async (options): Promise => { + const facts = await impl(options) + return facts ? reported(facts) : facts + }, + ) +} + // The settings each build root's directory resolves to, as one socket.json at // the filesystem root. function mockCascade(cascade: (dir: string) => unknown): void { @@ -88,32 +131,30 @@ describe('generateRecursiveManifests', () => { }) it('invokes the reactor root once and skips its declared members, but still visits an undeclared nested submodule and a differently-tooled nested project', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (cwd === reactor && ecosystem === 'maven') { - return { - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [ - { - type: 'maven', - name: 'moduleA', - subprojectDir: 'moduleA', - manifestFiles: [{ file: 'moduleA/pom.xml' }], - children: [], - }, - { - type: 'maven', - name: 'moduleB', - subprojectDir: 'moduleB', - manifestFiles: [{ file: 'moduleB/pom.xml' }], - children: [], - }, - ], - } + mockFacts(async ({ cwd, ecosystem }) => { + if (cwd === reactor && ecosystem === 'maven') { + return { + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [ + { + type: 'maven', + name: 'moduleA', + subprojectDir: 'moduleA', + manifestFiles: [{ file: 'moduleA/pom.xml' }], + children: [], + }, + { + type: 'maven', + name: 'moduleB', + subprojectDir: 'moduleB', + manifestFiles: [{ file: 'moduleB/pom.xml' }], + children: [], + }, + ], } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const outcomes = await generateRecursiveManifests({ cwd: monorepo, @@ -159,7 +200,7 @@ describe('generateRecursiveManifests', () => { const reactorA = path.join(outer, 'reactor-a') const sharedLib = path.join(outer, sharedLibName) const sharedFacts = path.join(sharedLib, 'pom.xml.socket.facts.json') - const sidecarAcc = new Map() + const workDir = newWorkDir() try { await fs.mkdir(reactorA, { recursive: true }) await fs.mkdir(sharedLib, { recursive: true }) @@ -167,10 +208,13 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(sharedLib, 'pom.xml'), '') await fs.writeFile(sharedFacts, 'committed') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { const factsPath = path.join(cwd, 'pom.xml.socket.facts.json') await fs.writeFile(factsPath, 'generated') - sidecarAcc.set(factsPath, { components: [], projects: [] }) + setSidecarEntry(workDir, factsPath, { + factsFile: factsPath, + stateDir: cwd, + }) return { factsPath, projects: @@ -190,8 +234,8 @@ describe('generateRecursiveManifests', () => { }) const outcomes = await generateRecursiveManifests({ + context: { workDir }, cwd: outer, - sidecarAcc, verbose: false, }) @@ -204,7 +248,7 @@ describe('generateRecursiveManifests', () => { .mock.calls.some(([opts]) => opts.cwd === sharedLib), ).toBe(builtAlone) expect(await fs.readFile(sharedFacts, 'utf8')).toBe('committed') - expect([...sidecarAcc.keys()]).toEqual([ + expect(workDir.entries.map(entry => entry.factsFile)).toEqual([ path.join(reactorA, 'pom.xml.socket.facts.json'), ]) // The restored file is not this scan's, so it is not to be collected. @@ -217,65 +261,6 @@ describe('generateRecursiveManifests', () => { }, ) - it.for([ - // The build that redirects Gradle with `-p` runs second, then first. - ['a-main', 'z-alias'], - ['z-main', 'a-alias'], - ])( - 'keeps the facts and sidecar entry of the kept run together when two runs write one facts file (%s, %s)', - async ([mainName, aliasName]) => { - const outer = await fs.realpath( - await fs.mkdtemp(path.join(tmpdir(), 'shared-facts-')), - ) - const main = path.join(outer, mainName!) - const alias = path.join(outer, aliasName!) - const sidecarAcc = new Map() - try { - for (const dir of [main, alias]) { - for (const file of ['settings.gradle', 'build.gradle']) { - // eslint-disable-next-line no-await-in-loop - await fs.mkdir(dir, { recursive: true }) - // eslint-disable-next-line no-await-in-loop - await fs.writeFile(path.join(dir, file), '') - } - } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { - const factsPath = path.join(main, 'gradle.socket.facts.json') - await fs.writeFile(factsPath, cwd) - sidecarAcc.set(factsPath, { components: [], projects: [], cwd }) - return { - factsPath, - projects: [ - { - type: 'maven' as const, - name: 'root', - id: 'root', - subprojectDir: '.', - children: [], - }, - ], - } - }) - - const outcomes = await generateRecursiveManifests({ - cwd: outer, - sidecarAcc, - verbose: false, - }) - - const generated = outcomes.filter(o => o.status === 'generated') - expect(generated).toHaveLength(1) - const { factsPath } = generated[0]! - expect(generated[0]!.discardedFactsPath).toBeUndefined() - // The kept build's own facts and sidecar entry, whichever ran last. - expect(await fs.readFile(factsPath!, 'utf8')).toBe(generated[0]!.dir) - expect(sidecarAcc.get(factsPath!)?.cwd).toBe(generated[0]!.dir) - } finally { - await fs.rm(outer, { recursive: true, force: true }) - } - }, - ) - it('removes the facts file of a dropped run when none existed before it', async () => { const outer = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'dropped-run-')), @@ -289,7 +274,7 @@ describe('generateRecursiveManifests', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(path.join(dir, 'pom.xml'), '') } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { const factsPath = path.join(cwd, 'pom.xml.socket.facts.json') await fs.writeFile(factsPath, 'generated') return { @@ -338,42 +323,40 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(gradleMember, 'build.gradle'), '') await fs.writeFile(path.join(gradleMember, 'pom.xml'), '') - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (cwd === outer && ecosystem === 'maven') { - return { - factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), - projects: [ - { - type: 'maven', - name: 'shared', - subprojectDir: 'shared', - manifestFiles: [{ file: 'shared/alt.xml' }], - children: [], - }, - ], - } - } - if (cwd === outer && ecosystem === 'gradle') { - return { - factsPath: path.join(cwd, 'gradle.socket.facts.json'), - projects: [ - { - type: 'maven', - name: 'gradle-member', - subprojectDir: 'gradle-member', - manifestFiles: [{ file: 'gradle-member/build.gradle' }], - children: [], - }, - ], - } + mockFacts(async ({ cwd, ecosystem }) => { + if (cwd === outer && ecosystem === 'maven') { + return { + factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + projects: [ + { + type: 'maven', + name: 'shared', + subprojectDir: 'shared', + manifestFiles: [{ file: 'shared/alt.xml' }], + children: [], + }, + ], } + } + if (cwd === outer && ecosystem === 'gradle') { return { - factsPath: path.join(cwd, `${ecosystem}.socket.facts.json`), - projects: [], + factsPath: path.join(cwd, 'gradle.socket.facts.json'), + projects: [ + { + type: 'maven', + name: 'gradle-member', + subprojectDir: 'gradle-member', + manifestFiles: [{ file: 'gradle-member/build.gradle' }], + children: [], + }, + ], } - }, - ) + } + return { + factsPath: path.join(cwd, `${ecosystem}.socket.facts.json`), + projects: [], + } + }) const outcomes = await generateRecursiveManifests({ cwd: outer, @@ -401,7 +384,7 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(outer, 'build.sbt'), '') await fs.writeFile(path.join(member, 'build.sbt'), '') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, 'sbt.socket.facts.json'), projects: cwd === outer @@ -443,7 +426,7 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(outer, 'settings.gradle'), "include 'tools'") await fs.writeFile(path.join(tools, 'settings.gradle'), '') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, 'gradle.socket.facts.json'), projects: cwd === outer @@ -485,7 +468,7 @@ describe('generateRecursiveManifests', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(path.join(dir, 'pom.xml'), '') } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { if (cwd === outer) { return { factsPath: path.join(buildRoot, 'x.xml.socket.facts.json'), @@ -528,7 +511,7 @@ describe('generateRecursiveManifests', () => { }) it("runs both ecosystems unconditionally at a dual-marker directory (matches auto's existing behavior)", async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -547,15 +530,13 @@ describe('generateRecursiveManifests', () => { }) it('aborts only the build roots in and under a failed one, which may be its members, while siblings and other ecosystems proceed', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (ecosystem === 'maven' && cwd === reactor) { - process.exitCode = 1 - return null - } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === reactor) { + process.exitCode = 1 + return null + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -614,7 +595,7 @@ describe('generateRecursiveManifests', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(path.join(dir, 'pom.xml'), '') } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { if (cwd === core) { process.exitCode = 1 return null @@ -650,15 +631,13 @@ describe('generateRecursiveManifests', () => { it('still classifies a failure as failed (not empty) when process.exitCode was already non-zero beforehand', async () => { process.exitCode = 1 - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (ecosystem === 'maven' && cwd === dualMarkerDir) { - process.exitCode = 1 - return null - } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === dualMarkerDir) { + process.exitCode = 1 + return null + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -677,15 +656,13 @@ describe('generateRecursiveManifests', () => { }) it('reports a non-fatal empty result distinctly from a failure', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (ecosystem === 'maven' && cwd === dualMarkerDir) { - // No resolvable dependencies; runManifestFacts warns but does not fail. - return undefined - } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === dualMarkerDir) { + // No resolvable dependencies; runManifestFacts warns but does not fail. + return undefined + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const outcomes = await generateRecursiveManifests({ cwd: monorepo, @@ -699,7 +676,7 @@ describe('generateRecursiveManifests', () => { }) it('passes every build root the scan-root-relative --exclude-paths and the scan root', async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -725,21 +702,19 @@ describe('generateRecursiveManifests', () => { try { await fs.writeFile(path.join(dir, 'pom.xml'), '') await fs.writeFile(path.join(dir, 'App.sln'), '') - vi.mocked(listDotnetEntryProjects).mockClear() - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [ - { - type: 'maven', - name: 'app', - subprojectDir: '', - manifestFiles: [{ file: 'pom.xml' }], - children: [], - }, - ], - }), - ) + vi.mocked(listDotnetSolutionMembers).mockClear() + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [ + { + type: 'maven', + name: 'app', + subprojectDir: '', + manifestFiles: [{ file: 'pom.xml' }], + children: [], + }, + ], + })) const outcomes = await generateRecursiveManifests({ cwd: dir, verbose: false, @@ -748,7 +723,7 @@ describe('generateRecursiveManifests', () => { expect( outcomes.map(o => `${o.ecosystem}:${o.entryFile}:${o.status}`).sort(), ).toEqual(['dotnet:App.sln:generated', 'maven:pom.xml:generated']) - expect(listDotnetEntryProjects).not.toHaveBeenCalled() + expect(listDotnetSolutionMembers).not.toHaveBeenCalled() } finally { await fs.rm(dir, { recursive: true, force: true }) } @@ -760,7 +735,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { javaHome: '/opt/jdk-11' } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -793,7 +768,7 @@ describe('generateRecursiveManifests', () => { } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -818,7 +793,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { verbose: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -853,7 +828,7 @@ describe('generateRecursiveManifests', () => { } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -878,7 +853,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { ignoreUnresolved: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -906,7 +881,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { gradle: { facts: false } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -957,7 +932,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { disabled: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1014,7 +989,7 @@ describe('generateRecursiveManifests', () => { } return {} }) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1045,7 +1020,7 @@ describe('generateRecursiveManifests', () => { mockCascade(dir => ({ defaults: { manifest: { maven: { disabled: dir !== reactor } } }, })) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1075,7 +1050,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { disabled: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1127,7 +1102,7 @@ describe('generateRecursiveManifests', () => { }), ) await fs.symlink(realCwd, cwdLink) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1142,137 +1117,29 @@ describe('generateRecursiveManifests', () => { } }) - it('shares one sbt tmpDir across every discovered sbt root, but passes tmpDir: undefined for gradle/maven', async () => { - const outer = await fs.mkdtemp(path.join(tmpdir(), 'sbt-shared-tmpdir-')) - const sbtA = path.join(outer, 'sbt-a') - const sbtB = path.join(outer, 'sbt-b') - const mavenRoot = path.join(outer, 'maven-root') - try { - await fs.mkdir(sbtA, { recursive: true }) - await fs.mkdir(sbtB, { recursive: true }) - await fs.mkdir(mavenRoot, { recursive: true }) - await fs.writeFile(path.join(sbtA, 'build.sbt'), '') - await fs.writeFile(path.join(sbtB, 'build.sbt'), '') - await fs.writeFile(path.join(mavenRoot, 'pom.xml'), '') - - const tmpDirsSeen: Record> = {} - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem, tmpDir }) => { - ;(tmpDirsSeen[ecosystem] ??= []).push(tmpDir) - return { - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [], - } - }, - ) - - await generateRecursiveManifests({ - cwd: outer, - verbose: false, - }) - - expect(tmpDirsSeen['sbt']).toHaveLength(2) - expect(tmpDirsSeen['sbt']![0]).toBeDefined() - expect(tmpDirsSeen['sbt']![0]).toBe(tmpDirsSeen['sbt']![1]) - expect(tmpDirsSeen['maven']).toEqual([undefined]) - } finally { - await fs.rm(outer, { recursive: true, force: true }) - } - }) - - it('does not allocate a shared tmpDir at all when no sbt root is discovered', async () => { - const outer = await fs.mkdtemp(path.join(tmpdir(), 'no-sbt-tmpdir-')) - try { - await fs.writeFile(path.join(outer, 'pom.xml'), '') - - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [], - })) - - await generateRecursiveManifests({ - cwd: outer, - verbose: false, - }) - - expect( - vi.mocked(runManifestFacts).mock.calls[0]?.[0].tmpDir, - ).toBeUndefined() - } finally { - await fs.rm(outer, { recursive: true, force: true }) - } - }) - - it('reuses a caller-supplied sbtTmpDir as-is for every sbt root, and does not delete it', async () => { - const outer = await fs.mkdtemp(path.join(tmpdir(), 'sbt-caller-tmpdir-')) - const sbtA = path.join(outer, 'sbt-a') - const sbtB = path.join(outer, 'sbt-b') - const callerOwnedDir = await fs.mkdtemp( - path.join(tmpdir(), 'caller-owned-sbt-base-'), - ) - try { - await fs.mkdir(sbtA, { recursive: true }) - await fs.mkdir(sbtB, { recursive: true }) - await fs.writeFile(path.join(sbtA, 'build.sbt'), '') - await fs.writeFile(path.join(sbtB, 'build.sbt'), '') - - const tmpDirsSeen: Array = [] - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, tmpDir }) => { - tmpDirsSeen.push(tmpDir) - return { - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [], - } - }, - ) - - await generateRecursiveManifests({ - cwd: outer, - sbtTmpDir: callerOwnedDir, - verbose: false, - }) - - expect(tmpDirsSeen).toEqual([callerOwnedDir, callerOwnedDir]) - // generateRecursiveManifests must not clean up a directory it didn't - // allocate - the caller (e.g. handleCreateNewScan keeping it alive - // until reachability analysis consumes the sidecar's resolved paths) - // owns that lifetime. - await expect(fs.access(callerOwnedDir)).resolves.toBeUndefined() - } finally { - await fs.rm(outer, { recursive: true, force: true }) - await fs.rm(callerOwnedDir, { recursive: true, force: true }) - } - }) - - it('threads sidecarAcc/withFiles through to every build root, not just the first', async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + it('threads the work dir through to every build root, not just the first', async () => { + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) - const sidecarAcc = new Map() - await generateRecursiveManifests({ - cwd: monorepo, - sidecarAcc, - verbose: false, - withFiles: true, - }) + const context = { workDir: newWorkDir() } + await generateRecursiveManifests({ context, cwd: monorepo, verbose: false }) expect(vi.mocked(runManifestFacts).mock.calls.length).toBeGreaterThan(1) for (const [opts] of vi.mocked(runManifestFacts).mock.calls) { - expect(opts.sidecarAcc).toBe(sidecarAcc) - expect(opts.withFiles).toBe(true) + expect(opts.context).toBe(context) + expect(opts.hints?.continueOnInstallErrorsFlag).toBe( + '--reach-continue-on-install-errors', + ) } }) it('runs every POM in a directory as its own build', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [], + })) const outcomes = await generateRecursiveManifests({ cwd: pomNames, @@ -1296,23 +1163,21 @@ describe('generateRecursiveManifests', () => { }) it('covers a POM by file, so a sibling POM in the same directory still runs', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: - cwd === pomNames && entryFile === 'pom.xml' - ? [ - { - type: 'maven', - name: 'bare', - subprojectDir: 'bare', - manifestFiles: [{ file: 'bare/pom' }], - children: [], - }, - ] - : [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: + cwd === pomNames && entryFile === 'pom.xml' + ? [ + { + type: 'maven', + name: 'bare', + subprojectDir: 'bare', + manifestFiles: [{ file: 'bare/pom' }], + children: [], + }, + ] + : [], + })) const outcomes = await generateRecursiveManifests({ cwd: pomNames, @@ -1338,12 +1203,10 @@ describe('generateRecursiveManifests', () => { }, })) vi.mocked(readSocketJsonChain).mockClear() - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1405,70 +1268,6 @@ describe('generateRecursiveManifests', () => { await fs.rm(outer, { recursive: true, force: true }) }) - it.for([ - // sub's own settings include `a`, which the outer build does not load. - [['.', 'a'], 'generated'], - // Everything sub loads, the outer build loads too. - [['.'], 'skippedCovered'], - ] as const)( - 'runs the nested build and keeps it only when it loads more (%j)', - async ({ 0: subProjects, 1: subStatus }) => { - const sub = path.join(outer, 'sub') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => - cwd === outer - ? gradleFacts(cwd, [ - '.', - 'sub', - ...(subProjects.length > 1 ? [] : ['sub/a']), - ]) - : gradleFacts(cwd, [...subProjects]), - ) - - const outcomes = await generateRecursiveManifests({ - cwd: outer, - purlTypes: ['maven'], - verbose: false, - }) - - const byDir = new Map( - outcomes - .filter(o => o.ecosystem === 'gradle') - .map(o => [path.relative(outer, o.dir) || '.', o.status]), - ) - expect(byDir.get('.')).toBe('generated') - expect(byDir.get('sub')).toBe(subStatus) - expect(byDir.get('sub/a')).toBe('skippedCovered') - expect( - vi - .mocked(runManifestFacts) - .mock.calls.map(([o]) => path.relative(outer, o.cwd) || '.'), - ).toEqual(['.', 'sub']) - }, - ) - - it('ignores the failure of a nested build of its own when the build that includes its directory succeeds', async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { - if (cwd === path.join(outer, 'sub')) { - process.exitCode = 1 - return null - } - return gradleFacts(cwd, ['.', 'sub', 'sub/a']) - }) - vi.spyOn(logger, 'info').mockImplementation(() => logger) - - const outcomes = await generateRecursiveManifests({ - cwd: outer, - purlTypes: ['maven'], - verbose: false, - }) - - expect( - outcomes.find(o => o.dir === path.join(outer, 'sub'))?.status, - ).toBe('skippedCovered') - expect(outcomes.some(o => o.status === 'failed')).toBe(false) - expect(process.exitCode).toBeUndefined() - }) - it.for([ // `a` is a project of sub: skipped with what sub loads. [['.', 'a'], 'and its 1 module'], @@ -1489,9 +1288,7 @@ describe('generateRecursiveManifests', () => { buildRoot: sub, projects: gradleFacts(sub, [...subProjects]).projects, }) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => - gradleFacts(cwd, ['.']), - ) + mockFacts(async ({ cwd }) => gradleFacts(cwd, ['.'])) const warnSpy = vi .spyOn(logger, 'warn') .mockImplementation(() => logger) @@ -1538,12 +1335,10 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [], + })) await generateRecursiveManifests({ cwd: pomNames, verbose: false }) @@ -1567,24 +1362,22 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => ({ - factsPath: path.join(cwd, '.socket.facts.json'), - projects: - cwd === reactor && ecosystem === 'maven' - ? [ - { - type: 'maven', - name: 'moduleA', - id: 'moduleA', - subprojectDir: 'moduleA', - manifestFiles: [{ file: 'moduleA/pom.xml' }], - children: [], - }, - ] - : [], - }), - ) + mockFacts(async ({ cwd, ecosystem }) => ({ + factsPath: path.join(cwd, '.socket.facts.json'), + projects: + cwd === reactor && ecosystem === 'maven' + ? [ + { + type: 'maven', + name: 'moduleA', + id: 'moduleA', + subprojectDir: 'moduleA', + manifestFiles: [{ file: 'moduleA/pom.xml' }], + children: [], + }, + ] + : [], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1636,21 +1429,19 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => { - const factsPath = path.join(cwd, `${entryFile}.socket.facts.json`) - await fs.writeFile(factsPath, 'generated') - return { - factsPath, - projects: [ - { - ...mavenProject('.'), - manifestFiles: [{ file: entryFile ?? 'pom.xml' }], - }, - ], - } - }, - ) + mockFacts(async ({ cwd, entryFile }) => { + const factsPath = path.join(cwd, `${entryFile}.socket.facts.json`) + await fs.writeFile(factsPath, 'generated') + return { + factsPath, + projects: [ + { + ...mavenProject('.'), + manifestFiles: [{ file: entryFile ?? 'pom.xml' }], + }, + ], + } + }) }) afterEach(async () => { await fs.rm(outer, { recursive: true, force: true }) @@ -1710,20 +1501,18 @@ describe('generateRecursiveManifests', () => { buildRoot: path.join(outer, 'legacy'), projects: [mavenProject('.')], }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: - cwd === path.join(outer, 'zzz-reactor') - ? [mavenProject('.'), mavenProject('../legacy')] - : [ - { - ...mavenProject('.'), - manifestFiles: [{ file: entryFile ?? 'pom.xml' }], - }, - ], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: + cwd === path.join(outer, 'zzz-reactor') + ? [mavenProject('.'), mavenProject('../legacy')] + : [ + { + ...mavenProject('.'), + manifestFiles: [{ file: entryFile ?? 'pom.xml' }], + }, + ], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1824,25 +1613,23 @@ describe('generateRecursiveManifests', () => { defaults: { manifest: { builds: { 'Y.sln': { disabled: true } } } }, }, }) - vi.mocked(listDotnetEntryProjects).mockImplementation( + vi.mocked(listDotnetSolutionMembers).mockImplementation( async ({ entryFile }) => members[entryFile ?? ''], ) vi.mocked(enumerateWorkspaces).mockResolvedValue({ buildRoot: at('skip'), projects: [projectRecord('../p/a/A.csproj')], }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: - entryFile === 'R.sln' - ? [ - projectRecord('../p/a/A.csproj'), - projectRecord('../p/c/C.csproj'), - ] - : [projectRecord(entryFile ?? '')], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: + entryFile === 'R.sln' + ? [ + projectRecord('../p/a/A.csproj'), + projectRecord('../p/c/C.csproj'), + ] + : [projectRecord(entryFile ?? '')], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) const outcomes = await generateRecursiveManifests({ @@ -1869,7 +1656,7 @@ describe('generateRecursiveManifests', () => { ), ) } finally { - vi.mocked(listDotnetEntryProjects).mockImplementation( + vi.mocked(listDotnetSolutionMembers).mockImplementation( async () => undefined, ) await fs.rm(outer, { recursive: true, force: true }) diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index baa3294813..043cec08d1 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -12,9 +12,8 @@ import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { resolveEcosystemConfig } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' -import { REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG } from './scripts/resolution-report-render.mts' -import { hasSidecarEntries, serializeSidecar } from './scripts/sidecar.mts' import { ENVIRONMENT_YML, REQUIREMENTS_TXT, @@ -24,12 +23,11 @@ import { InputError } from '../../utils/errors.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' import type { GeneratableManifests } from './detect-manifest-actions.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' import type { - ResolvedPathsSidecar, - SidecarAccumulator, -} from './scripts/sidecar.mts' + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' import type { OutputKind } from '../../types.mts' // Auto-manifest reads every build option from the root socket.json. @@ -41,8 +39,6 @@ const AUTO_MANIFEST_HINTS: BuildOptionHints = { export type GenerateAutoManifestResult = { generatedFiles: string[] - // Reachability path only: resolved on-disk paths from the build-tool run. - resolvedPathsSidecar?: ResolvedPathsSidecar | undefined } // A failed generator aborts --auto-manifest: a partial SBOM silently @@ -71,41 +67,30 @@ function abortManifestRunIfFailed( } export async function generateAutoManifest({ - computeArtifactsSidecar, + context, cwd, detected, excludePaths, outputKind, - tmpDir, verbose, }: { - // Reachability path: run build tools with files to emit the sidecar. - computeArtifactsSidecar?: boolean | undefined + context?: SocketFactsContext | undefined detected: GeneratableManifests cwd: string - // Scan-root-relative `--exclude-paths`: skip excluded subprojects and drop - // excluded source roots from the resolved-paths sidecar. + // Scan-root-relative `--exclude-paths`: skip excluded subprojects. excludePaths?: string[] | undefined outputKind: OutputKind - // Caller-owned; see ManifestScriptOptions.tmpDir. Only sbt reads it, but - // required here so every caller allocates one via withTmpDir uniformly. - tmpDir: string verbose: boolean }): Promise { const sockJson = readOrDefaultSocketJson(cwd) const generatedFiles: string[] = [] - const hints: BuildOptionHints = computeArtifactsSidecar + const hints: BuildOptionHints = context?.workDir?.withFiles ? { ...AUTO_MANIFEST_HINTS, continueOnInstallErrorsFlag: REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, } : AUTO_MANIFEST_HINTS - // Resolved paths across all JVM roots, serialized to one sidecar at the end. - const sidecarAcc: SidecarAccumulator | undefined = computeArtifactsSidecar - ? new Map() - : undefined - if (verbose) { logger.info(`Using this ${SOCKET_JSON} for defaults:`, sockJson) } @@ -136,10 +121,8 @@ export async function generateAutoManifest({ ), includeConfigs: sockJson.defaults?.manifest?.sbt?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.sbt?.javaHome ?? undefined, + context, hints, - sidecarAcc, - tmpDir, - withFiles: computeArtifactsSidecar, }) abortFactsRunIfFailed('sbt', outcome) } else { @@ -182,9 +165,8 @@ export async function generateAutoManifest({ includeConfigs: sockJson.defaults?.manifest?.gradle?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.gradle?.javaHome ?? undefined, + context, hints, - sidecarAcc, - withFiles: computeArtifactsSidecar, }) abortFactsRunIfFailed('gradle', outcome) } else { @@ -215,10 +197,9 @@ export async function generateAutoManifest({ mavenOpts: parseBuildToolOpts( sockJson.defaults?.manifest?.maven?.mavenOpts ?? undefined, ), + context, hints, - sidecarAcc, verbose: Boolean(sockJson.defaults?.manifest?.maven?.verbose), - withFiles: computeArtifactsSidecar, }) abortFactsRunIfFailed('maven', outcome) } @@ -229,11 +210,10 @@ export async function generateAutoManifest({ ) const outcome = await convertDotnetToFacts({ config: resolveEcosystemConfig('dotnet', cwd, sockJson), + context, cwd, excludePaths, hints, - sidecarAcc, - withFiles: computeArtifactsSidecar, }) abortFactsRunIfFailed('dotnet', outcome) } @@ -309,11 +289,5 @@ export async function generateAutoManifest({ } } - return { - generatedFiles, - resolvedPathsSidecar: - sidecarAcc && hasSidecarEntries(sidecarAcc) - ? serializeSidecar(sidecarAcc) - : undefined, - } + return { generatedFiles } } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index a0e789f9b0..3a14c91514 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -3,62 +3,282 @@ import path from 'node:path' import { logger } from '@socketsecurity/registry/lib/logger' -import { buildRootPath } from './discover-manifest-roots.mts' import { - expandEnvVarRefs, - formatMissingEnvVarRefs, -} from './expand-env-var-refs.mts' -import { looksLikeSbtBuild } from './scripts/build-tool.mts' -import { - FLAG_HINTS, - renderResolutionErrorReport, - verboseHint, -} from './scripts/resolution-report-render.mts' -import { runManifestScript } from './scripts/run.mts' -import { accumulateSidecar } from './scripts/sidecar.mts' + looksLikeSbtBuild, + resolveBuildToolBin, +} from './scripts/build-tool.mts' import constants from '../../constants.mts' +import { isStandaloneSea } from '../../sea/runtime.mts' +import { spawnCoana } from '../../utils/coana-release.mts' import { getErrorMessageOr } from '../../utils/errors.mts' -import { realpathOrResolved } from '../../utils/fs.mts' +import { withTmpDir } from '../../utils/fs.mts' +import { getOrInsert } from '../../utils/get-or-insert.mts' +import { getDefaultOrgSlug } from '../ci/fetch-default-org-slug.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { ManifestRunResult } from './scripts/run.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' -const MAX_FAILURE_OUTPUT_LINES = 40 +export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' -export type RunManifestFactsResult = { - factsPath: string - projects: SocketFactsSbomProject[] +// Where the invoking command lets the user set each build option, so a remedy +// in Coana's failure report names something they can actually set. +export type BuildOptionHints = { + // Reachability scans only: reachability cannot install a dependency that + // `ignoreUnresolved` lets through, so it must be told to continue too. + continueOnInstallErrorsFlag?: string | undefined + // Taken as flags; every other option is set in `socketJson`. + flags: ReadonlySet + // Wizard that writes `socketJson`. + setupCommand: string + socketJson: string +} + +export const DSI_SETUP_COMMAND = + 'socket manifest setup --dynamic-sbom-inference' + +export const REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG = + '--reach-continue-on-install-errors' + +// The single-build manifest commands take every option as a flag. +export const FLAG_HINTS: BuildOptionHints = { + flags: new Set([ + 'excludeConfigs', + 'ignoreUnresolved', + 'verbose', + ]), + setupCommand: 'socket manifest setup', + socketJson: constants.SOCKET_JSON, } -// Last N non-empty lines of the captured build output, for diagnosing a crash -// without forcing a --verbose rebuild. -export function tailBuildOutput(stdout: string, stderr: string): string { - const combined = [stdout, stderr] - .map(s => s.trimEnd()) - .filter(Boolean) - .join('\n') - return combined.split('\n').slice(-MAX_FAILURE_OUTPUT_LINES).join('\n') +// What a later Coana run needs of one generated build root; passed back to it +// unread. +export type SocketFactsSidecarEntry = { + factsFile: string + stateDir: string +} + +// A directory socket-cli owns until the Coana run that reads it is done, and +// the entries of the build roots generated into it. +export type SocketFactsWorkDir = { + dir: string + entries: SocketFactsSidecarEntry[] + // Reachability only: also install the dependencies the analysis reads. + withFiles: boolean +} + +export function sidecarEntryOf( + workDir: SocketFactsWorkDir, + factsFile: string, +): SocketFactsSidecarEntry | undefined { + return workDir.entries.find(entry => entry.factsFile === factsFile) +} + +// A facts file has one entry: the run that wrote it last. +export function setSidecarEntry( + workDir: SocketFactsWorkDir, + factsFile: string, + entry: SocketFactsSidecarEntry | undefined, +): void { + const kept = workDir.entries.filter(other => other.factsFile !== factsFile) + workDir.entries.splice(0, workDir.entries.length, ...kept) + if (entry) { + workDir.entries.push(entry) + } +} + +export type SocketFactsContext = { + // The Coana that reads `workDir` must be the one that wrote it. + coanaVersion?: string | undefined + orgSlug?: string | undefined + workDir?: SocketFactsWorkDir | undefined +} + +export type RunManifestFactsResult = { + // Realpath-resolved build files the build covers. + coveredBuildFiles: string[] + factsPath: string } // `null` = a real failure (crash, missing config, blocking unresolved // dependency); `undefined` = genuinely nothing to resolve, not a failure. -// Distinguishing the two here means callers never have to infer it from -// `process.exitCode`, which can already be non-zero for an unrelated reason. export type RunManifestFactsOutcome = RunManifestFactsResult | null | undefined -// Runs the bundled build-tool resolution script for a JVM project and writes -// its `.socket.facts.json` (see socketFactsFileName). `withFiles` -// (reachability only) additionally folds resolved artifact paths into -// `sidecarAcc`. A blocking resolution failure sets -// a non-zero exit code and returns (matching the `--pom` generator) unless -// `ignoreUnresolved`; a crashed build — a process failure, not an unresolved -// dependency — always fails. +// The request `coana generate-socket-facts --request` reads. +type SocketFactsRequest = { + buildRoot: string + config: { + bin?: string | undefined + buildOpts: string[] + excludeConfigs?: string | undefined + ignoreUnresolved: boolean + includeConfigs?: string | undefined + javaHome?: string | undefined + verbose: boolean + } + entryFile?: string | undefined + excludeBase: string + excludePaths?: string[] | undefined + hints: { + continueOnInstallErrorsFlag?: string | undefined + flags: BuildOption[] + setupCommand: string + socketJson: string + } + tool: BuildTool +} + +type SocketFactsResult = + | { + coveredBuildFiles: string[] + factsPath: string + sidecarEntry?: SocketFactsSidecarEntry | undefined + status: 'generated' + } + | { status: 'empty' } + | { status: 'failed' } + +type SolutionMembers = { members: string[] | null } + +let defaultOrgSlug: Promise | undefined + +// Resolved once: each build root is its own Coana run. +function orgSlugFor(context: SocketFactsContext): Promise { + if (context.orgSlug) { + return Promise.resolve(context.orgSlug) + } + defaultOrgSlug ??= getDefaultOrgSlug(true).then(r => + r.ok ? r.data : undefined, + ) + return defaultOrgSlug +} + +function toRequestHints(hints: BuildOptionHints): SocketFactsRequest['hints'] { + return { + ...(hints.continueOnInstallErrorsFlag + ? { continueOnInstallErrorsFlag: hints.continueOnInstallErrorsFlag } + : {}), + flags: [...hints.flags].sort(), + setupCommand: hints.setupCommand, + socketJson: hints.socketJson, + } +} + +async function runGenerateSocketFacts( + request: SocketFactsRequest, + flags: string[], + context: SocketFactsContext, +): Promise<{ message?: string | undefined; result: T | undefined }> { + return await withTmpDir('socket-facts-request-', async tmpDir => { + const requestFile = path.join(tmpDir, 'request.json') + const resultFile = path.join(tmpDir, 'result.json') + await fs.writeFile(requestFile, JSON.stringify(request), 'utf8') + const spawned = await spawnCoana( + [ + 'generate-socket-facts', + '--request', + requestFile, + '--output-file', + resultFile, + ...flags, + ], + await orgSlugFor(context), + { + coanaVersion: context.coanaVersion, + cwd: request.buildRoot, + // Coana logs to stdout; keep the command's own stdout machine-readable. + stdio: ['inherit', 2, 'inherit'], + }, + ) + const result = existsSync(resultFile) + ? (JSON.parse(await fs.readFile(resultFile, 'utf8')) as T) + : undefined + return { + message: spawned.ok + ? undefined + : [spawned.message, spawned.cause].filter(Boolean).join(': '), + result, + } + }) +} + +// Resolves `bin` as the build tool's own runner would: the SOCKET_CLI_*_PATH +// override first, then the given bin, the project wrapper, PATH. +function requestBin(tool: BuildTool, dir: string, bin: string | undefined) { + return resolveBuildToolBin( + tool, + dir, + bin || undefined, + tool !== 'dotnet' && isStandaloneSea(), + ) +} + +const membersByRequest = new Map>() + +// The projects a dotnet solution builds; undefined when the SDK cannot read +// it, empty when the listing fails, which the build itself then reports. +export function listDotnetSolutionMembers({ + bin, + buildOpts, + context = {}, + dir, + entryFile, + excludeBase, + excludePaths, +}: { + bin?: string | undefined + buildOpts: string[] + context?: SocketFactsContext | undefined + dir: string + entryFile: string + excludeBase?: string | undefined + excludePaths?: string[] | undefined +}): Promise { + const key = JSON.stringify([ + bin, + buildOpts, + dir, + entryFile, + excludeBase, + excludePaths, + ]) + return getOrInsert(membersByRequest, key, async () => { + let request: SocketFactsRequest + try { + request = { + buildRoot: path.resolve(dir), + config: { + bin: requestBin('dotnet', dir, bin), + buildOpts, + ignoreUnresolved: false, + verbose: false, + }, + entryFile, + excludeBase: path.resolve(excludeBase ?? dir), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: toRequestHints(FLAG_HINTS), + tool: 'dotnet', + } + } catch { + return [] + } + const { result } = await runGenerateSocketFacts( + request, + ['--list-members'], + context, + ) + if (!result) { + return [] + } + return result.members ?? undefined + }) +} + +// Generates one build root's `.socket.facts.json` with Coana. With a +// work dir in `context`, also collects what a later Coana run reads of it. A +// failure sets a non-zero exit code; Coana reports why. export async function runManifestFacts({ bin, buildOpts, + context = {}, cwd, ecosystem, entryFile, @@ -69,45 +289,28 @@ export async function runManifestFacts({ ignoreUnresolved, includeConfigs, javaHome, - sidecarAcc, - tmpDir, verbose, - withFiles, }: { bin: string buildOpts: string[] + context?: SocketFactsContext | undefined cwd: string ecosystem: BuildTool - // See ManifestScriptOptions.entryFile. + // The file in `cwd` to build: Maven's POM (unset leaves Maven's default), + // dotnet's solution or project (required). entryFile?: string | undefined - // See ManifestScriptOptions.excludeBase. + // What `excludePaths` are relative to, as a build can reach modules outside + // its own directory; `cwd` when unset. excludeBase?: string | undefined excludeConfigs: string excludePaths?: string[] | undefined - // Where the user sets build options, for remedy hints. hints?: BuildOptionHints | undefined ignoreUnresolved: boolean includeConfigs: string + // As written: Coana expands `$VAR` references itself. javaHome?: string | undefined - sidecarAcc?: SidecarAccumulator | undefined - // sbt only; see ManifestScriptOptions.tmpDir. - tmpDir?: string | undefined verbose: boolean - withFiles?: boolean | undefined }): Promise { - let resolvedJavaHome: string | undefined - if (javaHome) { - const expanded = expandEnvVarRefs(javaHome) - if (expanded.missing) { - process.exitCode = 1 - logger.fail( - `javaHome (\`${javaHome}\`) ${formatMissingEnvVarRefs(expanded.missing)}.`, - ) - return null - } - resolvedJavaHome = expanded.value - } - if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { process.exitCode = 1 logger.fail( @@ -116,193 +319,71 @@ export async function runManifestFacts({ return null } - const location = buildRootPath({ dir: cwd, entryFile }) - logger.info( - `Generating Socket facts for the ${ecosystem} project at \`${location}\` ...`, - ) - - const scriptOpts = { - bin: bin || undefined, - entryFile, - excludeBase, - excludeConfigs: excludeConfigs || undefined, - excludePaths: excludePaths?.length ? excludePaths : undefined, - // `env` replaces the spawned process's whole environment, not just JAVA_HOME. - env: resolvedJavaHome - ? { ...process.env, JAVA_HOME: resolvedJavaHome } - : undefined, - includeConfigs: includeConfigs || undefined, - projectDir: cwd, - // Stream the build tool's output only when asked; otherwise capture it and - // show a spinner, surfacing the output only if the build crashes. - stdio: verbose ? ('inherit' as const) : ('pipe' as const), - tmpDir, - toolOpts: buildOpts, - withFiles, - } - const { spinner } = constants - let result: ManifestRunResult + let resolvedBin: string try { - if (verbose) { - logger.info( - `(Running ${ecosystem} with output streaming; this can take a while.)`, - ) - result = await runManifestScript(ecosystem, scriptOpts) - } else { - logger.info( - `(No live output; to stream the ${ecosystem} build output, ${verboseHint(hints, ecosystem)}.)`, - ) - spinner.start(`Resolving ${ecosystem} dependencies ...`) - result = await runManifestScript(ecosystem, scriptOpts) - if (result.code === 0) { - spinner.successAndStop(`Resolved ${ecosystem} dependencies.`) - } else { - spinner.failAndStop( - `${ecosystem} build exited with code ${result.code}.`, - ) - } - } + resolvedBin = requestBin(ecosystem, cwd, bin) } catch (e) { - // Only a spawn-level failure (e.g. the build tool missing from PATH) reaches - // here; runNeverThrow returns non-zero build exits rather than throwing. - if (!verbose) { - spinner.failAndStop(`Failed to run ${ecosystem}.`) - } process.exitCode = 1 logger.fail( `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, ) return null } - const { - artifactPaths, - buildRoot, - code, - facts, - factsFileName, - report, - stderr, - stdout, - } = result - - // A non-zero build exit with no usable output (no graph, no first-party - // modules, no failure records) means the build died before the socketFacts - // task emitted anything — a script/plugin compile error, OOM, or an unchecked - // exception in the extension. The build tool's own exit is the only signal, so - // fail closed rather than silently dropping the ecosystem with an empty SBOM - // (the empty-facts branch below would otherwise just log "nothing to upload"). - // The dotnet tool exits non-zero only when it crashed, so whatever it - // recorded before is incomplete however much there is. - if ( - code !== 0 && - (ecosystem === 'dotnet' || - (!facts.components.length && - !facts.projects?.length && - !report.failures.length && - !report.unscannable.length)) - ) { - if (!verbose) { - const tail = tailBuildOutput(stdout, stderr) - if (tail) { - logger.group('Build output:') - logger.error(tail) - logger.groupEnd() - } - } - // A crashed build is a process failure (missing JDK/build tool, unparseable - // project, OOM, plugin error), not an unresolved dependency, so it fails - // regardless of `ignoreUnresolved` — that flag only tolerates dependencies a - // successful run couldn't resolve. - process.exitCode = 1 - logger.fail( - `The ${ecosystem} build at \`${location}\` failed (exit code ${code}) without completing its Socket facts.`, - ) - return null - } - const rendered = renderResolutionErrorReport( - report.failures, - report.scannedConfigs, - ecosystem, - { - hints, + const request: SocketFactsRequest = { + buildRoot: path.resolve(cwd), + config: { + bin: resolvedBin, + buildOpts, + ...(excludeConfigs ? { excludeConfigs } : {}), ignoreUnresolved, - resolvedModules: report.resolvedModules, - unscannable: report.unscannable, + ...(includeConfigs ? { includeConfigs } : {}), + ...(javaHome ? { javaHome } : {}), + verbose, }, - ) - - if (rendered.hasBlockingFailures) { - if (ignoreUnresolved) { - logger.warn(rendered.summary) - } else { - process.exitCode = 1 - logger.fail(rendered.summary) - if (verbose && rendered.details) { - logger.info(rendered.details) - } - return null - } - } - if (rendered.nonBlockingNotice) { - logger.info(rendered.nonBlockingNotice) - } - if (verbose && rendered.details) { - logger.info(rendered.details) - } - - // Nothing resolved at all — no dependencies and no first-party modules. A - // project with only first-party modules (empty components, non-empty projects) - // still has source roots reachability needs, so it must be written. - if (!facts.components.length && !facts.projects?.length) { - logger.warn( - `No resolvable ${ecosystem} dependencies found; nothing to upload.`, - ) - return + ...(entryFile ? { entryFile } : {}), + excludeBase: path.resolve(excludeBase ?? cwd), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: toRequestHints(hints), + tool: ecosystem, } + const { workDir } = context + const { message, result } = await runGenerateSocketFacts( + request, + workDir + ? [ + ...(workDir.withFiles ? ['--with-files'] : []), + '--work-dir', + workDir.dir, + ] + : [], + context, + ) - if (!buildRoot || !factsFileName) { + if (!result || result.status === 'failed') { process.exitCode = 1 - logger.fail( - `The ${ecosystem} build did not report its ${buildRoot ? 'entry build file' : 'root directory'}, so its Socket facts file cannot be placed.`, - ) + if (!result) { + logger.fail( + `Could not generate Socket facts for the ${ecosystem} project at \`${cwd}\`${message ? `: ${message}` : '.'}`, + ) + } return null } - // Every path in the facts is relative to the build root, which `-f`/`-p` - // can move away from cwd. - const factsPath = path.join(buildRoot, factsFileName) - // Not a name producers write, so a copy here is stale and would be uploaded - // alongside the new file. - const legacyFactsPath = path.join( - buildRoot, - constants.DOT_SOCKET_DOT_FACTS_JSON, - ) - if (existsSync(legacyFactsPath)) { - logger.warn( - `Found \`${legacyFactsPath}\`, which is uploaded alongside \`${factsFileName}\`. Delete it if an earlier \`socket manifest\` run left it behind.`, - ) + if (result.status === 'empty') { + return undefined } - - const socketCliVersion = constants.ENV.INLINED_SOCKET_CLI_VERSION - if (facts.metadata && socketCliVersion) { - facts.metadata.socketCliVersion = socketCliVersion + if (workDir) { + if (!result.sidecarEntry) { + process.exitCode = 1 + logger.fail( + `Coana did not keep what reachability analysis needs of \`${result.factsPath}\`.`, + ) + return null + } + setSidecarEntry(workDir, result.factsPath, result.sidecarEntry) } - await fs.writeFile(factsPath, JSON.stringify(facts), 'utf8') - - if (sidecarAcc) { - // Key by the symlink-resolved path so the sidecar's keys are comparable - // regardless of which caller's cwd it was joined against (the recursive - // discovery path already resolves symlinks before this point; the plain - // single-root path does not). - accumulateSidecar( - sidecarAcc, - facts, - artifactPaths, - await realpathOrResolved(factsPath), - !!withFiles, - ) + return { + coveredBuildFiles: result.coveredBuildFiles, + factsPath: result.factsPath, } - - logger.success('Generated Socket facts') - return { factsPath, projects: facts.projects ?? [] } } diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index e55a8892a1..6e8beeae46 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -4,47 +4,26 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('./scripts/run.mts', () => ({ - runManifestScript: vi.fn(), +vi.mock('../../utils/coana-release.mts', () => ({ + spawnCoana: vi.fn(), +})) +vi.mock('../ci/fetch-default-org-slug.mts', () => ({ + getDefaultOrgSlug: vi.fn(async () => ({ ok: true, data: 'default-org' })), })) -import { runManifestFacts } from './run-manifest-facts.mts' -import { runManifestScript } from './scripts/run.mts' -import constants from '../../constants.mts' - -import type { ManifestRunResult } from './scripts/run.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import { + listDotnetSolutionMembers, + runManifestFacts, +} from './run-manifest-facts.mts' +import { spawnCoana } from '../../utils/coana-release.mts' -const ENV_VAR = 'SOCKET_TEST_JAVA_HOME' +import type { SocketFactsWorkDir } from './run-manifest-facts.mts' -function okResult(buildRoot: string): ManifestRunResult { - return { - buildRoot, - code: 0, - facts: { - components: [{ id: 'a', type: 'maven', name: 'a' }], - projects: [], - }, - factsFileName: 'pom.xml.socket.facts.json', - report: { - failures: [], - resolvedModules: new Set(), - scannedConfigs: [], - unscannable: [], - }, - artifactPaths: { - pathsById: new Map(), - classpathByProject: new Map(), - directDependenciesByProject: new Map(), - }, - stderr: '', - stdout: '', - } -} +type Call = { args: string[]; request: any } const baseArgs = { bin: 'mvn', - buildOpts: [], + buildOpts: ['-Pci'], ecosystem: 'maven' as const, excludeConfigs: '', ignoreUnresolved: false, @@ -53,276 +32,206 @@ const baseArgs = { } let cwd = '' +let calls: Call[] = [] + +// Answers each Coana run with `result`, as `coana generate-socket-facts` writes +// it, or writes nothing when `result` is undefined. +function coanaAnswers(result: unknown, ok = true): void { + vi.mocked(spawnCoana).mockImplementation(async args => { + const list = [...args] + const request = JSON.parse( + await fs.readFile(list[list.indexOf('--request') + 1]!, 'utf8'), + ) + calls.push({ args: list, request }) + if (result !== undefined) { + await fs.writeFile( + list[list.indexOf('--output-file') + 1]!, + JSON.stringify(result), + ) + } + return ok + ? { ok: true, data: '' } + : { ok: false, message: 'Coana command failed', cause: 'exit code 3' } + }) +} beforeEach(async () => { - cwd = await fs.mkdtemp(path.join(tmpdir(), 'run-manifest-facts-')) - vi.mocked(runManifestScript).mockReset() + cwd = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'run-manifest-facts-')), + ) + calls = [] + vi.mocked(spawnCoana).mockReset() process.exitCode = undefined }) afterEach(async () => { await fs.rm(cwd, { recursive: true, force: true }) + delete process.env['SOCKET_CLI_MAVEN_PATH'] process.exitCode = undefined }) -describe('runManifestFacts - javaHome', () => { - beforeEach(() => { - delete process.env[ENV_VAR] - }) - afterEach(() => { - delete process.env[ENV_VAR] - }) - - it('passes a literal javaHome straight through as JAVA_HOME', async () => { - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - await runManifestFacts({ ...baseArgs, cwd, javaHome: '/opt/jdk-17' }) - const opts = vi.mocked(runManifestScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-17') - }) - - it('expands $VAR and ${VAR} references against the CLI process env', async () => { - process.env[ENV_VAR] = '/opt/jdk-11' - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - await runManifestFacts({ - ...baseArgs, - cwd, - javaHome: `\${${ENV_VAR}}`, +describe('runManifestFacts', () => { + it('asks Coana for one build root with its options as written', async () => { + coanaAnswers({ + coveredBuildFiles: [path.join(cwd, 'pom.xml')], + factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + status: 'generated', }) - const opts = vi.mocked(runManifestScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-11') - }) - - it('fails closed without invoking the build tool when the referenced var is unset', async () => { - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) const result = await runManifestFacts({ ...baseArgs, + context: { coanaVersion: '1.2.3', orgSlug: 'acme' }, cwd, - javaHome: `$${ENV_VAR}`, + entryFile: 'pom.xml', + excludeConfigs: 'test*', + excludePaths: ['docs/**'], + javaHome: '$JAVA11_HOME', }) - expect(result).toBeNull() - expect(runManifestScript).not.toHaveBeenCalled() - expect(process.exitCode).toBe(1) - }) - - it('leaves the environment untouched when javaHome is unset', async () => { - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - await runManifestFacts({ ...baseArgs, cwd }) - const opts = vi.mocked(runManifestScript).mock.calls[0]?.[1] - expect(opts?.env).toBeUndefined() - }) -}) - -describe('runManifestFacts - sidecar', () => { - it('keys the sidecar by the symlink-resolved factsPath, not the raw cwd-joined one', async () => { - const result = okResult(cwd) - result.facts.projects = [ - { - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: '.', - children: [], + expect(result).toEqual({ + coveredBuildFiles: [path.join(cwd, 'pom.xml')], + factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + }) + expect(calls[0]!.args.slice(0, 1)).toEqual(['generate-socket-facts']) + expect(calls[0]!.args).not.toContain('--work-dir') + expect(calls[0]!.request).toEqual({ + buildRoot: cwd, + config: { + bin: 'mvn', + buildOpts: ['-Pci'], + excludeConfigs: 'test*', + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + entryFile: 'pom.xml', + excludeBase: cwd, + excludePaths: ['docs/**'], + hints: { + flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], + setupCommand: 'socket manifest setup', + socketJson: 'socket.json', }, - ] - vi.mocked(runManifestScript).mockResolvedValue(result) - - const sidecarAcc: SidecarAccumulator = new Map() - await runManifestFacts({ ...baseArgs, cwd, sidecarAcc, withFiles: true }) - - const expectedFactsFile = await fs.realpath( - path.join(cwd, 'pom.xml.socket.facts.json'), - ) - expect([...sidecarAcc.keys()]).toEqual([expectedFactsFile]) - const bucket = sidecarAcc.get(expectedFactsFile) - expect(bucket?.projects.find(m => m.name === 'app')).toBeDefined() - }) - it('stamps the inlined socket-cli version into the written facts metadata', async () => { - const result = okResult(cwd) - result.facts.metadata = { - format: 'socket-facts-sbom', tool: 'maven', - toolVersion: '3.9.9', - } - vi.mocked(runManifestScript).mockResolvedValue(result) + }) + expect(vi.mocked(spawnCoana).mock.calls[0]![1]).toBe('acme') + expect(vi.mocked(spawnCoana).mock.calls[0]![2]).toMatchObject({ + coanaVersion: '1.2.3', + cwd, + }) + }) + it('sends the SOCKET_CLI_*_PATH override as the bin', async () => { + const mvn = path.join(cwd, 'mvn') + await fs.writeFile(mvn, '', { mode: 0o755 }) + process.env['SOCKET_CLI_MAVEN_PATH'] = mvn + coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd }) - - const written = JSON.parse( - await fs.readFile(path.join(cwd, 'pom.xml.socket.facts.json'), 'utf8'), - ) - // Unit tests run unbuilt, where the version isn't inlined; the field is - // then omitted rather than written empty. - expect(written.metadata.socketCliVersion).toBe( - constants.ENV.INLINED_SOCKET_CLI_VERSION || undefined, - ) + expect(calls[0]!.request.config.bin).toBe(mvn) }) -}) -describe('runManifestFacts - facts file naming', () => { - it('gives builds sharing a directory distinct facts files', async () => { - const sidecarAcc: SidecarAccumulator = new Map() - const outcomes = [] - for (const factsFileName of [ - 'pom.xml.socket.facts.json', - 'other-pom.xml.socket.facts.json', - ]) { - vi.mocked(runManifestScript).mockResolvedValueOnce({ - ...okResult(cwd), - factsFileName, - }) - // eslint-disable-next-line no-await-in-loop - outcomes.push(await runManifestFacts({ ...baseArgs, cwd, sidecarAcc })) + it('installs files into the work dir and collects the root for reachability', async () => { + const entry = { + factsFile: '/r/pom.xml.socket.facts.json', + stateDir: '/w/x', } - vi.mocked(runManifestScript).mockResolvedValueOnce({ - ...okResult(cwd), - factsFileName: 'gradle.socket.facts.json', + coanaAnswers({ + coveredBuildFiles: [], + factsPath: entry.factsFile, + sidecarEntry: entry, + status: 'generated', }) - outcomes.push( - await runManifestFacts({ - ...baseArgs, - cwd, - ecosystem: 'gradle', - sidecarAcc, - }), - ) - - expect(outcomes.map(o => o && path.basename(o.factsPath))).toEqual([ - 'pom.xml.socket.facts.json', - 'other-pom.xml.socket.facts.json', - 'gradle.socket.facts.json', - ]) - expect((await fs.readdir(cwd)).sort()).toEqual([ - 'gradle.socket.facts.json', - 'other-pom.xml.socket.facts.json', - 'pom.xml.socket.facts.json', + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: [], + withFiles: true, + } + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) + expect(calls[0]!.args.slice(-3)).toEqual([ + '--with-files', + '--work-dir', + '/w', ]) - expect(sidecarAcc.size).toBe(3) + expect(workDir.entries).toEqual([entry]) }) - it('writes the facts file into the build root the tool reports', async () => { - const buildRoot = path.join(cwd, 'sub') - await fs.mkdir(buildRoot) - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(buildRoot), - factsFileName: 'other-pom.xml.socket.facts.json', + it('keeps state without installing files for socket fix', async () => { + coanaAnswers({ + coveredBuildFiles: [], + factsPath: '/r/f', + sidecarEntry: { factsFile: '/r/f', stateDir: '/w/y' }, + status: 'generated', }) - - const outcome = await runManifestFacts({ ...baseArgs, cwd }) - - expect(outcome?.factsPath).toBe( - path.join(buildRoot, 'other-pom.xml.socket.facts.json'), - ) - expect(await fs.readdir(buildRoot)).toEqual([ - 'other-pom.xml.socket.facts.json', - ]) + const workDir = { dir: '/w', entries: [], withFiles: false } + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) + expect(calls[0]!.args.slice(-2)).toEqual(['--work-dir', '/w']) + expect(calls[0]!.args).not.toContain('--with-files') }) - it('fails without writing when the build did not report its root', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - buildRoot: undefined, - }) - - const outcome = await runManifestFacts({ ...baseArgs, cwd }) + it('is nothing to upload when the build resolves nothing', async () => { + coanaAnswers({ status: 'empty' }) + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeUndefined() + expect(process.exitCode).toBeUndefined() + }) - expect(outcome).toBeNull() + it('fails when Coana reports a failed build', async () => { + coanaAnswers({ status: 'failed' }, false) + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeNull() expect(process.exitCode).toBe(1) - expect(await fs.readdir(cwd)).toEqual([]) }) - it('fails without writing when the build did not report its entry file', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - factsFileName: undefined, - }) - - const outcome = await runManifestFacts({ ...baseArgs, cwd }) - - expect(outcome).toBeNull() + it('fails when Coana writes no result', async () => { + coanaAnswers(undefined, false) + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeNull() expect(process.exitCode).toBe(1) - expect(await fs.readdir(cwd)).toEqual([]) }) - it('leaves a legacy .socket.facts.json in place', async () => { - const legacy = path.join(cwd, '.socket.facts.json') - await fs.writeFile(legacy, '{}') - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - - await runManifestFacts({ ...baseArgs, cwd }) - - expect(await fs.readFile(legacy, 'utf8')).toBe('{}') - expect((await fs.readdir(cwd)).sort()).toEqual([ - '.socket.facts.json', - 'pom.xml.socket.facts.json', - ]) + it('does not run Coana outside an sbt build', async () => { + coanaAnswers({ status: 'empty' }) + expect( + await runManifestFacts({ + ...baseArgs, + bin: 'sbt', + cwd, + ecosystem: 'sbt', + }), + ).toBeNull() + expect(spawnCoana).not.toHaveBeenCalled() }) }) -describe('runManifestFacts - sbt build detection', () => { - it('fails without running sbt when the directory has no sbt build', async () => { - const outcome = await runManifestFacts({ - ...baseArgs, - cwd, - ecosystem: 'sbt', +describe('listDotnetSolutionMembers', () => { + it('lists the members once for the same request', async () => { + coanaAnswers({ members: ['/r/A/A.csproj'] }) + const request = { buildOpts: [], dir: cwd, entryFile: 'All.sln' } + expect(await listDotnetSolutionMembers(request)).toEqual(['/r/A/A.csproj']) + expect(await listDotnetSolutionMembers(request)).toEqual(['/r/A/A.csproj']) + expect(spawnCoana).toHaveBeenCalledOnce() + expect(calls[0]!.args).toContain('--list-members') + expect(calls[0]!.request).toMatchObject({ + buildRoot: cwd, + entryFile: 'All.sln', + excludeBase: cwd, + tool: 'dotnet', }) - - expect(outcome).toBeNull() - expect(process.exitCode).toBe(1) - expect(runManifestScript).not.toHaveBeenCalled() - await expect( - fs.access(path.join(cwd, 'pom.xml.socket.facts.json')), - ).rejects.toThrow() }) - it.each(['build.sbt', 'project'])( - 'runs sbt when the directory has %s', - async marker => { - if (marker === 'project') { - await fs.mkdir(path.join(cwd, marker)) - } else { - await fs.writeFile(path.join(cwd, marker), '') - } - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - - await runManifestFacts({ ...baseArgs, cwd, ecosystem: 'sbt' }) - - expect(runManifestScript).toHaveBeenCalledOnce() - }, - ) -}) - -describe('runManifestFacts - crashed build', () => { - it('fails closed on a dotnet tool exit, whatever it recorded before', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - code: 1, - factsFileName: 'App.sln.socket.facts.json', - stderr: 'socket-facts-dotnet: System.InvalidOperationException', - }) - - const outcome = await runManifestFacts({ - ...baseArgs, - bin: 'dotnet', - cwd, - ecosystem: 'dotnet', - entryFile: 'App.sln', - ignoreUnresolved: true, - }) - - expect(outcome).toBeNull() - expect(process.exitCode).toBe(1) - expect(await fs.readdir(cwd)).toEqual([]) + it('cannot tell when the SDK cannot read the solution', async () => { + coanaAnswers({ members: null }) + expect( + await listDotnetSolutionMembers({ + buildOpts: [], + dir: cwd, + entryFile: 'All.slnx', + }), + ).toBeUndefined() }) - it('keeps what a JVM build resolved before a non-zero exit', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - code: 1, - }) - - const outcome = await runManifestFacts({ ...baseArgs, cwd }) - - expect(outcome?.factsPath).toBe(path.join(cwd, 'pom.xml.socket.facts.json')) - expect(process.exitCode).toBeUndefined() + it('lists nothing when Coana fails', async () => { + coanaAnswers(undefined, false) + expect( + await listDotnetSolutionMembers({ + buildOpts: [], + dir: cwd, + entryFile: 'Broken.sln', + }), + ).toEqual([]) }) }) diff --git a/src/commands/manifest/scripts/assemble.test.mts b/src/commands/manifest/scripts/assemble.test.mts index 3c7bdf498f..6c246b221c 100644 --- a/src/commands/manifest/scripts/assemble.test.mts +++ b/src/commands/manifest/scripts/assemble.test.mts @@ -2,20 +2,8 @@ import { describe, expect, it } from 'vitest' import { assembleFacts } from './assemble.mts' import { parseRecords } from './records.mts' -import { accumulateSidecar, serializeSidecar } from './sidecar.mts' import type { SocketFactsSbom } from './facts.mts' -import type { SidecarAccumulator } from './sidecar.mts' - -function sidecarEntry( - facts: SocketFactsSbom, - artifactPaths: ReturnType['artifactPaths'], - factsFile: string, -) { - const acc: SidecarAccumulator = new Map() - accumulateSidecar(acc, facts, artifactPaths, factsFile) - return serializeSidecar(acc)[factsFile]! -} // Each project's tree, written out with component ids; a repeat on the current // path (a cycle) is written without its children. @@ -78,50 +66,7 @@ function cycle(root: string, project: string, extra: boolean): string[] { ] } -describe('records → assemble → sidecar', () => { - it('carries first-party project paths, external jars, and artifactless BOMs', () => { - // Inject fileExists so the synthetic absolute paths aren't filtered out. - const { artifactPaths, facts } = assembleFacts(parseRecords(RECORDS), { - fileExists: () => true, - }) - - expect(facts.metadata?.tool).toBe('gradle') - expect(facts.metadata?.javaVersion).toBe('17') - // contentHash/schemaVersion are intentionally absent from metadata. - expect(facts.metadata).not.toHaveProperty('contentHash') - expect(facts.metadata).not.toHaveProperty('schemaVersion') - - const bucket = sidecarEntry(facts, artifactPaths, '/abs/.socket.facts.json') - const byName = new Map(bucket.components.map(r => [r.name, r])) - - // First-party module: project-only (not a node), yet its source/output - // roots reach the sidecar, keyed by its own facts file. - expect(bucket.projects).toEqual([ - { - id: ':app', - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: '/abs/app', - dependencies: ['com.example:bom:2.0', 'com.example:lib:jar:1.0'], - targets: ['/abs/app/build/classes'], - sources: ['/abs/app/src/main/java'], - classpath: ['com.example:bom:2.0', 'com.example:lib:jar:1.0'], - }, - ]) - - // External dependency: jar target, empty (not undefined) sources - it was - // resolved, it just has no first-party source roots. - expect(byName.get('lib')?.targets).toEqual(['/abs/lib.jar']) - expect(byName.get('lib')?.sources).toEqual([]) - - // Artifactless BOM: present with explicit empty arrays (resolved, no - // artifact) - [] means resolved-and-empty, not "not resolved". - const bom = byName.get('bom') - expect(bom?.targets).toEqual([]) - expect(bom?.sources).toEqual([]) - }) +describe('records → assemble', () => { it("carries an excluded module's paths into the kept project that depends on it", () => { const records = [ 'meta\tgradle\t8.10\t17', @@ -145,49 +90,6 @@ describe('records → assemble → sidecar', () => { }) expect([...artifactPaths.classpathByProject.keys()]).toEqual([':app']) }) - it('states no targets for an artifact that failed to resolve or is gone from disk', () => { - const records = [ - 'meta\tmaven\t3.9.6\t17', - 'project\tg:app:1\tg\tapp\t1\t.', - 'root\t0\tg:app:1\tcompile\t1', - 'node\t0\tg:ok:jar:1\tg\tok\t1\tjar\t\t1', - 'node\t0\tg:nojar:jar:1\tg\tnojar\t1\tjar\t\t1', - 'node\t0\tg:nojar:test-jar:tests:1\tg\tnojar\t1\ttest-jar\ttests\t1', - 'node\t0\tg:gone:jar:1\tg\tgone\t1\tjar\t\t1', - 'node\t0\tg:bom:pom:1\tg\tbom\t1\tpom\t\t1', - 'node\t0\tg:half:jar:1\tg\thalf\t1\tjar\t\t1', - 'node\t0\tg:halfgone:jar:1\tg\thalfgone\t1\tjar\t\t1', - 'file\t0\tg:ok:jar:1\t/abs/ok.jar', - 'file\t0\tg:half:jar:1\t/abs/half-a.jar', - 'unfetched\t0\tg:half:jar:1', - 'file\t0\tg:halfgone:jar:1\t/abs/halfgone-a.jar', - 'file\t0\tg:halfgone:jar:1\t/abs/gone.jar', - 'file\t0\tg:gone:jar:1\t/abs/gone.jar', - 'file\t0\tg:nojar:test-jar:tests:1\t/abs/nojar-tests.jar', - 'unfetched\t0\tg:nojar:jar:1', - ].join('\n') - const { artifactPaths, facts } = assembleFacts(parseRecords(records), { - fileExists: p => p !== '/abs/gone.jar', - }) - const byId = new Map( - sidecarEntry( - facts, - artifactPaths, - '/abs/pom.xml.socket.facts.json', - ).components.map(c => [c.id, c]), - ) - - expect(byId.get('g:ok:jar:1')?.targets).toEqual(['/abs/ok.jar']) - expect(byId.get('g:nojar:jar:1')).not.toHaveProperty('targets') - expect(byId.get('g:nojar:test-jar:tests:1')?.targets).toEqual([ - '/abs/nojar-tests.jar', - ]) - expect(byId.get('g:gone:jar:1')).not.toHaveProperty('targets') - expect(byId.get('g:bom:pom:1')?.targets).toEqual([]) - // One of several files missing leaves the artifact incomplete. - expect(byId.get('g:half:jar:1')).not.toHaveProperty('targets') - expect(byId.get('g:halfgone:jar:1')).not.toHaveProperty('targets') - }) it('keeps the targets of an artifact that another root fetched', () => { const records = [ 'meta\tmaven\t3.9.6\t17', @@ -256,24 +158,20 @@ describe('records → assemble → sidecar', () => { ':b': ['g:junit:jar:4', 'g:lib:jar:1(g:dep:jar:2)'], }) - const byName = new Map( - sidecarEntry( - facts, - artifactPaths, - '/abs/.socket.facts.json', - ).projects.map(p => [p.name, p]), - ) - expect(byName.get('a')?.classpath).toEqual(['g:dep:jar:1', 'g:lib:jar:1']) - expect(byName.get('b')?.classpath).toEqual([ + const { classpathByProject, directDependenciesByProject } = artifactPaths + expect([...classpathByProject.get(':a')!]).toEqual([ + 'g:dep:jar:1', + 'g:lib:jar:1', + ]) + expect([...classpathByProject.get(':b')!]).toEqual([ 'g:dep:jar:2', 'g:junit:jar:4', 'g:lib:jar:1', ]) - expect(byName.get('b')?.dependencies).toEqual([ + expect([...directDependenciesByProject.get(':b')!]).toEqual([ 'g:junit:jar:4', 'g:lib:jar:1', ]) - expect(byName.get('b')).not.toHaveProperty('children') }) it('shares one dependency entry between identical subtrees across subprojects', () => { const records = [ @@ -496,7 +394,7 @@ describe('records → assemble → sidecar', () => { // Same name as a build project, but a published artifact, not the project. 'node\tr2\tg:b:jar:0.9\tg\tb\t0.9\tjar\t\t1\t', ].join('\n') - const { artifactPaths, facts } = assembleFacts(parseRecords(records)) + const { facts } = assembleFacts(parseRecords(records)) expect(facts.components.map(c => [c.id, c.firstParty ?? 'absent'])).toEqual( [ @@ -509,14 +407,7 @@ describe('records → assemble → sidecar', () => { ':a': ['g:ext:jar:2'], ':b': [':a(g:ext:jar:2)', 'g:b:jar:0.9'], }) - - const bucket = sidecarEntry( - facts, - artifactPaths, - '/abs/gradle.socket.facts.json', - ) - expect(bucket.components.find(c => c.id === ':a')?.firstParty).toBe(true) - for (const project of bucket.projects) { + for (const project of facts.projects ?? []) { expect(project).not.toHaveProperty('firstParty') } }) @@ -718,133 +609,8 @@ describe('dotnet records → assemble', () => { }) }) -describe('dotnet records → sidecar', () => { - it('carries assemblies, compile items and unresolved packages per nuget purl', () => { - const records = [ - 'meta\tdotnet\t8.0.414\t', - 'project\tApp.csproj\t\tApp\t1.0.0\t.', - 'projectSrc\tApp.csproj\t/abs/Program.cs', - 'projectTgt\tApp.csproj\t/abs/bin/App.dll', - 'root\tr\tApp.csproj\tnet8.0\t1', - 'node\tr\tlib:1.0.0\t\tLib\t1.0.0\t\t\t1\t', - 'file\tr\tlib:1.0.0\t/pkgs/lib/1.0.0/lib/net8.0/Lib.dll', - 'node\tr\tanalyzer:1.0.0\t\tAnalyzer\t1.0.0\t\t\t1\t', - 'node\tr\tgone:1.0.0\t\tGone\t1.0.0\t\t\t1\t', - 'unfetched\tr\tgone:1.0.0', - ].join('\n') - const { artifactPaths, facts } = assembleFacts(parseRecords(records), { - fileExists: () => true, - }) - const entry = sidecarEntry( - facts, - artifactPaths, - '/abs/App.csproj.socket.facts.json', - ) - expect(entry.components.map(c => [c.type, c.name, c.targets])).toEqual([ - ['nuget', 'Analyzer', []], - ['nuget', 'Gone', undefined], - ['nuget', 'Lib', ['/pkgs/lib/1.0.0/lib/net8.0/Lib.dll']], - ]) - expect(entry.projects).toMatchObject([ - { - id: 'App.csproj', - type: 'nuget', - sources: ['/abs/Program.cs'], - targets: ['/abs/bin/App.dll'], - dependencies: ['analyzer:1.0.0', 'gone:1.0.0', 'lib:1.0.0'], - }, - ]) - expect(entry.projects[0]).not.toHaveProperty('namespace') - }) -}) - -describe('dotnet records → per-framework sidecar', () => { - const records = [ - 'meta\tdotnet\t8.0.414\t', - 'project\tLib.csproj\t\tLib\t1.0.0\t.', - 'projectSrc\tLib.csproj\t/abs/L.cs\tnet8.0', - 'projectSrc\tLib.csproj\t/abs/A.cs\tnet8.0', - 'projectSrc\tLib.csproj\t/abs/Legacy.cs\tnetstandard2.0', - 'projectTgt\tLib.csproj\t/abs/bin/net8.0/Lib.dll\tnet8.0', - 'projectInfo\tLib.csproj\tnet8.0\tTargetFrameworkMoniker\t.NETCoreApp,Version=v8.0', - 'projectInfo\tLib.csproj\tnet8.0\tDefineConstant\tDEBUG', - 'projectInfo\tLib.csproj\tnet8.0\tFrameworkReference\tMicrosoft.NETCore.App', - 'projectInfo\tLib.csproj\tnet8.0\tNullable\tenable', - 'projectUsing\tLib.csproj\tnet8.0\tSystem.Linq\t\t0', - 'projectUsing\tLib.csproj\tnet8.0\tSystem.Math\t\t1', - 'root\ta\tLib.csproj\tnet8.0\t0\tnet8.0\t\tnet8.0', - 'node\ta\tx:1.0.0\t\tX\t1.0.0\t\t\t1\t', - 'file\ta\tx:1.0.0\t/pkgs/x/lib/net8.0/X.dll', - 'compileFile\ta\tx:1.0.0\t/pkgs/x/ref/net8.0/X.dll', - 'node\ta\tgone:1.0.0\t\tGone\t1.0.0\t\t\t1\t', - 'unfetched\ta\tgone:1.0.0', - 'root\tp\tLib.csproj\tnet8.0\t1\tnet8.0\t\tnet8.0', - 'node\tp\tx:1.0.0\t\tX\t1.0.0\t\t\t1\t', - 'node\tp\tgone:1.0.0\t\tGone\t1.0.0\t\t\t1\t', - 'root\ts\tLib.csproj\tnetstandard2.0\t0\tnetstandard2.0\t\tnetstandard2.0', - 'node\ts\tx:1.0.0\t\tX\t1.0.0\t\t\t1\t', - 'file\ts\tx:1.0.0\t/pkgs/x/lib/netstandard2.0/X.dll', - ].join('\n') - - it('gives each project build its own context and each package its assemblies per framework', () => { - const { artifactPaths, facts } = assembleFacts(parseRecords(records), { - fileExists: () => true, - }) - const entry = sidecarEntry( - facts, - artifactPaths, - '/abs/Lib.csproj.socket.facts.json', - ) - expect(entry.projects[0]!.frameworks).toEqual([ - { - alias: 'net8.0', - framework: 'net8.0', - targetFrameworkMoniker: '.NETCoreApp,Version=v8.0', - language: undefined, - langVersion: undefined, - nullable: 'enable', - assemblyName: undefined, - frameworkReferences: ['Microsoft.NETCore.App'], - defineConstants: ['DEBUG'], - usings: [ - { namespace: 'System.Linq' }, - { namespace: 'System.Math', static: true }, - ], - // Compiler order, not sorted. - sources: ['/abs/L.cs', '/abs/A.cs'], - targets: ['/abs/bin/net8.0/Lib.dll'], - dependencies: ['gone:1.0.0', 'x:1.0.0'], - classpath: ['gone:1.0.0', 'x:1.0.0'], - }, - expect.objectContaining({ - alias: 'netstandard2.0', - sources: ['/abs/Legacy.cs'], - targets: [], - classpath: ['x:1.0.0'], - }), - ]) - const byName = Object.fromEntries( - entry.components.map(c => [c.name, c.frameworks]), - ) - expect(byName['X']).toEqual([ - { - framework: 'net8.0', - targets: ['/pkgs/x/lib/net8.0/X.dll'], - compile: ['/pkgs/x/ref/net8.0/X.dll'], - }, - { - framework: 'netstandard2.0', - targets: ['/pkgs/x/lib/netstandard2.0/X.dll'], - compile: [], - }, - ]) - // A root without files (the prod one) does not count as resolving it. - expect(byName['Gone']).toEqual([{ framework: 'net8.0' }]) - }) -}) - describe('dotnet build without dependencies', () => { - it('still gets its compile context in the sidecar', () => { + it('still gets its compile context', () => { const records = [ 'meta\tdotnet\t8.0.414\t', 'project\tLeaf.csproj\t\tLeaf\t1.0.0\t.', diff --git a/src/commands/manifest/scripts/maven-extension/pom.xml b/src/commands/manifest/scripts/maven-extension/pom.xml index 8a867a7d9e..502c724fc9 100644 --- a/src/commands/manifest/scripts/maven-extension/pom.xml +++ b/src/commands/manifest/scripts/maven-extension/pom.xml @@ -7,12 +7,11 @@ 1.0 + their pom.xml is untouched. It emits the reactor's projects as line-protocol records, the + same contract as the Gradle init script and sbt plugin. --> jar Coana Maven extension - Core extension that emits Coana's dependency-graph records (socket-facts) without a local-repo install. + Core extension that emits a reactor's projects as records without a local-repo install. 8 @@ -86,30 +85,5 @@ ${maven.version} provided - - org.apache.maven - maven-model - ${maven.version} - provided - - - org.apache.maven - maven-artifact - ${maven.version} - provided - - - - org.apache.maven.resolver - maven-resolver-api - 1.9.18 - provided - - - org.slf4j - slf4j-api - 1.7.36 - provided - diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsEventSpy.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsEventSpy.java deleted file mode 100644 index 089964c759..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsEventSpy.java +++ /dev/null @@ -1,31 +0,0 @@ -package tech.coana.ext; - -import org.apache.maven.eventspy.AbstractEventSpy; -import org.eclipse.aether.RepositoryEvent; -import tech.coana.socket.CollectionObserver; - -import javax.inject.Named; -import javax.inject.Singleton; - -/** - * Relays repository events to the facts engine while it collects. Every Maven chains its event - * spies into the session's repository listener, which an extension cannot replace: the session is - * read-only since Maven 3.1 and immutable in Maven 4. - */ -@Named("coana-facts-events") -@Singleton -public class CoanaFactsEventSpy extends AbstractEventSpy { - - // Static: the container may hand the dispatcher and the participant different instances. - private static volatile CollectionObserver observer; - - static void observe(CollectionObserver o) { - observer = o; - } - - @Override - public void onEvent(Object event) { - CollectionObserver o = observer; - if (o != null && event instanceof RepositoryEvent) o.onEvent((RepositoryEvent) event); - } -} diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsLifecycleParticipant.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsLifecycleParticipant.java deleted file mode 100644 index 5a20e5ac26..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaFactsLifecycleParticipant.java +++ /dev/null @@ -1,92 +0,0 @@ -package tech.coana.ext; - -import org.apache.maven.AbstractMavenLifecycleParticipant; -import org.apache.maven.MavenExecutionException; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.ProjectDependenciesResolver; -import org.apache.maven.rtinfo.RuntimeInformation; -import org.eclipse.aether.RepositorySystem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import tech.coana.socket.CollectionObserver; -import tech.coana.socket.SocketFactsRecordsEngine; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -/** - * Core extension loaded via {@code -Dmaven.ext.class.path}, gated by {@code -Dcoana.task=socket-facts} - * (inert otherwise; no local-repo install, pom untouched). Runs at {@code afterSessionEnd} so - * {@code -Dsocket.withFiles} sees compiled classes / generated sources. - */ -@Named("coana-facts") -@Singleton -public class CoanaFactsLifecycleParticipant extends AbstractMavenLifecycleParticipant { - - private static final Logger LOG = LoggerFactory.getLogger("coana"); - - private final ProjectDependenciesResolver dependenciesResolver; - private final RepositorySystem repositorySystem; - private final RuntimeInformation runtimeInformation; - - @Inject - public CoanaFactsLifecycleParticipant( - ProjectDependenciesResolver dependenciesResolver, - RepositorySystem repositorySystem, - RuntimeInformation runtimeInformation) { - this.dependenciesResolver = dependenciesResolver; - this.repositorySystem = repositorySystem; - this.runtimeInformation = runtimeInformation; - } - - @Override - public void afterSessionEnd(MavenSession session) throws MavenExecutionException { - if (!"socket-facts".equals(normalize(opt(session, "coana.task")))) { - return; - } - String recordsFile = opt(session, "socket.recordsFile"); - if (recordsFile == null || recordsFile.isEmpty()) { - throw new MavenExecutionException("socket-facts requires -Dsocket.recordsFile", new IllegalStateException()); - } - SocketFactsRecordsEngine.Options opts = new SocketFactsRecordsEngine.Options(); - opts.recordsFile = recordsFile; - opts.withFiles = optBoolean(session, "socket.withFiles"); - opts.populateFilesFor = opt(session, "socket.populateFilesFor"); - opts.includeConfigs = opt(session, "socket.includeConfigs"); - opts.excludeConfigs = opt(session, "socket.excludeConfigs"); - opts.excludePaths = opt(session, "socket.excludePaths"); - opts.excludeBase = opt(session, "socket.excludeBase"); - File rootDir = new File(session.getExecutionRootDirectory()); - CollectionObserver observer = new CollectionObserver(); - CoanaFactsEventSpy.observe(observer); - try { - new SocketFactsRecordsEngine( - dependenciesResolver, repositorySystem, runtimeInformation.getMavenVersion(), observer, LOG) - .run(session, session.getProjects(), rootDir, opts); - } catch (IOException exception) { - throw new MavenExecutionException("Cannot write socket facts records", exception); - } finally { - CoanaFactsEventSpy.observe(null); - } - } - - // Accept the cross-tool camelCase alias used by the CLI / Gradle / SBT scripts. - private static String normalize(String task) { - return "socketFacts".equals(task) ? "socket-facts" : task; - } - - // -D values arrive as both session user-properties and JVM system properties; prefer the former. - private static String opt(MavenSession session, String key) { - Properties user = session.getUserProperties(); - if (user != null && user.getProperty(key) != null) return user.getProperty(key); - return System.getProperty(key); - } - - private static boolean optBoolean(MavenSession session, String key) { - return Boolean.parseBoolean(opt(session, key)); - } -} diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java index 3001b546e7..0e63312600 100644 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java +++ b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java @@ -14,8 +14,7 @@ import java.util.Properties; /** - * Sibling of {@link CoanaFactsLifecycleParticipant}, gated by {@code -Dcoana.task=socket-workspaces}. - * Hooks {@code afterProjectsRead} (fires once the reactor project list is known, before any + * Gated by {@code -Dcoana.task=socket-workspaces}. Hooks {@code afterProjectsRead} (fires once the reactor project list is known, before any * lifecycle phase runs) since it only needs that list, never a dependency graph. */ @Named("coana-workspaces") diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/CollectionObserver.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/CollectionObserver.java deleted file mode 100644 index f56dcd067d..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/CollectionObserver.java +++ /dev/null @@ -1,125 +0,0 @@ -package tech.coana.socket; - -import org.eclipse.aether.RepositoryEvent; -import org.eclipse.aether.RequestTrace; -import org.eclipse.aether.collection.CollectStepData; -import org.eclipse.aether.graph.Dependency; -import org.eclipse.aether.graph.DependencyNode; - -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * What the repository events of dependency collection reveal beyond its result: the POMs Maven's - * default {@code ArtifactDescriptorPolicy} tolerated as missing or invalid (the node stays, its - * dependencies are lost, and no collection error is raised), build-wide, and the graph position of - * each collect step of the current module. - */ -public final class CollectionObserver { - - // CollectStepData is maven-resolver 1.8.1+ (Maven 3.9+); older resolvers trace no collect step. - private static final boolean COLLECT_STEPS = classExists("org.eclipse.aether.collection.CollectStepData"); - - // The resolver caches a tolerated POM build-wide, so only the first module to reach one sees its - // event; that module's detail is kept. - private final Map incompleteDescriptors = new LinkedHashMap<>(); - private final Set incompleteInModule = new HashSet<>(); - private final Map stepParents = new IdentityHashMap<>(); - - public synchronized void onEvent(RepositoryEvent event) { - if (event.getType() == RepositoryEvent.EventType.ARTIFACT_DESCRIPTOR_MISSING) { - incomplete(event, "is missing, no dependency information available"); - } else if (event.getType() == RepositoryEvent.EventType.ARTIFACT_DESCRIPTOR_INVALID) { - incomplete(event, "is invalid, transitive dependencies (if any) will not be available"); - } - // The depth-first collector hands each step its live node stack, so the parent is only right now. - if (COLLECT_STEPS) Steps.recordParent(event.getTrace(), stepParents); - } - - private void incomplete(RepositoryEvent event, String problem) { - String gav = SocketFactsRecordsEngine.gav(event.getArtifact()); - if (incompleteDescriptors.containsKey(gav) && !incompleteInModule.contains(gav)) return; - incompleteInModule.add(gav); - incompleteDescriptors.put( - gav, - "The POM for " + event.getArtifact() + " " + problem + ": " - + SocketFactsRecordsEngine.rootMessage(event.getException())); - } - - /** Starts the next module's collection. */ - synchronized void reset() { - incompleteInModule.clear(); - stepParents.clear(); - } - - /** GAV to failure detail of each POM the collection tolerated as missing or invalid. */ - synchronized Map incompleteDescriptors() { - return new LinkedHashMap<>(incompleteDescriptors); - } - - /** The node whose children the collect step behind {@code trace} was adding, if it was observed. */ - synchronized DependencyNode parentOf(RequestTrace trace) { - return COLLECT_STEPS ? Steps.parentOf(trace, stepParents) : null; - } - - /** The dependency, before management, that the collect step behind {@code trace} was adding. */ - synchronized Dependency dependencyOf(RequestTrace trace) { - return COLLECT_STEPS ? Steps.dependencyOf(trace) : null; - } - - private static boolean classExists(String name) { - try { - Class.forName(name, false, RequestTrace.class.getClassLoader()); - return true; - } catch (ClassNotFoundException | LinkageError e) { - return false; - } - } - - // Only loaded when CollectStepData exists. - private static final class Steps { - static void recordParent(RequestTrace trace, Map parents) { - RequestTrace at = stepTrace(trace); - if (at == null || parents.containsKey(at.getData())) return; - List path = ((CollectStepData) at.getData()).getPath(); - if (!path.isEmpty()) parents.put(at.getData(), path.get(path.size() - 1)); - } - - static DependencyNode parentOf(RequestTrace trace, Map parents) { - RequestTrace at = stepTrace(trace); - if (at == null) return null; - DependencyNode observed = parents.get(at.getData()); - if (observed != null) return observed; - // The depth-first collector hands every step its one live node stack, so an unobserved step's path - // is only trusted when it is checkably its own: the breadth-first collector nests each step's - // trace in its parent's step, whose dependency is then the path's last node. - RequestTrace enclosing = stepTrace(at.getParent()); - List path = ((CollectStepData) at.getData()).getPath(); - if (enclosing == null || path.isEmpty()) return null; - DependencyNode last = path.get(path.size() - 1); - Dependency parent = ((CollectStepData) enclosing.getData()).getNode(); - if (last.getDependency() == null - || !last.getDependency().getArtifact().getGroupId().equals(parent.getArtifact().getGroupId()) - || !last.getDependency().getArtifact().getArtifactId().equals(parent.getArtifact().getArtifactId())) { - return null; - } - return last; - } - - static Dependency dependencyOf(RequestTrace trace) { - RequestTrace at = stepTrace(trace); - return at == null ? null : ((CollectStepData) at.getData()).getNode(); - } - - private static RequestTrace stepTrace(RequestTrace trace) { - for (RequestTrace t = trace; t != null; t = t.getParent()) { - if (t.getData() instanceof CollectStepData) return t; - } - return null; - } - } -} diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketFactsRecordsEngine.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketFactsRecordsEngine.java deleted file mode 100644 index 0587a61c01..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketFactsRecordsEngine.java +++ /dev/null @@ -1,1018 +0,0 @@ -package tech.coana.socket; - -import org.apache.maven.RepositoryUtils; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.Resource; -import org.apache.maven.project.DefaultDependencyResolutionRequest; -import org.apache.maven.project.DependencyResolutionException; -import org.apache.maven.project.DependencyResolutionRequest; -import org.apache.maven.project.DependencyResolutionResult; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectDependenciesResolver; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.RepositoryException; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.RequestTrace; -import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.collection.DependencyGraphTransformationContext; -import org.eclipse.aether.collection.DependencyGraphTransformer; -import org.eclipse.aether.graph.Dependency; -import org.eclipse.aether.graph.DependencyFilter; -import org.eclipse.aether.graph.DependencyNode; -import org.eclipse.aether.resolution.ArtifactDescriptorException; -import org.eclipse.aether.resolution.ArtifactDescriptorRequest; -import org.eclipse.aether.resolution.ArtifactResult; -import org.eclipse.aether.resolution.DependencyRequest; -import org.eclipse.aether.resolution.VersionRangeRequest; -import org.eclipse.aether.resolution.VersionRangeResolutionException; -import org.slf4j.Logger; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Pattern; - -/** - * Emits each reactor module's resolved dependency graph as line-protocol records for the TS assembler - * (same contract as the Gradle/SBT scripts; no JSON/hashing here). Per module: a test root with the - * whole resolution and a compile root with the nodes kept with a prod scope (compile/runtime/system), - * each with the resolved edges between its own nodes. A reactor module becomes a component only - * where another depends on one of its artifacts, each of which names the module as its project. - * - *

Resolution goes through {@link ProjectDependenciesResolver} — the same component Maven's own - * lifecycle uses to build a project's classpath — so the graph, the scope and management semantics, - * the per-node repository lists and the reactor substitution are Maven's, not an approximation of - * them. Resolving a dependency against only its root module's repositories, as a hand-rolled walk - * does, loses the repositories a dependency's own POM contributes and then cannot see artifacts - * cached from them (Aether's local repository tracks each file's origin repository). - */ -public final class SocketFactsRecordsEngine { - - public static final class Options { - public boolean withFiles; - public String populateFilesFor; - public String includeConfigs; - public String excludeConfigs; - // `--exclude-paths` (CSV) relative to excludeBase: a wholly excluded reactor module is skipped. - public String excludePaths; - // The directory excludePaths are relative to; the build root when unset. - public String excludeBase; - public String recordsFile; - } - - // Aether's ArtifactProperties.TYPE: Maven's `type` (jar, test-jar, ...) as opposed to the file - // extension, carried as an artifact property once a Maven dependency becomes an Aether one. - private static final String ARTIFACT_PROPERTY_TYPE = "type"; - // ConflictResolver.NODE_DATA_WINNER, inlined so nothing here needs maven-resolver-util. - private static final String NODE_DATA_CONFLICT_WINNER = "conflict.winner"; - // TransformationContextKeys.CONFLICT_IDS, inlined for the same reason. - private static final String CONTEXT_CONFLICT_IDS = "conflictIds"; - - private final ProjectDependenciesResolver dependenciesResolver; - private final RepositorySystem repositorySystem; - private final String mavenVersion; - private final CollectionObserver observer; - private final Logger log; - // Maven 3.2.5's collector (aether 1.0.0) leaves a dependency whose POM failed out of the graph; from - // aether 1.0.2 (Maven 3.3) on it stays, minus its children. - private final boolean collectorDropsFailedNodes; - // Maven 3's JavaScopeDeriver and ClassicDependencyManager, which absentScope models. - private final boolean maven3ScopeRules; - // The resolver caches a failed POM build-wide, keyed by artifact alone, so only the first module to - // reach one sees the failure; every later module gets the node without children and no error. - // Keyed by GAV. - private final Map brokenDescriptors = new LinkedHashMap<>(); - - public SocketFactsRecordsEngine( - ProjectDependenciesResolver dependenciesResolver, RepositorySystem repositorySystem, String mavenVersion, - CollectionObserver observer, Logger log) { - this.dependenciesResolver = dependenciesResolver; - this.repositorySystem = repositorySystem; - this.mavenVersion = mavenVersion; - this.observer = observer; - this.log = log; - this.collectorDropsFailedNodes = mavenVersion != null && mavenVersion.startsWith("3.2."); - this.maven3ScopeRules = mavenVersion == null || mavenVersion.startsWith("3."); - } - - public void run(MavenSession session, List reactor, File rootDir, Options opts) - throws IOException { - Scopes scopes = new Scopes(!maven3ScopeRules, opts.includeConfigs, opts.excludeConfigs); - // GAVs to materialize under --with-files (null = all). Scopes artifact downloads so reachability - // doesn't fetch the whole dependency universe. Module src/tgt dirs are emitted regardless (no download). - Set populateGavs = readPopulateGavs(opts); - // reactorGavs stays complete (all modules) so a KEPT module depending on an excluded one still - // recognizes it as internal; `excludes` only gates resolution + the project record. - Set reactorGavs = new HashSet<>(); - for (MavenProject p : reactor) { - reactorGavs.add(p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion()); - } - List excludes = SocketSupport.parseExcludePatterns(opts.excludePaths); - java.nio.file.Path excludeBase = SocketSupport.excludeBase(opts.excludeBase, rootDir); - - List lines = new ArrayList<>(); - rec(lines, "meta", "maven", mavenVersion, System.getProperty("java.version")); - rec(lines, "buildRoot", rootDir.getAbsolutePath()); - // The POM Maven was invoked on (`-f`, else the default it located), which names the facts file. - File entryPom = session.getRequest().getPom(); - if (entryPom != null) rec(lines, "entry", SocketSupport.relativePath(rootDir.toPath(), entryPom.getAbsoluteFile().toPath())); - - for (MavenProject module : reactor) { - // No basedir: Maven's stand-in project for a directory without a POM. Skipping it lets Maven's - // own "no POM in this directory" error surface instead of an NPE. - if (module.getBasedir() == null) continue; - String ws = SocketSupport.workspace(rootDir.toPath(), module.getBasedir().toPath()); - String key = projectKey(module); - boolean excluded = SocketSupport.isExcludedDir(excludeBase, module.getBasedir().toPath(), excludes); - if (excluded) { - // Not analysed on its own, but a kept module depending on it is analysed with its code. - if (opts.withFiles) rec(lines, "excludedProject", key); - } else { - rec(lines, "project", key, module.getGroupId(), module.getArtifactId(), module.getVersion(), ws); - File pom = module.getFile(); - if (pom != null && pom.isFile()) rec(lines, "projectBuild", key, SocketSupport.relativePath(rootDir.toPath(), pom.toPath())); - } - if (opts.withFiles) { - for (String s : collectSources(module)) rec(lines, "projectSrc", key, s); - for (String t : collectTargets(module)) rec(lines, "projectTgt", key, t); - } - } - - Set failures = new LinkedHashSet<>(); - Set unscannable = new LinkedHashSet<>(); - int rootIdx = 0; - for (MavenProject module : reactor) { - if (module.getBasedir() == null) continue; - // A wholly excluded reactor module is not resolved (matches the project-record skip above). - if (SocketSupport.isExcludedDir(excludeBase, module.getBasedir().toPath(), excludes)) continue; - Map nodes = new LinkedHashMap<>(); - Set directIds = new HashSet<>(); - ClassLoader previous = Thread.currentThread().getContextClassLoader(); - if (module.getClassRealm() != null) Thread.currentThread().setContextClassLoader(module.getClassRealm()); - try { - collectModule(session, module, scopes, reactorGavs, populateGavs, opts, nodes, directIds, failures, unscannable); - } finally { - Thread.currentThread().setContextClassLoader(previous); - } - rootIdx = emitModuleRoots(lines, rootIdx, projectKey(module), nodes, directIds); - } - - for (String scope : scopes.scanned()) rec(lines, "scanned", scope); - for (Failure f : failures) rec(lines, "failure", f.coord, f.detail, f.config, f.project); - for (Unscannable u : unscannable) rec(lines, "unscannable", "", u.detail, u.project); - - write(opts.recordsFile, lines); - } - - // Not the directory, which `x/a.xml` and `x/b.xml` share; Maven - // rejects a reactor with a duplicate GAV. Surfaces as the facts project id. - private static String projectKey(MavenProject module) { - return module.getGroupId() + ":" + module.getArtifactId() + ":" + module.getVersion(); - } - - // ---- resolution ---- - - // Run inside the module's class realm, as Maven's LifecycleDependencyResolver does: artifact types - // the build extensions contribute are only found from there. - private void collectModule( - MavenSession session, - MavenProject module, - Scopes scopes, - Set reactorGavs, - Set populateGavs, - Options opts, - Map nodes, - Set directIds, - Set failures, - Set unscannable) { - String moduleCoord = module.getGroupId() + ":" + module.getArtifactId() + ":" + module.getVersion(); - DependencyResolutionResult result; - DependencyResolutionException thrown = null; - DependencyFilter resolutionFilter = materializationFilter(opts, scopes, reactorGavs, populateGavs); - observer.reset(); - EdgeRecorder recorder = new EdgeRecorder(session.getRepositorySession().getDependencyGraphTransformer()); - DefaultRepositorySystemSession recording = new DefaultRepositorySystemSession(session.getRepositorySession()); - recording.setDependencyGraphTransformer(recorder); - try { - DependencyResolutionRequest request = new DefaultDependencyResolutionRequest(module, recording); - request.setResolutionFilter(resolutionFilter); - result = dependenciesResolver.resolve(request); - } catch (DependencyResolutionException e) { - // Maven attaches the partial result — graph plus per-dependency errors — to the exception, so - // one unresolvable artifact still yields a complete graph and a precise failure record. - thrown = e; - result = e.getResult(); - if (result == null) { - reportUnscannable(unscannable, moduleCoord, rootMessage(e)); - return; - } - } - boolean reported = false; - // Null when the transformer threw (the result then holds only the collected candidates) or the - // recorder never saw the graph Maven returned. - Map> edges = recorder.edges(); - DependencyNode returned = result.getDependencyGraph(); - DependencyNode graph = edges != null && edges.containsKey(returned) ? returned : null; - List collectionFailures = new ArrayList<>(); - for (Exception e : result.getCollectionErrors()) { - FailedRequest failed = failedRequest(e); - if (failed == null) { - unscannable.add(new Unscannable(rootMessage(e), moduleCoord)); - } else { - collectionFailures.add(failed); - if (failed.descriptor) { - brokenDescriptors.put(gav(failed.artifact), failed); - } - } - log.warn("[socket-facts] could not build dependency graph for " + moduleCoord + ": " + rootMessage(e)); - reported = true; - } - Map incompleteDescriptors = observer.incompleteDescriptors(); - // Dependencies whose own resolution failed are reported, not emitted, as Gradle and sbt do. One - // whose POM Maven tolerated as missing or invalid is still emitted: its own artifact may be fine. - Set unresolved = new HashSet<>(); - Map> scopesByGav = - brokenDescriptors.isEmpty() && incompleteDescriptors.isEmpty() && collectionFailures.isEmpty() - ? Collections.>emptyMap() - : scopesByGav(graph); - for (Map.Entry e : brokenDescriptors.entrySet()) { - Set gavScopes = scopesByGav.get(e.getKey()); - if (gavScopes == null) continue; - unresolved.add(e.getKey()); - reported |= addFailures(failures, e.getKey(), e.getValue().detail, gavScopes, scopes, moduleCoord); - } - for (Map.Entry e : incompleteDescriptors.entrySet()) { - // A strict descriptor policy also throws for it: already reported above. - if (brokenDescriptors.containsKey(e.getKey())) continue; - Set gavScopes = scopesByGav.get(e.getKey()); - if (gavScopes != null) reported |= addFailures(failures, e.getKey(), e.getValue(), gavScopes, scopes, moduleCoord); - } - Set placed = new HashSet<>(); - Set onClasspath = graph == null ? Collections.emptySet() : edges.keySet(); - for (FailedRequest failed : collectionFailures) { - String coord = gav(failed.artifact); - if (scopesByGav.containsKey(coord)) continue; - String scope = absentScope(session, module, failed, onClasspath); - placed.add(coord); - if (scope == null) { - log.debug("[socket-facts] " + coord + " failed but sits on no classpath of " + moduleCoord); - } else if (scope.isEmpty() || scopes.passes(scope)) { - failures.add(new Failure(coord, failed.detail, scope, moduleCoord)); - } - } - if (collectorDropsFailedNodes) { - // An earlier module's cached failure leaves no trace in this graph; only a direct dependency - // can still be placed. One still among the direct children resolved (a ranged declaration to - // another version), since a direct dependency never loses a conflict. - for (Map.Entry e : brokenDescriptors.entrySet()) { - if (scopesByGav.containsKey(e.getKey()) || placed.contains(e.getKey())) continue; - if (isDirectChild(graph, e.getValue().artifact)) continue; - String scope = declaredScope(session, module, e.getValue().artifact); - if (scope != null && scopes.passes(scope)) { - failures.add(new Failure(e.getKey(), e.getValue().detail, scope, moduleCoord)); - reported = true; - } - } - } - // Maven throws on a collection error before it fetches any artifact, which would leave every - // healthy node of the partial graph without its file. - Set unfetched = new HashSet<>(); - if (!result.getCollectionErrors().isEmpty() && graph != null && opts.withFiles) { - materialize(session, graph, resolutionFilter, unresolved, moduleCoord, failures, unfetched); - } - for (Dependency dep : result.getUnresolvedDependencies()) { - Artifact artifact = dep.getArtifact(); - if (artifact == null || unresolved.contains(gav(artifact))) continue; - reportUnfetched(dep, result.getResolutionErrors(dep), moduleCoord, failures, unfetched); - reported = true; - } - // Fail closed: a throw whose result named nothing must still surface, or an unresolved dependency - // would silently leave the reachability analysis blind to whatever that artifact contains. - if (thrown != null && !reported) { - reportUnscannable(unscannable, moduleCoord, rootMessage(thrown)); - } - // A transformer that threw is a collection error, reported above. Otherwise Maven's graph bypassed - // the recorder, and the module's whole graph would vanish unreported. - if (graph == null && !recorder.threw()) { - reportUnscannable(unscannable, moduleCoord, "dependencies resolved without the socket-facts graph transformer"); - } - if (graph == null) return; - for (DependencyNode child : edges.get(graph)) { - String id = visit(child, edges, scopes, reactorGavs, unresolved, opts, nodes); - if (id != null) directIds.add(id); - } - for (String id : unfetched) { - Node node = nodes.get(id); - if (node != null) node.unfetched = true; - } - } - - /** - * Which nodes Maven should MATERIALIZE (fetch the artifact for). Everything else is still collected - * — the graph stays complete — but never resolved, which is what keeps a plain {@code --facts} run - * download-free and keeps us from requesting a reactor sibling's jar: at the {@code validate} phase - * the CLI runs, no sibling has been packaged and none need be installed. - * - *

A node the filter rejects produces no {@code ArtifactResult}, so it lands in neither - * {@code getResolvedDependencies()} nor {@code getUnresolvedDependencies()} and can never be - * mistaken for a resolution failure. - */ - private static DependencyFilter materializationFilter( - final Options opts, - final Scopes scopes, - final Set reactorGavs, - final Set populateGavs) { - if (!opts.withFiles) { - return new DependencyFilter() { - @Override - public boolean accept(DependencyNode node, List parents) { - return false; - } - }; - } - return new DependencyFilter() { - @Override - public boolean accept(DependencyNode node, List parents) { - Dependency dep = node == null ? null : node.getDependency(); - Artifact artifact = dep == null ? null : dep.getArtifact(); - if (artifact == null) return false; - // A dependency on no path is never fetched. - String scope = scopeOf(dep); - if (!scopes.passes(scope) || !scopes.onClasspath(scope)) return false; - String gav = gav(artifact); - if (reactorGavs.contains(gav)) return false; - return populateGavs == null || populateGavs.contains(gav); - } - }; - } - - /** - * The artifact step Maven skipped, run on the partial graph the way the resolver's own - * {@code resolveDependencies} continues past a collection failure. The failed dependencies are left - * out: they are never emitted, and fetching them again would only repeat the failure. - */ - private void materialize( - MavenSession session, - DependencyNode graph, - final DependencyFilter resolutionFilter, - final Set unresolved, - String moduleCoord, - Set failures, - Set unfetched) { - DependencyFilter healthy = new DependencyFilter() { - @Override - public boolean accept(DependencyNode node, List parents) { - return resolutionFilter.accept(node, parents) && !unresolved.contains(gav(node.getArtifact())); - } - }; - List results; - try { - results = repositorySystem - .resolveDependencies(session.getRepositorySession(), new DependencyRequest(graph, healthy)) - .getArtifactResults(); - } catch (org.eclipse.aether.resolution.DependencyResolutionException e) { - results = e.getResult().getArtifactResults(); - } - for (ArtifactResult ar : results) { - if (ar.isResolved()) continue; - reportUnfetched(ar.getRequest().getDependencyNode().getDependency(), ar.getExceptions(), moduleCoord, failures, unfetched); - } - } - - private void reportUnscannable(Set unscannable, String moduleCoord, String reason) { - unscannable.add(new Unscannable(reason, moduleCoord)); - log.warn("[socket-facts] could not resolve dependencies for " + moduleCoord + ": " + reason); - } - - private void reportUnfetched( - Dependency dep, List errors, String moduleCoord, Set failures, Set unfetched) { - String id = externalId(dep.getArtifact()); - failures.add(new Failure(id, rootMessage(errors.isEmpty() ? null : errors.get(0)), scopeOf(dep), moduleCoord)); - unfetched.add(id); - log.debug("[socket-facts] could not materialize " + dep.getArtifact() + " (" + scopeOf(dep) + ")"); - } - - private String visit( - DependencyNode dn, - Map> edges, - Scopes scopes, - Set reactorGavs, - Set unresolved, - Options opts, - Map nodes) { - Dependency dep = dn.getDependency(); - Artifact artifact = dn.getArtifact(); - if (dep == null || artifact == null) return null; - String scope = scopeOf(dep); - if (!scopes.passes(scope)) return null; - - String gav = gav(artifact); - if (unresolved.contains(gav)) return null; - boolean internal = reactorGavs.contains(gav); - String type = artifact.getProperty(ARTIFACT_PROPERTY_TYPE, artifact.getExtension()); - String classifier = artifact.getClassifier(); - String id = externalId(artifact); - - // One walk per artifact: a shared subtree is already recorded. - if (nodes.containsKey(id)) return id; - - // A sibling module's artifacts, such as its jar and test-jar, name the module as their project; the - // assembler merges them into its component. - Node node = new Node(id, artifact.getGroupId(), artifact.getArtifactId(), - type == null ? "" : type, classifier == null ? "" : classifier, artifact.getBaseVersion(), internal ? gav : ""); - node.prod = scopes.prod(scope); - node.onClasspath = scopes.onClasspath(scope); - scopes.scanned(scope); - nodes.put(id, node); - - // Maven wrote each accepted node's resolved file back onto the node; a reactor module reports its - // own dirs through its `project` record instead of a `file` record. - if (!internal && opts.withFiles) { - String file = SocketSupport.existingAbsolutePath(artifact.getFile()); - if (file != null) node.files.add(file); - } - - for (DependencyNode child : edges.get(dn)) { - String childId = visit(child, edges, scopes, reactorGavs, unresolved, opts, nodes); - if (childId != null) node.children.add(childId); - } - return id; - } - - private static String externalId(Artifact artifact) { - // Maven's `type` rather than aether's file extension, so a test-jar keeps the coordId the - // assembler and the Gradle/SBT scripts already emit. Base version: a resolved remote snapshot's - // `version` is the timestamped build, which would put a coordinate in the records that no - // manifest ever names. - return SocketSupport.coordId( - artifact.getGroupId(), artifact.getArtifactId(), - artifact.getProperty(ARTIFACT_PROPERTY_TYPE, artifact.getExtension()), artifact.getClassifier(), - artifact.getBaseVersion()); - } - - static String gav(Artifact artifact) { - return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion(); - } - - private static String scopeOf(Dependency dep) { - String scope = dep == null ? null : dep.getScope(); - return scope == null || scope.isEmpty() ? "compile" : scope; - } - - // ---- emission ---- - - // Shaped like Gradle's runtime and test classpaths. An edge from a prod node onto a dev one, such as - // onto a dependency the module declares `provided`, lives in the test root only. A dependency on no - // path lives only in a root off every classpath, which holds the whole resolution. - private int emitModuleRoots( - List lines, int rootIdx, String projectKey, Map nodes, Set directIds) { - Map prod = new LinkedHashMap<>(); - Map classpath = new LinkedHashMap<>(); - Map noPath = new LinkedHashMap<>(); - for (Node n : nodes.values()) { - if (n.prod && n.onClasspath) prod.put(n.id, n); - if (n.onClasspath) classpath.put(n.id, n); - else noPath.put(n.id, n); - } - if (!prod.isEmpty()) { - rootIdx = emitRoot(lines, rootIdx, projectKey, "compile", true, true, prod, directIds); - } - if (!classpath.isEmpty()) { - rootIdx = emitRoot(lines, rootIdx, projectKey, "test", false, true, classpath, directIds); - } - if (!noPath.isEmpty()) { - rootIdx = emitRoot(lines, rootIdx, projectKey, "none", false, false, nodes, directIds); - } - return rootIdx; - } - - private int emitRoot( - List lines, int rootIdx, String projectKey, String config, boolean prod, boolean onClasspath, - Map nodeMap, Set directIds) { - String rootId = Integer.toString(rootIdx); - rec(lines, "root", rootId, projectKey, config, prod ? "1" : "0"); - if (!onClasspath) rec(lines, "noClasspath", rootId); - for (Node n : nodeMap.values()) { - rec(lines, "node", rootId, n.id, n.groupId, n.artifactId, n.version, n.type, n.classifier, - directIds.contains(n.id) ? "1" : "0", n.project); - for (String child : n.children) { - if (nodeMap.containsKey(child)) rec(lines, "edge", rootId, n.id, child); - } - for (String f : n.files) rec(lines, "file", rootId, n.id, f); - if (n.unfetched) rec(lines, "unfetched", rootId, n.id); - } - return rootIdx + 1; - } - - // ---- scopes / module files ---- - - /** - * How Maven treats a dependency scope, and which scopes --include-configs/--exclude-configs pass. - * Maven 3 knows five scopes and lets any other through every classpath filter, so an unknown scope - * (`import`, or a typo, in {@code }) is on every classpath. Maven 4 adds four, which - * maven-api-core's DependencyScope and PathScope define; a scope it does not define is treated as - * Maven 3 treats it, as Maven 4's default plugins do. - */ - private static final class Scopes { - private static final List MAVEN3 = Arrays.asList("compile", "provided", "runtime", "system", "test"); - private static final List MAVEN4 = Arrays.asList("compile-only", "none", "test-only", "test-runtime"); - private final boolean maven4; - private final List includes; - private final List excludes; - private final Map passing = new HashMap<>(); - private final Set scanned = new TreeSet<>(); - - Scopes(boolean maven4, String includeConfigs, String excludeConfigs) { - this.maven4 = maven4; - this.includes = SocketSupport.parsePatterns(includeConfigs); - this.excludes = SocketSupport.parsePatterns(excludeConfigs); - for (String scope : MAVEN3) scanned(scope); - if (maven4) for (String scope : MAVEN4) scanned(scope); - } - - boolean passes(String scope) { - return passing.computeIfAbsent( - scope, s -> !matchesAny(excludes, s) && (includes.isEmpty() || matchesAny(includes, s))); - } - - // Prod: Maven 4's main runtime path (compile, runtime), system, and any scope Maven 3 does not know. - boolean prod(String scope) { - if (scope.equals("provided") || scope.equals("test")) return false; - return !(maven4 && MAVEN4.contains(scope)); - } - - // Maven 4's none is in no path scope. - boolean onClasspath(String scope) { - return !(maven4 && scope.equals("none")); - } - - /** Records a scope as scanned if it passes: one Maven defines, or one a resolved graph used. */ - void scanned(String scope) { - if (passes(scope)) scanned.add(scope); - } - - Set scanned() { - return scanned; - } - } - - private static boolean matchesAny(List patterns, String name) { - for (Pattern p : patterns) if (p.matcher(name).matches()) return true; - return false; - } - - // Read the newline-delimited GAV file named by -Dsocket.populateFilesFor. Returns null (materialize - // all) when not under --with-files, unset, or the file is missing/empty (a wiring slip, not a - // deliberate "fetch nothing"), matching the Gradle/SBT scripts. - private Set readPopulateGavs(Options opts) throws IOException { - if (!opts.withFiles || opts.populateFilesFor == null || opts.populateFilesFor.trim().isEmpty()) return null; - File f = new File(opts.populateFilesFor.trim()); - if (!f.exists()) { - log.warn("[socket-facts] populateFilesFor file not found; materializing files for all resolved artifacts"); - return null; - } - Set gavs = new HashSet<>(); - for (String line : Files.readAllLines(f.toPath(), StandardCharsets.UTF_8)) { - String t = line.trim(); - if (!t.isEmpty()) gavs.add(t); - } - if (gavs.isEmpty()) { - log.warn("[socket-facts] populateFilesFor file empty; materializing files for all resolved artifacts"); - return null; - } - log.info("[socket-facts] --with-files scoped to " + gavs.size() + " artifact(s)"); - return gavs; - } - - // Configured source roots, emitted unconditionally (like gradle's srcDirs / sbt's sourceDirectories): - // the analysis never builds the project, so these need not exist yet. - private List collectSources(MavenProject module) { - Set sources = new TreeSet<>(); - addPaths(sources, module.getCompileSourceRoots()); - addPaths(sources, module.getTestCompileSourceRoots()); - for (Resource r : module.getBuild().getResources()) addPath(sources, r.getDirectory()); - for (Resource r : module.getBuild().getTestResources()) addPath(sources, r.getDirectory()); - // generated-source roots aren't on the model without a build; best-effort pick up the - // conventional dirs only if a prior `mvn compile` already produced them (else they'd be guesses). - String buildDir = module.getBuild().getDirectory(); - addExisting(sources, buildDir + File.separator + "generated-sources"); - addExisting(sources, buildDir + File.separator + "generated-test-sources"); - return new ArrayList<>(sources); - } - - // Configured compiled-output dirs, emitted unconditionally (like gradle's classesDirs / sbt's - // classDirectory): the analysis never builds the project, so these need not exist yet. - private List collectTargets(MavenProject module) { - Set targets = new TreeSet<>(); - addPath(targets, module.getBuild().getOutputDirectory()); - addPath(targets, module.getBuild().getTestOutputDirectory()); - return new ArrayList<>(targets); - } - - private static void addPaths(Set acc, List dirs) { - if (dirs == null) return; - for (String d : dirs) addPath(acc, d); - } - - // Existence-filtered: for speculative paths we only want to emit when they actually exist. - private static void addExisting(Set acc, String dir) { - if (dir == null) return; - String p = SocketSupport.existingAbsolutePath(new File(dir)); - if (p != null) acc.add(p); - } - - private static void addPath(Set acc, String dir) { - if (dir == null) return; - acc.add(new File(dir).getAbsolutePath()); - } - - // ---- records I/O ---- - - private static void rec(List lines, String... fields) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < fields.length; i++) { - if (i > 0) sb.append('\t'); - sb.append(SocketSupport.escapeField(fields[i])); - } - lines.add(sb.toString()); - } - - private void write(String recordsFile, List lines) throws IOException { - File out = new File(recordsFile); - if (out.getParentFile() != null) Files.createDirectories(out.getParentFile().toPath()); - try (PrintWriter writer = new PrintWriter(out, StandardCharsets.UTF_8.name())) { - for (String line : lines) writer.print(line + "\n"); - } - log.info("[socket-facts] records written to: " + out.getAbsolutePath()); - } - - static String rootMessage(Throwable t) { - Throwable cur = t; - String msg = null; - int guard = 0; - while (cur != null && guard++ < 12) { - if (cur.getMessage() != null) msg = cur.getMessage(); - Throwable next = cur.getCause(); - // Maven 4 batches requests: BatchRequestException carries each failed request as a suppressed - // exception, not as its cause. - if (next == null && cur.getSuppressed().length > 0) next = cur.getSuppressed()[0]; - cur = next; - } - return (msg != null ? msg : "unknown resolution failure").trim(); - } - - private static Map> scopesByGav(DependencyNode root) { - Map> scopes = new HashMap<>(); - if (root == null) return scopes; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - Deque todo = new ArrayDeque<>(root.getChildren()); - while (!todo.isEmpty()) { - DependencyNode dn = todo.pop(); - if (!seen.add(dn) || dn.getData().get(NODE_DATA_CONFLICT_WINNER) != null) continue; - if (dn.getArtifact() != null) { - scopes.computeIfAbsent(gav(dn.getArtifact()), k -> new TreeSet<>()).add(scopeOf(dn.getDependency())); - } - todo.addAll(dn.getChildren()); - } - return scopes; - } - - // The request a collection error is about, when the resolver names one. - private static FailedRequest failedRequest(Exception e) { - Throwable cur = e; - int guard = 0; - while (cur != null && guard++ < 12) { - if (cur instanceof ArtifactDescriptorException) { - ArtifactDescriptorException d = (ArtifactDescriptorException) cur; - if (d.getResult() != null) { - ArtifactDescriptorRequest request = d.getResult().getRequest(); - return new FailedRequest(request.getArtifact(), request.getTrace(), true, rootMessage(e)); - } - } else if (cur instanceof VersionRangeResolutionException) { - VersionRangeResolutionException r = (VersionRangeResolutionException) cur; - if (r.getResult() != null) { - VersionRangeRequest request = r.getResult().getRequest(); - return new FailedRequest(request.getArtifact(), request.getTrace(), false, rootMessage(e)); - } - } - cur = cur.getCause(); - } - return null; - } - - private static boolean addFailures( - Set failures, String coord, String detail, Set gavScopes, Scopes scopes, - String moduleCoord) { - boolean added = false; - for (String scope : gavScopes) { - if (scopes.passes(scope)) added |= failures.add(new Failure(coord, detail, scope, moduleCoord)); - } - return added; - } - - // Null: on no classpath (from Maven 3.3 the graph keeps a failed POM's node, so an absent one lost a - // conflict). Empty: position unknown (no collect step before 3.9; Maven 4's scope rules not modelled). - private String absentScope( - MavenSession session, MavenProject module, FailedRequest failed, Set onClasspath) { - if (failed.descriptor && !collectorDropsFailedNodes) return null; - DependencyNode parent = observer.parentOf(failed.trace); - Dependency dependency = observer.dependencyOf(failed.trace); - if (parent != null && dependency != null) { - if (parent.getDependency() == null) return scopeOf(dependency); - DependencyNode placed = classpathInstance(onClasspath, parent); - if (placed == null) return null; - if (!maven3ScopeRules) return ""; - // ConflictResolver keeps a managed scope as it is, without deriving it. - String managed = managedScope(session, module, dependency.getArtifact()); - return managed != null ? managed : derivedScope(placed.getDependency().getScope(), scopeOf(dependency)); - } - String declared = declaredScope(session, module, failed.artifact); - return declared != null ? declared : ""; - } - - // ClassicDependencyManager: below the direct dependencies, only the root's dependencyManagement applies. - private static String managedScope(MavenSession session, MavenProject module, Artifact artifact) { - if (module.getDependencyManagement() == null) return null; - org.apache.maven.model.Dependency d = - modelDependency(session, module.getDependencyManagement().getDependencies(), artifact, false); - return d == null || d.getScope() == null || d.getScope().isEmpty() ? null : d.getScope(); - } - - // maven-resolver's JavaScopeDeriver. - private static String derivedScope(String parentScope, String childScope) { - if ("system".equals(childScope) || "test".equals(childScope)) return childScope; - if (parentScope == null || parentScope.isEmpty() || "compile".equals(parentScope)) return childScope; - if ("test".equals(parentScope) || "runtime".equals(parentScope)) return parentScope; - if ("system".equals(parentScope) || "provided".equals(parentScope)) return "provided"; - return "runtime"; - } - - // The module's own declaration of the artifact, with management applied. - private static String declaredScope(MavenSession session, MavenProject module, Artifact artifact) { - org.apache.maven.model.Dependency d = modelDependency(session, module.getDependencies(), artifact, true); - if (d == null) return null; - return d.getScope() == null || d.getScope().isEmpty() ? "compile" : d.getScope(); - } - - // The first of `deps` naming the artifact, compared as the resolver sees it: a `test-jar` type - // becomes classifier `tests`. With `matchVersion`, a ranged version matches whichever it resolved to. - private static org.apache.maven.model.Dependency modelDependency( - MavenSession session, List deps, Artifact artifact, boolean matchVersion) { - for (org.apache.maven.model.Dependency d : deps) { - Artifact candidate = - RepositoryUtils.toDependency(d, session.getRepositorySession().getArtifactTypeRegistry()).getArtifact(); - String version = candidate.getVersion(); - if (candidate.getGroupId().equals(artifact.getGroupId()) - && candidate.getArtifactId().equals(artifact.getArtifactId()) - && candidate.getClassifier().equals(artifact.getClassifier()) - && candidate.getExtension().equals(artifact.getExtension()) - && (!matchVersion - || version.equals(artifact.getVersion()) || version.startsWith("[") || version.startsWith("("))) { - return d; - } - } - return null; - } - - // A direct dependency of `root` naming the artifact, at any version. - private static boolean isDirectChild(DependencyNode root, Artifact artifact) { - if (root == null) return false; - for (DependencyNode child : root.getChildren()) { - Artifact a = child.getArtifact(); - if (a != null - && a.getGroupId().equals(artifact.getGroupId()) - && a.getArtifactId().equals(artifact.getArtifactId()) - && a.getClassifier().equals(artifact.getClassifier()) - && a.getExtension().equals(artifact.getExtension())) { - return true; - } - } - return false; - } - - // Instances with the same artifact and collection context share one cached child list, whose failing - // collect step ran only under the first of them; that one may have lost a conflict. - private static DependencyNode classpathInstance(Set onClasspath, DependencyNode parent) { - if (onClasspath.contains(parent)) return parent; - for (DependencyNode dn : onClasspath) { - if (dn.getChildren() == parent.getChildren()) return dn; - } - return null; - } - - // The final graph's root and every node on its classpath, by identity. - private static Set onClasspath(DependencyNode root) { - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - if (root == null) return seen; - Deque todo = new ArrayDeque<>(); - todo.push(root); - while (!todo.isEmpty()) { - DependencyNode dn = todo.pop(); - if (dn.getData().get(NODE_DATA_CONFLICT_WINNER) != null || !seen.add(dn)) continue; - todo.addAll(dn.getChildren()); - } - return seen; - } - - private static final class FailedRequest { - final Artifact artifact; - final RequestTrace trace; - // The artifact's POM could not be read; else no version satisfied its range. - final boolean descriptor; - final String detail; - - FailedRequest(Artifact artifact, RequestTrace trace, boolean descriptor, String detail) { - this.artifact = artifact; - this.trace = trace; - this.descriptor = descriptor; - this.detail = detail; - } - } - - private static final class Failure { - final String coord; - final String detail; - // Empty when the failure cannot be placed in a scope. - final String config; - final String project; - - Failure(String coord, String detail, String config, String project) { - this.coord = coord; - this.detail = detail; - this.config = config; - this.project = project; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Failure)) return false; - Failure f = (Failure) o; - return coord.equals(f.coord) && detail.equals(f.detail) && config.equals(f.config) - && project.equals(f.project); - } - - @Override - public int hashCode() { - return (coord + "|" + detail + "|" + config + "|" + project).hashCode(); - } - } - - // A module whose dependencies could not be resolved at all, with no failing artifact to name. - private static final class Unscannable { - final String detail; - final String project; - - Unscannable(String detail, String project) { - this.detail = detail; - this.project = project; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Unscannable)) return false; - Unscannable u = (Unscannable) o; - return detail.equals(u.detail) && project.equals(u.project); - } - - @Override - public int hashCode() { - return (detail + "|" + project).hashCode(); - } - } - - // Records each node's children before conflict resolution removes the losers: every resolved edge, - // including one onto a dependency Maven kept elsewhere, possibly at another version. - private static final class EdgeRecorder implements DependencyGraphTransformer { - private final DependencyGraphTransformer delegate; - private Map> edges; - private boolean threw; - - EdgeRecorder(DependencyGraphTransformer delegate) { - this.delegate = delegate; - } - - /** - * The root and each node Maven kept, mapped to its children by every resolved edge, a child that - * lost its conflict replaced by the node kept for its conflict id. Null unless the last - * call to the transformer, recording included, completed. - */ - Map> edges() { - return edges; - } - - boolean threw() { - return threw; - } - - // A RepositoryException is a collection error, so a broken assumption fails this module only. - @Override - public DependencyNode transformGraph(DependencyNode root, DependencyGraphTransformationContext context) - throws RepositoryException { - // Resolver 2 may collect again when a DependencyCollectionChecker asks; the last run is the result. - edges = null; - threw = true; - Map> collected = snapshot(root); - DependencyNode transformed = delegate.transformGraph(root, context); - Map conflictIds = (Map) context.get(CONTEXT_CONFLICT_IDS); - if (conflictIds == null) throw new RepositoryException("Maven's graph transformer assigned no conflict ids"); - edges = resolvedEdges(transformed, collected, conflictIds); - threw = false; - return transformed; - } - - private static Map> snapshot(DependencyNode root) { - Map> children = new IdentityHashMap<>(); - // The collector gives nodes of one artifact and context one shared child list. - Map, List> copies = new IdentityHashMap<>(); - Deque todo = new ArrayDeque<>(); - todo.push(root); - while (!todo.isEmpty()) { - DependencyNode n = todo.pop(); - if (children.containsKey(n)) continue; - List copy = copies.get(n.getChildren()); - if (copy == null) { - copy = new ArrayList<>(n.getChildren()); - copies.put(n.getChildren(), copy); - todo.addAll(copy); - } - children.put(n, copy); - } - return children; - } - - private static Map> resolvedEdges( - DependencyNode graph, Map> collected, Map conflictIds) - throws RepositoryException { - Set classpath = onClasspath(graph); - Map kept = new HashMap<>(); - for (DependencyNode n : classpath) { - if (n == graph) continue; - DependencyNode other = kept.put(conflictId(conflictIds, n), n); - if (other != null) throw new RepositoryException("Maven kept two nodes for one conflict: " + other + " and " + n); - } - Map> edges = new IdentityHashMap<>(); - for (DependencyNode parent : classpath) { - List children = collected.get(parent); - if (children == null) throw new RepositoryException(parent + " was kept but never collected"); - List resolved = new ArrayList<>(); - for (DependencyNode child : children) { - // None kept: the resolved graph has no such dependency, so neither has the edge. - DependencyNode winner = kept.get(conflictId(conflictIds, child)); - if (winner != null) resolved.add(winner); - } - edges.put(parent, resolved); - } - return edges; - } - - private static Object conflictId(Map conflictIds, DependencyNode n) throws RepositoryException { - Object id = conflictIds.get(n); - if (id == null) throw new RepositoryException("Maven's graph transformer assigned " + n + " no conflict id"); - return id; - } - } - - private static final class Node { - final String id; - final String groupId; - final String artifactId; - final String type; - final String classifier; - final String version; - // The reactor module's project key when this is a sibling module, else empty. - final String project; - final TreeSet children = new TreeSet<>(); - final TreeSet files = new TreeSet<>(); - boolean prod; - boolean onClasspath = true; - boolean unfetched; - - Node(String id, String groupId, String artifactId, String type, String classifier, String version, String project) { - this.id = id; - this.groupId = groupId; - this.artifactId = artifactId; - this.type = type; - this.classifier = classifier; - this.version = version; - this.project = project; - } - } -} diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java index 12d68a11cc..2710de9640 100644 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java +++ b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java @@ -8,8 +8,7 @@ /** * Shared helpers kept byte-compatible with the Gradle/SBT scripts and the TS parsers: the - * build-root-relative workspace path, the full-coordinate {@code id} key, and the config-glob - * translation. + * build-root-relative workspace path, path exclusion and record-field escaping. */ public final class SocketSupport { private SocketSupport() {} @@ -23,58 +22,6 @@ public static String relativePath(Path rootDir, Path file) { return rootDir.relativize(file).toString().replace(File.separatorChar, '/'); } - /** - * Full Maven coordinate {@code groupId:artifactId:type:classifier:version} with empty segments - * dropped — the per-root node key the assembler uses. {@code type} is the Maven packaging (the - * Gradle/SBT {@code ext}). - */ - public static String coordId(String groupId, String artifactId, String type, String classifier, String version) { - StringBuilder sb = new StringBuilder(); - for (String segment : new String[] {groupId, artifactId, type, classifier, version}) { - if (segment == null || segment.isEmpty()) continue; - if (sb.length() > 0) sb.append(':'); - sb.append(segment); - } - return sb.toString(); - } - - /** - * Translate a config-name glob to a case-sensitive regex. Supports {@code *}, {@code ?}, and - * {@code [...]} character classes: enumerations ({@code [cC]}), ranges ({@code [a-z]}), and - * {@code [!..]}/{@code [^..]} negation. A malformed glob falls back to a literal match, never throws. - */ - public static Pattern globToRegex(String glob) { - StringBuilder sb = new StringBuilder(); - int i = 0; - int n = glob.length(); - while (i < n) { - char c = glob.charAt(i); - if (c == '*') { sb.append(".*"); i++; } - else if (c == '?') { sb.append('.'); i++; } - else if (c == '[') { - int j = glob.indexOf(']', i + 1); - // Treat as a class only with a non-empty body; else a literal '['. - if (j <= i + 1) { sb.append("\\["); i++; } - else { - String body = glob.substring(i + 1, j); - boolean neg = body.startsWith("!"); - if (neg) body = body.substring(1); - // Only literal chars and '-' ranges are meaningful; neutralize regex-class tricks. - body = body.replace("\\", "\\\\").replace("[", "\\[").replace("&", "\\&"); - sb.append('[').append(neg ? "^" : "").append(body).append(']'); - i = j + 1; - } - } else if ("\\.^$|+(){}]".indexOf(c) >= 0) { - sb.append('\\').append(c); i++; - } else { sb.append(c); i++; } - } - try { - return Pattern.compile(sb.toString()); - } catch (java.util.regex.PatternSyntaxException e) { - return Pattern.compile(Pattern.quote(glob)); - } - } - /** * Compile a comma-separated list of PRE-COMPILED {@code --exclude-paths} regex pattern sources * into {@link Pattern}s, used only to skip whole excluded reactor modules. The CLI compiles the @@ -138,22 +85,6 @@ public static boolean isExcludedPath(String rel, List patterns) { return false; } - /** Parse a comma-separated list of globs into case-sensitive patterns. */ - public static List parsePatterns(String csv) { - List out = new ArrayList<>(); - if (csv == null || csv.trim().isEmpty()) return out; - for (String raw : csv.split(",")) { - String p = raw.trim(); - if (!p.isEmpty()) out.add(globToRegex(p)); - } - return out; - } - - /** Absolute path of a file if it exists, else null. */ - public static String existingAbsolutePath(File f) { - return f != null && f.exists() ? f.getAbsolutePath() : null; - } - /** Backslash-escape a record field so it can never break line/field framing (see records.ts). */ public static String escapeField(String v) { if (v == null) return ""; diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java index c6b34fcf9d..d1bdafb3c0 100644 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java +++ b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java @@ -12,10 +12,9 @@ import java.util.regex.Pattern; /** - * Sibling of {@link SocketFactsRecordsEngine} that emits only `meta`/`buildRoot`/`project`/ - * `projectBuild` records from the already-populated reactor list, building no dependency graph - - * cheap workspace discovery for `socket manifest setup --dynamic-sbom-inference` without a full - * facts-generation build. + * Emits only `meta`/`buildRoot`/`project`/`projectBuild` records from the already-populated reactor + * list, building no dependency graph - cheap workspace discovery for + * `socket manifest setup --dynamic-sbom-inference`. */ public final class SocketWorkspacesRecordsEngine { diff --git a/src/commands/manifest/scripts/resolution-report-gradle.mts b/src/commands/manifest/scripts/resolution-report-gradle.mts deleted file mode 100644 index b2ff74a4a9..0000000000 --- a/src/commands/manifest/scripts/resolution-report-gradle.mts +++ /dev/null @@ -1,123 +0,0 @@ -import type { - FailureCategory, - ResolutionDialect, -} from './resolution-report-render.mts' - -// Gradle's variant-aware resolver: distinct exceptions give mutually-exclusive -// phrasing, so most-specific-first substring checks classify reliably. -export function classifyGradleFailure(detail: string): FailureCategory { - const t = (detail || '').toLowerCase() - // Check before variant ambiguity. - if (t.includes('conflict on capability')) { - return 'capability-conflict' - } - // Zero compatible variants — the opposite of ambiguity below. Gradle phrases - // this several ways depending on version and whether attributes were supplied. - if ( - t.includes('no matching variant') || - t.includes('no variants of') || - t.includes('unable to find a matching variant') || - t.includes('no compatible variant') - ) { - return 'no-matching-variant' - } - // The artifact-level form: several transforms produce the requested variant - // ("transformation chains" from Gradle 8.12, "transforms" before it). - if ( - t.includes('cannot choose between') || - t.includes('found multiple transformation chains') || - t.includes('found multiple transforms that can produce a variant') - ) { - return 'variant-ambiguity' - } - // One line per problem of the artifact; a checksum missing from the - // metadata is no evidence against it, unlike any other problem. - const problems = t.split('\n').filter(l => l.startsWith('on artifact ')) - if ( - problems.length && - problems.every(l => - l.endsWith(': checksum is missing from verification metadata.'), - ) - ) { - return 'checksum-missing' - } - if ( - t.includes('could not get') || - t.includes('could not head') || - t.includes('status code 401') || - t.includes('status code 403') || - t.includes('connection refused') || - t.includes('connection timed out') || - t.includes('read timed out') || - t.includes('certification path') || - t.includes('peer not authenticated') - ) { - return 'repository-or-network' - } - if (t.includes('could not find')) { - return 'not-found' - } - return 'other' -} - -// Every kind blocks except variant-ambiguity: the module demonstrably exists -// and is almost always captured via another configuration, so it's benign for -// the SBOM (non-blocking, count only). The renderer blocks it anyway when the -// module resolved in no configuration of its project. Nor does checksum-missing: -// teams often record checksums only for what their own tasks resolve. -export const GRADLE_DIALECT: ResolutionDialect = { - label: 'Gradle', - classify: classifyGradleFailure, - categories: [ - { - key: 'not-found', - header: () => ` Not found in any repository:`, - blocking: true, - }, - { - key: 'no-matching-variant', - header: n => - ` No compatible variant — ${n} found the module but no variant matched the requested attributes:`, - blocking: true, - }, - { - key: 'capability-conflict', - header: n => - ` Capability conflict — ${n} found two modules providing the same capability and cannot use both (add a capability-resolution or module-replacement rule):`, - showReason: true, - blocking: true, - }, - { - key: 'repository-or-network', - header: n => - ` Repository or network error — ${n} could not reach or authenticate to a repository:`, - blocking: true, - }, - { - key: 'config-problem', - header: n => ` Resolver/configuration problem (reason from ${n}):`, - showReason: true, - blocking: true, - }, - { - key: 'other', - header: n => ` Other resolution failures (reason from ${n}):`, - showReason: true, - blocking: true, - }, - { - key: 'variant-ambiguity', - header: n => - ` Ambiguous variant — ${n} could not choose a variant, and the module resolved in no other configuration:`, - blocking: false, - notice: (n, depCount, configCount) => - `Skipped ${depCount} dependency(ies) with ambiguous variant selection in ${configCount} configuration(s) — re-run with --verbose for ${n}'s messages.`, - }, - { - key: 'checksum-missing', - blocking: false, - notice: (n, depCount, configCount) => - `Left ${depCount} dependency(ies) uninstalled in ${configCount} configuration(s): ${n}'s verification metadata has no checksum for their artifacts — re-run with --verbose for ${n}'s messages.`, - }, - ], -} diff --git a/src/commands/manifest/scripts/resolution-report-ivy.mts b/src/commands/manifest/scripts/resolution-report-ivy.mts deleted file mode 100644 index f93f5e1e36..0000000000 --- a/src/commands/manifest/scripts/resolution-report-ivy.mts +++ /dev/null @@ -1,61 +0,0 @@ -import type { - FailureCategory, - ResolutionDialect, -} from './resolution-report-render.mts' - -// Ivy/sbt resolver: no attribute-based variants, so no variant categories -// (Gradle-only). Ivy degrades transport failures to "not found". -export function classifyIvyFailure(detail: string): FailureCategory { - const t = (detail || '').toLowerCase() - if ( - t.includes('server access error') || - t.includes('download failed') || - t.includes('connection timed out') || - t.includes('unauthorized') || - t.includes('forbidden') - ) { - return 'repository-or-network' - } - if ( - t.includes('no resolver found') || - t.includes('configuration not found') || - t.includes('configuration not public') - ) { - return 'config-problem' - } - if (t.includes('not found') || t.includes('unresolved dependency')) { - return 'not-found' - } - return 'other' -} - -// Every kind blocks; no non-blocking kind because Ivy has no variant ambiguity. -export const SBT_DIALECT: ResolutionDialect = { - label: 'sbt', - classify: classifyIvyFailure, - categories: [ - { - key: 'not-found', - header: () => ` Not found in any repository:`, - blocking: true, - }, - { - key: 'repository-or-network', - header: n => - ` Repository or network error — ${n} could not reach or authenticate to a repository:`, - blocking: true, - }, - { - key: 'config-problem', - header: n => ` Resolver/configuration problem (reason from ${n}):`, - showReason: true, - blocking: true, - }, - { - key: 'other', - header: n => ` Other resolution failures (reason from ${n}):`, - showReason: true, - blocking: true, - }, - ], -} diff --git a/src/commands/manifest/scripts/resolution-report-maven.mts b/src/commands/manifest/scripts/resolution-report-maven.mts deleted file mode 100644 index 25f3800f57..0000000000 --- a/src/commands/manifest/scripts/resolution-report-maven.mts +++ /dev/null @@ -1,85 +0,0 @@ -import type { - FailureCategory, - ResolutionDialect, -} from './resolution-report-render.mts' - -// Maven's resolver (Aether/maven-resolver): no attribute-based variants. Both -// failure shapes (artifact-resolution miss, dependency-graph build failure) -// classify off the root-cause message. -export function classifyMavenFailure(detail: string): FailureCategory { - const t = (detail || '').toLowerCase() - if ( - t.includes('could not transfer') || - t.includes('connection refused') || - t.includes('connect timed out') || - t.includes('connection timed out') || - t.includes('read timed out') || - t.includes('status code: 401') || - t.includes('status code: 403') || - t.includes('unauthorized') || - t.includes('forbidden') || - t.includes('peer not authenticated') || - t.includes('certpathbuilderexception') || - // Maven 3.8.1+ blocks plain-HTTP repositories behind its - // maven-default-http-blocker mirror. - t.includes('blocked mirror for repositories') || - // Offline (-o): no repository was asked, so the artifact may well exist. - t.includes('in offline mode') - ) { - return 'repository-or-network' - } - if ( - t.includes('could not find artifact') || - t.includes('failure to find') || - t.includes('could not resolve') || - t.includes('no versions available') || - t.includes('not found') || - // maven-resolver's remote repository filters (prefixes, groupId): the - // repository is known not to serve that path or group. - t.includes('not allowed from') - ) { - return 'not-found' - } - // POM exists but can't be read/parsed. - if ( - t.includes('failed to read artifact descriptor') || - t.includes('invalid pom') || - t.includes('could not parse pom') || - // Maven's warning for a POM its descriptor policy tolerated as invalid. - t.includes('is invalid, transitive dependencies') - ) { - return 'config-problem' - } - return 'other' -} - -// Every kind blocks; no non-blocking kind because Maven has no variant ambiguity. -export const MAVEN_DIALECT: ResolutionDialect = { - label: 'Maven', - classify: classifyMavenFailure, - categories: [ - { - key: 'not-found', - header: () => ` Not found in any repository:`, - blocking: true, - }, - { - key: 'repository-or-network', - header: n => - ` Repository or network error — ${n} could not reach or authenticate to a repository:`, - blocking: true, - }, - { - key: 'config-problem', - header: n => ` POM/descriptor problem (reason from ${n}):`, - showReason: true, - blocking: true, - }, - { - key: 'other', - header: n => ` Other resolution failures (reason from ${n}):`, - showReason: true, - blocking: true, - }, - ], -} diff --git a/src/commands/manifest/scripts/resolution-report-nuget.mts b/src/commands/manifest/scripts/resolution-report-nuget.mts deleted file mode 100644 index fb924414e3..0000000000 --- a/src/commands/manifest/scripts/resolution-report-nuget.mts +++ /dev/null @@ -1,63 +0,0 @@ -import type { - FailureCategory, - ResolutionDialect, -} from './resolution-report-render.mts' - -// NuGet's restore error codes, per -// https://learn.microsoft.com/en-us/nuget/reference/errors-and-warnings. -const NOT_FOUND_CODES = new Set(['NU1100', 'NU1101', 'NU1102', 'NU1103']) -// Loading a source's service index or package metadata failed; insecure -// (HTTP) sources. -const SOURCE_CODES = new Set(['NU1301', 'NU1302']) - -// The socket-facts-dotnet tool reports restore errors as `: `, -// and evaluation errors as `: : `; its findings -// without a code count as other failures. -export function classifyNugetFailure(detail: string): FailureCategory { - const code = /(?:^|: )(NU\d{4}|NETSDK\d{4}|MSB\d{4}):/.exec(detail || '')?.[1] - if (!code) { - return 'other' - } - if (NOT_FOUND_CODES.has(code)) { - return 'not-found' - } - if (SOURCE_CODES.has(code)) { - return 'repository-or-network' - } - // Any other NuGet, .NET SDK or MSBuild error is about the project, the - // lock file, central package management or framework compatibility. - return 'config-problem' -} - -export const NUGET_DIALECT: ResolutionDialect = { - label: 'NuGet', - classify: classifyNugetFailure, - categories: [ - { - key: 'not-found', - header: () => ' Not found in any package source:', - showReason: true, - blocking: true, - }, - { - key: 'repository-or-network', - header: n => - ` Package source or network error — ${n} could not reach or authenticate to a source:`, - showReason: true, - blocking: true, - }, - { - key: 'config-problem', - header: n => - ` Project or restore configuration problem (reason from ${n}):`, - showReason: true, - blocking: true, - }, - { - key: 'other', - header: n => ` Other resolution failures (reason from ${n}):`, - showReason: true, - blocking: true, - }, - ], -} diff --git a/src/commands/manifest/scripts/resolution-report-nuget.test.mts b/src/commands/manifest/scripts/resolution-report-nuget.test.mts deleted file mode 100644 index 52dc892517..0000000000 --- a/src/commands/manifest/scripts/resolution-report-nuget.test.mts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { classifyNugetFailure } from './resolution-report-nuget.mts' - -import type { FailureCategory } from './resolution-report-render.mts' - -const DETAILS_BY_CATEGORY = { - 'config-problem': [ - 'NU1004: The package references have changed for net8.0. Lock file is not consistent.', - 'NU1109: Detected package downgrade: Polly from 8.4.2 to centrally defined 7.2.4.', - 'NU1201: Project Fs is not compatible with netstandard2.0.', - 'NETSDK1147: To build this project, the following workloads must be installed: maui', - "MSB4236: The SDK 'Microsoft.Build.Traversal/2.0.24' specified could not be found.", - 'could not read the solution: MSB5009: Error parsing the nested project section in solution file.', - 'could not evaluate the project: MSB4019: The imported project "/repo/x.props" was not found. /repo/App.csproj', - ], - 'not-found': [ - 'NU1101: Unable to find package Foo. No packages exist with this id in source(s): nuget.org', - 'NU1102: Unable to find package Foo with version (>= 9.0.0)', - ], - other: [ - 'obj/project.assets.json belongs to B.csproj: the projects share an intermediate output directory, so restore output cannot be attributed', - 'runtime assemblies restore listed are missing from the package folders (lib/net8.0/Foo.dll); re-run `dotnet restore`', - ], - 'repository-or-network': [ - 'NU1301: Unable to load the service index for source https://feed/index.json.', - 'NU1301: Unable to load the service index for source https://feed/index.json. Response status code does not indicate success: 401 (Unauthorized).', - ], -} satisfies Partial> - -describe('classifyNugetFailure', () => { - it.for( - Object.entries(DETAILS_BY_CATEGORY).flatMap(({ 0: category, 1: details }) => - details.map(detail => [category, detail] as const), - ), - )('%s: %s', ({ 0: category, 1: detail }) => { - expect(classifyNugetFailure(detail)).toBe(category) - }) -}) diff --git a/src/commands/manifest/scripts/resolution-report-render.mts b/src/commands/manifest/scripts/resolution-report-render.mts deleted file mode 100644 index 8adc6e2e9b..0000000000 --- a/src/commands/manifest/scripts/resolution-report-render.mts +++ /dev/null @@ -1,507 +0,0 @@ -import { GRADLE_DIALECT } from './resolution-report-gradle.mts' -import { SBT_DIALECT } from './resolution-report-ivy.mts' -import { MAVEN_DIALECT } from './resolution-report-maven.mts' -import { NUGET_DIALECT } from './resolution-report-nuget.mts' -import { moduleKey } from './resolution-report.mts' -import constants from '../../../constants.mts' -import { camelToKebab } from '../../../utils/strings.mts' - -import type { BuildTool } from './build-tool.mts' -import type { ResolutionFailure, Unscannable } from './resolution-report.mts' - -// Recognized from the build tool's message; drives wording AND whether the kind -// is blocking. An unrecognized message degrades to 'other' (blocking) — safe. -export type FailureCategory = - | 'not-found' - | 'no-matching-variant' - | 'capability-conflict' - | 'variant-ambiguity' - | 'checksum-missing' - | 'repository-or-network' - | 'config-problem' - | 'other' - -export type FailureCategorySpec = { - key: FailureCategory - // Whether failures of this kind fail the run (fail-closed unless - // --ignore-unresolved). A non-blocking kind never affects the exit code and - // is surfaced only as a one-line `notice`. - blocking: boolean - header?: ((toolLabel: string) => string) | undefined - showReason?: boolean | undefined - notice?: - | ((toolLabel: string, depCount: number, configCount: number) => string) - | undefined -} - -// Per-resolver classify + render/score policy. -export type ResolutionDialect = { - label: string - classify: (detail: string) => FailureCategory - categories: FailureCategorySpec[] -} - -export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' - -// Where the invoking command lets the user set each build option, so a remedy -// names something they can actually set. -export type BuildOptionHints = { - // Reachability scans only: reachability cannot install a dependency that - // `ignoreUnresolved` lets through, so it must be told to continue too. - continueOnInstallErrorsFlag?: string | undefined - // Taken as flags; every other option is set in `socketJson`. - flags: ReadonlySet - // Wizard that writes `socketJson`. - setupCommand: string - socketJson: string -} - -export const DSI_SETUP_COMMAND = - 'socket manifest setup --dynamic-sbom-inference' - -export const REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG = - '--reach-continue-on-install-errors' - -// The single-build manifest commands take every option as a flag. -export const FLAG_HINTS: BuildOptionHints = { - flags: new Set([ - 'excludeConfigs', - 'ignoreUnresolved', - 'verbose', - ]), - setupCommand: 'socket manifest setup', - socketJson: constants.SOCKET_JSON, -} - -export type RenderedResolutionReport = { - // Failure report for blocking kinds; empty when nothing blocks. - summary: string - // Build tool's own full messages for all kinds; surfaced at --verbose. - details: string - // Caller fails the run iff this is true and not --ignore-unresolved. - hasBlockingFailures: boolean - // One-liner(s) for non-blocking kinds; empty when none. - nonBlockingNotice: string -} - -const RESOLUTION_REPORT_ARTIFACT_LIMIT = 15 -const RESOLUTION_REPORT_CONFIG_LIMIT = 20 - -// Drop a bare "group:name" when a versioned "group:name:v" of the same module -// failed for the same projects, or when both failures have no project. The -// lenient resolver reports both forms for a single failure. -function dedupInfos }>( - infos: T[], -): T[] { - const versioned = new Set() - for (const i of infos) { - const p = i.coord.split(':') - if (p.length >= 3) { - for (const project of i.projects) { - versioned.add(moduleKey(project, i.coord)) - } - } - } - return infos - .filter( - i => - i.coord.split(':').length >= 3 || - ![...i.projects].every(p => versioned.has(moduleKey(p, i.coord))), - ) - .sort((a, b) => (a.coord < b.coord ? -1 : a.coord > b.coord ? 1 : 0)) -} - -function firstLine(s: string): string { - return ( - (s || '') - .split('\n') - .map(l => l.trim()) - .find(Boolean) ?? '' - ) -} - -function fmtList(list: string[], limit: number): string { - const shown = list.slice(0, limit).join(', ') - return list.length > limit ? `${shown} (+${list.length - limit} more)` : shown -} - -function flagText(option: BuildOption, value: string | true): string { - const flag = `--${camelToKebab(option)}` - return value === true ? flag : `${flag} '${value}'` -} - -// Where a failure happened, for builds with several subprojects. -function inProjects(projects: string | Iterable): string { - const list = [...(typeof projects === 'string' ? [projects] : projects)] - .filter(Boolean) - .sort() - .map(p => `\`${p}\``) - return list.length ? ` (in ${fmtList(list, 3)})` : '' -} - -function installErrorsHint( - hints: BuildOptionHints, - ignored: boolean, -): string[] { - const flag = hints.continueOnInstallErrorsFlag - if (!flag) { - return [] - } - return [ - ignored - ? `Reachability analysis cannot install the ignored dependencies; pass ${flag} unless you already do.` - : `If you ignore unresolved dependencies, also pass ${flag}: reachability analysis cannot install them.`, - ] -} - -// `excludableConfigs` is empty when excluding configurations cannot clear -// every blocking failure. -function proceedHint( - hints: BuildOptionHints, - tool: BuildTool, - excludableConfigs: string[], -): string[] { - const options: Array<[BuildOption, string | true]> = [ - ['ignoreUnresolved', true], - ] - if (excludableConfigs.length) { - options.push(['excludeConfigs', excludableConfigs.join(',')]) - } - const asFlags = options.filter(o => hints.flags.has(o[0])) - const inSocketJson = options.filter(o => !hints.flags.has(o[0])) - const setup = `\`${hints.setupCommand}\`` - if (!inSocketJson.length) { - return asFlags.length === 1 - ? [`To proceed, re-run with ${flagText(...asFlags[0]!)}.`] - : [ - 'To proceed, re-run with either:', - ...asFlags.map(o => ` ${flagText(...o)}`), - ] - } - if (!asFlags.length) { - return [ - `To proceed, set ${options.length > 1 ? 'either of these' : 'this'} under defaults.manifest.${tool} in ${hints.socketJson} (${setup} walks you through it):`, - ...options.map( - ([option, value]) => ` "${option}": ${JSON.stringify(value)}`, - ), - ] - } - return [ - 'To proceed, either:', - ...asFlags.map(o => ` re-run with ${flagText(...o)}`), - ...inSocketJson.map( - ([option, value]) => - ` set defaults.manifest.${tool}.${option} to ${JSON.stringify(value)} in ${hints.socketJson} (${setup})`, - ), - ] -} - -// What resolved elsewhere is consulted only by module (group:name): a failed -// selector carries no classifier/type to relate it to one artifact. -export function renderResolutionReport( - failures: ResolutionFailure[], - scannedConfigs: string[], - tool: BuildTool, - opts: { - hints?: BuildOptionHints | undefined - ignoreUnresolved?: boolean | undefined - resolvedModules?: ReadonlySet | undefined - unscannable?: Unscannable[] | undefined - } = {}, -): RenderedResolutionReport { - const dialect = dialectFor(tool) - const name = dialect.label - const hints = opts.hints ?? FLAG_HINTS - const unscannable = opts.unscannable ?? [] - const unscannableConfigs = new Set( - unscannable.filter(u => u.config).map(u => u.config), - ) - const specOf = new Map(dialect.categories.map(c => [c.key, c])) - const isBlocking = (cat: FailureCategory): boolean => - specOf.get(cat)?.blocking ?? true - - // A non-blocking kind is only benign when its module resolved anyway: one - // that resolved in no configuration of its project is missing from that - // project's SBOM. - const resolved = opts.resolvedModules - const isFailureBlocking = ( - category: FailureCategory, - f: ResolutionFailure, - ): boolean => - isBlocking(category) || - (!!resolved && !resolved.has(moduleKey(f.project, f.coord))) - - // Aggregate by (coord, category, blocking): one module can fail with - // different causes across configs, and block in only some projects. Keep - // first-seen detail, union the configs and projects. - type CoordInfo = { - coord: string - category: FailureCategory - blocking: boolean - detail: string - configs: Set - // '' for a failure that belongs to no project. - projects: Set - // Some failure of this coord belongs to no configuration. - configless: boolean - } - const byKey = new Map() - for (const f of failures) { - const category = dialect.classify(f.detail) - const blocking = isFailureBlocking(category, f) - const key = `${f.coord} ${category} ${blocking}` - let info = byKey.get(key) - if (!info) { - info = { - coord: f.coord, - category, - blocking, - detail: f.detail, - configs: new Set(), - projects: new Set(), - configless: false, - } - byKey.set(key, info) - } - if (f.config) { - info.configs.add(f.config) - } else { - info.configless = true - } - info.projects.add(f.project) - } - const allInfos = [...byKey.values()] - const isInfoBlocking = (info: CoordInfo): boolean => info.blocking - - // A whole-config throw is classified by the same cause rules as a per-dep - // failure: ambiguity stays lenient, every other cause is fail-closed. - const unscannableInfos = unscannable.map(u => { - const category = dialect.classify(u.detail) - return { ...u, category, blocking: isBlocking(category) } - }) - const blockingUnscannable = unscannableInfos.filter(u => u.blocking) - const nonBlockingUnscannable = unscannableInfos.filter(u => !u.blocking) - const blockingUnscannableConfigs = blockingUnscannable.filter(u => u.config) - const blockingUnscannableProjects = blockingUnscannable.filter(u => !u.config) - - const perDepBlockingConfigs = new Set() - for (const info of allInfos) { - if (isInfoBlocking(info)) { - for (const c of info.configs) { - perDepBlockingConfigs.add(c) - } - } - } - const blockingConfigs = new Set([ - ...perDepBlockingConfigs, - ...blockingUnscannableConfigs.map(u => u.config), - ]) - const blockingFailed = [...blockingConfigs].sort() - // A blocking failure outside any configuration leaves every configuration of - // its project incomplete, so none can be reported as succeeded. - const hasBlockingConfiglessFailure = - blockingUnscannableProjects.length > 0 || - allInfos.some(i => i.configless && isInfoBlocking(i)) - // An un-scannable config was attempted but resolved nothing, so it didn't succeed. - const succeeded = hasBlockingConfiglessFailure - ? [] - : scannedConfigs - .filter(c => !blockingConfigs.has(c) && !unscannableConfigs.has(c)) - .sort() - - const groups = dialect.categories.map(spec => ({ - spec, - infos: dedupInfos(allInfos.filter(i => i.category === spec.key)), - })) - const blockingGroups = groups - .map(g => ({ ...g, infos: g.infos.filter(isInfoBlocking) })) - .filter(g => g.infos.length) - const nonBlockingGroups = groups - .map(g => ({ ...g, infos: g.infos.filter(i => !isInfoBlocking(i)) })) - .filter(g => g.infos.length) - const blockingCount = blockingGroups.reduce((n, g) => n + g.infos.length, 0) - const hasBlockingFailures = - blockingCount > 0 || blockingUnscannable.length > 0 - const willFail = hasBlockingFailures && !opts.ignoreUnresolved - - const out: string[] = [] - if (hasBlockingFailures) { - if (blockingCount > 0) { - const inConfigs = perDepBlockingConfigs.size - ? ` in ${perDepBlockingConfigs.size} configuration(s)` - : '' - out.push( - opts.ignoreUnresolved - ? `Ignored ${blockingCount} unresolved dependency(ies)${inConfigs}:` - : `Could not resolve ${blockingCount} dependency(ies)${inConfigs}:`, - ) - for (const { infos, spec } of blockingGroups) { - out.push('') - out.push(spec.header ? spec.header(name) : '') - for (const info of infos.slice(0, RESOLUTION_REPORT_ARTIFACT_LIMIT)) { - const fl = firstLine(info.detail) - const reasonSuffix = spec.showReason && fl ? ` [${fl}]` : '' - out.push( - ` - ${info.coord}${inProjects(info.projects)}${reasonSuffix}`, - ) - } - if (infos.length > RESOLUTION_REPORT_ARTIFACT_LIMIT) { - out.push( - ` … and ${infos.length - RESOLUTION_REPORT_ARTIFACT_LIMIT} more`, - ) - } - } - } - const pushUnscannable = ( - items: typeof blockingUnscannable, - header: string, - label: (u: (typeof blockingUnscannable)[number]) => string, - ): void => { - if (!items.length) { - return - } - // Separate from the block above, but only if there is one — otherwise the - // summary would lead with a blank line (a dangling ✗ under logger.fail). - if (out.length) { - out.push('') - } - out.push(header) - for (const u of items.slice(0, RESOLUTION_REPORT_CONFIG_LIMIT)) { - const fl = firstLine(u.detail) - out.push(` - ${label(u)}${fl ? ` [${fl}]` : ''}`) - } - if (items.length > RESOLUTION_REPORT_CONFIG_LIMIT) { - out.push( - ` … and ${items.length - RESOLUTION_REPORT_CONFIG_LIMIT} more`, - ) - } - } - pushUnscannable( - blockingUnscannableConfigs, - opts.ignoreUnresolved - ? `Ignored ${blockingUnscannableConfigs.length} configuration(s) that could not be scanned:` - : `Could not scan ${blockingUnscannableConfigs.length} configuration(s) (reason from ${name}):`, - u => `${u.config}${inProjects(u.project)}`, - ) - pushUnscannable( - blockingUnscannableProjects, - opts.ignoreUnresolved - ? `Ignored ${blockingUnscannableProjects.length} project(s) whose dependencies could not be resolved:` - : `Could not resolve the dependencies of ${blockingUnscannableProjects.length} project(s) (reason from ${name}):`, - u => `\`${u.project}\``, - ) - if (succeeded.length || blockingFailed.length) { - out.push('') - } - if (succeeded.length) { - out.push( - `Resolution succeeded in: ${fmtList(succeeded, RESOLUTION_REPORT_CONFIG_LIMIT)}`, - ) - } - if (blockingFailed.length) { - out.push( - `Resolution failed in: ${fmtList(blockingFailed, RESOLUTION_REPORT_CONFIG_LIMIT)}`, - ) - } - if (willFail) { - out.push('') - out.push( - ...proceedHint( - hints, - tool, - hasBlockingConfiglessFailure ? [] : blockingFailed, - ), - ...installErrorsHint(hints, false), - ) - } else if (hints.continueOnInstallErrorsFlag) { - out.push('', ...installErrorsHint(hints, true)) - } - out.push('') - out.push( - hints.flags.has('verbose') - ? `Re-run with --verbose for ${name}'s full messages.` - : `For ${name}'s full messages, ${verboseHint(hints, tool)}.`, - ) - } - - const notices: string[] = [] - for (const { infos, spec } of nonBlockingGroups) { - if (!spec.notice) { - continue - } - const configCount = new Set(infos.flatMap(i => [...i.configs])).size - notices.push(spec.notice(name, infos.length, configCount)) - } - // A config-level throw whose cause classifies as variant ambiguity is surfaced, not failed: many - // configurations are marked resolvable yet too underspecified to resolve. - if (nonBlockingUnscannable.length) { - const n = new Set(nonBlockingUnscannable.map(u => u.config)).size - notices.push( - hints.flags.has('verbose') - ? `Could not scan ${n} configuration(s) — re-run with --verbose for ${name}'s messages.` - : `Could not scan ${n} configuration(s); for ${name}'s messages, ${verboseHint(hints, tool)}.`, - ) - } - - const detailLines = [`${name}'s full message for each unresolved dependency:`] - for (const info of allInfos) { - detailLines.push('') - detailLines.push(` ${info.coord}:`) - for (const line of (info.detail || '(no message)').split('\n')) { - detailLines.push(` ${line}`) - } - } - if (unscannable.length) { - detailLines.push('') - detailLines.push(`${name} resolutions that could not be scanned:`) - for (const u of unscannable) { - detailLines.push('') - detailLines.push( - ` ${u.config || 'all dependencies'}${inProjects(u.project)}:`, - ) - for (const line of (u.detail || '(no message)').split('\n')) { - detailLines.push(` ${line}`) - } - } - } - - return { - summary: out.join('\n'), - details: detailLines.join('\n'), - hasBlockingFailures, - nonBlockingNotice: notices.join('\n'), - } -} - -function dialectFor(tool: BuildTool): ResolutionDialect { - switch (tool) { - case 'dotnet': - return NUGET_DIALECT - case 'gradle': - return GRADLE_DIALECT - case 'sbt': - return SBT_DIALECT - case 'maven': - return MAVEN_DIALECT - } -} - -export function renderResolutionErrorReport( - failures: ResolutionFailure[], - scannedConfigs: string[] = [], - tool: BuildTool = 'gradle', - opts: { - hints?: BuildOptionHints | undefined - ignoreUnresolved?: boolean | undefined - resolvedModules?: ReadonlySet | undefined - unscannable?: Unscannable[] | undefined - } = {}, -): RenderedResolutionReport { - return renderResolutionReport(failures, scannedConfigs, tool, opts) -} - -export function verboseHint(hints: BuildOptionHints, tool: BuildTool): string { - return hints.flags.has('verbose') - ? 'pass --verbose' - : `set defaults.manifest.${tool}.verbose to true in ${hints.socketJson}` -} diff --git a/src/commands/manifest/scripts/resolution-report-render.test.mts b/src/commands/manifest/scripts/resolution-report-render.test.mts deleted file mode 100644 index 76293bca50..0000000000 --- a/src/commands/manifest/scripts/resolution-report-render.test.mts +++ /dev/null @@ -1,605 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - DSI_SETUP_COMMAND, - REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, - renderResolutionErrorReport, -} from './resolution-report-render.mts' -import { moduleKey } from './resolution-report.mts' - -import type { BuildOptionHints } from './resolution-report-render.mts' -import type { ResolutionFailure } from './resolution-report.mts' - -const f = ( - coord: string, - detail: string, - config = 'runtimeClasspath', - project = ':', -): ResolutionFailure => ({ - coord, - detail, - config, - project, -}) - -describe('resolution failure classification', () => { - it('classifies a Gradle registry miss as blocking not-found', () => { - const r = renderResolutionErrorReport( - [f('com.example:missing:1.0', 'Could not find com.example:missing:1.0.')], - ['runtimeClasspath'], - 'gradle', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Not found in any repository') - expect(r.nonBlockingNotice).toBe('') - }) - - it('treats Gradle variant ambiguity as non-blocking (notice only, no summary)', () => { - const r = renderResolutionErrorReport( - [ - f( - 'com.example:amb:1.0', - 'Cannot choose between the following variants of com.example:amb:1.0', - ), - ], - ['runtimeClasspath'], - 'gradle', - ) - expect(r.hasBlockingFailures).toBe(false) - expect(r.summary).toBe('') - expect(r.nonBlockingNotice).toContain('ambiguous variant') - }) - - it.each([ - 'Found multiple transformation chains that produce a variant of com.example:amb:1.0', - 'Found multiple transforms that can produce a variant of com.example:amb:1.0', - ])( - 'classifies an ambiguous Gradle artifact transform as variant ambiguity: %s', - detail => { - const r = renderResolutionErrorReport( - [f('com.example:amb:1.0', detail)], - ['runtimeClasspath'], - 'gradle', - ) - expect(r.hasBlockingFailures).toBe(false) - expect(r.nonBlockingNotice).toContain('ambiguous variant') - }, - ) - - it('treats a checksum missing from Gradle verification metadata as non-blocking, unlike a mismatch', () => { - const header = - "Dependency verification failed for configuration ':runtimeClasspath':" - const missing = renderResolutionErrorReport( - [ - f( - 'com.example:lib:1.0', - `${header}\nOn artifact lib-1.0.jar (com.example:lib:1.0) in repository 'maven': checksum is missing from verification metadata.`, - ), - ], - ['runtimeClasspath'], - 'gradle', - { resolvedModules: new Set([moduleKey(':', 'com.example:lib')]) }, - ) - expect(missing.hasBlockingFailures).toBe(false) - expect(missing.nonBlockingNotice).toContain('no checksum') - const mismatch = renderResolutionErrorReport( - [ - f( - 'com.example:lib:1.0', - `${header}\nOn artifact lib-1.0.jar (com.example:lib:1.0) in repository 'maven': expected a 'sha256' checksum of '00' but was '11'`, - ), - ], - ['runtimeClasspath'], - 'gradle', - ) - expect(mismatch.hasBlockingFailures).toBe(true) - const both = renderResolutionErrorReport( - [ - f( - 'com.example:lib:1.0', - `${header}\nOn artifact lib-1.0.jar (com.example:lib:1.0) in repository 'a': checksum is missing from verification metadata.\nOn artifact lib-1.0.jar (com.example:lib:1.0) in repository 'b': expected a 'sha256' checksum of '00' but was '11'`, - ), - ], - ['runtimeClasspath'], - 'gradle', - { resolvedModules: new Set([moduleKey(':', 'com.example:lib')]) }, - ) - expect(both.hasBlockingFailures).toBe(true) - }) - - it("classifies Gradle's 'unable to find a matching variant' phrasing as blocking no-matching-variant", () => { - const r = renderResolutionErrorReport( - [ - f( - 'com.example:lib:1.0', - "Unable to find a matching variant of com.example:lib:1.0:\n - Variant 'apiElements'", - ), - ], - ['runtimeClasspath'], - 'gradle', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('No compatible variant') - expect(r.nonBlockingNotice).toBe('') - }) - - it('classifies a Gradle capability conflict as blocking', () => { - const r = renderResolutionErrorReport( - [ - f( - 'com.google.collections:google-collections:1.0', - 'Conflict on capability com.google.collections:google-collections', - ), - ], - ['runtimeClasspath'], - 'gradle', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Capability conflict') - }) - - it('surfaces both a blocking failure and a non-blocking notice together', () => { - const r = renderResolutionErrorReport( - [ - f('com.example:missing:1.0', 'Could not find com.example:missing:1.0.'), - f( - 'com.example:amb:1.0', - 'Cannot choose between the following variants', - 'testRuntime', - ), - ], - ['runtimeClasspath', 'testRuntime'], - 'gradle', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Not found in any repository') - expect(r.nonBlockingNotice).toContain('ambiguous variant') - }) - - it('classifies an sbt/Ivy unresolved dependency as blocking not-found', () => { - const r = renderResolutionErrorReport( - [ - f( - 'com.example:missing:1.0', - 'unresolved dependency: com.example#missing;1.0: not found', - ), - ], - ['compile'], - 'sbt', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Not found in any repository') - // Ivy has no variant categories. - expect(r.nonBlockingNotice).toBe('') - }) - - it('classifies a Maven artifact miss as blocking not-found', () => { - const r = renderResolutionErrorReport( - [ - f( - 'com.example:missing:jar:1.0', - 'Could not find artifact com.example:missing:jar:1.0', - 'compile', - ), - ], - ['compile'], - 'maven', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Not found in any repository') - }) - - it('reports blocking failures as ignored (not fatal) under ignoreUnresolved', () => { - const r = renderResolutionErrorReport( - [f('com.example:missing:1.0', 'Could not find com.example:missing:1.0.')], - ['runtimeClasspath'], - 'gradle', - { ignoreUnresolved: true }, - ) - // hasBlockingFailures still reflects the classification; the caller decides. - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Ignored') - expect(r.summary).not.toContain('To proceed, re-run') - }) - - it('returns an empty report when there are no failures', () => { - const r = renderResolutionErrorReport([], ['runtimeClasspath'], 'gradle') - expect(r.hasBlockingFailures).toBe(false) - expect(r.summary).toBe('') - expect(r.nonBlockingNotice).toBe('') - }) - - it('treats an ambiguity-driven config throw as a non-blocking notice', () => { - const r = renderResolutionErrorReport( - [], - ['debugAndroidTestCompileClasspath'], - 'gradle', - { - unscannable: [ - { - config: 'debugAndroidTestCompileClasspath', - detail: - 'Cannot choose between the following variants of com.example:foo:1.0', - project: ':', - }, - ], - }, - ) - expect(r.hasBlockingFailures).toBe(false) - expect(r.summary).toBe('') - expect(r.nonBlockingNotice).toContain('Could not scan 1 configuration(s)') - expect(r.details).toContain('debugAndroidTestCompileClasspath') - }) - - it('treats a non-ambiguity config throw as a blocking failure', () => { - const r = renderResolutionErrorReport([], ['runtimeClasspath'], 'gradle', { - unscannable: [ - { - config: 'runtimeClasspath', - detail: - 'Could not GET https://repo.example/foo. Received status code 401', - project: ':', - }, - ], - }) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Could not scan 1 configuration(s)') - expect(r.summary).toContain('runtimeClasspath') - expect(r.nonBlockingNotice).toBe('') - // With no per-dep failures the summary must not lead with a blank line - // (which would render as a dangling ✗ under logger.fail). - expect(r.summary.startsWith('\n')).toBe(false) - }) -}) - -describe('resolution failure remedies', () => { - const dsiCommand: BuildOptionHints = { - flags: new Set(['ignoreUnresolved', 'verbose']), - setupCommand: DSI_SETUP_COMMAND, - socketJson: 'socket.json', - } - const socketJsonOnly: BuildOptionHints = { - flags: new Set(), - setupCommand: DSI_SETUP_COMMAND, - socketJson: 'socket.json', - } - const mavenMiss = f( - 'com.example:missing:jar:1.0', - 'Could not find artifact com.example:missing:jar:1.0', - 'compile', - ) - // A dependency that failed while collecting the graph and is absent from - // it, so no scope holds it. - const mavenGraphFailure = f( - 'com.example:lib:1.0', - 'Could not transfer artifact com.example:lib-parent:pom:1.0 from/to internal: status code: 401', - '', - 'com.example:app:1.0', - ) - - it('suggests the flags for a single-build manifest command', () => { - const r = renderResolutionErrorReport([mavenMiss], ['compile'], 'maven') - expect(r.summary).toContain('To proceed, re-run with either:') - expect(r.summary).toContain(' --ignore-unresolved') - expect(r.summary).toContain(" --exclude-configs 'compile'") - expect(r.summary).toContain( - "Re-run with --verbose for Maven's full messages.", - ) - }) - - it('reports a failure outside any configuration by its artifact and project', () => { - const r = renderResolutionErrorReport( - [mavenGraphFailure], - ['compile', 'test'], - 'maven', - ) - expect(r.summary).toContain('Could not resolve 1 dependency(ies):') - expect(r.summary).toContain( - ' - com.example:lib:1.0 (in `com.example:app:1.0`)', - ) - // Its project's graph is incomplete, so no scope resolved fully. - expect(r.summary).not.toContain('Resolution succeeded in') - expect(r.summary).not.toContain('Resolution failed in') - expect(r.summary).toContain('To proceed, re-run with --ignore-unresolved.') - expect(r.summary).not.toContain('--exclude-configs') - }) - - it('offers no configuration exclusion when a failure outside any configuration also blocks', () => { - const r = renderResolutionErrorReport( - [mavenMiss, mavenGraphFailure], - ['compile', 'test'], - 'maven', - ) - expect(r.summary).toContain('Resolution failed in: compile') - expect(r.summary).toContain('To proceed, re-run with --ignore-unresolved.') - expect(r.summary).not.toContain('--exclude-configs') - }) - - it('reports a project whose dependencies could not be resolved at all', () => { - const r = renderResolutionErrorReport([], ['compile'], 'maven', { - unscannable: [ - { - config: '', - detail: - 'Could not resolve dependencies for project com.example:app:1.0', - project: 'com.example:app:1.0', - }, - ], - }) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain( - 'Could not resolve the dependencies of 1 project(s) (reason from Maven):', - ) - expect(r.summary).toContain(' - `com.example:app:1.0`') - expect(r.summary).not.toContain('Resolution succeeded in') - expect(r.summary).toContain('To proceed, re-run with --ignore-unresolved.') - }) - - it('names the subproject of a per-configuration failure', () => { - const r = renderResolutionErrorReport( - [ - f( - 'com.example:missing:1.0', - 'Could not find com.example:missing:1.0.', - 'runtimeClasspath', - ':app', - ), - ], - ['runtimeClasspath'], - 'gradle', - ) - expect(r.summary).toContain(' - com.example:missing:1.0 (in `:app`)') - expect(r.summary).toContain('Resolution failed in: runtimeClasspath') - }) - - it('points dynamic-sbom-inference at its flag and socket.json excludeConfigs', () => { - const r = renderResolutionErrorReport([mavenMiss], ['compile'], 'maven', { - hints: dsiCommand, - }) - expect(r.summary).toContain(' re-run with --ignore-unresolved') - expect(r.summary).toContain( - 'set defaults.manifest.maven.excludeConfigs to "compile" in socket.json (`socket manifest setup --dynamic-sbom-inference`)', - ) - expect(r.summary).not.toContain('--exclude-configs') - expect(r.summary).toContain( - "Re-run with --verbose for Maven's full messages.", - ) - }) - - it('points commands without these flags at socket.json and the dedicated command', () => { - const r = renderResolutionErrorReport([mavenMiss], ['compile'], 'maven', { - hints: socketJsonOnly, - }) - expect(r.summary).toContain( - 'To proceed, set either of these under defaults.manifest.maven in socket.json (`socket manifest setup --dynamic-sbom-inference` walks you through it):', - ) - expect(r.summary).toContain(' "ignoreUnresolved": true') - expect(r.summary).toContain(' "excludeConfigs": "compile"') - expect(r.summary).toContain( - "For Maven's full messages, set defaults.manifest.maven.verbose to true in socket.json.", - ) - expect(r.summary).not.toMatch(/--ignore-unresolved|--exclude-configs/) - }) - - it('tells a reachability scan to also continue on install errors', () => { - const r = renderResolutionErrorReport([mavenMiss], ['compile'], 'maven', { - hints: { - ...socketJsonOnly, - continueOnInstallErrorsFlag: REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, - }, - }) - expect(r.summary).toContain(' "ignoreUnresolved": true') - expect(r.summary).toContain( - 'If you ignore unresolved dependencies, also pass --reach-continue-on-install-errors: reachability analysis cannot install them.', - ) - }) - - it('does not mention install errors outside a reachability scan', () => { - const r = renderResolutionErrorReport([mavenMiss], ['compile'], 'maven', { - hints: socketJsonOnly, - }) - expect(r.summary).not.toContain('install') - }) - - it("names the failing build root's own socket.json", () => { - const r = renderResolutionErrorReport([mavenMiss], ['compile'], 'maven', { - hints: { ...socketJsonOnly, socketJson: 'tools/codegen/socket.json' }, - }) - expect(r.summary).toContain( - 'under defaults.manifest.maven in tools/codegen/socket.json', - ) - expect(r.summary).toContain( - 'set defaults.manifest.maven.verbose to true in tools/codegen/socket.json', - ) - }) - - it('uses the singular socket.json remedy when only ignoreUnresolved applies', () => { - const r = renderResolutionErrorReport( - [mavenGraphFailure], - ['compile'], - 'maven', - { hints: socketJsonOnly }, - ) - expect(r.summary).toContain( - 'To proceed, set this under defaults.manifest.maven', - ) - expect(r.summary).not.toContain('excludeConfigs') - }) - - it('points the non-blocking notice at socket.json when there is no --verbose flag', () => { - const r = renderResolutionErrorReport( - [], - ['debugCompileClasspath'], - 'gradle', - { - hints: socketJsonOnly, - unscannable: [ - { - config: 'debugCompileClasspath', - detail: - 'Cannot choose between the following variants of com.example:foo:1.0', - project: ':', - }, - ], - }, - ) - expect(r.nonBlockingNotice).toContain( - 'set defaults.manifest.gradle.verbose to true in socket.json', - ) - expect(r.nonBlockingNotice).not.toContain('re-run with --verbose') - }) -}) - -describe('failures checked against what resolved', () => { - const ambiguous = f( - 'com.example:amb:1.0', - 'Cannot choose between the following variants of com.example:amb:1.0', - 'runtimeClasspath', - ':app', - ) - - it('keeps variant ambiguity lenient when the module resolved in its project', () => { - const r = renderResolutionErrorReport( - [ambiguous], - ['runtimeClasspath'], - 'gradle', - { resolvedModules: new Set([':app\tcom.example:amb']) }, - ) - expect(r.hasBlockingFailures).toBe(false) - expect(r.nonBlockingNotice).toContain('ambiguous variant selection') - }) - - it('blocks on variant ambiguity when the module resolved nowhere in its project', () => { - const r = renderResolutionErrorReport( - [ambiguous], - ['runtimeClasspath'], - 'gradle', - { resolvedModules: new Set([':lib\tcom.example:amb']) }, - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Ambiguous variant') - expect(r.summary).toContain(' - com.example:amb:1.0 (in `:app`)') - expect(r.nonBlockingNotice).toBe('') - }) - - it('blocks on variant ambiguity in the project where the module resolved nowhere', () => { - const r = renderResolutionErrorReport( - [ambiguous, { ...ambiguous, project: ':lib' }], - ['runtimeClasspath'], - 'gradle', - { resolvedModules: new Set([':app\tcom.example:amb']) }, - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain(' - com.example:amb:1.0 (in `:lib`)') - expect(r.summary).not.toContain('`:app`') - expect(r.nonBlockingNotice).toContain('ambiguous variant selection') - }) - - it('keeps a bare module failure from another project than its versioned form', () => { - const r = renderResolutionErrorReport( - [ - f('com.example:x', 'Could not find com.example:x.', 'compile', ':a'), - f( - 'com.example:x:1.0', - 'Could not find com.example:x:1.0.', - 'compile', - ':b', - ), - ], - ['compile'], - 'gradle', - ) - expect(r.summary).toContain(' - com.example:x (in `:a`)') - expect(r.summary).toContain(' - com.example:x:1.0 (in `:b`)') - }) - - it('blocks on a failure placed in no project', () => { - const r = renderResolutionErrorReport( - [ - f( - 'App.sln', - 'NU1201: Project Fs is not compatible with net48.', - '', - '', - ), - ], - ['net48'], - 'dotnet', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain(' - App.sln') - }) - - it('drops a bare module failure placed in no project behind its versioned form', () => { - const r = renderResolutionErrorReport( - [ - f('com.example:x', 'Could not find com.example:x.', '', ''), - f('com.example:x:1.0', 'Could not find com.example:x:1.0.', '', ''), - ], - ['compile'], - 'gradle', - ) - expect(r.summary).toContain(' - com.example:x:1.0') - expect(r.summary).not.toMatch(/- com\.example:x\s/) - }) - - it('still reminds a reachability scan of install errors once failures are ignored', () => { - const r = renderResolutionErrorReport( - [f('com.example:missing:1.0', 'Could not find com.example:missing:1.0.')], - ['runtimeClasspath'], - 'gradle', - { - hints: { - continueOnInstallErrorsFlag: REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, - flags: new Set(), - setupCommand: 'socket manifest setup', - socketJson: 'socket.json', - }, - ignoreUnresolved: true, - }, - ) - expect(r.summary).toContain('Ignored 1 unresolved dependency(ies)') - expect(r.summary).toContain( - 'Reachability analysis cannot install the ignored dependencies; pass --reach-continue-on-install-errors unless you already do.', - ) - }) -}) - -const mavenReport = (detail: string) => - renderResolutionErrorReport( - [f('com.example:x:jar:1.0', detail, 'compile')], - ['compile'], - 'maven', - ) - -describe('Maven failure classification', () => { - it('classifies a repository blocked by the HTTP blocker as a repository error', () => { - const r = mavenReport( - 'Blocked mirror for repositories: [insecure (http://repo.example.invalid/maven, default, releases+snapshots)]', - ) - expect(r.hasBlockingFailures).toBe(true) - expect(r.summary).toContain('Repository or network error') - }) - - it('classifies offline mode as a repository error, not a miss', () => { - const r = mavenReport( - 'The POM for com.example:x:jar:1.0 is missing, no dependency information available: Cannot access central (https://repo.maven.apache.org/maven2) in offline mode', - ) - expect(r.summary).toContain('Repository or network error') - expect(r.summary).not.toContain('Not found in any repository') - }) - - it('classifies a POM Maven tolerated as invalid as a POM problem', () => { - const r = mavenReport( - 'The POM for com.example:x:jar:1.0 is invalid, transitive dependencies (if any) will not be available: 1 problem was encountered while building the effective model for com.example:x:1.0', - ) - expect(r.summary).toContain('POM/descriptor problem') - }) - - it('classifies a path the repository prefix filter rules out as not found', () => { - const r = mavenReport( - 'prefixes: Path com/example/x/1.0/x-1.0.pom NOT allowed from central', - ) - expect(r.summary).toContain('Not found in any repository') - }) -}) diff --git a/src/commands/manifest/scripts/run.mts b/src/commands/manifest/scripts/run.mts index c7057c872a..9500a82066 100644 --- a/src/commands/manifest/scripts/run.mts +++ b/src/commands/manifest/scripts/run.mts @@ -4,7 +4,7 @@ import path from 'node:path' import { spawn } from '@socketsecurity/registry/lib/spawn' import { assembleFacts } from './assemble.mts' -import { resolveBuildToolBin, socketFactsFileName } from './build-tool.mts' +import { resolveBuildToolBin } from './build-tool.mts' import { serializeExcludePathPatterns } from './exclude-paths-glob.mts' import { parseRecords } from './records.mts' import constants from '../../../constants.mts' @@ -14,12 +14,7 @@ import { getOrInsert } from '../../../utils/get-or-insert.mts' import { camelToKebab } from '../../../utils/strings.mts' import type { BuildTool } from './build-tool.mts' -import type { - ResolvedArtifactPaths, - SocketFactsSbom, - SocketFactsSbomProject, -} from './facts.mts' -import type { ResolutionReport } from './resolution-report.mts' +import type { SocketFactsSbomProject } from './facts.mts' export type ManifestScriptOptions = { projectDir: string @@ -28,23 +23,8 @@ export type ManifestScriptOptions = { // The file in projectDir to build: Maven's POM (unset leaves Maven's // default), dotnet's solution or project (required). entryFile?: string | undefined - // Reachability-only: also materialize resolved artifact paths (artifactPaths). - withFiles?: boolean | undefined - // sbt only: caller-supplied directory to use as sbt's isolated global base. - // sbt provisions the project's Scala toolchain (compiler/library/reflect) - // under `/boot`, which withFiles' artifactPaths point into, so - // the directory must outlive this call; the caller owns creating it and - // deleting it once those paths are no longer needed. Unset ⇒ an ephemeral - // dir is created and cleaned up before this call returns (the withFiles-less - // default, and the case for a standalone `socket manifest sbt --facts`). - tmpDir?: string | undefined - // Newline-delimited GAV file scoping withFiles materialization; absent ⇒ all. - populateFilesFor?: string | undefined - includeConfigs?: string | undefined - excludeConfigs?: string | undefined - // `--exclude-paths`, relative to excludeBase. Passed to the build script, which - // skips resolving a wholly excluded subproject. Source-file-level exclusion is - // left to the reachability analysis (coana's --exclude-dirs), not applied here. + // `--exclude-paths`, relative to excludeBase. Passed to the build script, + // which skips a wholly excluded subproject. excludePaths?: string[] | undefined // The scan root, which a build's modules can lie outside of (Maven `../x` // modules); projectDir when unset. @@ -55,28 +35,10 @@ export type ManifestScriptOptions = { signal?: AbortSignal | undefined } -export type ManifestRunResult = { - code: number - facts: SocketFactsSbom - // Undefined when the build did not report it. - buildRoot: string | undefined - // Undefined when a file-addressed build did not report its entry file. - factsFileName: string | undefined - report: ResolutionReport - artifactPaths: ResolvedArtifactPaths - // Captured build-tool output (empty when stdio is 'inherit', which streams it - // to stderr). - stderr: string - stdout: string -} - type RunOutput = { code: number; stdout: string; stderr: string } -const FACTS_TASK = 'socketFacts' const WORKSPACES_TASK = 'socketWorkspaces' -// Destination filename inside sbt's isolated plugins/ dir; unrelated to the source filename, which -// is whatever socket-facts.plugin.scala / socket-workspaces.plugin.scala are called on disk. -const SBT_FACTS_PLUGIN_FILENAME = 'SocketFactsPlugin.scala' +// Destination filename inside sbt's isolated plugins/ dir. const SBT_WORKSPACES_PLUGIN_FILENAME = 'SocketWorkspacesPlugin.scala' export type WorkspaceEnumerationResult = { @@ -97,9 +59,8 @@ function manifestScriptsPath(...parts: string[]): string { // stdout (e.g. --json) stays machine-readable. const STREAM_TO_STDERR = ['inherit', 2, 'inherit'] as const -// Don't throw on a non-zero exit: the script emits failure records, so a usable -// records file still exists. A non-exit spawn error (e.g. missing executable) -// propagates. +// Don't throw on a non-zero exit: the script may still have written records. A +// non-exit spawn error (e.g. missing executable) propagates. async function runNeverThrow( bin: string, args: string[], @@ -119,8 +80,7 @@ async function runNeverThrow( } } catch (e) { // A build tool that exits non-zero rejects with the spawn-result shape: a - // numeric exit `code` plus captured stdout/stderr. Return it so the caller - // can assemble failure records / surface the output. Anything else — e.g. a + // numeric exit `code` plus captured stdout/stderr. Anything else — e.g. a // missing executable, whose `code` is a string like 'ENOENT' — propagates. // This mirrors how utils/dlx.mts classifies spawn failures (a numeric `code` // is a real process exit); the registry's isSpawnError is avoided here @@ -141,51 +101,36 @@ async function runNeverThrow( } } -async function writeSbtPlugin( - globalBase: string, - sourceFilename: string, - destFilename: string, -): Promise { - const src = await fs.readFile(manifestScriptsPath(sourceFilename), 'utf8') +async function writeSbtPlugin(globalBase: string): Promise { + const src = await fs.readFile( + manifestScriptsPath('socket-workspaces.plugin.scala'), + 'utf8', + ) const pluginsDir = path.join(globalBase, 'plugins') await fs.mkdir(pluginsDir, { recursive: true }) - await fs.writeFile(path.join(pluginsDir, destFilename), src) -} - -async function assembleFromRecords( - tool: BuildTool, - out: RunOutput, - recordsFile: string, -): Promise { - return assembleRecords(tool, out, await readRecordsFile(recordsFile)) + await fs.writeFile(path.join(pluginsDir, SBT_WORKSPACES_PLUGIN_FILENAME), src) } async function readRecordsFile(recordsFile: string): Promise { return existsSync(recordsFile) ? await fs.readFile(recordsFile, 'utf8') : '' } -function assembleRecords( - tool: BuildTool, +function enumerationResult( out: RunOutput, text: string, -): ManifestRunResult { +): WorkspaceEnumerationResult { const parsed = parseRecords(text) - const factsFileName = socketFactsFileName(tool, parsed.entry || undefined) - const { artifactPaths, facts, report } = assembleFacts(parsed) return { buildRoot: parsed.buildRoot || undefined, code: out.code, - facts, - factsFileName, - report, - artifactPaths, + projects: assembleFacts(parsed).facts.projects ?? [], stderr: out.stderr, stdout: out.stdout, } } // Missing only in an unbuilt local checkout. Fail loudly: without the -// extension, Maven silently emits an empty SBOM. +// extension, Maven silently records nothing. function assertBundledAssetBuilt( assetPath: string, description: string, @@ -200,63 +145,26 @@ function assertBundledAssetBuilt( ) } -// Runs the build-tool script (which emits a records file) and assembles it. -// Writes no files; the caller persists facts or consumes artifactPaths. -export async function runManifestScript( +// Emits only `project` records, never resolving dependencies. +export async function enumerateWorkspaces( tool: BuildTool, opts: ManifestScriptOptions, -): Promise { +): Promise { switch (tool) { case 'dotnet': - return await runDotnet(opts) + return await enumerateDotnetWorkspaces(opts) case 'gradle': - return await runGradle(opts) + return await enumerateGradleWorkspaces(opts) case 'sbt': - return await runSbt(opts) + return await enumerateSbtWorkspaces(opts) case 'maven': - return await runMaven(opts) - } -} - -// Emits only `project` records, never resolving dependencies, for discovery -// before committing to a full `runManifestScript` resolution cost. -export async function enumerateWorkspaces( - tool: BuildTool, - opts: ManifestScriptOptions, -): Promise { - const result = await (tool === 'dotnet' - ? runDotnet(opts, '--workspaces') - : tool === 'gradle' - ? enumerateGradleWorkspaces(opts) - : tool === 'sbt' - ? enumerateSbtWorkspaces(opts) - : enumerateMavenWorkspaces(opts)) - return { - buildRoot: result.buildRoot, - code: result.code, - projects: result.facts.projects ?? [], - stderr: result.stderr, - stdout: result.stdout, + return await enumerateMavenWorkspaces(opts) } } // The options every build script reads, each in its own argument syntax. -function scriptOptions( - opts: ManifestScriptOptions, -): Array<[string, string | true]> { - const options: Array<[string, string | true]> = [] - if (opts.withFiles) { - options.push(['withFiles', true]) - } - if (opts.populateFilesFor) { - options.push(['populateFilesFor', opts.populateFilesFor]) - } - if (opts.includeConfigs) { - options.push(['includeConfigs', opts.includeConfigs]) - } - if (opts.excludeConfigs) { - options.push(['excludeConfigs', opts.excludeConfigs]) - } +function scriptOptions(opts: ManifestScriptOptions): Array<[string, string]> { + const options: Array<[string, string]> = [] // Globs compile to regex pattern sources HERE (exclude-paths-glob.mts is // the single glob implementation); the scripts just compile what they // receive. @@ -273,104 +181,63 @@ function commonProps( prefix: '-D' | '-P', ): string[] { return scriptOptions(opts).map( - ({ 0: name, 1: value }) => - `${prefix}socket.${name}=${value === true ? 'true' : value}`, + ({ 0: name, 1: value }) => `${prefix}socket.${name}=${value}`, ) } // The dotnet tool's flags are the kebab-cased script option names. function dotnetToolArgs(opts: ManifestScriptOptions): string[] { - if (opts.populateFilesFor) { - throw new Error('The dotnet manifest tool does not scope --with-files.') - } - return scriptOptions(opts).flatMap(({ 0: name, 1: value }) => { - const flag = `--${camelToKebab(name)}` - return value === true ? [flag] : [flag, value] - }) + return scriptOptions(opts).flatMap(({ 0: name, 1: value }) => [ + `--${camelToKebab(name)}`, + value, + ]) } -async function invokeGradle( +async function enumerateGradleWorkspaces( opts: ManifestScriptOptions, - initScriptFilename: string, - task: string, - tmpDirPrefix: string, -): Promise { +): Promise { const bin = resolveBuildToolBin( 'gradle', opts.projectDir, opts.bin, isStandaloneSea(), ) - const initScript = manifestScriptsPath(initScriptFilename) - return await withTmpDir(tmpDirPrefix, async tmp => { + const initScript = manifestScriptsPath('socket-workspaces.init.gradle') + return await withTmpDir('socket-gradle-workspaces-', async tmp => { const recordsFile = path.join(tmp, 'records.tsv') - // Disable the configuration cache: the init script's legacy - // resolvedConfiguration API and shared accumulator aren't cache-safe. + // Disable the configuration cache: the init script's shared accumulator + // isn't cache-safe. const args = [ '--init-script', initScript, '-Dorg.gradle.configuration-cache=false', - // Names each artifact's own verification problem, so a checksum missing - // from the metadata can be told apart from a mismatch. - '-Porg.gradle.dependency.verification.console=verbose', `-Psocket.recordsFile=${recordsFile}`, ...commonProps(opts, '-P'), ...(opts.toolOpts ?? []), - task, + WORKSPACES_TASK, '--no-daemon', '--console=plain', ] const out = await runNeverThrow(bin, args, opts) - return await assembleFromRecords('gradle', out, recordsFile) + return enumerationResult(out, await readRecordsFile(recordsFile)) }) } -async function runGradle( - opts: ManifestScriptOptions, -): Promise { - return await invokeGradle( - opts, - 'socket-facts.init.gradle', - FACTS_TASK, - 'socket-gradle-facts-', - ) -} - -async function enumerateGradleWorkspaces( - opts: ManifestScriptOptions, -): Promise { - return await invokeGradle( - opts, - 'socket-workspaces.init.gradle', - WORKSPACES_TASK, - 'socket-gradle-workspaces-', - ) -} - async function invokeSbtIn( globalBase: string, opts: ManifestScriptOptions, - pluginSourceFilename: string, - pluginDestFilename: string, - task: string, -): Promise { +): Promise { const bin = resolveBuildToolBin( 'sbt', opts.projectDir, opts.bin, isStandaloneSea(), ) - await writeSbtPlugin(globalBase, pluginSourceFilename, pluginDestFilename) + await writeSbtPlugin(globalBase) const recordsFile = path.join(globalBase, 'records.tsv') - // The global base is shared across sbt roots: a build that dies before - // writing must not be read as the previous root's records. - await fs.rm(recordsFile, { force: true }) // Fresh per-run global base (not ~/.sbt): sbt executes everything under // plugins/, so a shared path is a code-injection surface. BSP off for this - // run. sbt also provisions the project's Scala toolchain under - // /boot; when opts.tmpDir was supplied, the caller keeps this - // directory (and that toolchain) alive until it's done with withFiles' - // artifactPaths, so no special-casing is needed here. + // run. const props = [ `-Dsbt.global.base=${globalBase}`, '-Dsbt.server.autostart=false', @@ -389,49 +256,23 @@ async function invokeSbtIn( ...props, ...(opts.toolOpts ?? []), '--batch', - task, + WORKSPACES_TASK, ] const out = await runNeverThrow(bin, args, opts) - return await assembleFromRecords('sbt', out, recordsFile) -} - -async function runSbt(opts: ManifestScriptOptions): Promise { - const run = (globalBase: string) => - invokeSbtIn( - globalBase, - opts, - 'socket-facts.plugin.scala', - SBT_FACTS_PLUGIN_FILENAME, - FACTS_TASK, - ) - if (opts.tmpDir) { - return await run(opts.tmpDir) - } - return await withTmpDir('socket-sbt-facts-', run) + return enumerationResult(out, await readRecordsFile(recordsFile)) } async function enumerateSbtWorkspaces( opts: ManifestScriptOptions, -): Promise { - const run = (globalBase: string) => - invokeSbtIn( - globalBase, - opts, - 'socket-workspaces.plugin.scala', - SBT_WORKSPACES_PLUGIN_FILENAME, - WORKSPACES_TASK, - ) - if (opts.tmpDir) { - return await run(opts.tmpDir) - } - return await withTmpDir('socket-sbt-workspaces-', run) +): Promise { + return await withTmpDir('socket-sbt-workspaces-', globalBase => + invokeSbtIn(globalBase, opts), + ) } -async function invokeMaven( +async function enumerateMavenWorkspaces( opts: ManifestScriptOptions, - coanaTask: string, - tmpDirPrefix: string, -): Promise { +): Promise { const bin = resolveBuildToolBin( 'maven', opts.projectDir, @@ -447,13 +288,12 @@ async function invokeMaven( 'Maven manifest extension jar', 'build:maven-extension', ) - return await withTmpDir(tmpDirPrefix, async tmp => { + return await withTmpDir('socket-maven-workspaces-', async tmp => { const recordsFile = path.join(tmp, 'records.tsv') - // `validate` is the cheapest phase that triggers the extension; no compile - // needed (analysis uses configured paths, not classes). + // `validate` is the cheapest phase that triggers the extension. const props = [ `-Dmaven.ext.class.path=${jarPath}`, - `-Dcoana.task=${coanaTask}`, + '-Dcoana.task=socket-workspaces', `-Dsocket.recordsFile=${recordsFile}`, ...commonProps(opts, '-D'), ] @@ -466,26 +306,10 @@ async function invokeMaven( 'validate', ] const out = await runNeverThrow(bin, args, opts) - return await assembleFromRecords('maven', out, recordsFile) + return enumerationResult(out, await readRecordsFile(recordsFile)) }) } -async function runMaven( - opts: ManifestScriptOptions, -): Promise { - return await invokeMaven(opts, 'socket-facts', 'socket-maven-facts-') -} - -async function enumerateMavenWorkspaces( - opts: ManifestScriptOptions, -): Promise { - return await invokeMaven( - opts, - 'socket-workspaces', - 'socket-maven-workspaces-', - ) -} - // The global.json the dotnet host applies in `dir`: the first one in it or // any parent directory, the filesystem root included, which findUp skips. // https://github.com/dotnet/runtime/blob/b4548da6edfce1996a1d6ffe1521c9ce6128be2e/src/native/corehost/fxr/sdk_resolver.cpp#L296-L321 @@ -540,12 +364,11 @@ async function readDotnetSdkVersion( return out.stdout.trim() } -// Runs the bundled tool against the build's own dotnet, in `mode` (none: a -// full facts run), and returns its exit and records. -async function invokeDotnetTool( +// Runs the bundled tool against the build's own dotnet in its restore-free +// workspaces mode. +async function enumerateDotnetWorkspaces( opts: ManifestScriptOptions, - mode: '--members' | '--workspaces' | undefined, -): Promise<{ out: RunOutput; records: string }> { +): Promise { if (!opts.entryFile) { throw new Error('A dotnet build needs a solution or project file.') } @@ -562,7 +385,7 @@ async function invokeDotnetTool( DOTNET_ROLL_FORWARD_TO_PRERELEASE: '1', } : opts.env - return await withTmpDir('socket-dotnet-facts-', async tmp => { + return await withTmpDir('socket-dotnet-workspaces-', async tmp => { const recordsFile = path.join(tmp, 'records.tsv') const args = [ toolDll, @@ -572,61 +395,13 @@ async function invokeDotnetTool( opts.entryFile!, '--dotnet', bin, - ...(mode ? [mode] : []), + '--workspaces', ...dotnetToolArgs(opts), ...(opts.stdio === 'inherit' ? ['--verbose'] : []), '--', ...(opts.toolOpts ?? []), ] const out = await runNeverThrow(bin, args, { ...opts, env }) - return { out, records: await readRecordsFile(recordsFile) } + return enumerationResult(out, await readRecordsFile(recordsFile)) }) } - -async function runDotnet( - opts: ManifestScriptOptions, - mode?: '--workspaces' | undefined, -): Promise { - const { out, records } = await invokeDotnetTool(opts, mode) - return assembleRecords('dotnet', out, records) -} - -const entryProjectsByRun = new Map>() - -// Undefined when the SDK cannot read the entry (a .slnx before SDK 9.0.200); -// empty when the listing fails, which the build itself then reports. -export function listDotnetEntryProjects( - opts: ManifestScriptOptions, -): Promise { - const key = JSON.stringify([ - opts.bin, - opts.projectDir, - opts.entryFile, - opts.excludePaths, - opts.excludeBase, - opts.toolOpts, - ]) - return getOrInsert(entryProjectsByRun, key, () => - readDotnetEntryProjects(opts), - ) -} - -async function readDotnetEntryProjects( - opts: ManifestScriptOptions, -): Promise { - let listing - try { - listing = await invokeDotnetTool({ ...opts, stdio: 'pipe' }, '--members') - } catch { - return [] - } - const { out, records } = listing - if (out.code !== 0) { - return [] - } - const parsed = parseRecords(records) - if (parsed.failures.length) { - return undefined - } - return parsed.members.map(m => path.resolve(opts.projectDir, m)) -} diff --git a/src/commands/manifest/scripts/run.test.mts b/src/commands/manifest/scripts/run.test.mts index 663e5ca4de..ab3a7d7d33 100644 --- a/src/commands/manifest/scripts/run.test.mts +++ b/src/commands/manifest/scripts/run.test.mts @@ -6,11 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { spawn } from '@socketsecurity/registry/lib/spawn' -import { - enumerateWorkspaces, - listDotnetEntryProjects, - runManifestScript, -} from './run.mts' +import { enumerateWorkspaces } from './run.mts' vi.mock('@socketsecurity/registry/lib/spawn', () => ({ spawn: vi.fn(async () => ({ code: 0, stderr: '', stdout: '' })), @@ -51,42 +47,6 @@ describe('build tool output', () => { ) }) -describe('shared sbt global base', () => { - it("does not read the previous root's records when a build dies before writing", async () => { - const base = await fs.mkdtemp(path.join(os.tmpdir(), 'sbt-shared-base-')) - try { - const recordsArg = (args: readonly string[]) => - args - .find(a => a.startsWith('-Dsocket.recordsFile='))! - .slice('-Dsocket.recordsFile='.length) - vi.mocked(spawn).mockImplementationOnce((async ( - _bin: string, - args: readonly string[], - ) => { - await fs.writeFile( - recordsArg(args), - 'buildRoot\t/a\nroot\t0\troot\tcompile\t1\nnode\t0\tx:y:jar:1\tx\ty\t1\tjar\t\t1\t\n', - ) - return { code: 0, stderr: '', stdout: '' } - }) as any) - vi.mocked(spawn).mockImplementationOnce((async () => ({ - code: 1, - stderr: 'error: not found: value broken', - stdout: '', - })) as any) - const opts = { bin: 'sbt', stdio: 'pipe' as const, tmpDir: base } - const a = await runManifestScript('sbt', { ...opts, projectDir: base }) - const b = await runManifestScript('sbt', { ...opts, projectDir: base }) - expect(a.facts.components).toHaveLength(1) - expect(b.code).toBe(1) - expect(b.buildRoot).toBeUndefined() - expect(b.facts.components).toHaveLength(0) - } finally { - await fs.rm(base, { force: true, recursive: true }) - } - }) -}) - describe('maven entry file', () => { it.each([ ['app-dev.pom.xml', ['--file', 'app-dev.pom.xml', '-P', 'ci']], @@ -96,7 +56,7 @@ describe('maven entry file', () => { 'builds %s, ahead of the given options', async (entryFile, expected) => { vi.mocked(spawn).mockClear() - await runManifestScript('maven', { + await enumerateWorkspaces('maven', { bin: 'mvn', entryFile, projectDir: process.cwd(), @@ -168,33 +128,22 @@ function mockDotnet(sdk: string, records = '', code = 0): void { }) as any) } -function solutionOpts(projectDir: string) { - return { bin: 'dotnet', entryFile: 'App.sln', projectDir } -} - function toolCall() { - return toolCalls()[0] -} - -function toolCalls() { - return vi.mocked(spawn).mock.calls.filter(c => c[1]?.[0] !== '--version') + return vi.mocked(spawn).mock.calls.filter(c => c[1]?.[0] !== '--version')[0] } describe('dotnet tool invocation', () => { - it('runs the bundled tool on the build entry with the given options', async () => { + it('lists workspaces of the build entry with the given options', async () => { const projectDir = dotnetDir() mockDotnet('8.0.414', 'buildRoot\t/repo\nentry\tApp.sln\n') - const result = await runManifestScript('dotnet', { + const result = await enumerateWorkspaces('dotnet', { bin: '/opt/dotnet/dotnet', entryFile: 'App.sln', excludeBase: path.join(path.sep, 'repo'), - excludeConfigs: '*/*', excludePaths: ['test'], - includeConfigs: 'net8.0', projectDir, stdio: 'pipe', toolOpts: ['-p:Configuration=Release', '--locked-mode'], - withFiles: true, }) const { 0: bin, 1: args = [], 2: opts } = toolCall()! expect(bin).toBe('/opt/dotnet/dotnet') @@ -204,11 +153,7 @@ describe('dotnet tool invocation', () => { 'App.sln', '--dotnet', '/opt/dotnet/dotnet', - '--with-files', - '--include-configs', - 'net8.0', - '--exclude-configs', - '*/*', + '--workspaces', '--exclude-paths', '^(?:test)(?:/.*)?$', '--exclude-base', @@ -219,12 +164,12 @@ describe('dotnet tool invocation', () => { ]) expect(opts?.cwd).toBe(projectDir) expect(opts?.env).toBeUndefined() - expect(result.factsFileName).toBe('App.sln.socket.facts.json') + expect(result.buildRoot).toBe('/repo') }) it('lets a preview SDK roll the tool forward onto a preview runtime', async () => { mockDotnet('11.0.100-rc.3.26522.148') - await runManifestScript('dotnet', { + await enumerateWorkspaces('dotnet', { bin: 'dotnet', entryFile: 'App.csproj', env: { NUGET_PACKAGES: '/cache', PATH: '/bin' }, @@ -238,55 +183,9 @@ describe('dotnet tool invocation', () => { }) }) - it('lists workspaces in the restore-free mode', async () => { - mockDotnet('8.0.414') - await enumerateWorkspaces('dotnet', { - bin: 'dotnet', - entryFile: 'App.sln', - projectDir: dotnetDir(), - stdio: 'pipe', - }) - expect(toolCall()?.[1]).toContain('--workspaces') - }) - it('needs an entry file', async () => { await expect( - runManifestScript('dotnet', { bin: 'dotnet', projectDir: dotnetDir() }), + enumerateWorkspaces('dotnet', { bin: 'dotnet', projectDir: dotnetDir() }), ).rejects.toThrow(/solution or project file/) }) }) - -describe('listDotnetEntryProjects', () => { - it('resolves the members against the build directory', async () => { - const projectDir = dotnetDir() - mockDotnet('8.0.414', 'member\tsrc/A/A.csproj\nmember\tsrc/B/B.csproj\n') - expect(await listDotnetEntryProjects(solutionOpts(projectDir))).toEqual([ - path.join(projectDir, 'src', 'A', 'A.csproj'), - path.join(projectDir, 'src', 'B', 'B.csproj'), - ]) - }) - - it('cannot tell when the SDK cannot read the solution', async () => { - mockDotnet( - '8.0.414', - 'failure\tApp.slnx\tcould not read the solution\t\t\n', - ) - expect( - await listDotnetEntryProjects(solutionOpts(dotnetDir())), - ).toBeUndefined() - }) - - it('lists nothing when the tool exits non-zero', async () => { - mockDotnet('8.0.414', 'member\tsrc/A/A.csproj\n', 1) - expect(await listDotnetEntryProjects(solutionOpts(dotnetDir()))).toEqual([]) - }) - - it('lists an entry once for the same options', async () => { - const opts = solutionOpts(dotnetDir()) - mockDotnet('8.0.414', 'member\tsrc/A/A.csproj\n') - await listDotnetEntryProjects(opts) - await listDotnetEntryProjects({ ...opts }) - await listDotnetEntryProjects({ ...opts, excludePaths: ['src/A'] }) - expect(toolCalls()).toHaveLength(2) - }) -}) diff --git a/src/commands/manifest/scripts/sidecar.mts b/src/commands/manifest/scripts/sidecar.mts deleted file mode 100644 index 679b1dd421..0000000000 --- a/src/commands/manifest/scripts/sidecar.mts +++ /dev/null @@ -1,158 +0,0 @@ -import type { - AnyPURL, - ComponentFramework, - ProjectFramework, - ResolvedArtifactPaths, - SocketFactsSbom, - SocketFactsSbomComponent, - SocketFactsSbomProject, -} from './facts.mts' - -export type SidecarComponentEntry = SocketFactsSbomComponent & { - // Classpath entries (jars, or a sibling project's own build output dirs - // when this component is that project). `[]` means resolved and found - // nothing (e.g. a pom/BOM); undefined means paths were not resolved. - targets?: string[] | undefined - // First-party source roots; `[]` for a genuinely external dependency (still - // attempted, nothing to find), not undefined. - sources?: string[] | undefined - // dotnet: `targets` per target framework, which differ by framework. - frameworks?: ComponentFramework[] | undefined -} - -export type SidecarProjectEntry = Omit & { - targets?: string[] | undefined - sources?: string[] | undefined - // Ids of this facts file's components[] the project depends on directly. - dependencies: string[] - // Ids of this facts file's components[] forming the project's full - // transitive classpath across all its configurations. - classpath: string[] - // dotnet: each build of the project, by target framework. - frameworks?: ProjectFramework[] | undefined -} - -// Frozen contract with `coana run --compute-artifacts-sidecar`; change only -// in sync with the coana consumer. Keyed by the absolute path of the -// `*.socket.facts.json` file whose own projects[]/components[] these entries -// describe - the key IS the scope, so two independent reactors that happen to -// emit the same purl identity (e.g. a shared internal module name) can never -// collide: each is only ever looked up within its own key. No cross-reactor -// deduplication - the same external dependency resolved by several -// independent reactors is intentionally duplicated across all of their -// components[]. -export type ResolvedPathsSidecar = Record< - string, - { - // This facts file's own first-party modules. - projects: SidecarProjectEntry[] - // This reactor's dependency-position entries: genuinely external - // artifacts, and dependency edges that resolve to a sibling first-party - // project (reported via that project's own source/target roots instead - // of a jar path). - components: SidecarComponentEntry[] - } -> - -export type SidecarAccumulator = Map< - string, - { projects: SidecarProjectEntry[]; components: SidecarComponentEntry[] } -> - -// `[]` means resolved and found nothing (e.g. a pom/BOM with no artifact); no -// `targets` means the artifact did not resolve. -function attachPaths( - entry: T, - artifactPaths: ResolvedArtifactPaths, -): T & { targets?: string[]; sources: string[] } { - const paths = artifactPaths.pathsById.get(entry.id) - const targets = paths ? paths.targets : [] - return { - ...entry, - ...(targets ? { targets: [...targets] } : {}), - sources: [...(paths?.sources ?? [])], - } -} - -function purlSortKey(entry: AnyPURL): string { - return `${entry.type}:${entry.namespace ?? ''}:${entry.name}:${entry.version ?? ''}:${entry.qualifiers?.['ext'] ?? ''}:${entry.qualifiers?.['classifier'] ?? ''}` -} - -function sortByPurl(entries: T[]): T[] { - return entries.sort((a, b) => { - const ka = purlSortKey(a) - const kb = purlSortKey(b) - return ka < kb ? -1 : ka > kb ? 1 : 0 - }) -} - -// Emit an entry for every SBOM component AND every first-party project: a -// top-level module is a project, not a dependency component, yet its source -// roots are where reachability starts, so the sidecar must carry them. -// A run writing a facts file another run wrote replaces its entry. -export function accumulateSidecar( - acc: SidecarAccumulator, - facts: SocketFactsSbom, - artifactPaths: ResolvedArtifactPaths, - factsFile: string, - // Off when artifact paths were not resolved; entries then omit `targets` and `sources`. - withPaths = true, -): void { - const paths = (entry: T) => - withPaths ? attachPaths(entry, artifactPaths) : { ...entry } - function frameworks(byId: Map | undefined, id: string) { - const list = withPaths ? byId?.get(id) : undefined - return list ? { frameworks: list } : {} - } - acc.set(factsFile, { - components: facts.components.map(c => ({ - ...paths(c), - ...frameworks(artifactPaths.frameworksById, c.id), - })), - projects: (facts.projects ?? []).map( - ({ children: _children, ...proj }) => ({ - ...paths(proj), - dependencies: [ - ...(artifactPaths.directDependenciesByProject.get(proj.id) ?? []), - ], - classpath: [...(artifactPaths.classpathByProject.get(proj.id) ?? [])], - ...frameworks(artifactPaths.frameworksByProject, proj.id), - }), - ), - }) -} - -export function hasResolvedPathsSidecarEntries( - sidecar: ResolvedPathsSidecar, -): boolean { - return Object.keys(sidecar).length > 0 -} - -export function hasSidecarEntries(acc: SidecarAccumulator): boolean { - return acc.size > 0 -} - -// Combines two already-serialized sidecars (e.g. the recursive-discovery path -// and the plain conda/bazel auto-manifest path). Keys are already scoped to -// one facts file each and can't collide between the two inputs in practice, -// so this is a plain merge; the later input wins on a genuine key collision. -export function mergeResolvedPathsSidecars( - a: ResolvedPathsSidecar, - b: ResolvedPathsSidecar, -): ResolvedPathsSidecar { - return { __proto__: null, ...a, ...b } as unknown as ResolvedPathsSidecar -} - -export function serializeSidecar( - acc: SidecarAccumulator, -): ResolvedPathsSidecar { - const result = { __proto__: null } as unknown as ResolvedPathsSidecar - for (const factsFile of [...acc.keys()].sort()) { - const bucket = acc.get(factsFile)! - result[factsFile] = { - projects: sortByPurl(bucket.projects), - components: sortByPurl(bucket.components), - } - } - return result -} diff --git a/src/commands/manifest/scripts/sidecar.test.mts b/src/commands/manifest/scripts/sidecar.test.mts deleted file mode 100644 index 412819d19b..0000000000 --- a/src/commands/manifest/scripts/sidecar.test.mts +++ /dev/null @@ -1,423 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - accumulateSidecar, - hasResolvedPathsSidecarEntries, - hasSidecarEntries, - mergeResolvedPathsSidecars, - serializeSidecar, -} from './sidecar.mts' - -import type { ResolvedArtifactPaths, SocketFactsSbom } from './facts.mts' -import type { SidecarAccumulator } from './sidecar.mts' - -function emptyArtifactPaths(): ResolvedArtifactPaths { - return { - pathsById: new Map(), - classpathByProject: new Map(), - directDependenciesByProject: new Map(), - } -} - -function mkComponentFixture(target: string): { - facts: SocketFactsSbom - paths: ResolvedArtifactPaths -} { - const paths = emptyArtifactPaths() - paths.pathsById.set('g:a:jar:1', { sources: [], targets: [target] }) - return { - facts: { - components: [ - { - type: 'maven', - namespace: 'g', - name: 'a', - version: '1', - qualifiers: { ext: 'jar' }, - id: 'g:a:jar:1', - }, - ], - }, - paths, - } -} - -describe('compute-artifacts sidecar', () => { - it('carries only the classpaths when artifact paths were not resolved', () => { - const facts: SocketFactsSbom = { - projects: [ - { - id: ':app', - type: 'maven', - namespace: 'g', - name: 'app', - subprojectDir: 'app', - children: [0], - }, - ], - components: [ - { - type: 'maven', - namespace: 'g', - name: 'a', - version: '1', - qualifiers: { ext: 'jar' }, - id: 'g:a:jar:1', - }, - ], - } - const artifactPaths = emptyArtifactPaths() - artifactPaths.classpathByProject.set(':app', ['g:a:jar:1']) - artifactPaths.directDependenciesByProject.set(':app', ['g:a:jar:1']) - - const acc: SidecarAccumulator = new Map() - accumulateSidecar( - acc, - facts, - artifactPaths, - '/root/.socket.facts.json', - false, - ) - const entry = serializeSidecar(acc)['/root/.socket.facts.json']! - - expect(entry.projects[0]).toEqual({ - id: ':app', - type: 'maven', - namespace: 'g', - name: 'app', - subprojectDir: 'app', - dependencies: ['g:a:jar:1'], - classpath: ['g:a:jar:1'], - }) - expect(entry.components[0]).toEqual(facts.components[0]) - }) - - it('carries a component through with resolved targets/sources attached, keyed by its own facts file', () => { - const facts: SocketFactsSbom = { - components: [ - { - type: 'maven', - namespace: 'com.example', - name: 'lib', - version: 'da517db', - qualifiers: { ext: 'jar' }, - id: 'com.example:lib:jar:da517db', - }, - ], - } - const artifactPaths = emptyArtifactPaths() - artifactPaths.pathsById.set('com.example:lib:jar:da517db', { - sources: ['/abs/lib/src/main/java'], - targets: ['/abs/lib.jar'], - }) - - const acc: SidecarAccumulator = new Map() - accumulateSidecar(acc, facts, artifactPaths, '/root/.socket.facts.json') - const resolved = serializeSidecar(acc) - - expect(resolved).toEqual({ - '/root/.socket.facts.json': { - projects: [], - components: [ - { - type: 'maven', - namespace: 'com.example', - name: 'lib', - version: 'da517db', - qualifiers: { ext: 'jar' }, - id: 'com.example:lib:jar:da517db', - targets: ['/abs/lib.jar'], - sources: ['/abs/lib/src/main/java'], - }, - ], - }, - }) - }) - - it('emits explicit empty targets/sources for a resolved-but-artifactless coord (pom/BOM) - [] means resolved, not "not resolved"', () => { - const facts: SocketFactsSbom = { - components: [ - { - type: 'maven', - namespace: 'com.example', - name: 'bom', - version: '1.0', - qualifiers: { ext: 'pom' }, - id: 'com.example:bom:pom:1.0', - }, - ], - } - const acc: SidecarAccumulator = new Map() - accumulateSidecar( - acc, - facts, - emptyArtifactPaths(), - '/root/.socket.facts.json', - ) - const resolved = serializeSidecar(acc) - - const entry = resolved['/root/.socket.facts.json']!.components[0]! - expect(entry.targets).toEqual([]) - expect(entry.sources).toEqual([]) - }) - - it("gives each sibling project's component that project's own paths, even when they share a coordinate", () => { - const util = { - type: 'maven', - namespace: 'ex', - name: 'util', - version: '1', - children: [], - } - const facts: SocketFactsSbom = { - components: [ - { ...util, id: ':a:util', firstParty: true }, - { ...util, id: ':b:util', firstParty: true }, - ], - projects: [ - { ...util, id: ':a:util', subprojectDir: 'a/util' }, - { ...util, id: ':b:util', subprojectDir: 'b/util' }, - ], - } - const artifactPaths = emptyArtifactPaths() - artifactPaths.pathsById.set(':a:util', { - sources: ['/abs/a/util/src'], - targets: ['/abs/a/util/classes'], - }) - artifactPaths.pathsById.set(':b:util', { - sources: ['/abs/b/util/src'], - targets: ['/abs/b/util/classes'], - }) - - const acc: SidecarAccumulator = new Map() - accumulateSidecar( - acc, - facts, - artifactPaths, - '/root/gradle.socket.facts.json', - ) - const entry = serializeSidecar(acc)['/root/gradle.socket.facts.json']! - - for (const entries of [entry.components, entry.projects]) { - expect(Object.fromEntries(entries.map(e => [e.id, e.sources]))).toEqual({ - ':a:util': ['/abs/a/util/src'], - ':b:util': ['/abs/b/util/src'], - }) - } - }) - - it('preserves the original component fields (id, qualifiers) untouched', () => { - const facts: SocketFactsSbom = { - components: [ - { - type: 'maven', - namespace: 'g', - name: 'a', - version: '1', - qualifiers: { ext: 'jar', classifier: 'sources' }, - id: 'g:a:jar:sources:1', - direct: true, - }, - ], - } - const acc: SidecarAccumulator = new Map() - accumulateSidecar( - acc, - facts, - emptyArtifactPaths(), - '/root/.socket.facts.json', - ) - const entry = - serializeSidecar(acc)['/root/.socket.facts.json']!.components[0]! - expect(entry.qualifiers?.['classifier']).toBe('sources') - expect(entry.id).toBe('g:a:jar:sources:1') - expect(entry.direct).toBe(true) - }) - - it('carries a first-party module (project, not a component) source/target roots, keyed by its own facts file', () => { - const facts: SocketFactsSbom = { - // The app module is a project but nothing depends on it, so it is absent - // from components — its source roots must still reach the sidecar. - components: [], - projects: [ - { - id: 'com.example:app:1.0', - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: 'app', - children: [], - }, - ], - } - const artifactPaths = emptyArtifactPaths() - artifactPaths.pathsById.set('com.example:app:1.0', { - sources: ['/abs/app/src/main/java'], - targets: ['/abs/app/build/classes'], - }) - - const acc: SidecarAccumulator = new Map() - accumulateSidecar(acc, facts, artifactPaths, '/root/app/.socket.facts.json') - const resolved = serializeSidecar(acc) - - expect(resolved['/root/app/.socket.facts.json']!.components).toEqual([]) - expect(resolved['/root/app/.socket.facts.json']!.projects).toEqual([ - { - id: 'com.example:app:1.0', - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: 'app', - dependencies: [], - targets: ['/abs/app/build/classes'], - sources: ['/abs/app/src/main/java'], - classpath: [], - }, - ]) - }) - - it('attaches each project its own classpath ids, keyed by project id even within one directory', () => { - const project = { - type: 'maven', - namespace: 'com.example', - version: '1.0', - children: [], - subprojectDir: 'x', - } - const facts: SocketFactsSbom = { - components: [], - projects: [ - { ...project, id: 'x/a.xml', name: 'a' }, - { ...project, id: 'x/b.xml', name: 'b' }, - ], - } - const artifactPaths = emptyArtifactPaths() - artifactPaths.classpathByProject.set('x/a.xml', ['g:x:jar:1']) - artifactPaths.classpathByProject.set('x/b.xml', ['g:x:jar:2']) - - const acc: SidecarAccumulator = new Map() - accumulateSidecar(acc, facts, artifactPaths, '/root/.socket.facts.json') - const projects = serializeSidecar(acc)['/root/.socket.facts.json']!.projects - - expect(projects.map(p => p.classpath)).toEqual([ - ['g:x:jar:1'], - ['g:x:jar:2'], - ]) - }) - - it('does NOT reunion the same external coordinate across build roots - duplication across reactors is intentional', () => { - const acc: SidecarAccumulator = new Map() - const a = mkComponentFixture('/root-a/a.jar') - const b = mkComponentFixture('/root-b/a.jar') - accumulateSidecar(acc, a.facts, a.paths, '/root-a/.socket.facts.json') - accumulateSidecar(acc, b.facts, b.paths, '/root-b/.socket.facts.json') - const resolved = serializeSidecar(acc) - - expect( - resolved['/root-a/.socket.facts.json']!.components[0]!.targets, - ).toEqual(['/root-a/a.jar']) - expect( - resolved['/root-b/.socket.facts.json']!.components[0]!.targets, - ).toEqual(['/root-b/a.jar']) - }) - - it('keeps first-party modules from two independent roots fully separate, even with the same purl identity', () => { - const sharedModuleFacts: SocketFactsSbom = { - components: [], - projects: [ - { - id: 'com.example:shared:1.0', - type: 'maven', - namespace: 'com.example', - name: 'shared', - version: '1.0', - subprojectDir: '.', - children: [], - }, - ], - } - const pathsA = emptyArtifactPaths() - pathsA.pathsById.set('com.example:shared:1.0', { - sources: ['/root-a/src/main/java'], - targets: [], - }) - const pathsB = emptyArtifactPaths() - pathsB.pathsById.set('com.example:shared:1.0', { - sources: ['/root-b/src/main/java'], - targets: [], - }) - - const acc: SidecarAccumulator = new Map() - accumulateSidecar( - acc, - sharedModuleFacts, - pathsA, - '/root-a/.socket.facts.json', - ) - accumulateSidecar( - acc, - sharedModuleFacts, - pathsB, - '/root-b/.socket.facts.json', - ) - const resolved = serializeSidecar(acc) - - expect(Object.keys(resolved)).toEqual([ - '/root-a/.socket.facts.json', - '/root-b/.socket.facts.json', - ]) - expect( - resolved['/root-a/.socket.facts.json']!.projects[0]!.sources, - ).toEqual(['/root-a/src/main/java']) - expect( - resolved['/root-b/.socket.facts.json']!.projects[0]!.sources, - ).toEqual(['/root-b/src/main/java']) - }) - - it('hasSidecarEntries reports empty until a facts file is accumulated', () => { - const acc: SidecarAccumulator = new Map() - expect(hasSidecarEntries(acc)).toBe(false) - - accumulateSidecar( - acc, - { components: [] }, - emptyArtifactPaths(), - '/root/.socket.facts.json', - ) - expect(hasSidecarEntries(acc)).toBe(true) - }) - - it('mergeResolvedPathsSidecars unions distinct facts-file keys from two already-serialized sidecars', () => { - const accA: SidecarAccumulator = new Map() - accumulateSidecar( - accA, - { components: [] }, - emptyArtifactPaths(), - '/root-a/.socket.facts.json', - ) - const sidecarA = serializeSidecar(accA) - - const accB: SidecarAccumulator = new Map() - accumulateSidecar( - accB, - { components: [] }, - emptyArtifactPaths(), - '/root-b/.socket.facts.json', - ) - const sidecarB = serializeSidecar(accB) - - const merged = mergeResolvedPathsSidecars(sidecarA, sidecarB) - - expect(Object.keys(merged)).toEqual([ - '/root-a/.socket.facts.json', - '/root-b/.socket.facts.json', - ]) - expect(hasResolvedPathsSidecarEntries(merged)).toBe(true) - }) - - it('hasResolvedPathsSidecarEntries reports false for a wholly empty sidecar', () => { - expect(hasResolvedPathsSidecarEntries({})).toBe(false) - }) -}) diff --git a/src/commands/manifest/scripts/socket-facts.init.gradle b/src/commands/manifest/scripts/socket-facts.init.gradle deleted file mode 100644 index 7558a68c60..0000000000 --- a/src/commands/manifest/scripts/socket-facts.init.gradle +++ /dev/null @@ -1,832 +0,0 @@ -// Invoke via: -// ./gradlew --init-script socket-facts.init.gradle socketFacts - -import java.util.Collections - -// Emits a flat line-protocol RECORDS file (NOT the final .socket.facts.json, and NOT to stdout). The -// TS assembler (utils/src/manifest-scripts/assemble.ts) reads the records and owns all SBOM -// construction — graph merge and per-subproject classpaths. This script only RESOLVES and emits -// raw facts. See records.ts for the record grammar. - -// `Project.findProperty` only exists since Gradle 2.13; fall back to hasProperty/property for older Gradle. -gradle.ext.socketProp = { proj, name -> proj.hasProperty(name) ? proj.property(name) : null } - -// `-Psocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only -// to skip whole excluded subprojects (source-file-level exclusion is left to the reachability -// analysis). The CLI compiles the user-facing globs in exclude-paths-glob.mts (the single glob -// implementation, tested in CI); this script only Pattern.compile()s what it receives. -gradle.ext.socketExcludeMatchersCache = null -gradle.ext.socketExcludeMatchers = { - if (gradle.ext.socketExcludeMatchersCache != null) return gradle.ext.socketExcludeMatchersCache - def raw = gradle.socketProp.call(gradle.rootProject, 'socket.excludePaths')?.toString() - def patterns = [] - if (raw != null && !raw.trim().isEmpty()) { - raw.split(',').each { r -> - def p = r.trim() - if (!p.isEmpty()) { - // A pattern that doesn't compile is dropped, never thrown: the CLI emits a - // dialect-portable subset, so this only guards against a broken transport. - try { patterns << java.util.regex.Pattern.compile(p) } - catch (java.util.regex.PatternSyntaxException ignored) { } - } - } - } - gradle.ext.socketExcludeMatchersCache = patterns - patterns -} -gradle.ext.socketIsExcluded = { String rel -> - def c = (rel == null ? '' : rel).replace('\\', '/') - while (c.startsWith('./')) { c = c.substring(2) } - while (c.startsWith('/')) { c = c.substring(1) } - while (c.endsWith('/')) { c = c.substring(0, c.length() - 1) } - if (c.isEmpty()) { return false } - gradle.ext.socketExcludeMatchers.call().any { p -> p.matcher(c).matches() } -} -// `-Psocket.excludeBase` (the scan root; the root project's dir by default) anchors `--exclude-paths`: -// a project relocated outside the build root still matches, one outside the scan root never does. -gradle.ext.socketExcludeBaseCache = null -gradle.ext.socketIsExcludedDir = { java.io.File dir -> - if (gradle.ext.socketExcludeMatchers.call().isEmpty()) { return false } - if (gradle.ext.socketExcludeBaseCache == null) { - def base = gradle.socketProp.call(gradle.rootProject, 'socket.excludeBase')?.toString() - gradle.ext.socketExcludeBaseCache = (base ? new java.io.File(base) : gradle.rootProject.projectDir).canonicalFile.toPath() - } - def path = dir.canonicalFile.toPath() - // On another Windows drive than the scan root, so outside it. - if (path.root != gradle.ext.socketExcludeBaseCache.root) { return false } - def rel = gradle.ext.socketExcludeBaseCache.relativize(path).toString().replace(File.separator, '/') - !(rel == '..' || rel.startsWith('../')) && gradle.ext.socketIsExcluded.call(rel.isEmpty() ? '.' : rel) -} - -// Synchronized collections so --parallel-enabled builds don't race; lives on gradle.ext so every -// collector and the root aggregator share one instance. -gradle.ext.socketFactsState = [ - nodes : Collections.synchronizedMap([:]), - directIds : Collections.synchronizedSet([] as Set), - // `detail` is the build tool's failure message verbatim; Coana classifies the failure KIND from it. - failures : Collections.synchronizedList([]), - // Whole configs whose resolution threw (vs a single unresolved dep in `failures`). - unscannable : Collections.synchronizedList([]), - scannedConfigs : Collections.synchronizedSet([] as Set), - // Only populated with `-Psocket.withFiles=true`: reading `artifact.file` downloads the artifact. - paths : Collections.synchronizedMap([:]), - perSub : Collections.synchronizedMap([:]), - projectsInfo : Collections.synchronizedList([]), - // Project path -> the module's real artifact extension (e.g. jar), so an intra-project dep that - // resolves without selecting a published artifact still gets its true coordinate, not ext-less. - projectArtifactExt : Collections.synchronizedMap([:]), - // Project path -> "group:name", to tell this build's projects from an included build's. - projectGaByPath : Collections.synchronizedMap([:]), - // Project path -> "group:name:version", the coordinate a failed project dependency is reported by. - projectGavByPath : Collections.synchronizedMap([:]), -] - -// Capture every project's identity before collectors run so they can recognize intra-project deps -// without an ordering dependency on other subprojects. -gradle.projectsEvaluated { g -> - def rootPath = g.rootProject.projectDir.toPath() - // '/'-normalized so values are stable across OSes and portable to another machine. - def rel = { java.io.File f -> - def r = rootPath.relativize(f.toPath()).toString().replace(File.separator, '/') - r.isEmpty() ? '.' : r - } - g.rootProject.allprojects.each { p -> - // The module's real artifact extension (jar for java; '' for a project that builds no archive, - // e.g. a pure aggregator). Used to stamp intra-project deps that resolve without an artifact. - def artExt = '' - try { - def jt = p.tasks.findByName('jar') - if (jt != null) { - artExt = 'jar' - try { def e = jt.archiveExtension.getOrNull(); if (e) artExt = e } catch (Exception ig1) { - try { def e = jt.extension; if (e) artExt = e } catch (Exception ig2) {} - } - } - } catch (Exception ignore) {} - g.socketFactsState.projectArtifactExt[p.path] = artExt - g.socketFactsState.projectGaByPath[p.path] = "${p.group ?: ''}:${p.name}".toString() - g.socketFactsState.projectGavByPath[p.path] = "${p.group ?: ''}:${p.name}:${p.version ?: ''}".toString() - // A wholly excluded subproject emits no project record and its configs are never resolved (see the - // collector). The project maps above stay populated so a KEPT project depending on it - // still recognizes it as a first-party module, and its paths are kept so it is analysed with its code. - def excluded = g.ext.socketIsExcludedDir.call(p.projectDir) - // Guarded: projects without the java `sourceSets` convention (pure aggregators) contribute empty - // lists rather than failing. Kotlin and Android code lives outside it (see below). - // ALL source sets are emitted (not just main/test) so custom ones (integrationTest, - // functionalTest, ...) reach the analysis; source-file-level exclusion is coana's job. - // `classesDirs` (Gradle 4+) falls back to the legacy single `classesDir` on older Gradle. - def sources = [] as Set - def targets = [] as Set - try { - if (p.hasProperty('sourceSets')) { - p.sourceSets.each { ss -> - if (ss != null) { - ss.allSource.srcDirs.each { d -> sources << d.absolutePath } - try { - ss.output.classesDirs.each { d -> targets << d.absolutePath } - } catch (Exception e1) { - try { targets << ss.output.classesDir.absolutePath } catch (Exception ignore) {} - } - } - } - } - } catch (Exception ignore) {} - // Kotlin compilations for the JVM (kotlin-jvm, KMP `jvm()`, Android): Kotlin source sets, shared - // ones like commonMain included, are not java source sets. Untyped: KGP is not on this classpath. - def kotlin = p.extensions.findByName('kotlin') - if (kotlin != null) { - try { - (kotlin.hasProperty('targets') ? kotlin.targets : [kotlin.target]).each { t -> - try { - if (t.platformType.name() in ['jvm', 'androidJvm']) { - t.compilations.each { c -> - c.allKotlinSourceSets.each { ks -> - sources.addAll(ks.kotlin.srcDirs*.absolutePath) - sources.addAll(ks.resources.srcDirs*.absolutePath) - } - targets.addAll(c.output.classesDirs*.absolutePath) - } - } - } catch (Exception ignore) {} - } - } catch (Exception ignore) {} - } - // AGP keeps its source sets in the `android` extension and leaves the java ones empty. - def android = p.extensions.findByName('android') - if (android != null) { - try { - android.sourceSets.each { ss -> - try { - sources.addAll(ss.java.srcDirs*.absolutePath) - sources.addAll(ss.resources.srcDirs*.absolutePath) - // Last: older AGP has no `kotlin`. - sources.addAll(ss.kotlin.srcDirs*.absolutePath) - } catch (Exception ignore) {} - } - } catch (Exception ignore) {} - // Class dirs come from the compile tasks: AGP's built-in Kotlin (AGP 9) leaves the Kotlin - // compilations' classesDirs empty. - def compileTypes = [JavaCompile] - if (kotlin != null) { - try { - compileTypes << Class.forName('org.jetbrains.kotlin.gradle.tasks.KotlinCompileTool', false, kotlin.getClass().classLoader) - } catch (Throwable ignore) {} - } - compileTypes.each { type -> - try { - p.tasks.withType(type).each { t -> - try { - targets << t.destinationDirectory.get().asFile.absolutePath - } catch (Exception e1) { - try { targets << t.destinationDir.absolutePath } catch (Exception ignore) {} - } - } - } catch (Exception ignore) {} - } - } - // `buildFile` is the configured script, absent on disk for a project configured from the root or - // a convention plugin. Still emitted: a direct dependency's mark must name its subproject. - def buildFiles = [] - try { - def bf = p.buildFile - if (bf != null) buildFiles << rel(bf) - } catch (Exception ignore) {} - g.socketFactsState.projectsInfo.add([ - path : p.path, - group : (p.group ?: '').toString(), - name : p.name, - version: (p.version ?: '').toString(), - dir : rel(p.projectDir), - sources: (sources as List).sort(), - targets: (targets as List).sort(), - buildFiles: buildFiles, - excluded: excluded, - ]) - } -} - -allprojects { project -> - def collectTask = project.tasks.create('socketFactsCollect') { - description = "Resolves ${project.path}'s configurations into the build-wide Socket facts accumulator" - // Dependency resolution depends on state Gradle's up-to-date tracking can't represent reliably. - outputs.upToDateWhen { false } - - doLast { - def state = gradle.socketFactsState - // Skip resolving a wholly excluded subproject: `--exclude-paths` covering its dir means we don't - // resolve for it at all (matches the project-record skip in projectsEvaluated). - if (gradle.ext.socketIsExcludedDir.call(project.projectDir)) { - return - } - // Per-RESOLUTION-ROOT accumulators, LOCAL to this collector: one (subproject, configuration) - // classpath resolved into its own coordinate-keyed tree. Reassigned per config below (the - // visit/upsertNode closures capture them); `failures`/`scannedConfigs` stay shared. - def nodes = [:] - def directIds = [] as Set - def configName = '' - // "group:name:version" -> path of the build project this config resolved it to. - def projectByGav = [:] - def failures = state.failures - def scannedConfigs = state.scannedConfigs - def projectArtifactExt = state.projectArtifactExt - def paths = [:] - // Ids of nodes whose requested artifact yielded no file. - def unfetched = [] as Set - def withFiles = gradle.socketProp.call(project, 'socket.withFiles')?.toString()?.toLowerCase() == 'true' - // Optional `-Psocket.populateFilesFor=` (newline-delimited GAVs): scope `--with-files` - // materialization to those GAVs. This run walks EVERY resolvable config (not told the SBOM's - // include/exclude), so without a scope it would force-download the build's entire dep universe. - // Matched at GAV level to tolerate untrustworthy-ext SBOMs (lockfile / version catalog hardcode - // ext=jar). Absent/empty/missing file -> materialize all. Parsed once under the state monitor. - def populateFilesFor = gradle.socketProp.call(project, 'socket.populateFilesFor')?.toString() - def populateGavs = null - if (withFiles && populateFilesFor != null && !populateFilesFor.trim().isEmpty()) { - synchronized (state) { - if (!state.containsKey('populateGavs')) { - def f = new File(populateFilesFor.trim()) - if (f.exists()) { - def set = [] as Set - f.eachLine { line -> def t = line.trim(); if (!t.isEmpty()) { set << t } } - if (set.isEmpty()) { - // Empty file is more likely a wiring slip than a deliberate "fetch nothing"; materialize all. - state.populateGavs = null - println "[socket-facts] WARN populateFilesFor file empty; materializing files for all resolved artifacts" - } else { - state.populateGavs = set - println "[socket-facts] --with-files scoped to ${set.size()} SBOM artifact(s)" - } - } else { - // Missing file is more likely a wiring bug than an intentional empty scope; materialize all. - state.populateGavs = null - println "[socket-facts] WARN populateFilesFor file not found; materializing files for all resolved artifacts" - } - } - } - populateGavs = state.populateGavs - } - - // Full Maven coordinate (absent segments dropped) — each ext/classifier variant is its own - // component; the id is the coordinate key reachability joins on (see mavenCoordinateKey). - def coordId = { coord -> - [coord.groupId, coord.artifactId, coord.ext, coord.classifier, coord.version].findAll { it }.join(':') - } - - // A first-party module dep can resolve with no published artifact (classes-dir variant, or - // variant-ambiguous moduleArtifacts), leaving it ext-less. Stamp the module's real artifact - // extension so it keeps a full, stable coordinate instead of an ext-less one. - def effExt = { String projPath, String ext -> - if ((ext == null || ext.isEmpty()) && projPath != null) { - projectArtifactExt[projPath] ?: '' - } else { - ext ?: '' - } - } - - // A node is created once; its prod flag accumulates (OR) across the configs that reach it. - def upsertNode = { Map coord, boolean isProd, String projPath -> - def id = coordId(coord) - synchronized (nodes) { - def node = nodes[id] - if (node == null) { - node = [coord: coord, children: [] as Set, prod: false, project: projPath] - nodes[id] = node - } - if (isProd) { - node.prod = true - } - } - id - } - - def causeMessages = { problem -> - def out = [] - def t = problem - int guard = 0 - while (t != null && guard++ < 12) { out << t.message; t = t.cause } - out - } - - // The deepest cause's full message: the TS report classifies it, so nothing is categorized here. - def rawDetail = { problem -> - def messages = causeMessages(problem).findAll { it } - return (messages ? messages[-1] : 'unknown resolution failure').toString().trim() - } - - def recordFailure = { String coord, String detail -> - failures << [coord: coord, detail: detail, config: configName, project: project.path] - } - - // Walk a resolved dependency and its transitive closure. We never touch `artifact.file` here — - // that forces Gradle to download the file (catastrophic on builds declaring distribution - // archives as deps); `artifact.extension`/`artifact.classifier` read already-resolved metadata. - // Intra-project deps (project(':lib')) ARE emitted and recursed, so an external the consumer - // pins/forces to a different version THROUGH the edge is captured (firstLevelModuleDependencies - // lists only declared deps, so a project dep's transitives are reachable only via the edge). - def visit - visit = { dep, boolean isProd, Map cache -> - if (cache.containsKey(dep)) { - return cache[dep] - } - // Pre-populate the cache to break cycles before we recurse. - def producedIds = [] as Set - cache[dep] = producedIds - - // `moduleArtifacts` forces ARTIFACT-level variant selection, which can throw on a - // variant-ambiguous dep even when the dependency GRAPH resolves fine. Guard per-dep: on - // failure keep walking so one ambiguous artifact can't sink the config. - def gav = "${dep.moduleGroup ?: ''}:${dep.moduleName}:${dep.moduleVersion ?: ''}".toString() - def shouldMaterialize = withFiles && (populateGavs == null || populateGavs.contains(gav)) - def projPath = projectByGav[gav] - def artifacts - def artifactsError = null - try { - artifacts = dep.moduleArtifacts - } catch (Exception e) { - artifacts = [] as Set - artifactsError = e - } - if (artifactsError != null && projPath == null) { - // No artifact was selected, so there is no coordinate to emit: report the module and - // bubble its children up (below), as for a skipped first-party module. - recordFailure(gav, rawDetail(artifactsError)) - } else if (artifacts.isEmpty()) { - def ext = effExt(projPath, '') - // Skip a no-artifact first-party module (aggregator / build root): it builds no archive, so - // it's fully described by `projects` and is never a real artifact dependency. - if (!(ext.isEmpty() && projPath != null)) { - producedIds << upsertNode([ - groupId : dep.moduleGroup ?: '', - artifactId: dep.moduleName, - version : dep.moduleVersion ?: '', - classifier: '', - ext : ext, - ], isProd, projPath) - } - } else { - artifacts.each { a -> - // Directory variants (java-classes-directory etc.) carry no extension; for a first-party - // module fall back to its real artifact ext (never artifact.type, a Gradle variant attr). - def ext = effExt(projPath, a.extension) - // Skip a no-artifact first-party module (see the empty-artifacts branch above). - if (ext.isEmpty() && projPath != null) return - def aid = upsertNode([ - groupId : dep.moduleGroup ?: '', - artifactId: dep.moduleName, - version : dep.moduleVersion ?: '', - classifier: a.classifier ?: '', - ext : ext, - ], isProd, projPath) - producedIds << aid - // `a.file` downloads the artifact if not already cached, so scoping avoids fetching - // artifacts the SBOM doesn't reference. Per-artifact try/catch: a single download can - // fail without the whole config being unresolvable. - if (shouldMaterialize) { - try { - def path = a.file.absolutePath - synchronized (paths) { - def set = paths[aid] - if (set == null) { set = [] as Set; paths[aid] = set } - set << path - } - } catch (Exception e) { - println "[socket-facts] could not materialize ${aid}: ${rawDetail(e).readLines().find()}" - // A requested artifact that yields no file is a failure: without one, the dependency - // would read as resolved with nothing to analyse. - if (projPath == null) { - recordFailure(gav, rawDetail(e)) - unfetched << aid - } - } - } - } - } - - def childIds = [] as Set - dep.children.each { child -> - childIds.addAll(visit(child, isProd, cache)) - } - // A skipped no-artifact first-party module, or a module whose artifacts could not be - // selected, produced no node, so bubble its resolved children up to the parent (return - // childIds); otherwise the module's transitives would be attached to nothing. - if (producedIds.isEmpty()) { - cache[dep] = childIds - return childIds - } - synchronized (nodes) { - producedIds.each { pid -> - // Drop self-edges: a project that depends on its own output (test → main) can resolve - // to the same coordinate as its root, which would otherwise emit a node listing itself. - nodes[pid].children.addAll(childIds.findAll { it != pid }) - } - } - producedIds - } - - def isTestConfig = { String name -> name.toLowerCase().contains('test') } - // Matches real compile/runtime classpaths (modern `*Classpath`, legacy `compile`/`runtime`), - // NOT a loose substring that would wrongly promote war-plugin `providedCompile`/`providedRuntime` - // (provided deps are dev). Sets the informational `dev` flag only — never gates analysis. - def isClasspathConfig = { String name -> - def n = name.toLowerCase() - n.contains('classpath') || n == 'compile' || n == 'runtime' - } - - // Config-name glob to a case-SENSITIVE regex (matching is documented as case-sensitive). - // Supports `*`, `?`, and `[...]` character classes: enumerations (`[cC]`), ranges (`[a-z]`), - // and `[!..]`/`[^..]` negation. A malformed glob falls back to a literal match, never throws. - def globToRegex = { String glob -> - def sb = new StringBuilder() - int i = 0 - int n = glob.length() - while (i < n) { - def ch = glob[i] - if (ch == '*') { sb << '.*'; i++ } - else if (ch == '?') { sb << '.'; i++ } - else if (ch == '[') { - int j = glob.indexOf(']', i + 1) - // Treat as a class only with a non-empty body; else a literal `[`. - if (j <= i + 1) { sb << '\\['; i++ } - else { - def body = glob.substring(i + 1, j) - boolean neg = body.startsWith('!') - if (neg) { body = body.substring(1) } - // Only literal chars and `-` ranges are meaningful; neutralize regex-class tricks. - body = body.replace('\\', '\\\\').replace('[', '\\[').replace('&', '\\&') - sb << '[' << (neg ? '^' : '') << body << ']' - i = j + 1 - } - } - else if ('.\\^$|+(){}]'.contains(ch)) { sb << '\\' << ch; i++ } - else { sb << ch; i++ } - } - try { - java.util.regex.Pattern.compile(sb.toString()) - } catch (java.util.regex.PatternSyntaxException e) { - java.util.regex.Pattern.compile(java.util.regex.Pattern.quote(glob)) - } - } - - // `-Psocket.includeConfigs`/`-Psocket.excludeConfigs`: comma-separated config-name globs. A - // config is walked when it matches some include (or there are none) AND matches no exclude. - def parsePatterns = { String s -> - def out = [] - if (s != null && !s.trim().isEmpty()) { - s.split(',').each { raw -> - def p = raw.trim() - if (!p.isEmpty()) out << globToRegex(p) - } - } - out - } - def includePatterns = parsePatterns(gradle.socketProp.call(project, 'socket.includeConfigs')?.toString()) - def excludePatterns = parsePatterns(gradle.socketProp.call(project, 'socket.excludeConfigs')?.toString()) - - // Don't filter by canBeConsumed: Gradle defaults both role flags to true, so a plain resolvable - // config is also consumable, and excluding consumable configs would drop legitimate custom ones. - // `isCanBeResolved` only exists since Gradle 3.3; older Gradle has no split (all resolvable). - def isResolvable = { c -> c.metaClass.respondsTo(c, 'isCanBeResolved') ? c.canBeResolved : true } - def targetConfigs = project.configurations.findAll { - if (!isResolvable(it)) return false - def name = it.name - if (excludePatterns.any { p -> p.matcher(name).matches() }) return false - if (!includePatterns.isEmpty() && !includePatterns.any { p -> p.matcher(name).matches() }) return false - return true - } - - // A failed edge is reported by the selector Gradle ATTEMPTED (after forces and substitutions). - // A project of this build is named by its own coordinate, as its resolved node would be. - def selectorCoord = { sel -> - if (sel instanceof org.gradle.api.artifacts.component.ModuleComponentSelector) { - return "${sel.group}:${sel.module}${sel.version ? ':' + sel.version : ''}".toString() - } - if (sel instanceof org.gradle.api.artifacts.component.ProjectComponentSelector) { - def build = sel.metaClass.respondsTo(sel, 'getBuildPath') ? sel.buildPath : - sel.metaClass.respondsTo(sel, 'getBuildName') ? sel.buildName : ':' - def gav = build == ':' ? state.projectGavByPath[sel.projectPath] : null - if (gav != null) { - return gav - } - } - sel.displayName.toString() - } - - // Gradle verifies only artifact-set reads, never the walk's `ResolvedArtifact.file`, and fails - // them with every fatal failure so far; only STRICT throws, from 6.2, with the root build's metadata. - def rootBuild = gradle - while (rootBuild.parent != null) { - rootBuild = rootBuild.parent - } - def startParameter = gradle.startParameter - def verifyArtifacts = withFiles && - new File(rootBuild.rootProject.rootDir, 'gradle/verification-metadata.xml').isFile() && - startParameter.metaClass.respondsTo(startParameter, 'getDependencyVerificationMode') && - startParameter.dependencyVerificationMode.toString() == 'STRICT' - def gavOf = { Map c -> "${c.groupId}:${c.artifactId}:${c.version}".toString() } - def verificationMessage = { Throwable e -> - causeMessages(e).find { it?.startsWith('Dependency verification failed') } - } - // Old Gradle splits a module into one ResolvedDependency per target configuration, of which only - // some carry its artifacts: an artifact-less one is the same component, so fold it into them. - def foldArtifactless = { - if (!nodes.values().any { n -> !n.coord.ext && n.project == null }) { - return - } - def withExt = [:] - nodes.each { id, n -> - if (n.coord.ext) { - withExt.get(gavOf(n.coord), []) << id - } - } - def folds = [:] - nodes.each { id, n -> - def siblings = (!n.coord.ext && n.project == null) ? withExt[gavOf(n.coord)] : null - if (siblings) { - folds[id] = siblings - } - } - if (folds.isEmpty()) { - return - } - def replaced = { Collection ids -> ids.collectMany { c -> folds[c] ?: [c] } } - folds.each { id, siblings -> - def folded = nodes.remove(id) - siblings.each { sid -> - nodes[sid].children.addAll(replaced(folded.children).findAll { it != sid }) - if (folded.prod) { - nodes[sid].prod = true - } - } - } - nodes.each { nid, n -> - if (n.children.any { folds.containsKey(it) }) { - def children = replaced(n.children).findAll { it != nid } - n.children.clear() - n.children.addAll(children) - } - } - def direct = replaced(directIds) - directIds.clear() - directIds.addAll(direct) - } - - // Drops the files of this config's artifacts that failed verification and reports them. - def checkVerification = { cfg -> - def external = paths.keySet().findAll { id -> nodes[id].project == null } - if (external.isEmpty()) { - return - } - def fetched = external.collect { id -> gavOf(nodes[id].coord) } as Set - def message = null - try { - cfg.incoming.artifactView { - lenient(true) - componentFilter { id -> - id instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier && - fetched.contains("${id.group}:${id.module}:${id.version}".toString()) - } - }.artifacts.each { it.file } - } catch (Exception e) { - message = verificationMessage(e) - if (message == null) { - // Any other failure concerns files the walk already read without it. - println "[socket-facts] could not check artifact verification for ${cfg.name}: ${rawDetail(e).readLines().find()}" - } - } - if (message == null) { - return - } - // Each failed artifact is named by its identifier's display name, " (::)", - // whose file part is `-[-].` rather than the cached file's own name. - def artifactRef = /(\S+) \(([^\s():]+):([^\s():]+):([^\s()]+)\)/ - def lines = message.readLines() - def header = lines ? lines[0] : '' - // The verbose report (the Socket CLI sets org.gradle.dependency.verification.console=verbose) gives - // each artifact's problems: "On artifact in repository '': ", or "On artifact - // multiple problems reported:" followed by one "in repository '': " line each. - def failed = [] - def current = null - lines.each { raw -> - def line = raw.trim().replaceFirst(/^- /, '') - def m = line =~ ('^On artifact ' + artifactRef + ' (.*)$') - if (m.matches()) { - current = [gav: "${m.group(2)}:${m.group(3)}:${m.group(4)}".toString(), file: m.group(1), problems: []] - failed << current - if (m.group(5) != 'multiple problems reported:') { - current.problems << m.group(5) - } - } else if (current != null && line.startsWith("in repository '")) { - current.problems << line - } else { - current = null - } - } - failed.each { f -> - f.detail = ([header] + f.problems.collect { "On artifact ${f.file} (${f.gav}) ${it}" }).join('\n') - } - if (failed.isEmpty()) { - // The summary report names only the artifacts. - (message =~ artifactRef).each { m -> - failed << [gav: "${m[2]}:${m[3]}:${m[4]}".toString(), file: m[1], detail: message] - } - } - def markUnfetched = { Collection ids -> - ids.each { id -> - paths.remove(id) - unfetched << id - } - } - if (failed.isEmpty()) { - // No artifact can be told apart: the walked graph stands, without any of its external files. - state.unscannable << [config: cfg.name, detail: message, project: project.path] - markUnfetched(external) - return - } - failed.each { f -> - def ids = external.findAll { id -> gavOf(nodes[id].coord) == f.gav } - // A failed metadata file (pom, module) names none of the module's artifacts: all are suspect. - // A failed artifact this config did not fetch leaves it untouched. - def hit = (f.file.endsWith('.pom') || f.file.endsWith('.module')) ? ids : ids.findAll { id -> - def c = nodes[id].coord - def named = "${c.artifactId}-${c.version}${c.classifier ? '-' + c.classifier : ''}${c.ext ? '.' + c.ext : ''}" - f.file == named.toString() || paths[id]?.any { p -> f.file == new File(p).name } - } - if (!hit.isEmpty()) { - recordFailure(f.gav, f.detail) - markUnfetched(hit) - } - } - } - - targetConfigs.each { cfg -> - // Recorded even if it resolves nothing or throws — Coana surfaces the full scanned set. - scannedConfigs.add(cfg.name) - // Informational only (OR-accumulated across configs); never gates analysis, so this name - // heuristic can only mis-bucket a dep in prod/dev views, never drop it. - def isProd = isClasspathConfig(cfg.name) && !isTestConfig(cfg.name) - // Fresh tree for THIS resolution root — captured by visit/upsertNode, so no union with siblings. - nodes = [:] - directIds = [] as Set - configName = cfg.name - paths = [:] - unfetched = [] as Set - projectByGav = [:] - // Per-config try/catch: AGP-style configs can fail variant ambiguity from an init-script - // context lacking the consumer attributes AGP sets internally. - def walked = false - try { - def lenient = cfg.resolvedConfiguration.lenientConfiguration - // The resolution graph names a project dependency by project path; within one graph a - // module resolves to a single component, so its GAV identifies that project here. - cfg.incoming.resolutionResult.allComponents.each { comp -> - def cid = comp.id - def mv = comp.moduleVersion - if (cid instanceof org.gradle.api.artifacts.component.ProjectComponentIdentifier && mv != null && - state.projectGaByPath[cid.projectPath] == "${mv.group ?: ''}:${mv.name}".toString()) { - projectByGav["${mv.group ?: ''}:${mv.name}:${mv.version ?: ''}".toString()] = cid.projectPath - } - } - def cache = [:] - // No-arg getter only since Gradle 3.3; older Gradle has just the Spec-taking overload. - def firstLevel - try { - firstLevel = lenient.firstLevelModuleDependencies - } catch (MissingPropertyException e) { - firstLevel = lenient.getFirstLevelModuleDependencies({ true } as org.gradle.api.specs.Spec) - } - firstLevel.each { dep -> - directIds.addAll(visit(dep, isProd, cache)) - } - foldArtifactless() - // Unresolved deps drive the root aggregator's abort/warn decision but are NOT emitted as - // nodes — their selector-only coordinates would surface as half-formed phantom artifacts. - // hasError() covers every unresolved dependency, project ones included. - if (cfg.resolvedConfiguration.hasError()) { - def reported = [] as Set - cfg.incoming.resolutionResult.allDependencies.each { d -> - if (d instanceof org.gradle.api.artifacts.result.UnresolvedDependencyResult) { - def coord = selectorCoord(d.attempted ?: d.requested) - if (reported.add(coord)) { - recordFailure(coord, rawDetail(d.failure)) - } - } - } - } - if (verifyArtifacts) { - checkVerification(cfg) - } - walked = true - } catch (Exception e) { - // A config-LEVEL resolution failure (a resolutionStrategy/beforeResolve rule that throws, - // an artifact-transform failure, a broken repository, ...) rather than a per-dep failure. - // Record it instead of swallowing; the build still exits cleanly and the TS layer surfaces it. - state.unscannable << [config: cfg.name, detail: rawDetail(e), project: project.path] - } - // Stash this resolution root's tree; the key only has to be unique per root. Skip empty - // configs, which contribute nothing, and a partial walk, which can orphan components. - if (walked && !nodes.isEmpty()) { - synchronized (state.perSub) { - state.perSub["${project.path}::${cfg.name}".toString()] = - [nodes: nodes, direct: directIds, paths: paths, unfetched: unfetched, projectPath: project.path, config: cfg.name, prod: isProd] - } - } - } - } - } -} - -rootProject { rp -> - // Hoist property reads to configuration time: the configuration cache forbids `Task.project` from - // task actions. The Socket CLI disables the cache for this run, but hoisting is cheap insurance. - def recordsFileOverride = gradle.socketProp.call(rp, 'socket.recordsFile')?.toString() - def defaultRecordsFile = new File(rp.projectDir, '.socket.facts.records.tsv').absolutePath - def buildRootPath = rp.projectDir.absolutePath - // `sources`/`targets` are --with-files-only; a plain run emits only the graph fields. - def withFilesProjects = gradle.socketProp.call(rp, 'socket.withFiles')?.toString()?.toLowerCase() == 'true' - - rp.tasks.create('socketFacts') { - group = 'socket' - description = 'Emits Socket facts records for the entire build' - outputs.upToDateWhen { false } - - doLast { - def state = gradle.socketFactsState - - // Backslash-escape so a value can never break line/field framing (see records.ts unescape). - def esc = { v -> - (v == null ? '' : v.toString()) - .replace('\\', '\\\\').replace('\t', '\\t').replace('\n', '\\n').replace('\r', '\\r') - } - def lines = [] - def rec = { List fields -> lines << fields.collect { esc(it) }.join('\t') } - - rec(['meta', 'gradle', gradle.gradleVersion, System.getProperty('java.version')]) - rec(['buildRoot', buildRootPath]) - - // One `project` record per build module (sources/targets only with --with-files). - def projectsInfo - synchronized (state.projectsInfo) { projectsInfo = new ArrayList(state.projectsInfo) } - projectsInfo.each { pi -> - if (pi.excluded) { - if (withFilesProjects) rec(['excludedProject', pi.path]) - } else { - rec(['project', pi.path, pi.group ?: '', pi.name, pi.version ?: '', pi.dir]) - pi.buildFiles.each { f -> rec(['projectBuild', pi.path, f]) } - } - if (withFilesProjects) { - pi.sources.each { s -> rec(['projectSrc', pi.path, s]) } - pi.targets.each { t -> rec(['projectTgt', pi.path, t]) } - } - } - - // One resolution root per (subproject, configuration); the TS assembler merges them by - // coordinate and derives each subproject's classpath from its roots. - def perSub - synchronized (state.perSub) { perSub = new LinkedHashMap(state.perSub) } - int rootIdx = 0 - perSub.each { rootKey, tree -> - def rootId = (rootIdx++).toString() - rec(['root', rootId, tree.projectPath, tree.config, tree.prod ? '1' : '0']) - tree.nodes.each { coordId, node -> - def c = node.coord - rec(['node', rootId, coordId, c.groupId ?: '', c.artifactId ?: '', c.version ?: '', c.ext ?: '', - c.classifier ?: '', tree.direct.contains(coordId) ? '1' : '0', node.project ?: '']) - node.children.each { childId -> rec(['edge', rootId, coordId, childId]) } - def fs = tree.paths[coordId] - if (fs) { (fs as List).sort().each { p -> rec(['file', rootId, coordId, p]) } } - if (tree.unfetched.contains(coordId)) rec(['unfetched', rootId, coordId]) - } - } - - // Scanned configs + raw failures (Coana owns the abort/warn policy and report rendering). - def scanned - synchronized (state.scannedConfigs) { scanned = (state.scannedConfigs as List).sort() } - scanned.each { name -> rec(['scanned', name]) } - def failures - synchronized (state.failures) { failures = new ArrayList(state.failures) } - failures.each { f -> rec(['failure', f.coord, f.detail, f.config, f.project]) } - def unscannable - synchronized (state.unscannable) { unscannable = new ArrayList(state.unscannable) } - unscannable.each { u -> rec(['unscannable', u.config, u.detail, u.project]) } - - def outFile = new File(recordsFileOverride ?: defaultRecordsFile) - outFile.parentFile?.mkdirs() - // Explicit UTF-8: the TS reader reads UTF-8, but `File.text =` would encode - // with the JVM default charset (Cp1252 / US-ASCII on Windows or a non-UTF-8 - // locale on JDK <=17), corrupting non-ASCII paths and failure messages. - outFile.withWriter('UTF-8') { it.write(lines.join('\n') + '\n') } - println "Socket facts records written to: ${outFile.absolutePath}" - } - } -} - -gradle.projectsEvaluated { g -> - def aggregator = g.rootProject.tasks.findByName('socketFacts') - if (aggregator) { - g.rootProject.allprojects.each { p -> - def collector = p.tasks.findByName('socketFactsCollect') - if (collector) { - aggregator.dependsOn(collector) - } - } - } -} diff --git a/src/commands/manifest/scripts/socket-facts.plugin.scala b/src/commands/manifest/scripts/socket-facts.plugin.scala deleted file mode 100644 index 6a736865d4..0000000000 --- a/src/commands/manifest/scripts/socket-facts.plugin.scala +++ /dev/null @@ -1,1018 +0,0 @@ -package socket - -import sbt._ -import sbt.Keys._ - -import scala.collection.mutable - -/** - * Emits a flat line-protocol RECORDS file at the build root (NOT the final - * `.socket.facts.json`, and NOT to stdout — sbt prints resolution noise to stdout - * with no way to silence it). The TS assembler (utils/src/manifest-scripts/assemble.ts) - * reads the records and owns all SBOM construction — graph merge and per-subproject - * classpaths. This plugin only RESOLVES and emits raw facts. See records.ts for - * the record grammar. - * - * Must compile on Scala 2.10/sbt 0.13 and Scala 2.12/sbt 1.x (compiled by the sbt - * meta-build), hence string-named TaskKeys and reflection for version-specific - * UpdateConfiguration / ResolveException / ConfigRef shapes. - */ -object SocketFactsPlugin extends AutoPlugin { - override def trigger = allRequirements - - object autoImport { - val socketFacts = - taskKey[Unit]("Emit Socket facts records for the whole build") - } - import autoImport._ - - override def projectSettings: Seq[Setting[_]] = Seq( - aggregate in socketFacts := false, - socketFacts := { - val st = state.value - val buildRoot = (baseDirectory in ThisBuild).value - val withFiles = boolProp("socket.withFiles") - val populateScope: Option[Set[String]] = readPopulateScope() - - val extracted = Project.extract(st) - val allRefs = extracted.structure.allProjectRefs - - // `-Dsocket.excludePaths` (scan-root-relative globs): a subproject whose dir is wholly excluded is - // never resolved and emits no project record. Source-file-level exclusion is left to the analysis. - val excludeMatchers = parseExcludeMatchers() - val rootCanonPath = buildRoot.getCanonicalFile.toPath - def relTo(base: java.nio.file.Path)(f: File): String = { - val r = base.relativize(f.getCanonicalFile.toPath).toString.replace(java.io.File.separator, "/") - if (r.isEmpty) "." else r - } - def relOf(f: File): String = relTo(rootCanonPath)(f) - // `-Dsocket.excludeBase`: the directory `--exclude-paths` is relative to (the scan root; the - // build root by default); a project outside it never matches. - val excludeBase = sys.props.get("socket.excludeBase").filter(_.nonEmpty) - .map(b => new File(b).getCanonicalFile.toPath).getOrElse(rootCanonPath) - def isExcludedRef(ref: ProjectRef): Boolean = excludeMatchers.nonEmpty && { - val dir = extracted.get(baseDirectory.in(ref)) - // Another Windows drive than the scan root is outside it. - dir.getCanonicalFile.toPath.getRoot == excludeBase.getRoot && { - val rel = relTo(excludeBase)(dir) - rel != ".." && !rel.startsWith("../") && isExcludedPath(rel, excludeMatchers) - } - } - - // Prefer `updateFull` (coursier `update` returns empty callers); fall back to `update` (sbt 0.13). - val hasUpdateFull = - extracted.structure.settings.map(_.key.key).exists(_.label == "updateFull") - val updateTaskName = if (hasUpdateFull) "updateFull" else "update" - - // One tree per resolution root (project, config); the TS assembler merges them path-sensitively. - val perSub = mutable.LinkedHashMap.empty[String, RootTree] - val failures = mutable.LinkedHashSet.empty[Failure] - val unscannable = mutable.LinkedHashSet.empty[Unscannable] - val scannedConfigs = mutable.LinkedHashSet.empty[String] - val matcher = buildConfigMatcher() - - // Real artifact ext per build module, so an ext-less inter-project dep gets its true coordinate. - val moduleExts = buildModuleExts(allRefs, extracted) - - // Every project: `update` also runs each upstream project's update, which would fail strictly. - lazy val lenientState = extracted.append(allRefs.map(r => updateConfiguration.in(r) ~= (c => withMissingOk(c))), st) - val pomsByCache = mutable.HashMap.empty[Option[File], PomPackaging] - - allRefs.foreach { ref => - if (!isExcludedRef(ref)) { - // Built-in lm-coursier (sbt 1.3+) and the legacy sbt-coursier plugin name their caches differently. - val legacyCoursierCache = extracted.getOpt(SettingKey[File]("coursierCache").in(ref)) - val csrCache = extracted.getOpt(SettingKey[File]("csrCacheDirectory").in(ref)).orElse(legacyCoursierCache) - val poms = pomsByCache.getOrElseUpdate(csrCache, new PomPackaging(csrCache)) - // sbt 0.13 has no `useCoursier`: it resolves with Ivy unless the legacy plugin replaces it. - val ivy = extracted.getOpt(SettingKey[Boolean]("useCoursier").in(ref)) match { - case Some(useCoursier) => !useCoursier - case None => legacyCoursierCache.isEmpty - } - val resolver = new Resolver(ivy, poms) - runUpdateResilient(updateTaskName, ref, extracted, st, lenientState, matcher, failures, unscannable, resolver) - .foreach { case (report, unresolved, ivyUnfetched, updateFailed) => - foldReport(report, unresolved, ref, extracted, matcher, scannedConfigs, withFiles, populateScope, moduleExts, - resolver, ivyUnfetched, updateFailed, failures).foreach { - case (rootKey, tree) => perSub(rootKey) = tree - } - } - } - } - - val moduleDirs: Map[String, (Seq[String], Seq[String])] = - if (withFiles) buildModuleDirs(allRefs, extracted, st) else Map.empty - - // Where sbt recorded the project's own settings as defined (the root build.sbt for a subproject - // defined there); positions outside the build are sbt defaults, plugins or our injected base. - val buildFilesByRef: Map[ProjectRef, Seq[String]] = - extracted.structure.settings - .flatMap { setting => - (setting.key.scope.project, setting.pos) match { - case (Select(ref: ProjectRef), pos: FilePosition) => - val f = new File(pos.path) - if (f.isAbsolute && f.isFile && f.getCanonicalFile.toPath.startsWith(rootCanonPath)) Some(ref -> relOf(f)) - else None - case _ => None - } - } - .groupBy(_._1) - .map { case (ref, pairs) => ref -> pairs.map(_._2) } - - val sb = new StringBuilder - def rec(fields: String*): Unit = { - sb.append(fields.map(esc).mkString("\t")); sb.append('\n') - } - - rec("meta", "sbt", extracted.getOpt(sbtVersion).getOrElse(""), sys.props.getOrElse("java.version", "")) - rec("buildRoot", rootCanonPath.toString) - - // One `project` record per build module (sources/targets only with --with-files). Excluded - // subprojects get none (they were also skipped during resolution above), but keep their paths so - // a kept project depending on one is analysed with its code. - allRefs.foreach { ref => - val mid = rootIdOf(extracted, ref) - val ver = if (mid.revision == null) "" else mid.revision - if (isExcludedRef(ref)) { - if (withFiles) rec("excludedProject", ref.project) - } else { - val baseDir = extracted.get(baseDirectory.in(ref)) - rec("project", ref.project, mid.organization, mid.name, ver, relOf(baseDir)) - (buildFilesByRef.getOrElse(ref, Nil) ++ baseBuildSbt(baseDir, rootCanonPath).map(relOf)).distinct.sorted - .foreach(f => rec("projectBuild", ref.project, f)) - } - if (withFiles) { - moduleDirs.get(mid.organization + ":" + mid.name + ":" + ver).foreach { - case (sources, targets) => - sources.foreach(s => rec("projectSrc", ref.project, s)) - targets.foreach(t => rec("projectTgt", ref.project, t)) - } - } - } - - // One resolution root per (subproject, configuration); the TS assembler merges them by - // coordinate and derives each subproject's classpath from its roots. - var rootIdx = 0 - perSub.foreach { - case (_, tree) => - val rootId = rootIdx.toString - rootIdx += 1 - rec("root", rootId, tree.projectKey, tree.config, if (tree.prod) "1" else "0") - tree.nodes.foreach { - case (coordId, node) => - val c = node.coord - rec("node", rootId, coordId, c.org, c.name, c.version, c.ext, c.classifier, if (node.direct) "1" else "0", - node.project) - node.children.foreach(ch => rec("edge", rootId, coordId, ch)) - node.targets.foreach(p => rec("file", rootId, coordId, p)) - if (node.unfetched) rec("unfetched", rootId, coordId) - } - } - - // Scanned configs + raw failures (Coana owns the abort/warn policy and report rendering). - scannedConfigs.toList.sorted.foreach(c => rec("scanned", c)) - failures.foreach(f => rec("failure", f.coord, f.detail, f.config, f.project)) - unscannable.foreach(u => rec("unscannable", "", u.detail, u.project)) - - val recordsFile = sys.props.get("socket.recordsFile").filter(_.nonEmpty) match { - case Some(p) => new File(p) - case None => new File(buildRoot, ".socket.facts.records.tsv") - } - Option(recordsFile.getParentFile).foreach(_.mkdirs()) - IO.write(recordsFile, sb.toString) - println("Socket facts records written to: " + recordsFile.getAbsolutePath) - } - ) - - // ---- resolution --------------------------------------------------------- - - private def crossOf(extracted: Extracted, ref: ProjectRef): ModuleID => ModuleID = - CrossVersion.apply(extracted.get(scalaVersion.in(ref)), extracted.get(scalaBinaryVersion.in(ref))) - - private def rootIdOf(extracted: Extracted, ref: ProjectRef): ModuleID = - crossOf(extracted, ref)(extracted.get(projectID.in(ref))) - - // GAV -> a build module's real artifact extension (jar for a normal project). coursier reports an - // inter-project dependency with no resolved artifact, so it would otherwise be ext-less and not - // match how depscan ingests it (ext=jar); stamping the real ext keeps a full, matching coordinate. - private def buildModuleExts(allRefs: Seq[ProjectRef], extracted: Extracted): Map[String, String] = { - allRefs.map { ref => - val ext = extracted.getOpt(artifact.in(ref)).map(_.extension).filter(e => e != null && e.nonEmpty).getOrElse("jar") - gavKey(rootIdOf(extracted, ref)) -> ext - }.toMap - } - - // Absolute source roots + compiled-output dirs per build module, keyed by GAV. --with-files only; - // absolute because reachability locates an internal module's code on THIS machine (no registry jar). - // ALL of the project's configurations are scanned (not just Compile/Test) so custom ones - // (IntegrationTest, ...) reach the analysis; source-file-level exclusion is coana's job. - private def buildModuleDirs( - allRefs: Seq[ProjectRef], - extracted: Extracted, - state: State - ): Map[String, (Seq[String], Seq[String])] = { - allRefs.map { ref => - val mid = rootIdOf(extracted, ref) - val ver = if (mid.revision == null) "" else mid.revision - val configs: Seq[Configuration] = - extracted.getOpt(thisProject.in(ref)).map(_.configurations).getOrElse(Seq(Compile, Test)) - val sources = (configs.flatMap(c => extracted.getOpt(sourceDirectories.in(ref).in(c)).getOrElse(Nil)) ++ - baseDirSources(ref, configs, extracted, state)) - .map(_.getAbsolutePath).distinct.sorted - val targets = configs - .flatMap(c => extracted.getOpt(classDirectory.in(ref).in(c))) - .map(_.getAbsolutePath).distinct.sorted - (mid.organization + ":" + mid.name + ":" + ver) -> ((sources, targets)) - }.toMap - } - - // Sources sbt compiles from the base dir itself (`sourcesInBase`), as files: sbt includes them - // non-recursively, and the base dir as a source root would be walked into nested subprojects. - private def baseDirSources( - ref: ProjectRef, - configs: Seq[Configuration], - extracted: Extracted, - state: State - ): Seq[File] = { - val base = extracted.get(baseDirectory.in(ref)).getCanonicalFile - // A configuration that only inherits the task (Runtime from Compile) would re-run the same walk. - val definingScopes = configs.flatMap { c => - val key = unmanagedSources.in(ref).in(c) - extracted.structure.data.definingScope(key.scope, key.key) - }.distinct - definingScopes.flatMap { scope => - Project.runTask(Def.ScopedKey(scope, unmanagedSources.key), state) match { - case Some((_, sbt.Value(files))) => - files.groupBy(_.getAbsoluteFile.getParentFile).collect { - case (dir, inDir) if dir.getCanonicalFile == base => inDir - }.flatten - case _ => Nil - } - } - } - - // A failure naming no module is an artifact that could not be fetched, which only the lenient - // report's missing artifacts reveal; with neither, the project is unscannable. - private def runUpdateResilient( - taskName: String, - ref: ProjectRef, - extracted: Extracted, - state: State, - lenient: => State, - matcher: String => Boolean, - failures: mutable.LinkedHashSet[Failure], - unscannable: mutable.LinkedHashSet[Unscannable], - resolver: Resolver - ): Option[(UpdateReport, Set[String], IvyUnfetched, Boolean)] = { - val key = TaskKey[UpdateReport](taskName) - - def runOn(st: State): Either[(Seq[ModuleID], String), UpdateReport] = - Project.runTask(key.in(ref).scopedKey, st) match { - case Some((_, sbt.Value(rep))) => Right(rep) - case Some((_, sbt.Inc(inc))) => Left((extractFailedModules(inc), incompleteMessage(inc))) - case _ => Left((Nil, s"$taskName did not run")) - } - - runOn(state) match { - case Right(rep) => Some((rep, Set.empty[String], Map.empty: IvyUnfetched, false)) - case Left((failed, detail)) => - val lenientRun = runOn(lenient).right.map { rep => - (rep, if (resolver.ivy) ivyUnfetchedOf(rep, extracted.get(target.in(ref))) else Map.empty: IvyUnfetched) - } - lenientRun match { - case Right((rep, ivyUnfetched)) - if failed.isEmpty && ivyUnfetched.isEmpty && - !rep.configurations.exists(_.modules.exists(m => !m.evicted && resolver.missingOf(m).nonEmpty)) => - unscannable += Unscannable(detail, ref.project) - None - case Right((rep, ivyUnfetched)) => - val confsByGav = mutable.HashMap.empty[String, mutable.LinkedHashSet[String]] - rep.configurations.foreach { cr => - cr.modules.foreach { r => - if (!r.evicted) confsByGav.getOrElseUpdate(gavKey(r.module), mutable.LinkedHashSet.empty[String]) += confName(cr) - } - } - failed.foreach { m => - // Absent from the graph: no configuration. Present only in excluded ones: not reported. - confsByGav.get(gavKey(m)) match { - case None => failures += Failure(coordOf(m), detailFor(m, detail), "", ref.project) - case Some(confs) => confs.filter(matcher).foreach(c => failures += Failure(coordOf(m), detailFor(m, detail), c, ref.project)) - } - } - Some((rep, failed.map(gavKey).toSet, ivyUnfetched, failed.isEmpty)) - case Left(_) => - // Even a lenient update failed: the whole project is unresolved, but the modules sbt - // named are still reported. - failed.foreach(m => failures += Failure(coordOf(m), detailFor(m, detail), "", ref.project)) - unscannable += Unscannable(detail, ref.project) - None - } - } - } - - // config -> "org:name:rev" -> artifacts Ivy failed to download. - private type IvyUnfetched = Map[String, Map[String, Seq[IvyArtifact]]] - - private final case class IvyArtifact(ext: String, classifier: String, detail: String) - - // sbt 0.13's UpdateReport omits artifacts Ivy failed to download; Ivy's own report per configuration, - // `/reports/--.xml`, keeps them. - private def ivyUnfetchedOf(rep: UpdateReport, projectTarget: File): IvyUnfetched = { - val descriptor = Option(rep.cachedDescriptor).filter(_.isFile) - val bound = projectTarget.getCanonicalFile.toPath - def reportsDirs(f: File): Stream[File] = - Option(f.getParentFile).filter(_.getCanonicalFile.toPath.startsWith(bound)).toStream - .flatMap(p => new File(p, "reports") #:: reportsDirs(p)) - (for { - d <- descriptor.toSeq - id <- ivyResolveId(d).toSeq - cr <- rep.configurations - conf = confName(cr) - report <- reportsDirs(d).map(new File(_, id + "-" + conf + ".xml")).find(_.isFile).toSeq - arts = ivyFailedArtifacts(report) - if arts.nonEmpty - } yield conf -> arts).toMap - } - - private def parseXml(f: File): org.w3c.dom.Document = { - // A POM may declare a DOCTYPE, so only what it could pull in from outside is refused. - val dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance() - dbf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true) - dbf.setFeature("http://xml.org/sax/features/external-general-entities", false) - dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false) - dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) - dbf.setXIncludeAware(false) - dbf.setExpandEntityReferences(false) - dbf.newDocumentBuilder().parse(f) - } - - // Child elements by local name; "*" for all. - private def pomKids(e: org.w3c.dom.Element, name: String): Seq[org.w3c.dom.Element] = { - val ns = e.getChildNodes - (0 until ns.getLength).map(ns.item).collect { - case c: org.w3c.dom.Element if name == "*" || c.getNodeName.split(':').last == name => c - } - } - - private def pomText(e: org.w3c.dom.Element, name: String): Option[String] = - pomKids(e, name).headOption.map(_.getTextContent.trim).filter(_.nonEmpty) - - private def pomGroupId(e: org.w3c.dom.Element): String = - pomText(e, "groupId").orElse(pomKids(e, "parent").headOption.flatMap(pomText(_, "groupId"))).getOrElse("") - - private val PropertyRef = "\\$\\{([^}]+)\\}".r - - // A POM after inheritance: its dependencies (groupId:artifactId -> declared scope, optional), its - // managed scopes, the BOMs it imports, and its properties. - private final case class PomModel( - deps: Map[String, (String, Boolean)], - managed: Map[String, String], - imports: Seq[(String, String, String)], - props: Map[String, String]) - - private object PomModel { - val empty = PomModel(Map.empty, Map.empty, Nil, Map.empty) - } - - // Until nothing changes, as a property's value may refer to another. - private def interpolate(s: String, props: Map[String, String]): String = { - var cur = s - var prev = "" - var rounds = 0 - while (cur != prev && rounds < 16) { - prev = cur - cur = PropertyRef.replaceAllIn(cur, m => java.util.regex.Matcher.quoteReplacement(props.getOrElse(m.group(1), m.matched))) - rounds += 1 - } - cur - } - - // Ivy's ResolveOptions.getDefaultResolveId: `-` of the resolved descriptor. - private def ivyResolveId(descriptor: File): Option[String] = - try { - val info = parseXml(descriptor).getElementsByTagName("info") - if (info.getLength == 0) None - else { - val e = info.item(0).asInstanceOf[org.w3c.dom.Element] - Some(e.getAttribute("organisation") + "-" + e.getAttribute("module")) - } - } catch { case _: Exception => None } - - private def ivyFailedArtifacts(report: File): Map[String, Seq[IvyArtifact]] = - try { - val modules = parseXml(report).getElementsByTagName("module") - val out = for { - mi <- 0 until modules.getLength - module = modules.item(mi).asInstanceOf[org.w3c.dom.Element] - revisions = module.getElementsByTagName("revision") - ri <- 0 until revisions.getLength - revision = revisions.item(ri).asInstanceOf[org.w3c.dom.Element] - if revision.getAttribute("evicted").isEmpty - artifacts = revision.getElementsByTagName("artifact") - ai <- 0 until artifacts.getLength - a = artifacts.item(ai).asInstanceOf[org.w3c.dom.Element] - if a.getAttribute("status") == "failed" - } yield { - val (org, name, rev) = (module.getAttribute("organisation"), module.getAttribute("name"), revision.getAttribute("name")) - val classifier = a.getAttribute("extra-classifier") - val file = a.getAttribute("name") + (if (classifier.isEmpty) "" else "-" + classifier) + "." + a.getAttribute("ext") - // An absent artifact is "missing artifact" (empty under sbt 0.13's Ivy); one the resolver chain - // failed itself has "null"; anything else is a transfer failure's message. - val details = a.getAttribute("details") - val cause = - if (details.isEmpty || details == "missing artifact") "not found" - else if (details == "null") "download failed" - else "download failed (" + details + ")" - (org + ":" + name + ":" + rev) -> IvyArtifact(a.getAttribute("ext"), classifier, cause + ": " + org + "#" + name + ";" + rev + "!" + file) - } - out.groupBy(_._1).map { case (gav, pairs) => gav -> pairs.map(_._2).distinct } - } catch { case _: Exception => Map.empty } - - // UpdateConfiguration has `withMissingOk` on sbt 1.x; on 0.13 its only Boolean field is missingOk. - private def withMissingOk[T](c: T): T = { - val cls = c.getClass - try cls.getMethod("withMissingOk", classOf[Boolean]).invoke(c, java.lang.Boolean.TRUE).asInstanceOf[T] - catch { - case _: NoSuchMethodException => - val copy = cls.getMethods.find(_.getName == "copy").get - val args = copy.getParameterTypes.zipWithIndex.map { case (t, i) => - if (t == classOf[Boolean]) java.lang.Boolean.TRUE - else cls.getMethod("copy$default$" + (i + 1)).invoke(c) - } - copy.invoke(c, args: _*).asInstanceOf[T] - } - } - - // One module's part of a batch resolve message, so records grow with the failure count, not its - // square: Coursier writes an indented "Error downloading org:name:rev" block per module, Ivy a line. - private def detailFor(m: ModuleID, batch: String): String = { - val lines = batch.split("\n").toList - val keys = Seq(coordOf(m), s"${orEmpty(m.organization)}#${orEmpty(m.name)};${orEmpty(m.revision)}") - val start = lines.indexWhere(l => keys.exists(k => l.contains(k))) - if (start < 0) lines.map(_.trim).find(_.nonEmpty).getOrElse(batch) - else (lines(start) :: lines.drop(start + 1).takeWhile(l => l.startsWith(" ") || l.startsWith("\t"))).mkString("\n").trim - } - - private def incompleteMessage(inc: sbt.Incomplete): String = { - def first(i: sbt.Incomplete): Option[String] = - i.directCause.flatMap(ex => Option(ex.getMessage)).orElse(i.causes.view.flatMap(first).headOption) - first(inc).map(_.trim).filter(_.nonEmpty).getOrElse("unresolved dependency") - } - - // Reflection: ResolveException's package and the `failed` accessor differ between sbt 0.13 and 1.x. - private def extractFailedModules(inc: sbt.Incomplete): Seq[ModuleID] = { - val out = mutable.ListBuffer.empty[ModuleID] - def walk(i: sbt.Incomplete): Unit = { - i.directCause.foreach { ex => - val cn = ex.getClass.getName - if (cn == "sbt.ResolveException" || cn == "sbt.librarymanagement.ResolveException") { - try { - val m = ex.getClass.getMethod("failed") - out ++= m.invoke(ex).asInstanceOf[Seq[ModuleID]] - } catch { case _: Throwable => } - } - } - i.causes.foreach(walk) - } - walk(inc) - out.toList.distinct - } - - // Fold one project's UpdateReport into one tree per configuration (rootKey -> tree), keyed by coordinate. - private def foldReport( - report: UpdateReport, - unresolved: Set[String], - ref: ProjectRef, - extracted: Extracted, - matcher: String => Boolean, - scannedConfigs: mutable.LinkedHashSet[String], - withFiles: Boolean, - populateScope: Option[Set[String]], - moduleExts: Map[String, String], - resolver: Resolver, - ivyUnfetched: IvyUnfetched, - // sbt's own update failed on artifacts alone, so one it could not fetch is a failure even - // without files. - updateFailed: Boolean, - failures: mutable.LinkedHashSet[Failure] - ): mutable.LinkedHashMap[String, RootTree] = { - val perRoot = mutable.LinkedHashMap.empty[String, RootTree] - val rootKey = moduleKey(rootIdOf(extracted, ref)) - - // Build modules come from the build structure instead: lm-coursier lists every inter-project - // dependency in every configuration, and cross-versioning can merge distinct ones. - def emittable(m: ModuleReport): Boolean = - !m.evicted && !moduleExts.contains(gavKey(m.module)) && !unresolved.contains(gavKey(m.module)) - - def confsOf(r: ProjectRef): Seq[Configuration] = extracted.getOpt(ivyConfigurations.in(r)).getOrElse(Nil) - lazy val refByProject: Map[String, ProjectRef] = extracted.structure.allProjectRefs.map(r => r.project -> r).toMap - // Whether build project `r` declares module `c` in one of `confs`. A declaration without a - // configuration goes to Compile; the report names the module cross-versioned. - def declares(r: ProjectRef, c: ModuleID, confs: Set[String]): Boolean = { - val cross = crossOf(extracted, r) - extracted.getOpt(libraryDependencies.in(r)).getOrElse(Nil).exists { d => - val masters = d.configurations.getOrElse("compile").split(';').flatMap(_.split("->").head.split(',')).map(_.trim) - d.organization == c.organization && cross(d).name == c.name && masters.exists(m => m == "*" || confs(m)) - } - } - val buildDeps = extracted.get(buildDependencies) - - // Classpaths.interSort, recording the (project -> dependency project) edges it follows and the - // configurations of each project it reaches. - def interProjectEdges(conf: Configuration): (mutable.LinkedHashSet[(ProjectRef, ProjectRef)], Map[String, Set[String]]) = { - val masterConfs = confsOf(ref).map(_.name) - val visited = mutable.HashSet.empty[(ProjectRef, String)] - val edges = mutable.LinkedHashSet.empty[(ProjectRef, ProjectRef)] - def visit(p: ProjectRef, c: Configuration): Unit = { - val applicable = Classpaths.allConfigs(c) - applicable.foreach(ac => visited += (p -> ac.name)) - buildDeps.classpath.getOrElse(p, Nil).foreach { d => - val depConfs = confsOf(d.project) - val mapping = Classpaths.mapped(d.configuration, masterConfs, depConfs.map(_.name), "compile", "*->compile") - for { - ac <- applicable - depConfName <- mapping(ac.name) - depConf <- depConfs.find(_.name == depConfName) - } { - edges += (p -> d.project) - if (!visited((d.project, depConfName))) visit(d.project, depConf) - } - } - } - visit(ref, conf) - (edges, visited.toSeq.groupBy(_._1.project).map { case (p, vs) => p -> vs.map(_._2).toSet }) - } - - def buildModuleCoord(r: ProjectRef): Coord = { - val mid = rootIdOf(extracted, r) - val ver = if (mid.revision == null) "" else mid.revision - Coord(mid.organization, mid.name, ver, moduleExts.getOrElse(gavKey(mid), ""), "") - } - - def inScope(m: ModuleID): Boolean = populateScope match { - case None => true - case Some(gavs) => gavs.contains(gavKey(m)) - } - - report.configurations.foreach { cr => - val cfg = confName(cr) - if (matcher(cfg)) { - scannedConfigs += cfg - val prod = isProdConf(cfg) && !isTestConf(cfg) - val nodes = mutable.LinkedHashMap.empty[String, Node] - // org:name -> component ids (caller edges are module-level). - val midToIds = mutable.HashMap.empty[String, mutable.LinkedHashSet[String]] - var reachedConfs = Map.empty[String, Set[String]] - - confsOf(ref).find(_.name == cfg).foreach { conf => - // Keyed by project id, as projects need not have distinct coordinates. - def buildModuleNode(r: ProjectRef): String = { - midToIds.getOrElseUpdate(moduleKey(rootIdOf(extracted, r)), mutable.LinkedHashSet.empty[String]) += r.project - nodes.getOrElseUpdate(r.project, { - val node = new Node(buildModuleCoord(r)) - node.project = r.project - node - }) - r.project - } - val (edges, reached) = interProjectEdges(conf) - reachedConfs = reached - edges.foreach { case (p, d) => - val child = buildModuleNode(d) - if (p == ref) nodes(child).direct = true - else nodes(buildModuleNode(p)).children += child - } - } - - cr.modules.foreach { m => - if (emittable(m)) { - val ids = midToIds.getOrElseUpdate(moduleKey(m.module), mutable.LinkedHashSet.empty[String]) - val ivyMissing = - if (ivyUnfetched.isEmpty) Nil - else ivyUnfetched.getOrElse(cfg, Map.empty[String, Seq[IvyArtifact]]).getOrElse(gavKey(m.module), Nil) - val recordFiles = withFiles && inScope(m.module) - variantsOf(m, resolver, ivyMissing).foreach { v => - val node = nodes.getOrElseUpdate(v.coord.id, new Node(v.coord)) - ids += v.coord.id - if (recordFiles) v.file.foreach(f => node.targets += f.getAbsolutePath) - v.unfetched.foreach { url => - if (recordFiles) node.unfetched = true - if (recordFiles || updateFailed) failures += Failure(coordOf(m.module), url, cfg, ref.project) - } - } - } - } - - // Caller edges within this config: a root caller marks the child direct, any other becomes its parent. - // Coursier resolves a Maven relocation's target in place of the relocating module, but reports - // neither the relocating module nor who declared it, so that caller is missing from the report. - // Its declarers are read off the build's own declarations and the POMs instead. - val candidates = cr.modules.filter(emittable) - // Drops self-edges (test → main resolving to the same coordinate), matching gradle. - def link(parentIds: Iterable[String], childIds: Iterable[String]): Unit = - parentIds.foreach(pid => childIds.foreach(cid => if (pid != cid) nodes(pid).children += cid)) - def declaredBy(p: String, c: ModuleID): Boolean = - refByProject.get(p).exists(declares(_, c, reachedConfs.getOrElse(p, Set.empty))) - candidates.foreach { m => - midToIds.get(moduleKey(m.module)).foreach { childIds => - // lm-coursier gives a declared caller its declared revision, not the resolved one, so - // callers match by org:name (a configuration resolves one version per module). - m.callers.foreach { c => - val callerKey = moduleKey(c.caller) - if (callerKey == rootKey) childIds.foreach(cid => nodes(cid).direct = true) - else midToIds.get(callerKey) match { - case Some(parentIds) => link(parentIds, childIds) - case None if !resolver.ivy && resolver.poms.relocates(c.caller, m) => - if (declaredBy(ref.project, c.caller)) childIds.foreach(cid => nodes(cid).direct = true) - link(nodes.collect { case (nid, n) if n.project.nonEmpty && declaredBy(n.project, c.caller) => nid }, childIds) - resolver.poms.declaringModules(c.caller, candidates).foreach(p => midToIds.get(moduleKey(p)).foreach(link(_, childIds))) - case None => - } - } - } - } - - if (nodes.nonEmpty) perRoot(ref.project + "::" + cfg) = new RootTree(ref.project, cfg, prod, nodes) - } - } - perRoot - } - - private def variantsOf(m: ModuleReport, resolver: Resolver, ivyMissing: Seq[IvyArtifact]): Seq[Variant] = { - val mid = m.module - // `mid.revision` is normally set for a resolved module, but normalize null (Coord.id calls - // `.nonEmpty`, which NPEs on null) to match the other call sites (gavKey, module records). - val ver = if (mid.revision == null) "" else mid.revision - def coordFor(art: Artifact) = Coord(mid.organization, mid.name, ver, extOf(art), classifierOf(art)) - val fetched = Option(m.artifacts).toList.flatten.map { case (art, file) => Variant(coordFor(art), Option(file), None) } - val missing = resolver.missingOf(m).map { art => - // The update report does not say why: a 401 or a timeout is as likely as an absent file. - Variant(coordFor(art), None, Some("could not be fetched: " + art.url.map(_.toString).getOrElse(coordFor(art).id))) - } ++ ivyMissing.map(a => Variant(Coord(mid.organization, mid.name, ver, a.ext, a.classifier), None, Some(a.detail))) - if (fetched.isEmpty && missing.isEmpty) - // No artifact expected (a pom-only module): leave it ext-less. - Seq(Variant(Coord(mid.organization, mid.name, ver, "", ""), None, None)) - else fetched ++ missing - } - - // Artifacts the resolver expected and did not fetch. Under Ivy they come from its resolution report - // instead (see ivyUnfetchedOf). - private final class Resolver(val ivy: Boolean, val poms: PomPackaging) { - def missingOf(m: ModuleReport): List[Artifact] = - if (ivy) Nil else Option(m.missingArtifacts).toList.flatten.filterNot(poms.isUnexpectedDefault) - } - - // Coursier requests the default jar of every Maven module and skips it silently when absent unless - // the POM declares a jar packaging. Only the module's own POM tells whether its artifact is a jar - // (packaging defaults to jar, so a parent's never applies); an unreadable POM counts as one. - private final class PomPackaging(csrCacheDir: Option[File]) { - private val pomMemo = mutable.HashMap.empty[String, Option[org.w3c.dom.Element]] - - private def pom(url: String): Option[org.w3c.dom.Element] = - pomMemo.getOrElseUpdate(url, coursierLocalFiles(url, csrCacheDir).find(_.isFile).flatMap { f => - try Some(parseXml(f).getDocumentElement) - catch { case _: Exception => None } - }) - - // Maven repository layout. - private def moduleDir(base: String, org: String, name: String): String = - base + org.replace('.', '/') + "/" + name + "/" - - private def pomUrl(base: String, org: String, name: String, rev: String): String = - moduleDir(base, org, name) + rev + "/" + name + "-" + rev + ".pom" - - // The repository root a module's artifacts were fetched from. - private def repoBase(m: ModuleReport): Option[String] = { - val mid = m.module - val marker = moduleDir("/", mid.organization, mid.name) + orEmpty(mid.revision) + "/" - val urls = Option(m.artifacts).toList.flatten.flatMap(_._1.url) ++ - Option(m.missingArtifacts).toList.flatten.flatMap(_.url) - urls.map(_.toString).collectFirst { case u if u.contains(marker) => u.substring(0, u.indexOf(marker) + 1) } - } - - private val modelMemo = mutable.HashMap.empty[String, PomModel] - - // Maven model inheritance and interpolation of a POM, as far as its dependencies' scopes need. - private def model(base: String, org: String, name: String, rev: String, depth: Int): PomModel = { - val url = pomUrl(base, org, name, rev) - modelMemo.getOrElseUpdate(url, pom(url) match { - case None => PomModel.empty - case Some(e) => - val parent = pomKids(e, "parent").headOption - val pm = parent match { - case Some(p) if depth < 16 => - model(base, pomText(p, "groupId").getOrElse(""), pomText(p, "artifactId").getOrElse(""), - pomText(p, "version").getOrElse(""), depth + 1) - case _ => PomModel.empty - } - val groupId = pomGroupId(e) - val artifactId = pomText(e, "artifactId").getOrElse("") - val version = pomText(e, "version").orElse(parent.flatMap(pomText(_, "version"))).getOrElse("") - val own = pomKids(e, "properties").flatMap(ps => pomKids(ps, "*")).map(p => p.getNodeName.split(':').last -> p.getTextContent.trim) - val props = pm.props ++ own ++ Seq( - "project.groupId" -> groupId, "pom.groupId" -> groupId, "groupId" -> groupId, - "project.artifactId" -> artifactId, "pom.artifactId" -> artifactId, "artifactId" -> artifactId, - "project.version" -> version, "pom.version" -> version, "version" -> version - ) ++ parent.toSeq.flatMap { p => - Seq("project.parent.groupId" -> pomText(p, "groupId").getOrElse(""), - "project.parent.version" -> pomText(p, "version").getOrElse("")) - } - def field(d: _root_.org.w3c.dom.Element, name: String) = interpolate(pomText(d, name).getOrElse(""), props) - def ga(d: _root_.org.w3c.dom.Element) = field(d, "groupId") + ":" + field(d, "artifactId") - val deps = pomKids(e, "dependencies").flatMap(ds => pomKids(ds, "dependency")) - val managed = pomKids(e, "dependencyManagement").flatMap(pomKids(_, "dependencies")).flatMap(pomKids(_, "dependency")) - val (imports, scoped) = managed.partition(d => field(d, "scope") == "import" && field(d, "type") == "pom") - PomModel( - pm.deps ++ deps.map(d => ga(d) -> ((field(d, "scope"), field(d, "optional") == "true"))), - pm.managed ++ scoped.map(d => ga(d) -> field(d, "scope")), - imports.map(d => (field(d, "groupId"), field(d, "artifactId"), field(d, "version"))) ++ pm.imports, - props) - }) - } - - private val managedMemo = mutable.HashMap.empty[String, Map[String, String]] - - // Managed scopes after BOM imports: the POM's own and inherited entries win, then the first import. - private def managedScopes(base: String, org: String, name: String, rev: String, depth: Int): Map[String, String] = - managedMemo.getOrElseUpdate(pomUrl(base, org, name, rev), { - val m = model(base, org, name, rev, 0) - m.imports.reverse.foldLeft(Map.empty[String, String]) { case (acc, (g, a, v)) => - if (depth < 16) acc ++ managedScopes(base, g, a, v, depth + 1) else acc - } ++ m.managed - }) - - // org:name of the modules each relocating module's cached POMs relocate to. - private val relocationsMemo = mutable.HashMap.empty[(String, String), Set[String]] - - // Whether `relocating` is a POM relocated to `target`'s module. The report gives the relocating - // module its declared revision, which may be a range, so every cached version is tried; the - // target may have resolved to another version than the relocation names. - def relocates(relocating: ModuleID, target: ModuleReport): Boolean = - repoBase(target).exists { base => - relocationsMemo.getOrElseUpdate((base, gavKey(relocating)), { - val dir = moduleDir(base, relocating.organization, relocating.name) - val versions = orEmpty(relocating.revision) +: coursierLocalFiles(dir, csrCacheDir) - .flatMap(d => Option(d.listFiles).toSeq.flatten).filter(_.isDirectory).map(_.getName) - versions.distinct.flatMap { v => - pom(pomUrl(base, relocating.organization, relocating.name, v)).toSeq.flatMap { e => - pomKids(e, "distributionManagement").flatMap(pomKids(_, "relocation")).headOption.map { r => - pomText(r, "groupId").getOrElse(pomGroupId(e)) + ":" + - pomText(r, "artifactId").orElse(pomText(e, "artifactId")).getOrElse("") - } - } - }.toSet - })(moduleKey(target.module)) - } - - // The modules among `candidates` whose POM passes `declared` on to their dependents: compile or - // runtime scope, declared or managed, and not optional. - def declaringModules(declared: ModuleID, candidates: Seq[ModuleReport]): Seq[ModuleID] = { - val key = moduleKey(declared) - candidates.filter { p => - repoBase(p).exists { base => - val m = model(base, p.module.organization, p.module.name, orEmpty(p.module.revision), 0) - m.deps.get(key).exists { case (scope, optional) => - val effective = - if (scope.nonEmpty) scope - else managedScopes(base, p.module.organization, p.module.name, orEmpty(p.module.revision), 0).getOrElse(key, "") - Set("", "compile", "runtime")(effective) && !optional - } - } - }.map(_.module) - } - - def isUnexpectedDefault(a: Artifact): Boolean = { - val ext = extOf(a) - a.classifier.isEmpty && ext == "jar" && a.url.map(_.toString).exists { url => - url.endsWith("." + ext) && - pom(url.dropRight(ext.length) + "pom").exists(e => !JarPackagings(pomText(e, "packaging").getOrElse("jar"))) - } - } - } - - // coursier.maven.MavenAttributes.typeExtensions (2.1.24, which adds ejb): the packagings whose - // artifact is a `.jar`. Any other packaging (pom, aar, war, ...) publishes its own artifact. - private val JarPackagings = Set("eclipse-plugin", "maven-plugin", "hk2-jar", "orbit", "scala-jar", "jar", "bundle", - "doc", "src", "test-jar", "ejb-client", "ejb") - - // coursier.paths.CachePath.localFile. A repository with credentials is cached under `user@host`, - // and the update report does not carry the user. - private def coursierLocalFiles(url: String, csrCacheDir: Option[File]): Seq[File] = - if (url.startsWith("file:/")) - try Seq(new File(new java.net.URI(url))) - catch { case _: Exception => Nil } - else { - val i = url.indexOf(':') - val protocol = if (i < 0) "" else url.substring(0, i) - val rest = if (i < 0) "" else url.substring(i + 1).dropWhile(_ == '/') - csrCacheDir.toSeq.flatMap { dir => - val protocolDir = new File(dir, coursierEscape(protocol)) - val host = coursierEscape(rest.takeWhile(_ != '/')) - val path = coursierEscape(rest.dropWhile(_ != '/').drop(1)) - val withUser = Option(protocolDir.listFiles).toSeq.flatten.filter(_.getName.endsWith("%40" + host)) - (new File(protocolDir, host) +: withUser).map(new File(_, path)) - } - } - - private def coursierEscape(s: String): String = - s.flatMap { ch => - if (ch > 128 || " %$&+,:;=?@<>#".indexOf(ch) >= 0) "%" + "%02X".format(ch.toInt) else ch.toString - } - - // ---- config selection --------------------------------------------------- - - // With no includes the default is ALL configurations (captures build/tooling deps). - private def buildConfigMatcher(): String => Boolean = { - def parse(prop: String): List[java.util.regex.Pattern] = - sys.props.get(prop) match { - case Some(s) if s.trim.nonEmpty => - s.split(",").map(_.trim).filter(_.nonEmpty).toList.map(globToRegex) - case _ => Nil - } - val includes = parse("socket.includeConfigs") - val excludes = parse("socket.excludeConfigs") - (name: String) => { - val included = - if (includes.isEmpty) true - else includes.exists(_.matcher(name).matches()) - included && !excludes.exists(_.matcher(name).matches()) - } - } - - // Case-SENSITIVE (matching is documented as case-sensitive). Supports `*`, `?`, and `[...]` - // character classes: enumerations (`[cC]`), ranges (`[a-z]`), and `[!..]`/`[^..]` negation. A - // malformed glob falls back to a literal match, never throws. - private def globToRegex(glob: String): java.util.regex.Pattern = { - val sb = new StringBuilder - var i = 0 - val n = glob.length - while (i < n) { - val c = glob.charAt(i) - if (c == '*') { sb.append(".*"); i += 1 } - else if (c == '?') { sb.append('.'); i += 1 } - else if (c == '[') { - val j = glob.indexOf(']', i + 1) - // Treat as a class only with a non-empty body; else a literal `[`. - if (j <= i + 1) { sb.append("\\["); i += 1 } - else { - var body = glob.substring(i + 1, j) - val neg = body.startsWith("!") - if (neg) body = body.substring(1) - // Only literal chars and `-` ranges are meaningful; neutralize regex-class tricks. - body = body.replace("\\", "\\\\").replace("[", "\\[").replace("&", "\\&") - sb.append('[').append(if (neg) "^" else "").append(body).append(']') - i = j + 1 - } - } else if ("\\.^$|+(){}]".indexOf(c.toInt) >= 0) { - sb.append('\\').append(c); i += 1 - } else { sb.append(c); i += 1 } - } - try java.util.regex.Pattern.compile(sb.toString) - catch { - case _: java.util.regex.PatternSyntaxException => - java.util.regex.Pattern.compile(java.util.regex.Pattern.quote(glob)) - } - } - - // ConfigurationReport.configuration is a String on sbt 0.13, a ConfigRef on 1.x: read `.name` reflectively. - private def confName(cr: ConfigurationReport): String = { - val c: Any = cr.configuration - try c.getClass.getMethod("name").invoke(c).toString - catch { case _: Throwable => c.toString } - } - - // `-Dsocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only - // to skip whole excluded subprojects. The CLI compiles the user-facing globs in - // exclude-paths-glob.mts (the single glob implementation, tested in CI); this plugin only - // Pattern.compile()s what it receives. - private def parseExcludeMatchers(): Seq[java.util.regex.Pattern] = { - sys.props.get("socket.excludePaths").map(_.trim).filter(_.nonEmpty) match { - case None => Nil - case Some(raw) => - raw.split(",").toSeq.flatMap { r => - val p = r.trim - // A pattern that doesn't compile is dropped, never thrown: the CLI emits a - // dialect-portable subset, so this only guards against a broken transport. - if (p.isEmpty) Nil - else - try Seq(java.util.regex.Pattern.compile(p)) - catch { case _: java.util.regex.PatternSyntaxException => Nil } - } - } - } - - private def isExcludedPath(rel: String, patterns: Seq[java.util.regex.Pattern]): Boolean = { - if (patterns.isEmpty) false - else { - var c = (if (rel == null) "" else rel).replace("\\", "/") - while (c.startsWith("./")) c = c.substring(2) - while (c.startsWith("/")) c = c.substring(1) - while (c.endsWith("/")) c = c.substring(0, c.length - 1) - if (c.isEmpty) false - else patterns.exists(_.matcher(c).matches()) - } - } - - private def isTestConf(name: String): Boolean = name.toLowerCase.contains("test") - - // Only feeds the informational `dev` flag, never gates analysis. - private def isProdConf(name: String): Boolean = { - val n = name.toLowerCase - n == "compile" || n == "runtime" - } - - // ---- misc helpers -------------------------------------------------------- - - // sbt loads the `.sbt` files in a project's base directory into that project - // (Load.configurationSources), so its build.sbt is the project's even when it sets nothing. - private def baseBuildSbt(base: File, rootCanonPath: java.nio.file.Path): Option[File] = - Some(new File(base, "build.sbt")).filter(f => f.isFile && f.getCanonicalFile.toPath.startsWith(rootCanonPath)) - - private def boolProp(name: String): Boolean = - java.lang.Boolean.parseBoolean(sys.props.getOrElse(name, "false")) - - private def readPopulateScope(): Option[Set[String]] = { - sys.props.get("socket.populateFilesFor").map(_.trim).filter(_.nonEmpty) match { - case None => None - case Some(path) => - val f = new java.io.File(path) - if (!f.exists) { - println("[socket-facts] WARN populateFilesFor file not found; recording files for all resolved artifacts") - None - } else { - val src = scala.io.Source.fromFile(f, "UTF-8") - try { - val set = src.getLines().map(_.trim).filter(_.nonEmpty).toSet - if (set.isEmpty) { - println("[socket-facts] WARN populateFilesFor file empty; recording files for all resolved artifacts") - None - } else { - println("[socket-facts] --with-files scoped to " + set.size + " SBOM artifact(s)") - Some(set) - } - } finally src.close() - } - } - } - - private def orEmpty(v: String): String = if (v == null) "" else v - - private def moduleKey(m: ModuleID): String = orEmpty(m.organization) + ":" + orEmpty(m.name) - - private def gavKey(m: ModuleID): String = moduleKey(m) + ":" + orEmpty(m.revision) - - private def coordOf(m: ModuleID): String = { - val rev = m.revision - m.organization + ":" + m.name + (if (rev != null && rev.nonEmpty) ":" + rev else "") - } - - private def extOf(a: Artifact): String = { - val e = a.extension - if (e == null || e.isEmpty) "jar" else e - } - - private def classifierOf(a: Artifact): String = - a.classifier.getOrElse("") - - // Backslash-escape so a value can never break line/field framing (see records.ts unescape). - private def esc(v: String): String = { - if (v == null) "" - else v.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r") - } - - // Empty `config`: the failure belongs to no configuration. - private final case class Failure(coord: String, detail: String, config: String, project: String) - - private final case class Unscannable(detail: String, project: String) - - private final case class Coord( - org: String, - name: String, - version: String, - ext: String, - classifier: String - ) { - val id: String = Seq(org, name, ext, classifier, version).filter(_.nonEmpty).mkString(":") - } - - private final class Node(val coord: Coord) { - val children = mutable.TreeSet.empty[String] - var direct = false - // Id of the build project this node is, when it is one. - var project = "" - // External artifact's resolved jar(s); --with-files only. - val targets = mutable.TreeSet.empty[String] - // An expected artifact was not fetched; --with-files only. - var unfetched = false - } - - // `unfetched`: why the expected artifact could not be fetched. - private final case class Variant(coord: Coord, file: Option[File], unfetched: Option[String]) - - private final class RootTree( - val projectKey: String, - val config: String, - val prod: Boolean, - val nodes: mutable.LinkedHashMap[String, Node] - ) -} diff --git a/src/commands/manifest/scripts/socket-workspaces.init.gradle b/src/commands/manifest/scripts/socket-workspaces.init.gradle index 2592786d5e..edf2c79536 100644 --- a/src/commands/manifest/scripts/socket-workspaces.init.gradle +++ b/src/commands/manifest/scripts/socket-workspaces.init.gradle @@ -1,9 +1,8 @@ // Invoke via: // ./gradlew --init-script socket-workspaces.init.gradle socketWorkspaces -// Sibling of socket-facts.init.gradle: emits only `meta`/`buildRoot`/`project`/`projectBuild` -// records, no dependency resolution. Kept as a separate script so it can't affect that file's -// already-verified, wide Gradle-version compatibility (1.0+). +// Emits only `meta`/`buildRoot`/`project`/`projectBuild` records, no dependency resolution, for +// the setup wizard; Coana generates the facts themselves. // `Project.findProperty` only exists since Gradle 2.13; fall back to hasProperty/property for older Gradle. gradle.ext.socketProp = { proj, name -> proj.hasProperty(name) ? proj.property(name) : null } @@ -58,8 +57,7 @@ gradle.ext.socketIsExcludedDir = { java.io.File dir -> gradle.ext.socketWorkspacesInfo = Collections.synchronizedList([]) // Collect every non-excluded project's identity at configuration time - cheap, no dependency -// resolution, no sourceSets/jar introspection (unlike the full facts script, which also stamps -// sources/targets/artifact-ext for resolution-time use). +// resolution, no sourceSets/jar introspection. gradle.projectsEvaluated { g -> def rootPath = g.rootProject.projectDir.toPath() def rel = { java.io.File f -> diff --git a/src/commands/manifest/scripts/socket-workspaces.plugin.scala b/src/commands/manifest/scripts/socket-workspaces.plugin.scala index 7d838f842a..95ecc2efd9 100644 --- a/src/commands/manifest/scripts/socket-workspaces.plugin.scala +++ b/src/commands/manifest/scripts/socket-workspaces.plugin.scala @@ -4,11 +4,10 @@ import sbt._ import sbt.Keys._ /** - * Sibling of SocketFactsPlugin (socket-facts.plugin.scala): emits only `meta`/`buildRoot`/ - * `project`/`projectBuild` records, no dependency resolution. Kept as a separate plugin so it - * can't affect that file's already-verified wide sbt-version compatibility (0.13.x+). + * Emits only `meta`/`buildRoot`/`project`/`projectBuild` records, no dependency resolution, for + * the setup wizard; Coana generates the facts themselves. * - * Must compile on Scala 2.10/sbt 0.13 and Scala 2.12/sbt 1.x, same constraint as the facts plugin. + * Must compile on Scala 2.10/sbt 0.13 and Scala 2.12/sbt 1.x. */ object SocketWorkspacesPlugin extends AutoPlugin { override def trigger = allRequirements @@ -29,7 +28,7 @@ object SocketWorkspacesPlugin extends AutoPlugin { val allRefs = extracted.structure.allProjectRefs // `-Dsocket.excludePaths` (scan-root-relative globs): a subproject whose dir is wholly excluded - // emits no project record. Mirrors socket-facts.plugin.scala / the gradle / maven producers. + // emits no project record, as in the gradle / maven producers. val excludeMatchers = parseExcludeMatchers() val rootCanonPath = buildRoot.getCanonicalFile.toPath def relTo(base: java.nio.file.Path)(f: File): String = { @@ -56,7 +55,6 @@ object SocketWorkspacesPlugin extends AutoPlugin { CrossVersion.apply(sv, sbv)(extracted.get(projectID.in(ref))) } - // Mirrors socket-facts.plugin.scala's projectBuild records. val buildFilesByRef: Map[ProjectRef, Seq[String]] = extracted.structure.settings .flatMap { setting => @@ -100,7 +98,7 @@ object SocketWorkspacesPlugin extends AutoPlugin { } ) - // ---- config selection / path exclusion (mirrors socket-facts.plugin.scala) ---------------- + // ---- path exclusion --------------------------------------------------------------------------- // `-Dsocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only // to skip whole excluded subprojects. The CLI compiles the user-facing globs in diff --git a/src/commands/manifest/scripts/test/README.md b/src/commands/manifest/scripts/test/README.md index e11a36663a..abfca26ad0 100644 --- a/src/commands/manifest/scripts/test/README.md +++ b/src/commands/manifest/scripts/test/README.md @@ -1,98 +1,29 @@ -# Manifest-script compatibility tests +# Workspace-enumeration compatibility tests -These exercise the bundled build-tool scripts — the Gradle init script -(`socket-facts.init.gradle`), the sbt plugin (`socket-facts.plugin.scala`), the -Maven extension (`maven-extension/`), and each ecosystem's lightweight -workspace-enumeration sibling (`socket-workspaces.init.gradle`, -`socket-workspaces.plugin.scala`, `CoanaWorkspacesLifecycleParticipant`) — -against a matrix of build-tool versions, asserting they still emit the -expected line-protocol records. +These exercise the build-tool scripts `socket manifest setup --dynamic-sbom-inference` +still runs itself to list a build's projects without resolving dependencies: +`socket-workspaces.init.gradle`, `socket-workspaces.plugin.scala`, the Maven +extension's `CoanaWorkspacesLifecycleParticipant` and the dotnet tool's +`--workspaces`/`--members` modes. Coana generates the Socket facts themselves. -The main Gradle, Maven and sbt smoke tests also assemble their records with the -facts assembler (`assemble-records.mts`). It fails on a root outside every -project, and on a resolved dependency no direct dependency of its project -reaches, the manifest consumer's orphaned component. This runs the assembler's -TypeScript directly, so the suites need Node 22+ and the repo's installed -dependencies (`pnpm install`). +Each ecosystem has two suites: `smoke-test-workspaces.sh` asserts the project +records, `smoke-test-exclude-base.sh` scan-root-relative `--exclude-paths`. ## Run locally, on demand -There is **no CI for this matrix**: SocketDev's org action allowlist forbids -`actions/setup-java` and `sbt/setup-sbt`, so the build-tool matrix has no GitHub -Actions home. Run it locally whenever you change one of the scripts or the -Maven extension: +There is no CI for this matrix: SocketDev's org action allowlist forbids +`actions/setup-java` and `sbt/setup-sbt`. ```sh src/commands/manifest/scripts/test/run-compat.sh [dotnet|gradle|sbt|maven|all] ``` -The matrix needs several JDKs. Point `JDK8` / `JDK11` / `JDK17` / `JDK21` at JDK -homes to use the right one per row; otherwise the current `java` is used. The -sbt rows also need the `sbt` launcher on `PATH`. - -The runner does not fetch the build-tool distributions: SocketDev's CDN allowlist -keeps downloads out of a committed script. It expects each Gradle and Maven -distribution already unzipped under the cache root below, and prints the archive -URL for any that is missing; sbt comes from the `sbt` launcher on `PATH`. It then -invokes the per-ecosystem `smoke-test.sh`. The unit-level assembler/sidecar -behavior is covered separately by the `*.test.mts` unit tests. - -## Stub dependencies - -All three fixtures declare their dependencies as stub artifacts — empty jars plus -generated poms — that `make-stub-repo.sh` writes into a file-based Maven repo at -test time. The fixtures only need the *shape* of a dependency graph (a prod dep, a -test dep, a transitive), never the code, so a stub is behaviourally identical here -and can never age into a CVE alert or a version bump. The generated repos are -gitignored; nothing binary is committed. - -The exception is `maven-compat/duplicate-failure`, whose dependency is deliberately -absent from every repository: it asserts how an unresolvable dependency is -reported, so it needs no stub and runs offline. - -Each build tool still fetches its own closure — Maven's plugins, sbt's -scala-library, the Gradle distribution — from the network, so these fixtures are -not "fully offline"; they simply declare no third-party dependencies of their own. -Gradle is the exception: it also passes `--offline` and resolves everything it -needs for the smoke test from the stub repo. - -## Caches - -No suite reads or writes the developer's own caches. Maven gets its local -repository from `-Dmaven.repo.local`, Gradle its user home from `-g`, and sbt its -Ivy home from `-Dsbt.ivy.home` plus `COURSIER_CACHE`, all under one root that -`compat-cache.sh` resolves: - -``` -${SOCKET_COMPAT_CACHE:-${TMPDIR:-/tmp}/socket-manifest-compat} -``` - -That root is stable, so each tool's own closure is downloaded once and reused; the -first run after clearing it pays for the download. The *stub* artifacts are evicted -from it before every run, so a run can never pass on a stale copy of the thing -under test. Set `SOCKET_COMPAT_CACHE` to a fresh `mktemp -d` for a completely cold -run. - -## dotnet - -`dotnet-compat/smoke-test.sh` runs the built CLI's `socket manifest dotnet` -over fixtures covering solutions (`.sln`, `.slnx`), multi-targeting, -target-framework-conditional project references, test projects, -`PrivateAssets` and `developmentDependency` packages, floating versions, -central package management with transitive pinning, `VersionOverride` and -`GlobalPackageReference`, lock files and locked mode, runtime-specific packages, -packages.config next to SDK projects, F# and VB, several builds in one -directory, `--exclude-paths`, `--include-configs` and failures. Each -PackageReference project's tree is compared with what -`dotnet list package --include-transitive` reports for the same restore. -`smoke-test-workspaces.sh` checks the restore-free `--workspaces` and -`--members` listings, `smoke-test-exclude-base.sh` scan-root-relative -`--exclude-paths`. - -- Rows are SDK versions, each pinned with a `global.json`; install them side by - side under `$SOCKET_COMPAT_CACHE/dotnet` with `dotnet-install.sh`. -- Dependencies are stub packages `make-stub-feed.py` writes into a local feed, - routed there by the fixtures' `nuget.config` package source mapping. Only the - SDK's own packs (targeting packs, `NETStandard.Library`) come from nuget.org. -- `NUGET_PACKAGES` and the NuGet HTTP cache live under the cache root, and the - stubs are evicted from it before every run. +- Point `JDK8` / `JDK11` / `JDK17` / `JDK21` at JDK homes to use the right one + per row; otherwise the current `java` is used. The sbt rows need the `sbt` + launcher on `PATH`. +- Gradle and Maven distributions are expected unzipped under + `${SOCKET_COMPAT_CACHE:-${TMPDIR:-/tmp}/socket-manifest-compat}`; the runner + prints the archive URL for any that is missing. +- dotnet rows are SDK versions, each pinned with a `global.json`; install them + side by side under `$SOCKET_COMPAT_CACHE/dotnet` with `dotnet-install.sh`, and + build the tool first (`pnpm run build:dotnet-tool && pnpm build:dist:src`). diff --git a/src/commands/manifest/scripts/test/assemble-records.mts b/src/commands/manifest/scripts/test/assemble-records.mts deleted file mode 100644 index 531391fa1b..0000000000 --- a/src/commands/manifest/scripts/test/assemble-records.mts +++ /dev/null @@ -1,22 +0,0 @@ -// Assemble a records file the way `socket manifest` does. The assembler throws on a resolved -// dependency no direct dependency of its project reaches, the manifest consumer's "orphaned -// component", but checks only the roots of known projects, so a root of any other project fails here. -import { readFileSync } from 'node:fs' - -import { assembleFacts } from '../assemble.mts' -import { parseRecords } from '../records.mts' - -const recordsFile = process.argv[2] -if (!recordsFile) { - throw new Error('usage: assemble-records.mts ') -} -const parsed = parseRecords(readFileSync(recordsFile, 'utf8')) -for (const [rootId, root] of parsed.roots) { - if (!parsed.projects.has(root.projectKey)) { - throw new Error( - `root ${rootId} belongs to ${root.projectKey}, which has no project record`, - ) - } -} -assembleFacts(parsed, { fileExists: () => true }) -console.log(`PASS (assembled): ${recordsFile}`) diff --git a/src/commands/manifest/scripts/test/compat-cache.sh b/src/commands/manifest/scripts/test/compat-cache.sh index 65c68127ef..a4e5d6bf4c 100755 --- a/src/commands/manifest/scripts/test/compat-cache.sh +++ b/src/commands/manifest/scripts/test/compat-cache.sh @@ -1,14 +1,6 @@ #!/usr/bin/env bash -# Shared cache root for the JVM compat suites: the downloaded build-tool distributions plus each -# tool's dependency cache. Keeping the caches here rather than in ~/.m2, ~/.gradle and ~/.ivy2 means -# a run can't pass off a warm home cache, can't write a home path into the records it emits, and -# can't leave anything behind in the developer's own caches. Point SOCKET_COMPAT_CACHE at a fresh +# Shared cache root for the compat suites: the downloaded build-tool distributions. Point SOCKET_COMPAT_CACHE at a fresh # `mktemp -d` for a cold run. SOCKET_COMPAT_CACHE="${SOCKET_COMPAT_CACHE:-${TMPDIR:-/tmp}/socket-manifest-compat}" mkdir -p "$SOCKET_COMPAT_CACHE" -# Assemble a records file the way `socket manifest` does, failing on an orphaned component. Runs the -# assembler's TypeScript directly, so it needs Node 22+ and the repo's installed dependencies. -assemble_records() { - node --experimental-strip-types --no-warnings "$(dirname "${BASH_SOURCE[0]}")/assemble-records.mts" "$1" -} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/.gitignore b/src/commands/manifest/scripts/test/dotnet-compat/.gitignore index 8923a28ce2..cd42ee34e8 100644 --- a/src/commands/manifest/scripts/test/dotnet-compat/.gitignore +++ b/src/commands/manifest/scripts/test/dotnet-compat/.gitignore @@ -1,6 +1,2 @@ bin/ obj/ -packages/ -stub-feed/ -packages.lock.json -*.socket.facts.json diff --git a/src/commands/manifest/scripts/test/dotnet-compat/assert-dotnet-list.py b/src/commands/manifest/scripts/test/dotnet-compat/assert-dotnet-list.py deleted file mode 100644 index d98117e109..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/assert-dotnet-list.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python3 -"""Compare a dotnet facts file with NuGet's own view of the same restore. - -`dotnet list package --include-transitive --format json` reports, per -PackageReference project and target framework, the top-level and transitive -packages restore resolved. Each project's tree in the facts file must hold -exactly those packages, at those versions, with the top-level ones direct. - -Runtime-specific targets are not part of `dotnet list`, so the facts file must -come from a run that skipped them (--exclude-configs '*/*'). SDK 7.x lists -ProjectReferences among the transitive packages; with it, entries named like -one of the build's own projects are left out. - -Usage: assert-dotnet-list.py [dotnet] -""" -import json -import os -import subprocess -import sys - - -def nuget_view(entry, dotnet): - cwd = os.path.dirname(os.path.abspath(entry)) - # Where available, read the restore under test instead of restoring again - # (a restore of its own runs NuGet audit, which a project may fail on). - help_text = subprocess.run( - [dotnet, 'list', 'package', '--help'], capture_output=True, text=True, cwd=cwd, - ).stdout - no_restore = ['--no-restore'] if '--no-restore' in help_text else [] - # Exits non-zero, still printing its JSON, when a solution member is not - # restored, as one the solution's configuration does not build. - out = subprocess.run( - [dotnet, 'list', entry, 'package', '--include-transitive', '--format', 'json', *no_restore], - check=False, - capture_output=True, - text=True, - cwd=cwd, - ).stdout - view = {} - for project in json.loads(out).get('projects', []): - if 'frameworks' not in project: - continue - direct, every = set(), set() - for framework in project.get('frameworks', []): - for pkg in framework.get('topLevelPackages', []): - key = (pkg['id'].lower(), pkg['resolvedVersion']) - direct.add(key) - every.add(key) - for pkg in framework.get('transitivePackages', []): - every.add((pkg['id'].lower(), pkg['resolvedVersion'])) - view[os.path.realpath(project['path'])] = (direct, every) - return view - - -def facts_view(facts, build_root): - components = facts['components'] - deps = facts.get('dependencies', []) - first_party = {p['id'] for p in facts.get('projects', [])} - - def key(index): - c = components[index] - return None if c['id'] in first_party else (c['name'].lower(), c.get('version', '')) - - view = {} - for project in facts.get('projects', []): - direct = {key(deps[i]['component']) for i in project['children']} - {None} - every, stack, seen = set(), list(project['children']), set() - while stack: - i = stack.pop() - if i in seen: - continue - seen.add(i) - k = key(deps[i]['component']) - if k: - every.add(k) - stack.extend(deps[i].get('children', [])) - path = os.path.realpath(os.path.join(build_root, project['id'])) - view[path] = (direct, every) - return view - - -def main(): - facts_path, entry = sys.argv[1], os.path.abspath(sys.argv[2]) - dotnet = sys.argv[3] if len(sys.argv) > 3 else 'dotnet' - with open(facts_path) as f: - facts = json.load(f) - ours = facts_view(facts, os.path.dirname(os.path.abspath(facts_path))) - sdk = subprocess.run( - [dotnet, '--version'], check=True, capture_output=True, text=True, - cwd=os.path.dirname(entry), - ).stdout.strip() - own = {p['name'].lower() for p in facts.get('projects', [])} if sdk.startswith('7.') else set() - theirs = { - path: ({k for k in direct if k[0] not in own}, {k for k in every if k[0] not in own}) - for path, (direct, every) in nuget_view(entry, dotnet).items() - } - if not theirs: - sys.exit(f'dotnet list reported no project of {entry}') - problems = [] - for path, (direct, every) in sorted(theirs.items()): - if path not in ours: - problems.append(f'{path}: missing from the facts file') - continue - our_direct, our_every = ours[path] - for label, a, b in (('direct', our_direct, direct), ('resolved', our_every, every)): - if a != b: - problems.append( - f'{path}: {label} differs; only in facts: {sorted(a - b)}; only in dotnet list: {sorted(b - a)}' - ) - if problems: - print('\n'.join(problems)) - sys.exit(1) - print(f'facts match dotnet list for {len(theirs)} project(s)') - - -if __name__ == '__main__': - main() diff --git a/src/commands/manifest/scripts/test/dotnet-compat/assert-facts.py b/src/commands/manifest/scripts/test/dotnet-compat/assert-facts.py deleted file mode 100644 index 35949de33d..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/assert-facts.py +++ /dev/null @@ -1,227 +0,0 @@ -#!/usr/bin/env python3 -"""Fixture-specific assertions for the dotnet compat smoke test. - -Usage: assert-facts.py [phase] - phase: (default) the plain runs; exclude-paths, include-configs, - ignore-unresolved: the option runs; records: the --with-files records. -""" -import json -import os -import re -import sys - -WORK, SDK, CPM_ENTRY = sys.argv[1], sys.argv[2], sys.argv[3] -PHASE = sys.argv[4] if len(sys.argv) > 4 else 'default' -SDK_MAJOR = int(SDK.split('.')[0]) -problems = [] - - -def check(cond, message): - if not cond: - problems.append(message) - - -def load(rel): - path = os.path.join(WORK, rel) - check(os.path.exists(path), f'{rel}: missing') - if not os.path.exists(path): - return {'components': [], 'projects': [], 'dependencies': []} - with open(path) as f: - return json.load(f) - - -def comps(facts, name): - return [c for c in facts['components'] if c['name'] == name] - - -def comp(facts, name, version=None): - found = [c for c in comps(facts, name) if version is None or c.get('version') == version] - check(len(found) == 1, f'{name}@{version}: expected one component, got {found}') - return found[0] if found else {} - - -def project_ids(facts): - return sorted(p['id'] for p in facts.get('projects', [])) - - -def common(rel, facts): - check(facts.get('metadata', {}).get('tool') == 'dotnet', f'{rel}: metadata.tool') - for c in facts['components'] + facts.get('projects', []): - check(c.get('type') == 'nuget', f'{rel}: {c["id"]} type {c.get("type")}') - check('namespace' not in c, f'{rel}: {c["id"]} carries a namespace key') - - -def default_phase(): - basic = load('basic/Basic.sln.socket.facts.json') - common('basic', basic) - check( - project_ids(basic) == [ - 'src/App/App.csproj', 'src/Extra/Extra.csproj', 'src/Lib/Lib.csproj', - 'test/App.Tests/App.Tests.csproj', - ], - f'basic projects: {project_ids(basic)}', - ) - lib = next(p for p in basic['projects'] if p['id'] == 'src/Lib/Lib.csproj') - check((lib['name'], lib.get('version')) == ('Acme.Lib', '2.3.4'), f'Lib identity: {lib}') - check(comp(basic, 'Acme.Lib').get('firstParty') is True, 'Lib as a component is first-party') - check(comp(basic, 'Acme.Lib').get('id') == 'src/Lib/Lib.csproj', 'Lib component id') - check(comp(basic, 'Demo.Ext.Floating').get('version') == '1.1.0', 'floating 1.* resolves to 1.1.0') - check(comp(basic, 'Demo.Ext.Tool').get('dev') is None, 'Tool is prod') - check(comp(basic, 'Demo.Ext.Shared').get('dev') is None, 'Shared is prod') - for dev in ('Demo.Ext.Analyzer', 'Demo.Ext.TestSdk', 'Demo.Ext.Harness', 'Demo.Ext.HarnessCore'): - check(comp(basic, dev).get('dev') is True, f'{dev} is dev') - check(comp(basic, 'Demo.Ext.Analyzer').get('direct') is True, 'Analyzer is direct') - check(comp(basic, 'Demo.Ext.HarnessCore').get('direct') is None, 'HarnessCore is transitive') - check(bool(comps(basic, 'NETStandard.Library')), 'netstandard2.0 target read') - app = next(p for p in basic['projects'] if p['id'] == 'src/App/App.csproj') - check(app.get('manifestFiles') == [{'file': 'src/App/App.csproj'}], f'App manifestFiles {app.get("manifestFiles")}') - - cpm_facts = f'{CPM_ENTRY}.socket.facts.json' - cpm = load(cpm_facts) - common('cpm', cpm) - pinned = comp(cpm, 'Demo.Ext.Shared') - check(pinned.get('version') == '2.0.0' and not pinned.get('direct'), f'transitive pin: {pinned}') - check({c.get('version') for c in comps(cpm, 'Demo.Ext.Harness')} == {'1.0.0', '1.1.0'}, 'VersionOverride') - if SDK_MAJOR >= 7: - # GlobalPackageReference needs NuGet 6.4 (SDK 7.0.100). - analyzer = comp(cpm, 'Demo.Ext.Analyzer') - check(analyzer.get('direct') and analyzer.get('dev'), f'GlobalPackageReference: {analyzer}') - base = os.path.dirname(CPM_ENTRY) - core_id = os.path.relpath('cpm/src/Core/Core.csproj', base) - core = next((p for p in cpm['projects'] if p['id'] == core_id), {}) - files = {m['file'] for m in core.get('manifestFiles', [])} - want = {os.path.relpath(f, base) for f in ('cpm/Directory.Packages.props', 'cpm/src/Core/Core.csproj', 'cpm/src/Core/packages.lock.json')} - check(files == want, f'Core manifestFiles {files} != {want}') - - rid = load('rid/Rid.csproj.socket.facts.json') - check(bool(comps(rid, 'runtime.win-x64.Demo.Ext.Native')), 'runtime-specific package from runtime.json') - - pc = load('packages-config/Mixed.sln.socket.facts.json') - common('packages-config', pc) - legacy = next((p for p in pc['projects'] if p['id'] == 'Legacy/Legacy.csproj'), {}) - check({m['file'] for m in legacy.get('manifestFiles', [])} == {'Legacy/Legacy.csproj', 'Legacy/packages.config'}, f'Legacy manifestFiles {legacy}') - check(comp(pc, 'Demo.Ext.Shared', '1.0.0').get('direct') is True, 'packages.config versions normalize') - check(comp(pc, 'Demo.Ext.Analyzer').get('dev') is True, 'developmentDependency is dev') - check(comp(pc, 'Demo.Ext.Logging').get('direct') is True, 'Modern restored alongside Legacy') - - langs = load('langs/Vb/Vb.vbproj.socket.facts.json') - check(project_ids(langs) == ['../Fs/Fs.fsproj', 'Vb.vbproj'], f'langs projects {project_ids(langs)}') - check(bool(comps(langs, 'FSharp.Core')), 'implicit FSharp.Core') - - for rel in ('multi/One.sln', 'multi/Two.sln', 'multi/Stray.csproj'): - load(f'{rel}.socket.facts.json') - check(not os.path.exists(os.path.join(WORK, 'multi/One/One.csproj.socket.facts.json')), 'covered project built alone') - check(not os.path.exists(os.path.join(WORK, 'multi/One.slnx.socket.facts.json')), 'covered solution built again') - - for name, package in (('A', 'Demo.Ext.Tool'), ('B', 'Demo.Ext.Logging')): - pair = load(f'pair/{name}.csproj.socket.facts.json') - check(project_ids(pair) == [f'{name}.csproj'], f'pair {name} projects {project_ids(pair)}') - check(bool(comps(pair, package)), f'pair {name} resolves {package}') - - dev = load('dev/Dev.csproj.socket.facts.json') - for name, is_dev in (('Demo.Ext.Tool', None), ('Demo.Ext.Shared', None), ('Demo.Ext.Logging', True), ('Demo.Ext.Analyzer', True), ('Demo.Ext.Payload', None), ('Demo.Ext.BuildTool', True)): - check(comp(dev, name).get('dev') is is_dev, f'{name} dev={comp(dev, name).get("dev")}, want {is_dev}') - - load('sibling/sln/All.sln.socket.facts.json') - check(not os.path.exists(os.path.join(WORK, 'sibling/src/A/A.csproj.socket.facts.json')), 'project a sibling solution covers built alone') - - with open(os.path.join(WORK, 'missing.log')) as f: - log = f.read() - check('Demo.Ext.DoesNotExist' in log and 'NU1101' in log, 'missing package reported') - with open(os.path.join(WORK, 'broken.log')) as f: - log = f.read() - check(re.search(r'could not evaluate the project: MSB\d{4}: ', log), 'evaluation failure reported with its code') - - -def records(name): - rows = [] - with open(os.path.join(WORK, name)) as f: - for line in f: - rows.append(line.rstrip('\n').split('\t')) - return rows - - -def failures(rows): - return [r for r in rows if r[0] == 'failure'] - - -def records_phase(): - basic = records('basic.tsv') - check(not failures(basic), f'basic failures {failures(basic)}') - files = {r[2]: r[3] for r in basic if r[0] == 'file'} - check(any(k.startswith('demo.ext.tool:') for k in files), 'Tool assembly recorded') - check(not any(k.startswith('demo.ext.analyzer:') for k in files), 'analyzer has no runtime assembly') - check(all(os.path.exists(p) for p in files.values()), 'recorded assemblies exist') - lib_roots = [r for r in basic if r[0] == 'root' and r[2] == 'src/Lib/Lib.csproj'] - check({r[5] for r in lib_roots} == {'net6.0', 'netstandard2.0'}, f'root frameworks {[r[5] for r in lib_roots]}') - check(all(r[7] == r[3] for r in lib_roots), f'root aliases {[(r[3], r[7]) for r in lib_roots]}') - info = {(r[2], r[3], r[4]) for r in basic if r[0] == 'projectInfo' and r[1] == 'src/Lib/Lib.csproj'} - check(('net6.0', 'TargetFrameworkMoniker', '.NETCoreApp,Version=v6.0') in info, 'net6.0 moniker recorded') - check(('net6.0', 'DefineConstant', 'DEBUG') in info, 'evaluated symbols recorded') - check(('net6.0', 'FrameworkReference', 'Microsoft.NETCore.App') in info, 'framework reference recorded') - check(any(r[0] == 'compileFile' and r[2].startswith('demo.ext.tool:') for r in basic), 'compile assemblies recorded') - sources = [r[2] for r in basic if r[0] == 'projectSrc'] - check(any(s.endswith('/shared/Linked.cs') for s in sources), 'linked source recorded') - - netstandard = records('basic-netstandard.tsv') - built = {(r[1], r[3]) for r in netstandard if r[0] == 'projectSrc'} - built |= {(r[1], r[2]) for r in netstandard if r[0] == 'projectInfo'} - check(built and {c for _, c in built} == {'netstandard2.0'}, f'builds outside --include-configs {sorted(built)}') - - stale = records('basic-stale.tsv') - check(any(r[0] == 'failure' and 'Demo.Ext.DoesNotExist' in '\t'.join(r) for r in stale), 'failed restore reported') - reused = {r[2] for r in stale if r[0] == 'root'} - {'test/App.Tests/App.Tests.csproj'} - check(not reused, f'projects read from a previous restore {sorted(reused)}') - unknown = {r[3] for r in stale if r[0] == 'unscannable' and 'may have skipped this project' in r[2]} - check({'src/App/App.csproj', 'src/Extra/Extra.csproj', 'src/Lib/Lib.csproj'} <= unknown, f'unrestored projects reported {sorted(unknown)}') - - evaluation = records('evaluation.tsv') - faults = [r for r in evaluation if r[0] in ('failure', 'unscannable')] - check(not faults, f'evaluation faults {faults}') - lib = [r[2] for r in evaluation if r[0] == 'projectSrc' and r[1] == 'Lib/Lib.csproj'] - check(len(lib) == 1 and lib[0].endswith('/Lib/Class.cs'), f'sources of a project failing any target run {lib}') - check(any(r[0] == 'project' and r[1] == 'Build.csproj' for r in evaluation), 'compiler-less aggregator recorded') - - langs = records('langs.tsv') - vb = {r[4] for r in langs if r[0] == 'projectInfo' and r[1] == 'Vb.vbproj' and r[3] == 'DefineConstant'} - check({'DEBUG=-1', 'TRACE=-1'} <= vb, f'VB compiler constants {vb}') - fs = [r[2] for r in langs if r[0] == 'projectSrc' and r[1] == '../Fs/Fs.fsproj'] - check([os.path.basename(f) for f in fs] == ['First.fs', 'Library.fs'], f'F# sources in compile order {fs}') - - missing = records('pc-missing.tsv') - unfetched = {r[2] for r in missing if r[0] == 'unfetched'} - check(unfetched == {'demo.ext.tool:1.0.0', 'demo.ext.shared:1.0.0'}, f'unfetched {unfetched}') - check(len(failures(missing)) == 2, 'missing packages.config assemblies fail') - - present = records('pc-present.tsv') - check(not failures(present) and not any(r[0] == 'unfetched' for r in present), 'installed packages.config resolves') - legacy_roots = {(r[3], r[5], r[7]) for r in present if r[0] == 'root' and r[2] == 'Legacy/Legacy.csproj'} - check(legacy_roots == {('net48', 'net48', 'net48')}, f'Legacy roots (config, framework, alias) {legacy_roots}') - present_files = {r[2] for r in present if r[0] == 'file'} - check({'demo.ext.tool:1.0.0', 'demo.ext.shared:1.0.0'} <= present_files, f'packages.config files {present_files}') - - -def main(): - if PHASE == 'default': - default_phase() - elif PHASE == 'exclude-paths': - facts = load('basic/Basic.sln.socket.facts.json') - check('test/App.Tests/App.Tests.csproj' not in project_ids(facts), 'excluded project resolved') - check(not comps(facts, 'Demo.Ext.TestSdk'), 'excluded project dependencies emitted') - elif PHASE == 'include-configs': - facts = load('basic/Basic.sln.socket.facts.json') - check(not comps(facts, 'NETStandard.Library'), 'netstandard2.0 target read despite --include-configs') - elif PHASE == 'ignore-unresolved': - facts = load('failures/missing/Missing.csproj.socket.facts.json') - check(bool(comps(facts, 'Demo.Ext.Tool')), 'resolved dependency kept') - check(not comps(facts, 'Demo.Ext.DoesNotExist'), 'unresolved dependency emitted') - elif PHASE == 'records': - records_phase() - if problems: - print('\n'.join(f'FAIL [{PHASE}] {p}' for p in problems)) - sys.exit(1) - print(f'assert-facts: {PHASE} ok') - - -if __name__ == '__main__': - main() diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/Cpm.slnx b/src/commands/manifest/scripts/test/dotnet-compat/cpm/Cpm.slnx deleted file mode 100644 index 27e75ac299..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/Cpm.slnx +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Build.props b/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Build.props deleted file mode 100644 index f8602219c9..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Build.props +++ /dev/null @@ -1,5 +0,0 @@ - - - true - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Packages.props b/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Packages.props deleted file mode 100644 index b527d72133..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/Directory.Packages.props +++ /dev/null @@ -1,14 +0,0 @@ - - - true - true - - - - - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/A.cs b/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/A.cs deleted file mode 100644 index 9f4b93d846..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/A.cs +++ /dev/null @@ -1 +0,0 @@ -public class A {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/Api.csproj b/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/Api.csproj deleted file mode 100644 index 9b70774d4c..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/Api.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - net6.0 - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/C.cs b/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/C.cs deleted file mode 100644 index 9d83983cd6..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/C.cs +++ /dev/null @@ -1 +0,0 @@ -public class C {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/Core.csproj b/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/Core.csproj deleted file mode 100644 index ab46ffdf9b..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/Core.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - net6.0 - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/dev/Dev.csproj b/src/commands/manifest/scripts/test/dotnet-compat/dev/Dev.csproj deleted file mode 100644 index 34cdcb7262..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/dev/Dev.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - Exenet6.0 - - - - - - - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/dev/Program.cs b/src/commands/manifest/scripts/test/dotnet-compat/dev/Program.cs deleted file mode 100644 index 5aa94bea08..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/dev/Program.cs +++ /dev/null @@ -1 +0,0 @@ -System.Console.WriteLine(); diff --git a/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Build.csproj b/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Build.csproj deleted file mode 100644 index a504a68d34..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Build.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - PackageReference - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Class.cs b/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Class.cs deleted file mode 100644 index a7220561ed..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Class.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace Lib; - -public static class Class { } diff --git a/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Lib.csproj b/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Lib.csproj deleted file mode 100644 index 03cdb68c10..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/Lib.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - net6.0 - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/failures/broken/Broken.csproj b/src/commands/manifest/scripts/test/dotnet-compat/failures/broken/Broken.csproj deleted file mode 100644 index ea793a6528..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/failures/broken/Broken.csproj +++ /dev/null @@ -1,5 +0,0 @@ - - net6.0 - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/failures/missing/Missing.csproj b/src/commands/manifest/scripts/test/dotnet-compat/failures/missing/Missing.csproj deleted file mode 100644 index 4cd3dd9579..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/failures/missing/Missing.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - net6.0 - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/First.fs b/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/First.fs deleted file mode 100644 index 597f374f29..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/First.fs +++ /dev/null @@ -1,3 +0,0 @@ -module First - -let value = 1 diff --git a/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Fs.fsproj b/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Fs.fsproj deleted file mode 100644 index 15ac4e7ba2..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Fs.fsproj +++ /dev/null @@ -1,8 +0,0 @@ - - net6.0 - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Library.fs b/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Library.fs deleted file mode 100644 index c1dc68de8e..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/Library.fs +++ /dev/null @@ -1,2 +0,0 @@ -module Library -let x = 1 diff --git a/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/V.vb b/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/V.vb deleted file mode 100644 index 7780292ca8..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/V.vb +++ /dev/null @@ -1,2 +0,0 @@ -Public Class V -End Class diff --git a/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/Vb.vbproj b/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/Vb.vbproj deleted file mode 100644 index 4eaa39ccf2..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/Vb.vbproj +++ /dev/null @@ -1,7 +0,0 @@ - - net6.0 - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/make-stub-feed.py b/src/commands/manifest/scripts/test/dotnet-compat/make-stub-feed.py deleted file mode 100644 index 3ede820c73..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/make-stub-feed.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python3 -"""Generate a local NuGet feed of stub packages for the dotnet compat fixtures. - -Like ../make-stub-repo.sh for the JVM fixtures: the fixtures only need the -shape of a dependency graph, never the code, so each stub is a nuspec plus -empty files, generated at test time and never committed. - -Usage: make-stub-feed.py ... - spec = Id:Version[+DepId:DepRange,...][#flag,...] - flags: - analyzer no runtime assembly, only analyzers/dotnet/cs/.dll - test build/.props sets IsTestProject, as Microsoft.NET.Test.Sdk does - payload no assemblies; build/.targets and a native file it would copy - buildtool no assemblies; build/.targets, a developmentDependency - rid= its assembly is runtimes//lib/netstandard2.0/.dll only - runtime= runtime.json makes it depend on runtime.. for -""" -import os -import shutil -import sys -import zipfile -from xml.sax.saxutils import escape - - -def parse(spec): - flags = [] - if '#' in spec: - spec, flag_text = spec.split('#', 1) - flags = [f for f in flag_text.split(',') if f] - deps = [] - if '+' in spec: - spec, dep_text = spec.split('+', 1) - deps = [d.split(':', 1) for d in dep_text.split(',') if d] - pkg_id, version = spec.split(':', 1) - return pkg_id, version, deps, flags - - -def nuspec(pkg_id, version, deps, flags): - dep_xml = ''.join( - f'' for d, v in deps - ) - dev = ( - 'true' - if 'analyzer' in flags or 'buildtool' in flags - else '' - ) - return ( - '' - '' - f'{escape(pkg_id)}{escape(version)}' - f'socketstub{dev}' - f'{dep_xml}' - ) - - -def main(): - feed = sys.argv[1] - specs = sys.argv[2:] - if not specs: - sys.exit('make-stub-feed.py: no package specs given') - shutil.rmtree(feed, ignore_errors=True) - os.makedirs(feed) - for spec in specs: - pkg_id, version, deps, flags = parse(spec) - files = {f'{pkg_id}.nuspec': nuspec(pkg_id, version, deps, flags)} - rid = next((f[4:] for f in flags if f.startswith('rid=')), None) - runtime = next((f[8:] for f in flags if f.startswith('runtime=')), None) - if 'analyzer' in flags: - files[f'analyzers/dotnet/cs/{pkg_id}.dll'] = '' - elif 'payload' in flags or 'buildtool' in flags: - files[f'build/{pkg_id}.targets'] = '' - if 'payload' in flags: - files[f'build/x64/{pkg_id}.native.dll'] = '' - elif rid: - files[f'runtimes/{rid}/lib/netstandard2.0/{pkg_id}.dll'] = '' - files['lib/netstandard2.0/_._'] = '' - else: - files[f'lib/netstandard2.0/{pkg_id}.dll'] = '' - if 'test' in flags: - files[f'build/{pkg_id}.props'] = ( - 'true' - '' - ) - if runtime: - files['runtime.json'] = ( - '{"runtimes": {"%s": {"%s": {"runtime.%s.%s": "%s"}}}}' - % (runtime, pkg_id, runtime, pkg_id, version) - ) - path = os.path.join(feed, f'{pkg_id.lower()}.{version}.nupkg') - with zipfile.ZipFile(path, 'w') as z: - for name, content in files.items(): - z.writestr(name, content) - - -if __name__ == '__main__': - main() diff --git a/src/commands/manifest/scripts/test/dotnet-compat/multi/One.sln b/src/commands/manifest/scripts/test/dotnet-compat/multi/One.sln deleted file mode 100644 index 318b250197..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/multi/One.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "One", "One\One.csproj", "{D648480D-09A5-4D87-8AD2-35B88071DE76}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Debug|x64.ActiveCfg = Debug|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Debug|x64.Build.0 = Debug|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Debug|x86.ActiveCfg = Debug|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Debug|x86.Build.0 = Debug|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Release|Any CPU.Build.0 = Release|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Release|x64.ActiveCfg = Release|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Release|x64.Build.0 = Release|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Release|x86.ActiveCfg = Release|Any CPU - {D648480D-09A5-4D87-8AD2-35B88071DE76}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/commands/manifest/scripts/test/dotnet-compat/multi/One.slnx b/src/commands/manifest/scripts/test/dotnet-compat/multi/One.slnx deleted file mode 100644 index 94cd133150..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/multi/One.slnx +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/multi/One/One.csproj b/src/commands/manifest/scripts/test/dotnet-compat/multi/One/One.csproj deleted file mode 100644 index e040792f84..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/multi/One/One.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0 - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/multi/Stray.csproj b/src/commands/manifest/scripts/test/dotnet-compat/multi/Stray.csproj deleted file mode 100644 index ac11aa7666..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/multi/Stray.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0false - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/multi/Two.sln b/src/commands/manifest/scripts/test/dotnet-compat/multi/Two.sln deleted file mode 100644 index 17323f598b..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/multi/Two.sln +++ /dev/null @@ -1,48 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Two", "Two\Two.csproj", "{5FCA314C-9CC0-4773-9265-3DCE2F400D2C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "One", "One\One.csproj", "{2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Debug|x64.ActiveCfg = Debug|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Debug|x64.Build.0 = Debug|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Debug|x86.ActiveCfg = Debug|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Debug|x86.Build.0 = Debug|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Release|Any CPU.Build.0 = Release|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Release|x64.ActiveCfg = Release|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Release|x64.Build.0 = Release|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Release|x86.ActiveCfg = Release|Any CPU - {5FCA314C-9CC0-4773-9265-3DCE2F400D2C}.Release|x86.Build.0 = Release|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Debug|x64.ActiveCfg = Debug|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Debug|x64.Build.0 = Debug|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Debug|x86.ActiveCfg = Debug|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Debug|x86.Build.0 = Debug|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Release|Any CPU.Build.0 = Release|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Release|x64.ActiveCfg = Release|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Release|x64.Build.0 = Release|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Release|x86.ActiveCfg = Release|Any CPU - {2F89B4FD-FF70-42FE-87D0-46F2F5F94C42}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/commands/manifest/scripts/test/dotnet-compat/multi/Two/Two.csproj b/src/commands/manifest/scripts/test/dotnet-compat/multi/Two/Two.csproj deleted file mode 100644 index ab9c87f16a..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/multi/Two/Two.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0 - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/nuget.config b/src/commands/manifest/scripts/test/dotnet-compat/nuget.config deleted file mode 100644 index 1fdc15d43a..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/nuget.config +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Class1.cs b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Class1.cs deleted file mode 100644 index fadefcb685..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Class1.cs +++ /dev/null @@ -1 +0,0 @@ -namespace Legacy { public class Class1 {} } diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Legacy.csproj b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Legacy.csproj deleted file mode 100644 index 360e145667..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Legacy.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - - Debug - AnyCPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F} - Library - Legacy - v4.8 - bin\$(Configuration)\ - 17.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - ..\packages\Demo.Ext.Tool.1.0.0\lib\netstandard2.0\Demo.Ext.Tool.dll - - - ..\packages\Demo.Ext.Shared.1.0\lib\netstandard2.0\Demo.Ext.Shared.dll - - - - - - - - - - - - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Properties/AssemblyInfo.cs b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Properties/AssemblyInfo.cs deleted file mode 100644 index 6ca0988a3d..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Properties/AssemblyInfo.cs +++ /dev/null @@ -1 +0,0 @@ -[assembly: System.Reflection.AssemblyTitle("Legacy")] diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/packages.config b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/packages.config deleted file mode 100644 index 28f0b996eb..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Mixed.sln b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Mixed.sln deleted file mode 100644 index dd5c49a21a..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Mixed.sln +++ /dev/null @@ -1,48 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Legacy", "Legacy\Legacy.csproj", "{8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Modern", "Modern\Modern.csproj", "{547B8BBF-C848-4F81-83E2-82C1B62B9011}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Debug|x64.ActiveCfg = Debug|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Debug|x64.Build.0 = Debug|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Debug|x86.ActiveCfg = Debug|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Debug|x86.Build.0 = Debug|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Release|Any CPU.Build.0 = Release|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Release|x64.ActiveCfg = Release|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Release|x64.Build.0 = Release|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Release|x86.ActiveCfg = Release|Any CPU - {8E5C1B5E-0D7A-4C8C-9B0E-3B7A1C2D4E5F}.Release|x86.Build.0 = Release|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Debug|Any CPU.Build.0 = Debug|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Debug|x64.ActiveCfg = Debug|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Debug|x64.Build.0 = Debug|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Debug|x86.ActiveCfg = Debug|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Debug|x86.Build.0 = Debug|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Release|Any CPU.ActiveCfg = Release|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Release|Any CPU.Build.0 = Release|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Release|x64.ActiveCfg = Release|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Release|x64.Build.0 = Release|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Release|x86.ActiveCfg = Release|Any CPU - {547B8BBF-C848-4F81-83E2-82C1B62B9011}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/M.cs b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/M.cs deleted file mode 100644 index 9b4658fd8b..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/M.cs +++ /dev/null @@ -1 +0,0 @@ -public class M {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/Modern.csproj b/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/Modern.csproj deleted file mode 100644 index cb60089eef..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/Modern.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - net6.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v17.0 - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/pair/A.csproj b/src/commands/manifest/scripts/test/dotnet-compat/pair/A.csproj deleted file mode 100644 index 3a774aae0f..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/pair/A.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0false - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/pair/B.csproj b/src/commands/manifest/scripts/test/dotnet-compat/pair/B.csproj deleted file mode 100644 index 601838e75e..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/pair/B.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0false - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/rid/R.cs b/src/commands/manifest/scripts/test/dotnet-compat/rid/R.cs deleted file mode 100644 index 0f15cebabe..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/rid/R.cs +++ /dev/null @@ -1 +0,0 @@ -public class R {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/rid/Rid.csproj b/src/commands/manifest/scripts/test/dotnet-compat/rid/Rid.csproj deleted file mode 100644 index 937679614f..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/rid/Rid.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0linux-x64;win-x64 - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/sibling/sln/All.sln b/src/commands/manifest/scripts/test/dotnet-compat/sibling/sln/All.sln deleted file mode 100644 index a2724ed1a1..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/sibling/sln/All.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "A", "..\src\A\A.csproj", "{DC04A8EA-230D-4A3A-93BE-416D33654BEB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Debug|x64.ActiveCfg = Debug|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Debug|x64.Build.0 = Debug|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Debug|x86.ActiveCfg = Debug|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Debug|x86.Build.0 = Debug|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Release|Any CPU.Build.0 = Release|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Release|x64.ActiveCfg = Release|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Release|x64.Build.0 = Release|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Release|x86.ActiveCfg = Release|Any CPU - {DC04A8EA-230D-4A3A-93BE-416D33654BEB}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.cs b/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.cs deleted file mode 100644 index 9f4b93d846..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.cs +++ /dev/null @@ -1 +0,0 @@ -public class A {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.csproj b/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.csproj deleted file mode 100644 index e040792f84..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/A.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0 - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/smoke-test.sh b/src/commands/manifest/scripts/test/dotnet-compat/smoke-test.sh deleted file mode 100755 index fb6cd09342..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/smoke-test.sh +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env bash -# Runs the built CLI's `socket manifest dotnet` over the fixtures with one .NET -# SDK and checks the facts against `dotnet list package` and assert-facts.py. -# -# Usage: smoke-test.sh [sdk-version] -# sdk-version pins the SDK with a global.json, as a project would. -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -DOTNET="${1:?usage: smoke-test.sh [sdk-version]}" -SDK="${2:-}" -# shellcheck source=SCRIPTDIR/lib.sh -. "$HERE/lib.sh" -CLI="$REPO/bin/cli.js" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" - -export NUGET_PACKAGES="$SOCKET_COMPAT_CACHE/nuget-packages" -export NUGET_HTTP_CACHE_PATH="$SOCKET_COMPAT_CACHE/nuget-http" -# Stubs are regenerated per run under the same versions, so no stale copy -# may survive in the package folder. -rm -rf "$NUGET_PACKAGES"/demo.* "$NUGET_PACKAGES"/runtime.win-x64.demo.* - -WORK="$(mktemp -d)" -trap 'rm -rf "$WORK"' EXIT -# A copy per run keeps obj/, lock files and global.json out of the source tree. -copy_fixture "$WORK" . -python3 "$HERE/make-stub-feed.py" "$WORK/stub-feed" \ - 'Demo.Ext.Tool:1.0.0+Demo.Ext.Shared:1.0.0' \ - 'Demo.Ext.Shared:1.0.0' \ - 'Demo.Ext.Shared:2.0.0' \ - 'Demo.Ext.Logging:1.0.0+Demo.Ext.Shared:1.0.0' \ - 'Demo.Ext.Harness:1.0.0+Demo.Ext.HarnessCore:1.0.0' \ - 'Demo.Ext.Harness:1.1.0+Demo.Ext.HarnessCore:1.0.0' \ - 'Demo.Ext.HarnessCore:1.0.0' \ - 'Demo.Ext.TestSdk:1.0.0#test' \ - 'Demo.Ext.Analyzer:1.0.0#analyzer' \ - 'Demo.Ext.Payload:1.0.0#payload' \ - 'Demo.Ext.BuildTool:1.0.0#buildtool' \ - 'Demo.Ext.Floating:1.0.0' \ - 'Demo.Ext.Floating:1.1.0' \ - 'Demo.Ext.Native:1.0.0#runtime=win-x64' \ - 'runtime.win-x64.Demo.Ext.Native:1.0.0#rid=win-x64' -pin_sdk "$WORK" "$SDK" -echo "+ dotnet SDK $SDK_VERSION" - -socket_dotnet() { - node "$CLI" manifest dotnet --bin "$DOTNET" "$@" -} -expect_fail() { - local log="$WORK/fail.log" - if socket_dotnet "$@" >"$log" 2>&1; then - cat "$log" - echo "expected failure: socket manifest dotnet $*" >&2 - exit 1 - fi - cat "$log" -} - -# .slnx needs SDK 9.0.200; older SDKs build the solution's top project. -CPM_ENTRY="cpm/Cpm.slnx" -python3 -c 'import sys; v=[int(x) for x in sys.argv[1].split("-")[0].split(".")]; sys.exit(0 if (v[0], v[2]) >= (9, 200) else 1)' "$SDK_VERSION" \ - || CPM_ENTRY="cpm/src/Api/Api.csproj" - -socket_dotnet "$WORK/basic" -socket_dotnet "$WORK/$CPM_ENTRY" -# The lock files the first restore wrote now pin the second. -socket_dotnet "$WORK/$CPM_ENTRY" --dotnet-opts=--locked-mode -socket_dotnet "$WORK/rid" -socket_dotnet "$WORK/packages-config" -socket_dotnet "$WORK/langs/Vb/Vb.vbproj" -socket_dotnet "$WORK/multi" -socket_dotnet "$WORK/pair" -socket_dotnet "$WORK/dev" -# Recursive discovery, configured through socket.json: a solution in a -# sibling folder covers its projects. -printf '{"version": 1, "defaults": {"manifest": {"dotnet": {"bin": "%s"}}}}\n' "$DOTNET" > "$WORK/sibling/socket.json" -node "$CLI" manifest dynamic-sbom-inference "$WORK/sibling" -expect_fail "$WORK/failures/missing" > "$WORK/missing.log" -expect_fail "$WORK/failures/broken" > "$WORK/broken.log" -python3 "$HERE/assert-facts.py" "$WORK" "$SDK_VERSION" "$CPM_ENTRY" - -if python3 -c 'import sys; v=[int(x) for x in sys.argv[1].split("-")[0].split(".")]; sys.exit(0 if (v[0], v[2]) >= (7, 200) else 1)' "$SDK_VERSION"; then - # `dotnet list package` reports no runtime-specific targets. - for entry in basic/Basic.sln "$CPM_ENTRY" langs/Vb/Vb.vbproj multi/One.sln multi/Two.sln multi/Stray.csproj; do - socket_dotnet "$WORK/$entry" --exclude-configs '*/*' >/dev/null 2>&1 - ( cd "$WORK" && python3 "$HERE/assert-dotnet-list.py" "$entry.socket.facts.json" "$entry" "$DOTNET" ) - done -fi - -# Option handling, on fresh copies of the facts. -socket_dotnet "$WORK/basic" --exclude-paths test -python3 "$HERE/assert-facts.py" "$WORK" "$SDK_VERSION" "$CPM_ENTRY" exclude-paths -socket_dotnet "$WORK/basic" --include-configs net6.0 -python3 "$HERE/assert-facts.py" "$WORK" "$SDK_VERSION" "$CPM_ENTRY" include-configs -socket_dotnet "$WORK/failures/missing" --ignore-unresolved -python3 "$HERE/assert-facts.py" "$WORK" "$SDK_VERSION" "$CPM_ENTRY" ignore-unresolved - -# --with-files: the records the reachability sidecar is built from. -records() { - run_tool "$(dirname "$1")" --records "$2" --entry "$1" --with-files "${@:3}" -} -records "$WORK/basic/Basic.sln" "$WORK/basic-netstandard.tsv" --include-configs netstandard2.0 -records "$WORK/basic/Basic.sln" "$WORK/basic.tsv" -records "$WORK/langs/Vb/Vb.vbproj" "$WORK/langs.tsv" -records "$WORK/evaluation/Build.csproj" "$WORK/evaluation.tsv" -records "$WORK/packages-config/Mixed.sln" "$WORK/pc-missing.tsv" -# What `nuget restore` lays out for packages.config: .. -python3 - "$WORK" <<'PY' -import os, sys, zipfile -work = sys.argv[1] -for pkg_id, version, folder in (('Demo.Ext.Tool', '1.0.0', '1.0.0'), ('Demo.Ext.Shared', '1.0.0', '1.0'), ('Demo.Ext.Analyzer', '1.0.0', '1.0.0')): - nupkg = os.path.join(work, 'stub-feed', f'{pkg_id.lower()}.{version}.nupkg') - zipfile.ZipFile(nupkg).extractall(os.path.join(work, 'packages-config', 'packages', f'{pkg_id}.{folder}')) -PY -records "$WORK/packages-config/Mixed.sln" "$WORK/pc-present.tsv" -# A restore failing in one project leaves the others' caches as the last -# restore wrote them, which cannot show they are current. -python3 - "$WORK/basic/test/App.Tests/App.Tests.csproj" <<'PY' -import sys -path = sys.argv[1] -with open(path) as f: - project = f.read() -with open(path, 'w') as f: - f.write(project.replace('', '')) -PY -records "$WORK/basic/Basic.sln" "$WORK/basic-stale.tsv" -python3 "$HERE/assert-facts.py" "$WORK" "$SDK_VERSION" "$CPM_ENTRY" records - -echo "dotnet compat smoke test passed: SDK $SDK_VERSION" diff --git a/src/commands/manifest/scripts/test/gradle-compat/.gitignore b/src/commands/manifest/scripts/test/gradle-compat/.gitignore index 176f55a41a..4369ca91c7 100644 --- a/src/commands/manifest/scripts/test/gradle-compat/.gitignore +++ b/src/commands/manifest/scripts/test/gradle-compat/.gitignore @@ -1,15 +1,4 @@ -# generated at test time -project/localrepo/ -project/records.tsv +# Generated at test time. project/workspaces-records.tsv -project/.socket.facts.json project/.gradle/ project/build/ -.populate-for.txt -failures/localrepo/ -failures/records.tsv -failures/.gradle/ -failures/build/ -failures/lib/build/ -failures/app/build/ -failures/categories.tsv diff --git a/src/commands/manifest/scripts/test/gradle-compat/README.md b/src/commands/manifest/scripts/test/gradle-compat/README.md deleted file mode 100644 index e8c3625cea..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Gradle-version compatibility smoke test - -`socket-facts.init.gradle` must run across a very wide Gradle range. It uses several -reflective shims so it degrades gracefully on Gradle older than its modern target: - -- `socketProp` (hasProperty/property) instead of `Project.findProperty` (Gradle 2.13+) -- a reflective `isResolvable` probe instead of `Configuration.isCanBeResolved` (Gradle 3.3+) -- a `try`/`catch` fallback to the `Spec`-taking `getFirstLevelModuleDependencies(Spec)` when the - no-arg overload is absent (Gradle 3.3+) - -Those fallback branches never execute on modern Gradle, so without a test on *old* Gradle they -could silently rot. This smoke test exercises them. - -## What it does -`smoke-test.sh ` generates a tiny **local** Maven repo (`../make-stub-repo.sh` — two -transitive-free artifacts, a prod `demo.lib:foo` and a test `demo.test:bar`), runs the init script's -`socketFacts` task against `project/` **fully offline**, and asserts the emitted RECORDS (the script's -only output — the TS assembler that turns records into `.socket.facts.json` is covered by -`nx test utils`): exactly the two expected dependency nodes, `foo` in a prod root, `bar` only in -non-prod roots, and an on-disk jar `file` record for each under `-Psocket.withFiles`. - -A local repo (not Maven Central) is essential: Gradle 1.x/2.x can't negotiate modern Maven Central's -TLS, so only an offline local repo makes the old-version matrix entries testable at all. - -## Running locally -```bash -curl -fsSL https://services.gradle.org/distributions/gradle-2.14.1-bin.zip -o g.zip && unzip -q g.zip -JAVA_HOME= ./smoke-test.sh "$PWD/gradle-2.14.1/bin/gradle" -``` -CI runs it (and the SBT equivalent) across a label-gated matrix in -`.github/workflows/manifest-scripts-compat.yml` — add the `manifest-scripts` label to a PR to run it. diff --git a/src/commands/manifest/scripts/test/gradle-compat/failures/app/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/failures/app/build.gradle deleted file mode 100644 index 6dc323bcab..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/failures/app/build.gradle +++ /dev/null @@ -1,8 +0,0 @@ -// Kept out of the root project: on some old Gradle, a project dependency on a missing configuration -// fails resolving the declaring project's other configurations too. -configurations { - projectFail -} -dependencies { - projectFail project(path: ':lib', configuration: 'nonexistent') -} diff --git a/src/commands/manifest/scripts/test/gradle-compat/failures/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/failures/build.gradle deleted file mode 100644 index cdc64bb0fa..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/failures/build.gradle +++ /dev/null @@ -1,64 +0,0 @@ -// Hermetic fixture for ../smoke-test-failures.sh: each configuration fails to resolve in one way, -// against a generated local Maven repo (see ../../make-stub-repo.sh). -allprojects { - repositories { - maven { url rootProject.file('localrepo').toURI() } - } -} - -configurations { - forced - shadowing - verified - walkAborted - quiet - unparsed -} -configurations.forced.resolutionStrategy.force 'demo:c:9.9' - -dependencies { - forced 'demo:a:1.0' - // Shares the group:name of project :lib, but is an external module. - shadowing 'demo:lib:7.7' - verified 'demo:a:1.0' - verified 'demo:tampered:1.0' - verified 'demo:unlisted:1.0' - walkAborted 'demo:a:1.0' - walkAborted 'demo:boom:1.0' - quiet 'demo:quiet:1.0' - unparsed 'demo:a:1.0' -} - -// Artifact transforms and dependency verification exist only on newer Gradle. -if (org.gradle.util.GradleVersion.current() >= org.gradle.util.GradleVersion.version('6.2')) { - apply from: 'transforms.gradle' -} - -// No build throws from the walk's own reads on demand, so make two of them throw for one module -// each: boom's children, and quiet's file with an empty message. unparsed's verification read -// fails with a message that names no artifact. -tasks.matching { it.name == 'socketFactsCollect' }.all { t -> - t.doFirst { - def boom = configurations.walkAborted.resolvedConfiguration.firstLevelModuleDependencies.find { it.moduleName == 'boom' } - def depMeta = boom.getClass().metaClass - def children = depMeta.getMetaMethod('getChildren', [] as Object[]) - depMeta.getChildren = { -> - if (delegate.moduleName == 'boom') { - throw new IllegalStateException('walk aborted by the fixture') - } - children.invoke(delegate) - } - def quiet = configurations.quiet.resolvedConfiguration.resolvedArtifacts.find { it.name == 'quiet' } - def artifactMeta = quiet.getClass().metaClass - def file = artifactMeta.getMetaMethod('getFile', [] as Object[]) - artifactMeta.getFile = { -> - if (delegate.name == 'quiet') { - throw new RuntimeException('') - } - file.invoke(delegate) - } - configurations.unparsed.incoming.metaClass.artifactView = { Closure spec -> - throw new GradleException("Dependency verification failed for configuration ':unparsed'") - } - } -} diff --git a/src/commands/manifest/scripts/test/gradle-compat/failures/gradle/verification-metadata.xml b/src/commands/manifest/scripts/test/gradle-compat/failures/gradle/verification-metadata.xml deleted file mode 100644 index e79d509a0f..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/failures/gradle/verification-metadata.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - false - false - - - - - - - - - - - - diff --git a/src/commands/manifest/scripts/test/gradle-compat/failures/lib/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/failures/lib/build.gradle deleted file mode 100644 index 82fbf7fc9f..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/failures/lib/build.gradle +++ /dev/null @@ -1,3 +0,0 @@ -apply plugin: 'java' -group = 'demo' -version = '3.0' diff --git a/src/commands/manifest/scripts/test/gradle-compat/failures/settings.gradle b/src/commands/manifest/scripts/test/gradle-compat/failures/settings.gradle deleted file mode 100644 index 53f191a18a..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/failures/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'gradle-compat-failures' -include 'lib', 'app' diff --git a/src/commands/manifest/scripts/test/gradle-compat/failures/transforms.gradle b/src/commands/manifest/scripts/test/gradle-compat/failures/transforms.gradle deleted file mode 100644 index e688dc60e1..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/failures/transforms.gradle +++ /dev/null @@ -1,25 +0,0 @@ -// Two transforms producing the same artifact type, so selecting a `foo` artifact is ambiguous even -// though the graph resolves. -abstract class IdentityOne implements org.gradle.api.artifacts.transform.TransformAction { - @org.gradle.api.artifacts.transform.InputArtifact - abstract Provider getInputArtifact() - void transform(org.gradle.api.artifacts.transform.TransformOutputs outputs) { outputs.file(inputArtifact.get().asFile) } -} -abstract class IdentityTwo implements org.gradle.api.artifacts.transform.TransformAction { - @org.gradle.api.artifacts.transform.InputArtifact - abstract Provider getInputArtifact() - void transform(org.gradle.api.artifacts.transform.TransformOutputs outputs) { outputs.file(inputArtifact.get().asFile) } -} -def artifactType = Attribute.of('artifactType', String) -dependencies { - registerTransform(IdentityOne) { from.attribute(artifactType, 'jar'); to.attribute(artifactType, 'foo') } - registerTransform(IdentityTwo) { from.attribute(artifactType, 'jar'); to.attribute(artifactType, 'foo') } -} -configurations { - ambiguous { - attributes { attribute(artifactType, 'foo') } - } -} -dependencies { - ambiguous 'demo:a:1.0' -} diff --git a/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle index 06a7e6911c..b14a29e089 100644 --- a/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle +++ b/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle @@ -1,22 +1,4 @@ -// Hermetic smoke-test project for ../../socket-facts.init.gradle. -// -// Resolves two artifacts from a generated local Maven repo (see ../../make-stub-repo.sh) -// so it runs fully OFFLINE on every Gradle version — including pre-3.3, which the -// script must still support (old Gradle can't negotiate modern Maven Central's TLS, -// so a network repo would make the old-version matrix entries impossible to test). +// Smoke project for ../../socket-workspaces.init.gradle. apply plugin: 'java' group = 'demo' version = '1.0.0' - -repositories { - maven { url file('localrepo').toURI() } -} - -// `compile`/`testCompile` were removed in Gradle 7; `implementation`/`testImplementation` -// arrived in 3.4. Pick the pair that exists on the running Gradle so this one build -// script spans Gradle 1.x through 9.x. -def modern = org.gradle.util.GradleVersion.current() >= org.gradle.util.GradleVersion.version('3.4') -dependencies { - add(modern ? 'implementation' : 'compile', 'demo.lib:foo:1.0') // production dep - add(modern ? 'testImplementation' : 'testCompile', 'demo.test:bar:1.0') // test (dev) dep -} diff --git a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-failures.sh b/src/commands/manifest/scripts/test/gradle-compat/smoke-test-failures.sh deleted file mode 100644 index ff1ef43a3f..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-failures.sh +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env bash -# Run socket-facts.init.gradle against the `failures` project, whose configurations each fail to -# resolve in one way, and assert every failure is reported and no partial or fabricated component -# is emitted: -# - a forced version that doesn't exist is reported as that version, not the one requested; -# - a failed project dependency, and an external module sharing a project's group:name, are reported; -# - an artifact failing dependency verification (Gradle 6.2+) is reported and has no file, a missing -# checksum as non-blocking and a mismatch as blocking, and one whose report names no artifact -# leaves the configuration unscannable but keeps its graph, without files; -# - a module whose artifact can't be selected is reported with no component, with or without -# --with-files; -# - a walk that throws midway leaves no resolution root, only an unscannable configuration; -# - a file that can't be read with an empty message is reported like any other. -# -# Usage: smoke-test-failures.sh /path/to/gradle -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -GRADLE="${1:?usage: smoke-test-failures.sh }" -INIT="$HERE/../../socket-facts.init.gradle" -CLASSIFY="$HERE/../../resolution-report-gradle.mts" -RECORDS_PARSER="$HERE/../../records.mts" -PROJECT="$HERE/failures" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -GUH="$SOCKET_COMPAT_CACHE/gradle-home" - -bash "$HERE/../make-stub-repo.sh" "$PROJECT/localrepo" \ - 'demo:a:1.0+demo:c:1.0' 'demo:c:1.0' 'demo:boom:1.0+demo:c:1.0' 'demo:quiet:1.0' 'demo:tampered:1.0' 'demo:unlisted:1.0' - -run() { - rm -rf "$GUH" "$RECORDS" "$PROJECT/.gradle" "$PROJECT/build" "$PROJECT/lib/build" "$PROJECT/app/build" - ( cd "$PROJECT" && "$GRADLE" --no-daemon --offline -g "$GUH" \ - --init-script "$INIT" -Porg.gradle.dependency.verification.console=verbose \ - -Psocket.recordsFile="$RECORDS" "$@" socketFacts -q ) > /dev/null -} - -# The category the Socket CLI gives each failure record, as "configcoordcategory" lines. -categories() { - node --input-type=module -e ' - import { readFileSync } from "node:fs" - import { parseRecords } from "'"$RECORDS_PARSER"'" - import { classifyGradleFailure } from "'"$CLASSIFY"'" - for (const f of parseRecords(readFileSync(process.argv[1], "utf8")).failures) { - console.log([f.config, f.coord, classifyGradleFailure(f.detail)].join("\t")) - }' "$RECORDS" -} - -echo "+ $("$GRADLE" --version 2>/dev/null | sed -n 's/^Gradle //p' | head -1) (failures)" -for files in true false; do - run -Psocket.withFiles="$files" - categories > "$PROJECT/categories.tsv" - python3 - "$RECORDS" "$files" "$PROJECT/categories.tsv" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -with_files = sys.argv[2] == 'true' -categories = {} -for l in open(sys.argv[3]): - if l.strip(): - config, coord, category = l.rstrip('\n').split('\t') - categories.setdefault((config, coord), set()).add(category) -version = next(r[2] for r in rows if r[0] == 'meta') -modern = tuple(int(p) for p in version.split('.')[:2]) >= (6, 2) -roots = {r[1]: r[3] for r in rows if r[0] == 'root'} -nodes = {(roots[r[1]], r[2]): r for r in rows if r[0] == 'node'} -files = {(roots[r[1]], r[2]) for r in rows if r[0] == 'file'} -unfetched = {(roots[r[1]], r[2]) for r in rows if r[0] == 'unfetched'} -failures = {(r[3], r[1]) for r in rows if r[0] == 'failure'} -unscannable = {r[1] for r in rows if r[0] == 'unscannable'} -errors = [] - -def expect(cond, msg): - if not cond: - errors.append(msg) - -expect(('forced', 'demo:c:9.9') in failures, f"forced: missing failure for the forced demo:c:9.9: {sorted(failures)}") -expect(('forced', 'demo:c:1.0') not in failures, "forced: failure names the requested demo:c:1.0, not the attempted 9.9") -# Old Gradle fails the whole configuration instead of the one dependency. -expect(('projectFail', 'demo:lib:3.0') in failures or 'projectFail' in unscannable, - f"projectFail: failed project dependency not reported: {sorted(failures)}") -expect(('shadowing', 'demo:lib:7.7') in failures, f"shadowing: external module sharing :lib's group:name not reported: {sorted(failures)}") -expect(not [n for n in nodes.values() if not n[6]], f"ext-less component emitted: {[n[2] for n in nodes.values() if not n[6]]}") -expect('walkAborted' in unscannable, f"walkAborted: walk that threw not reported unscannable: {sorted(unscannable)}") -expect('walkAborted' not in roots.values(), "walkAborted: partial tree of a walk that threw was emitted") -if modern: - # Only some Gradle versions select legacy-API artifacts through the transforms; the others return - # the untransformed jar. Either way, a module is emitted with an artifact or reported, never both. - ambiguous = [k for k in nodes if k[0] == 'ambiguous'] - reported = ('ambiguous', 'demo:a:1.0') in failures - expect(reported != bool(ambiguous), f"ambiguous: components {ambiguous}, reported={reported}") - if reported: - expect(categories[('ambiguous', 'demo:a:1.0')] == {'variant-ambiguity'}, - f"ambiguous: classified {categories[('ambiguous', 'demo:a:1.0')]}, not variant-ambiguity") - -tampered = ('verified', 'demo:tampered:jar:1.0') -unlisted = ('verified', 'demo:unlisted:jar:1.0') -if with_files: - expect(('quiet', 'demo:quiet:1.0') in failures, f"quiet: unreadable file not reported: {sorted(failures)}") - expect(('quiet', 'demo:quiet:jar:1.0') in unfetched, f"quiet: unreadable file not marked unfetched: {sorted(unfetched)}") - expect('quiet' not in unscannable, "quiet: unreadable file sank the whole configuration") - expect(('verified', 'demo:a:jar:1.0') in files, f"verified: trusted demo:a has no file: {sorted(files)}") - if modern: - expect(('verified', 'demo:tampered:1.0') in failures, f"verified: verification failure not reported: {sorted(failures)}") - expect(tampered in unfetched, f"verified: tampered jar not marked unfetched: {sorted(unfetched)}") - expect(tampered not in files, "verified: tampered jar emitted as a file") - expect(categories.get(('verified', 'demo:tampered:1.0')) == {'other'}, - f"verified: checksum mismatch not blocking: {categories.get(('verified', 'demo:tampered:1.0'))}") - expect(unlisted in unfetched and unlisted not in files, "verified: unlisted jar not marked unfetched") - expect(categories.get(('verified', 'demo:unlisted:1.0')) == {'checksum-missing'}, - f"verified: missing checksum not non-blocking: {categories.get(('verified', 'demo:unlisted:1.0'))}") - expect('unparsed' in unscannable, f"unparsed: unparseable verification failure not reported: {sorted(unscannable)}") - expect(('unparsed', 'demo:a:jar:1.0') in nodes, "unparsed: graph dropped for an unparseable verification failure") - expect(('unparsed', 'demo:a:jar:1.0') in unfetched and ('unparsed', 'demo:a:jar:1.0') not in files, - "unparsed: files kept despite an unparseable verification failure") - else: - expect(tampered in files, "verified: no verification before Gradle 6.2, so the jar must materialize") -else: - expect(not files and not unfetched, "file or unfetched record emitted without --with-files") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS (failures, withFiles={sys.argv[2]}): every failure reported, no partial or fabricated component") -PY - assemble_records "$RECORDS" -done diff --git a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh index 387800111c..870bdc4342 100755 --- a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh +++ b/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh @@ -1,9 +1,7 @@ #!/usr/bin/env bash -# Run socket-workspaces.init.gradle (the lightweight workspace-enumeration sibling of -# socket-facts.init.gradle) against the smoke project and assert it emits exactly the expected -# project record - no dependency resolution, no node/root/file records at all. Guards, across the -# same Gradle compat matrix as the facts script, that the socketWorkspaces task registers and runs -# cleanly. +# Run socket-workspaces.init.gradle against the smoke project and assert it emits exactly the +# expected project record - no dependency resolution, no node/root/file records at all. Guards, +# across the Gradle compat matrix, that the socketWorkspaces task registers and runs cleanly. # # Usage: smoke-test-workspaces.sh /path/to/gradle set -euo pipefail diff --git a/src/commands/manifest/scripts/test/gradle-compat/smoke-test.sh b/src/commands/manifest/scripts/test/gradle-compat/smoke-test.sh deleted file mode 100755 index 08ff69c888..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/smoke-test.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env bash -# Run socket-facts.init.gradle against the hermetic local-repo project on a given Gradle binary and -# assert it emits the expected RECORDS (the script's only output now — the TS assembler turns these -# into .socket.facts.json and is tested separately in `nx test utils`). Guards, across the supported -# Gradle range, that the reflective old-Gradle shims (findProperty / canBeResolved / -# firstLevelModuleDependencies) keep producing correct facts: -# - exactly the two expected dependency nodes, demo.lib:foo + demo.test:bar; -# - foo (prod) appears in a prod root, bar (test) only in non-prod roots -> the assembler's dev flag; -# - every resolved dependency gets an on-disk jar `file` record under -Psocket.withFiles (incl. the -# production dep reached via the legacy `compile` config on old Gradle); -# - its records assemble into facts with no orphaned components; -# - -Psocket.populateFilesFor scopes materialization to a single GAV; -# - a jar that cannot be fetched is reported as a failure, and the other jars still materialize. -# -# Usage: smoke-test.sh /path/to/gradle -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -GRADLE="${1:?usage: smoke-test.sh }" -INIT="$HERE/../../socket-facts.init.gradle" -PROJECT="$HERE/project" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -GUH="$SOCKET_COMPAT_CACHE/gradle-home" # isolated Gradle user home -> hermetic, no global init scripts - -bash "$HERE/../make-stub-repo.sh" "$PROJECT/localrepo" 'demo.lib:foo:1.0' 'demo.test:bar:1.0' - -run() { - rm -rf "$GUH" "$RECORDS" "$PROJECT/.gradle" "$PROJECT/build" - ( cd "$PROJECT" && "$GRADLE" --no-daemon --offline -g "$GUH" \ - --init-script "$INIT" -Psocket.withFiles=true -Psocket.recordsFile="$RECORDS" "$@" socketFacts -q ) -} - -echo "+ $("$GRADLE" --version 2>/dev/null | sed -n 's/^Gradle //p' | head -1)" -run - -python3 - "$RECORDS" 'full' <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -scoped = sys.argv[2] == 'scoped' -roots, nodes, files = {}, {}, {} -for r in rows: - if r[0] == 'root': roots[r[1]] = (r[4] == '1') # rootId -> prod - elif r[0] == 'node': nodes.setdefault(r[2], set()).add(r[1]) # coordId -> {rootId} - elif r[0] == 'file': files.setdefault(r[2], set()).add(r[3]) # coordId -> {path} -errors = [] - -foo, bar = 'demo.lib:foo:jar:1.0', 'demo.test:bar:jar:1.0' -if sorted(nodes) != [foo, bar]: - errors.append(f"nodes {sorted(nodes)} != expected {[foo, bar]}") -# prod/dev is derived by the assembler from which roots a node appears in: foo in a prod root, -# bar only in non-prod (test) roots. -if foo in nodes and not any(roots.get(rid) for rid in nodes[foo]): - errors.append("production dep foo not present in any prod root") -if bar in nodes and any(roots.get(rid) for rid in nodes[bar]): - errors.append("test dep bar wrongly present in a prod root") - -def has_jar(cid): return any(p.endswith('.jar') for p in files.get(cid, ())) -# foo is always materialized; bar only on the unscoped run. -if not has_jar(foo): - errors.append(f"foo missing materialized jar under --with-files: {files.get(foo)}") -if scoped: - if has_jar(bar): errors.append(f"scoped run: bar (out of scope) was materialized: {files.get(bar)}") -else: - if not has_jar(bar): errors.append(f"bar missing materialized jar under --with-files: {files.get(bar)}") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS ({'scoped' if scoped else 'full'}): nodes {sorted(nodes)}; foo prod+jar; bar dev" - + ("; bar skipped" if scoped else "; bar jar")) -PY - -assemble_records "$RECORDS" - -# Second run: scope --with-files to a single GAV and assert ONLY that artifact is materialized. -SCOPE="$HERE/.populate-for.txt" -printf 'demo.lib:foo:1.0\n' > "$SCOPE" -run -Psocket.populateFilesFor="$SCOPE" -rm -f "$SCOPE" - -python3 - "$RECORDS" 'scoped' <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -files = {} -for r in rows: - if r[0] == 'file': files.setdefault(r[2], set()).add(r[3]) -errors = [] -if not any(p.endswith('.jar') for p in files.get('demo.lib:foo:jar:1.0', ())): - errors.append(f"scoped run: foo (in scope) not materialized: {files.get('demo.lib:foo:jar:1.0')}") -if files.get('demo.test:bar:jar:1.0'): - errors.append(f"scoped run: bar (out of scope) was materialized: {files.get('demo.test:bar:jar:1.0')}") -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print("PASS (populateFilesFor scoping): foo materialized, bar skipped") -PY - -assemble_records "$RECORDS" - -# Third run: bar's jar is gone from the repository, so it must be reported rather than emitted as -# resolved with no file. -find "$PROJECT/localrepo/demo/test/bar" -name '*.jar' -delete -run > /dev/null - -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -files = {r[2] for r in rows if r[0] == 'file'} -failures = {r[1] for r in rows if r[0] == 'failure'} -unfetched = {r[2] for r in rows if r[0] == 'unfetched'} -errors = [] -if 'demo.lib:foo:jar:1.0' not in files: - errors.append(f"missing jar run: foo must still be materialized: {sorted(files)}") -if 'demo.test:bar:1.0' not in failures: - errors.append(f"missing jar run: bar's jar cannot be fetched, so it must be reported: {sorted(failures)}") -if unfetched != {'demo.test:bar:jar:1.0'}: - errors.append(f"missing jar run: only bar's jar is unfetched: {sorted(unfetched)}") -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print("PASS (missing jar): bar reported, foo materialized") -PY diff --git a/src/commands/manifest/scripts/test/make-stub-repo.sh b/src/commands/manifest/scripts/test/make-stub-repo.sh deleted file mode 100755 index f6ef753024..0000000000 --- a/src/commands/manifest/scripts/test/make-stub-repo.sh +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env bash -# Generate a hermetic file-based Maven repository of stub artifacts for the JVM compat fixtures. -# Each stub gets a .pom and an empty-but-valid .jar in standard repo layout, so a build tool can -# resolve the declared graph shape without reaching a network repository. The fixtures never compile -# against or execute these artifacts — only their coordinates and scopes are observed — so stubs are -# behaviourally identical to the real thing here, and they can never age into a CVE or a version bump. -# -# Text-only in git: everything under is produced at test time and gitignored. -# -# Usage: make-stub-repo.sh ... -# spec = group:artifact:version[+dep-group:dep-artifact:dep-version[,...]] -# Deps listed after `+` are written as compile-scope dependencies of that stub, so a consumer that -# depends on the stub also pulls them transitively; `dep@scope` writes that scope instead. -# spec = group:artifact:version>new-group:new-artifact:new-version writes a POM that relocates the -# stub to the new coordinate, and no jar. -set -euo pipefail - -REPO="${1:?usage: make-stub-repo.sh ...}" -shift -if [ "$#" -eq 0 ]; then - echo "make-stub-repo.sh: no artifact specs given" >&2 - exit 1 -fi - -rm -rf "$REPO" -mkdir -p "$REPO" -REPO="$(cd "$REPO" && pwd)" # `jar` runs from an empty dir, so the output path must be absolute - -EMPTY="$(mktemp -d)" -trap 'rm -rf "$EMPTY"' EXIT - -for spec in "$@"; do - if [[ "$spec" == *">"* ]]; then - IFS=: read -r group art ver <<<"${spec%%>*}" - IFS=: read -r ngroup nart nver <<<"${spec#*>}" - if [ -z "${group:-}" ] || [ -z "${art:-}" ] || [ -z "${ver:-}" ] || [ -z "${ngroup:-}" ] || [ -z "${nart:-}" ] || [ -z "${nver:-}" ]; then - echo "make-stub-repo.sh: malformed relocation '$spec' (want group:artifact:version>group:artifact:version)" >&2 - exit 1 - fi - dir="$REPO/${group//.//}/$art/$ver" - mkdir -p "$dir" - cat >"$dir/$art-$ver.pom" < - 4.0.0 - $group - $art - $ver - - - $ngroup - $nart - $nver - - - -POM - continue - fi - coord="${spec%%+*}" - deps="" - [ "$coord" = "$spec" ] || deps="${spec#*+}" - IFS=: read -r group art ver <<<"$coord" - if [ -z "${group:-}" ] || [ -z "${art:-}" ] || [ -z "${ver:-}" ]; then - echo "make-stub-repo.sh: malformed spec '$spec' (want group:artifact:version[+dep,...])" >&2 - exit 1 - fi - - dir="$REPO/${group//.//}/$art/$ver" - mkdir -p "$dir" - - { - echo '' - echo ' 4.0.0' - echo " $group" - echo " $art" - echo " $ver" - echo ' jar' - if [ -n "$deps" ]; then - echo ' ' - IFS=, read -r -a dep_list <<<"$deps" - for dep in "${dep_list[@]}"; do - dscope="" - [ "${dep%@*}" = "$dep" ] || dscope="${dep#*@}" - IFS=: read -r dgroup dart dver <<<"${dep%@*}" - if [ -z "${dgroup:-}" ] || [ -z "${dart:-}" ] || [ -z "${dver:-}" ]; then - echo "make-stub-repo.sh: malformed dependency '$dep' in spec '$spec'" >&2 - exit 1 - fi - echo ' ' - echo " $dgroup" - echo " $dart" - echo " $dver" - [ -z "$dscope" ] || echo " $dscope" - echo ' ' - done - echo ' ' - fi - echo '' - } >"$dir/$art-$ver.pom" - - # empty but valid jar (jar ships with every JDK, which these fixtures already need) - ( cd "$EMPTY" && jar cf "$dir/$art-$ver.jar" . ) -done - -# A version list per module, so a version range can resolve against the repo. -find "$REPO" -name '*.pom' | while read -r pom; do - dir="$(dirname "$(dirname "$pom")")" - art="$(basename "$dir")" - group="$(dirname "${dir#"$REPO"/}")" - { - echo '' - echo " ${group//\//.}" - echo " $art" - echo ' ' - echo ' ' - for v in "$dir"/*/; do echo " $(basename "$v")"; done - echo ' ' - echo ' ' - echo '' - } >"$dir/maven-metadata.xml" -done - -echo "built stub repo at $REPO" diff --git a/src/commands/manifest/scripts/test/maven-compat/.gitignore b/src/commands/manifest/scripts/test/maven-compat/.gitignore index d37906a3c9..8caaf77173 100644 --- a/src/commands/manifest/scripts/test/maven-compat/.gitignore +++ b/src/commands/manifest/scripts/test/maven-compat/.gitignore @@ -1,28 +1,4 @@ -project/localrepo/ -project/records.tsv +# Generated at test time. project/workspaces-records.tsv project/target/ project/*/target/ -repo-inheritance/localrepo/ -repo-inheritance/records.tsv -repo-inheritance/target/ -repo-inheritance/*/target/ -repo-inheritance/.mirror-settings.xml -duplicate-failure/records.tsv -duplicate-failure/target/ -duplicate-failure/*/target/ -graph-failure/records.tsv -graph-failure/target/ -descriptor-failure/records.tsv -descriptor-failure/target/ -descriptor-failure/*/target/ -unsolvable-conflict/records.tsv -unsolvable-conflict/target/ -unsolvable-conflict/localrepo/ -extension-type/localrepo/ -extension-type/records.tsv -extension-type/target/ -unknown-scopes/localrepo/ -unknown-scopes/records.tsv -maven4-scopes/localrepo/ -maven4-scopes/records.tsv diff --git a/src/commands/manifest/scripts/test/maven-compat/assert-fail-closed.py b/src/commands/manifest/scripts/test/maven-compat/assert-fail-closed.py deleted file mode 100644 index f32220ef52..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/assert-fail-closed.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env python3 -# Assert the extension failed CLOSED: a dependency it could not materialize must appear as a -# `failure` record, which the CLI turns into an aborted scan. Silently dropping the jar would leave -# the reachability analysis unable to see through that artifact and under-report reachability. -# -# Both fixture modules reach demo.scoped:widget, so both fail on it, each naming the repository it -# attempted — so the count of records is not pinned here. What is pinned: the failure is attributed -# to the artifact's own scope, never reported as a scope-less or whole-module failure, which would -# claim the dependency graph could not be built when it collected fine. -# smoke-test-duplicate-failure.sh covers the identical-message case, where those records collapse. -import sys - -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -failures = [r[1:] for r in rows if r[0] == 'failure'] -widget = [f for f in failures if f[0].startswith('demo.scoped:widget:')] -graph = [f for f in failures if not f[2]] + [r[1:] for r in rows if r[0] == 'unscannable'] -errors = [] - -if not widget: - errors.append(f"an unresolvable dependency emitted no failure record; failures={failures}") -elif any(f[2] != 'compile' for f in widget): - errors.append(f"demo.scoped:widget should fail in config 'compile', got {[f[2] for f in widget]}") -if graph: - errors.append(f"graph collected fine, so no graph-level failure should exist: {graph}") - -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (fail closed): unresolvable demo.scoped:widget reported in config 'compile' ({len(widget)} record(s)); no graph-level failure") diff --git a/src/commands/manifest/scripts/test/maven-compat/assert-no-invented-failures.py b/src/commands/manifest/scripts/test/maven-compat/assert-no-invented-failures.py deleted file mode 100644 index 976aeccd44..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/assert-no-invented-failures.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python3 -# Assert the extension reported the unresolvable dependency, and only that: no scope-less or -# whole-module failure may be invented for a reactor whose graph collected fine. Counting the -# artifact's own failures is deliberately loose: it depends on how each Maven version words them, -# while the no-invented-failure invariant does not. -import sys - -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -failures = [r[1:] for r in rows if r[0] == 'failure'] -ghost = [f for f in failures if f[0].startswith('demo.missing:ghost:')] -# A failure with no scope, or an unscannable module, would claim graph collection failed. -graph = [f for f in failures if not f[2]] + [r[1:] for r in rows if r[0] == 'unscannable'] -errors = [] - -if not ghost: - errors.append(f"unresolvable demo.missing:ghost emitted no failure record; failures={failures}") -elif any(f[2] != 'compile' for f in ghost): - errors.append(f"demo.missing:ghost should fail in config 'compile', got {[f[2] for f in ghost]}") -if graph: - errors.append(f"every module's graph collected fine, so no graph-level failure should exist: {graph}") - -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print("PASS (no invented failures): demo.missing:ghost reported in config 'compile'; no graph-level failure") diff --git a/src/commands/manifest/scripts/test/maven-compat/assert-records.py b/src/commands/manifest/scripts/test/maven-compat/assert-records.py deleted file mode 100755 index 1275559c00..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/assert-records.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python3 -# Assert the RECORDS the Coana Maven core extension emitted for the multi-module smoke project. -# Invoked by smoke-test.sh with the records file as its only argument; exits non-zero and prints every -# failure it found. Kept in its own file, rather than a heredoc inside smoke-test.sh, so the unit -# suite can run these assertions over synthetic records without Maven or a JDK. -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -tool = None -roots, root_projects, nodes, projects, files, direct, edges = {}, {}, {}, {}, {}, {}, {} -for r in rows: - if r[0] == 'meta': tool = r[1] - elif r[0] == 'root': - # rootId to prod and to projectKey. - roots[r[1]] = (r[4] == '1') - root_projects[r[1]] = r[2] - elif r[0] == 'node': - nodes.setdefault(r[2], set()).add(r[1]) # coordId -> {rootId} - if r[8] == '1': direct.setdefault(r[2], set()).add(r[1]) # coordId -> {rootId where direct} - # coordId to the build projects its rows resolve it to. - projects.setdefault(r[2], set()).add(r[9] if len(r) > 9 else '') - elif r[0] == 'file': files.setdefault(r[2], set()).add(r[3]) # coordId -> {path} - elif r[0] == 'edge': - # (parent, child) to the roots that hold the edge. - edges.setdefault((r[2], r[3]), set()).add(r[1]) - -errors = [] - -# NOTE: smoke-test.sh also assembles the records (../assemble-records.mts), which fails on an -# orphaned component. What remains here is Maven-specific: which coordinate lands in which root, -# and jar materialization. - -def coord(prefix): - """The one emitted coordId starting with prefix, or None. Keeps assertions version-agnostic.""" - hits = sorted(c for c in set(nodes) | set(files) if c.startswith(prefix)) - if len(hits) > 1: - errors.append(f"expected one coordinate for {prefix!r}, got {hits}") - return hits[0] if hits else None - -ext = coord('demo.ext:tool:jar:') -harness = coord('demo.ext:harness:jar:') -harness_core = coord('demo.ext:harness-core:jar:') -# Sibling module demo:lib: app reaches its jar through mid and declares its test-jar. -lib_jar, lib_tests = coord('demo:lib:jar:'), coord('demo:lib:test-jar:') - -if tool != 'maven': errors.append(f"meta tool {tool!r} != 'maven'") - -def in_prod(cid): return any(roots.get(rid) for rid in nodes.get(cid, ())) -def has_jar(cid): return any(p.endswith('.jar') for p in files.get(cid, ())) - -if not ext: errors.append("missing external prod dep demo.ext:tool") -elif not in_prod(ext): errors.append("demo.ext:tool not in a prod root") -elif not has_jar(ext): errors.append(f"demo.ext:tool jar not materialized: {files.get(ext)}") - -if not harness: errors.append("missing test dep demo.ext:harness") -elif in_prod(harness): errors.append("test dep demo.ext:harness wrongly in a prod root") -elif not has_jar(harness): errors.append(f"demo.ext:harness jar not materialized: {files.get(harness)}") -if not harness_core: errors.append("missing transitive test dep demo.ext:harness-core") -elif in_prod(harness_core): errors.append("transitive test dep demo.ext:harness-core wrongly in a prod root") - -def edge_roots(parent, child): - return edges.get((parent, child), set()) - -def direct_in(cid, project): return any(root_projects.get(rid) == project for rid in direct.get(cid, ())) - -if 'demo:lib:1.0' in nodes: errors.append("sibling demo:lib emitted under its bare id") -elif not lib_jar or not lib_tests: errors.append("sibling demo:lib's jar or test-jar missing") -elif projects.get(lib_jar, set()) | projects.get(lib_tests, set()) != {'demo:lib:1.0'}: - errors.append("sibling demo:lib's artifacts do not name demo:lib:1.0 as their project") -elif not any(roots.get(rid) and root_projects.get(rid) == 'demo:app:1.0' for rid in nodes.get(lib_jar, ())): - errors.append("sibling demo:lib's jar not in app's prod root") -elif not any(root_projects.get(rid) == 'demo:app:1.0' for rid in edge_roots(coord('demo:mid:jar:'), lib_jar)): - errors.append("edge demo:mid -> demo:lib's jar missing from app") -elif in_prod(lib_tests): errors.append("sibling demo:lib's test-jar wrongly in a prod root") -elif direct_in(lib_jar, 'demo:app:1.0'): errors.append("sibling demo:lib's jar wrongly direct in app") -elif not direct_in(lib_tests, 'demo:app:1.0'): errors.append("sibling demo:lib's test-jar not direct in app") - -def edge_pair(parent, child): - """Both coordinates, or None after reporting the missing ones.""" - found = (coord(parent), coord(child)) - missing = [p for p, c in zip((parent, child), found) if not c] - if missing: - errors.append(f"missing {', '.join(m.rstrip(':') for m in missing)}") - return None - return found - -# Scope conflict: Maven keeps demo.ext:shared under the test parent but selects compile, the -# scope conflict-prod's path gives it, so it is on the runtime classpath. Its edge from -# conflict-prod, onto the copy Maven kept under the test parent, keeps it reachable in the prod root. -pair = edge_pair('demo.ext:conflict-prod:jar:', 'demo.ext:shared:jar:') -if pair: - if not in_prod(pair[1]): errors.append("scope-conflict demo.ext:shared not in a prod root") - elif not any(roots.get(rid) for rid in edge_roots(*pair)): - errors.append("edge demo.ext:conflict-prod -> demo.ext:shared missing from a prod root") - -# An edge onto a dependency Maven kept elsewhere: dup-io's dup-util is the direct one. -pair = edge_pair('demo.ext:dup-io:jar:', 'demo.ext:dup-util:jar:') -if pair and not edge_roots(*pair): errors.append("edge demo.ext:dup-io -> demo.ext:dup-util missing") - -# A mediated edge: med-io asks for another med-util than mid declares, and points at mid's. -# coord() fails if the med-util version med-io asked for is also emitted. -pair = edge_pair('demo.ext:med-io:jar:', 'demo.ext:med-util:jar:') -if pair and not any(root_projects.get(rid) == 'demo:mid:1.0' for rid in edge_roots(*pair)): - errors.append("edge demo.ext:med-io -> demo.ext:med-util missing from mid") - -# A managed scope applies to a transitive dependency as it is: demo.ext:managed is compile under -# its test parent, so it is on the runtime classpath. -pair = edge_pair('demo.ext:mgd-test:jar:', 'demo.ext:managed:jar:') -if pair: - if in_prod(pair[0]): errors.append("test dep demo.ext:mgd-test wrongly in a prod root") - elif not in_prod(pair[1]): errors.append("managed-scope demo.ext:managed not in a prod root") - elif not edge_roots(*pair): errors.append("edge demo.ext:mgd-test -> demo.ext:managed missing") - -# An edge across the prod/dev split: container-lib (compile) onto container-api, which app -# declares provided. The edge is kept and container-api stays dev. -pair = edge_pair('demo.ext:container-lib:jar:', 'demo.ext:container-api:jar:') -if pair: - if in_prod(pair[1]): errors.append("provided demo.ext:container-api wrongly in a prod root") - elif not in_prod(pair[0]): errors.append("demo.ext:container-lib not in a prod root") - elif not edge_roots(*pair): - errors.append("edge demo.ext:container-lib -> demo.ext:container-api missing") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS: tool=maven; {ext} prod+jar; harness/harness-core dev; sibling demo:lib jar prod, test-jar direct; demo.ext:shared prod; edges onto kept dependencies") diff --git a/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/a/pom.xml b/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/a/pom.xml deleted file mode 100644 index 769d3d25db..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/a/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - 4.0.0 - - demo - descriptor-failure - 1.0 - - a - - - - - demo.descfail - managedchild - [7.0,8.0) - compile - - - - - - demo.descfail - broken - 1.0 - - - demo.descfail - rebroken - [2.0,3.0) - - - demo.descfail - nopom - 1.0 - - - demo.descfail - nothing - 1.0 - - - demo.descfail - sys - 1.0 - system - ${descfail.sysDir}/sys.jar - - - demo.descfail - sysmissing - 1.0 - system - ${descfail.sysDir}/missing.jar - - - demo.descfail - testparent - 1.0 - test - - - demo.descfail - conflict - 2.0 - - - demo.descfail - loserparent - 1.0 - - - demo.descfail - viaq - 1.0 - - - demo.descfail - nearb - 1.0 - - - demo.descfail - viax - 1.0 - - - demo.descfail - nearx - 1.0 - - - demo.descfail - managedparent - 1.0 - test - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/b/pom.xml b/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/b/pom.xml deleted file mode 100644 index de0d1a4678..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/b/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - 4.0.0 - - demo - descriptor-failure - 1.0 - - b - - - demo.descfail - ok - 1.0 - - - demo.descfail - broken - 1.0 - test - - - demo.descfail - rebroken - 1.0 - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/pom.xml b/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/pom.xml deleted file mode 100644 index b9ced32fc7..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/pom.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - 4.0.0 - demo - descriptor-failure - 1.0 - pom - - - b - a - - diff --git a/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m1/pom.xml b/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m1/pom.xml deleted file mode 100644 index 7a2a7ca62c..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m1/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 4.0.0 - - demo - dup-root - 1.0 - - m1 - diff --git a/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m2/pom.xml b/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m2/pom.xml deleted file mode 100644 index f053c10061..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m2/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 4.0.0 - - demo - dup-root - 1.0 - - m2 - diff --git a/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/pom.xml b/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/pom.xml deleted file mode 100644 index f8edf851a2..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - demo - dup-root - 1.0 - pom - - m1 - m2 - - - 8 - 8 - UTF-8 - - - - - demo.missing - ghost - 9.9.9 - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/extension-type/pom.xml b/src/commands/manifest/scripts/test/maven-compat/extension-type/pom.xml deleted file mode 100644 index 86e622b6f1..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/extension-type/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - demo - extension-type - 1.0 - - file://${maven.multiModuleProjectDirectory}/localrepo - - - - socket-stubs - ${stub.repo.url} - - true - ignore - - - false - - - - - - socket-stubs - ${stub.repo.url} - - true - ignore - - - false - - - - - - - demo.ext - fat - 1.0 - fat - - - - - - demo.ext - types-ext - 1.0 - - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/graph-failure/pom.xml b/src/commands/manifest/scripts/test/maven-compat/graph-failure/pom.xml deleted file mode 100644 index b932991238..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/graph-failure/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - demo - graph-failure - 1.0 - - 8 - 8 - UTF-8 - - - - - demo.graphfail - ok - 1.0 - - - demo.graphfail - nojar - 1.0 - - - demo.graphfail - lib - 1.0 - - - demo.graphfail - testlib - 1.0 - test - - - demo.graphfail - ranged - [1.0,2.0) - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/maven4-scopes/pom.xml b/src/commands/manifest/scripts/test/maven-compat/maven4-scopes/pom.xml deleted file mode 100644 index 541d14d25c..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/maven4-scopes/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.1.0 - demo - maven4-scopes - 1.0 - - file://${maven.multiModuleProjectDirectory}/localrepo - - - - socket-stubs - ${stub.repo.url} - - true - ignore - - - false - - - - - - - demo.scopes - compile-only - 1.0 - compile-only - - - demo.scopes - test-only - 1.0 - test-only - - - demo.scopes - test-runtime - 1.0 - test-runtime - - - demo.scopes - lib - 1.0 - - - demo.scopes - none - 1.0 - none - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml index 5c54ecb76a..0a0161cc74 100644 --- a/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml +++ b/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml @@ -7,90 +7,4 @@ 1.0 app - - - - - demo.ext - managed - 1.0 - compile - - - - - - - demo - mid - 1.0 - - - - demo.ext - tool - 1.0 - - - - demo.ext - harness - 1.0 - test - - - - demo.ext - conflict-test - 1.0 - test - - - demo.ext - conflict-prod - 1.0 - - - - demo.ext - dup-util - 1.0 - - - demo.ext - dup-io - 1.0 - - - - demo.ext - container-api - 1.0 - provided - - - demo.ext - container-lib - 1.0 - - - demo - lib - 1.0 - test-jar - test - - - demo.ext - mgd-test - 1.0 - test - - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/demo/App.java b/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/demo/App.java deleted file mode 100644 index 16e82b6da8..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/demo/App.java +++ /dev/null @@ -1,7 +0,0 @@ -package demo; - -public final class App { - public static void main(String[] args) { - System.out.println(Lib.greet()); - } -} diff --git a/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml index 37cba8823a..f16c76bf3b 100644 --- a/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml +++ b/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml @@ -7,25 +7,4 @@ 1.0 lib - - - demo.ext - libdep - 1.0 - - - - - - maven-jar-plugin - - - - test-jar - - - - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/demo/Lib.java b/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/demo/Lib.java deleted file mode 100644 index 294b73fafe..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/demo/Lib.java +++ /dev/null @@ -1,7 +0,0 @@ -package demo; - -public final class Lib { - public static String greet() { - return "lib"; - } -} diff --git a/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml index 677893ccfb..c835d62bf7 100644 --- a/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml +++ b/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml @@ -7,28 +7,4 @@ 1.0 mid - - - demo - lib - 1.0 - - - demo.ext - libdep - - - - - - demo.ext - med-util - 1.0 - - - demo.ext - med-io - 1.0 - - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/demo/Mid.java b/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/demo/Mid.java deleted file mode 100644 index 5d5b917c99..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/demo/Mid.java +++ /dev/null @@ -1,4 +0,0 @@ -package demo; - -public class Mid { -} diff --git a/src/commands/manifest/scripts/test/maven-compat/project/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/pom.xml index c9dc686a95..e1cf2d9cc8 100644 --- a/src/commands/manifest/scripts/test/maven-compat/project/pom.xml +++ b/src/commands/manifest/scripts/test/maven-compat/project/pom.xml @@ -10,26 +10,4 @@ mid app - - 8 - 8 - UTF-8 - - file://${maven.multiModuleProjectDirectory}/localrepo - - - - socket-stubs - ${stub.repo.url} - - true - - ignore - - - false - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/liba/pom.xml b/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/liba/pom.xml deleted file mode 100644 index 7fcf3743be..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/liba/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - demo - inherit-root - 1.0 - - liba - - - - socket-scoped-stubs - ${stub.repo.url} - - true - - ignore - - - false - - - - - - demo.scoped - widget - 1.0 - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/libb/pom.xml b/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/libb/pom.xml deleted file mode 100644 index d9612220d5..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/libb/pom.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - 4.0.0 - - demo - inherit-root - 1.0 - - libb - - - - demo - liba - 1.0 - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/pom.xml b/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/pom.xml deleted file mode 100644 index 4add413fc8..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - demo - inherit-root - 1.0 - pom - - liba - libb - - - - 8 - 8 - UTF-8 - file://${maven.multiModuleProjectDirectory}/localrepo - - diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-descriptor-failure.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-descriptor-failure.sh deleted file mode 100755 index 9eadf9cdba..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-descriptor-failure.sh +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/env bash -# Regression guard for failures Maven's resolver hides from a plain resolution result: -# - A POM that failed once is cached build-wide, so a later module gets the dependency without an -# error. It must still fail there, in that module's scope (broken: test in b, compile in a), but -# not where a range resolved to another version (rebroken: 1.0 in b, [2.0,3.0) in a). -# - A missing POM is tolerated by Maven's default descriptor policy, losing the dependency's own -# dependencies. It must fail; the dependency stays emitted with its jar (nopom), and one whose jar -# is missing too gets no file (nothing). -# - A system-scope jar gets its file; a missing systemPath fails, under the full coordinate. -# - A failure absent from the graph fails in the scope it would have had: rangedchild under the -# test-scoped testparent is test; before Maven 3.9 and on Maven 4 the position is unknown (no scope). -# It is placed even when the collector met its parent first where that parent lost a conflict -# (sharedchild), but not where the instance on the classpath excludes it (sharedxchild; before Maven -# 3.9 its position is unknown, so it has no scope), and a scope the module manages is kept, not -# derived (managedchild: compile). -# - A version-conflict loser (conflict 1.0) is on no classpath and must not fail; Maven 3.2 drops -# a failed POM's node, so there it cannot be told apart and has no scope. -# -# Runs offline: the POMs are seeded straight into the local repository. -# -# Usage: smoke-test-descriptor-failure.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-descriptor-failure.sh }" -JAR="${2:?usage: smoke-test-descriptor-failure.sh }" -PROJECT="$HERE/descriptor-failure" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" -REPO="$M2/demo/descfail" -SYS_DIR="$SOCKET_COMPAT_CACHE/descfail-sys" - -pom() { - # $1 artifactId, $2 version, $3 extra POM body. - mkdir -p "$REPO/$1/$2" - cat > "$REPO/$1/$2/$1-$2.pom" < - 4.0.0 - demo.descfail - $1 - $2 - $3 - -POM -} - -jar_for() { - mkdir -p "$REPO/$1/$2/empty" - ( cd "$REPO/$1/$2" && jar cf "$1-$2.jar" -C empty . && rm -r empty ) -} - -dep() { - echo "demo.descfail$1$2" -} - -rm -rf "$REPO" "$SYS_DIR" -pom ok 1.0 '' -jar_for ok 1.0 -pom broken 1.0 'demo.descfailabsent-parent1.0' -jar_for broken 1.0 -jar_for nopom 1.0 -pom testparent 1.0 "$(dep rangedchild '[5.0,6.0)')" -jar_for testparent 1.0 -pom rebroken 1.0 'demo.descfailabsent-parent1.0' -jar_for rebroken 1.0 -pom rebroken 2.0 '' -jar_for rebroken 2.0 -cat > "$REPO/rebroken/maven-metadata-local.xml" <<'XML' - - demo.descfail - rebroken - 1.02.0 - -XML -pom conflict 2.0 '' -jar_for conflict 2.0 -pom conflict 1.0 'demo.descfailabsent-parent1.0' -pom loserparent 1.0 "$(dep conflict 1.0)" -jar_for loserparent 1.0 -for parent in viaq:q q:shared nearb:shared viax:qx qx:sharedx; do - pom "${parent%%:*}" 1.0 "$(dep "${parent#*:}" 1.0)" - jar_for "${parent%%:*}" 1.0 -done -pom shared 1.0 "$(dep sharedchild '[5.0,6.0)')" -jar_for shared 1.0 -pom sharedx 1.0 "$(dep sharedxchild '[5.0,6.0)')" -jar_for sharedx 1.0 -pom nearx 1.0 'demo.descfailsharedx1.0demo.descfailsharedxchild' -jar_for nearx 1.0 -pom managedparent 1.0 "$(dep managedchild 1.0)" -jar_for managedparent 1.0 -mkdir -p "$SYS_DIR/empty" -( cd "$SYS_DIR" && jar cf sys.jar -C empty . && rm -r empty ) - -run() { - rm -f "$RECORDS" - ( cd "$PROJECT" && "$MVN" --batch-mode -q -o \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - "-Dmaven.repo.local=$M2" \ - "-Ddescfail.sysDir=$SYS_DIR" \ - "-Dsocket.recordsFile=$RECORDS" \ - -Dsocket.withFiles=true \ - "$@" \ - validate ) -} - -# $1: whether test scope is scanned. -check() { - python3 - "$RECORDS" "$1" "$STEPS" "$KEEPS_FAILED" "$TRACED" <<'PY' -import sys -with_test, steps, keeps_failed, traced = (a == 'true' for a in sys.argv[2:6]) -a, b = 'demo:a:1.0', 'demo:b:1.0' -expected = { - ('demo.descfail:broken:1.0', 'compile', a), - ('demo.descfail:nopom:1.0', 'compile', a), - ('demo.descfail:nothing:1.0', 'compile', a), - ('demo.descfail:nothing:jar:1.0', 'compile', a), - ('demo.descfail:sysmissing:jar:1.0', 'system', a), -} -if not keeps_failed: - expected.add(('demo.descfail:conflict:1.0', '', a)) -expected.add(('demo.descfail:rebroken:1.0', 'compile', b)) -if with_test: - expected.add(('demo.descfail:broken:1.0', 'test', b)) -if with_test or not steps: - expected.add(('demo.descfail:rangedchild:[5.0,6.0)', 'test' if steps else '', a)) -expected.add(('demo.descfail:sharedchild:[5.0,6.0)', 'compile' if steps else '', a)) -expected.add(('demo.descfail:managedchild:[7.0,8.0)', 'compile' if steps else '', a)) -if not traced: - expected.add(('demo.descfail:sharedxchild:[5.0,6.0)', '', a)) -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -failures = [r[1:] for r in rows if r[0] == 'failure'] -actual = {(f[0], f[2], f[3]) for f in failures} -nodes = {r[2] for r in rows if r[0] == 'node'} -files = {r[2] for r in rows if r[0] == 'file'} -unfetched = {r[2] for r in rows if r[0] == 'unfetched'} -unscannable = [r[1:] for r in rows if r[0] == 'unscannable'] -errors = [] -if actual != expected: - errors.append(f"failures differ: missing={sorted(expected - actual)} unexpected={sorted(actual - expected)}") -for f in failures: - if 'One or more requests failed' in f[1]: - errors.append(f"{f[0]} reports the batch wrapper, not its cause: {f[1]!r}") -if any(n.startswith('demo.descfail:broken:') for n in nodes): - errors.append(f"broken's POM failed, so it must not be emitted; nodes={sorted(nodes)}") -for coord in ('demo.descfail:ok:jar:1.0', 'demo.descfail:nopom:jar:1.0', 'demo.descfail:sys:jar:1.0', - 'demo.descfail:rebroken:jar:2.0'): - if coord not in files: - errors.append(f"{coord} must be emitted with its jar; files={sorted(files)}") -if unfetched != {'demo.descfail:nothing:jar:1.0', 'demo.descfail:sysmissing:jar:1.0'}: - errors.append(f"only nothing's and sysmissing's jars are unfetched; unfetched={sorted(unfetched)}") -if any(f.startswith(('demo.descfail:nothing:', 'demo.descfail:sysmissing:')) for f in files): - errors.append(f"a jar that is missing must get no file; files={sorted(files)}") -if unscannable: - errors.append(f"every failure names its artifact, so nothing is unscannable: {unscannable}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (descriptor failure): {len(actual)} failure(s)") -PY -} - -VERSION="$("$MVN" -v 2>/dev/null | head -1)" -echo "+ $VERSION (descriptor failure)" -case "$VERSION" in - *"Maven 3.2."*) STEPS=false; KEEPS_FAILED=false; TRACED=false ;; - *"Maven 3.9."*) STEPS=true; KEEPS_FAILED=true; TRACED=true ;; - *"Maven 4."*) STEPS=false; KEEPS_FAILED=true; TRACED=true ;; - *) STEPS=false; KEEPS_FAILED=true; TRACED=false ;; -esac - -run -check true -run -Dsocket.excludeConfigs=test -check false diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-duplicate-failure.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-duplicate-failure.sh deleted file mode 100755 index 365c1411ab..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-duplicate-failure.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: an unresolvable dependency shared by several reactor modules must be reported as -# what it is — a per-artifact resolution failure — and must never be reported as a whole-module -# failure, which would claim the dependency graph itself could not be built. -# -# Every module inherits the same missing dependency and the same repository list, so every module's -# failure carries an identical message. A fail-closed check that asks "did this module add -# anything?" by comparing the size of a reactor-wide value-equality set would conclude, wrongly, -# that the module reported nothing and invent a whole-module failure for it. -# -# Runs offline: the missing artifact is never looked for in a remote repository, so this needs no -# stub repo and never touches the network. -# -# Usage: smoke-test-duplicate-failure.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-duplicate-failure.sh }" -JAR="${2:?usage: smoke-test-duplicate-failure.sh }" -PROJECT="$HERE/duplicate-failure" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" - -rm -rf "$M2/demo/missing" "$RECORDS" - -echo "+ $("$MVN" -v 2>/dev/null | head -1) (duplicate failure)" -( cd "$PROJECT" && "$MVN" --batch-mode -q -o \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dsocket.recordsFile=$RECORDS" \ - validate ) - -python3 "$HERE/assert-no-invented-failures.py" "$RECORDS" diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-extension-type.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-extension-type.sh deleted file mode 100755 index b941c41f6a..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-extension-type.sh +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: an artifact type a build extension defines must apply as it does in Maven's own -# resolution. Type fat, from the types-ext extension, includes its dependencies and is a jar on disk, -# so demo.ext:inner below demo.ext:fat must not be emitted, and --with-files must fetch fat-1.0.jar. -# -# Usage: smoke-test-extension-type.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-extension-type.sh }" -JAR="${2:?usage: smoke-test-extension-type.sh }" -PROJECT="$HERE/extension-type" -RECORDS="$PROJECT/records.tsv" -STUBS="$PROJECT/localrepo" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" - -bash "$HERE/../make-stub-repo.sh" "$STUBS" \ - 'demo.ext:types-ext:1.0' \ - 'demo.ext:fat:1.0+demo.ext:inner:1.0' \ - 'demo.ext:inner:1.0' -# The extension is a components.xml registering Maven's own handler class for type fat. -EXT_DIR="$(mktemp -d)" -trap 'rm -rf "$EXT_DIR"' EXIT -mkdir -p "$EXT_DIR/META-INF/plexus" -cat > "$EXT_DIR/META-INF/plexus/components.xml" <<'XML' - - - - org.apache.maven.artifact.handler.ArtifactHandler - fat - org.apache.maven.artifact.handler.DefaultArtifactHandler - - fat - jar - true - - - - -XML -( cd "$EXT_DIR" && jar cf "$STUBS/demo/ext/types-ext/1.0/types-ext-1.0.jar" META-INF ) -rm -rf "$M2/demo/ext/types-ext" "$M2/demo/ext/fat" "$M2/demo/ext/inner" "$RECORDS" - -echo "+ $("$MVN" -v 2>/dev/null | head -1) (extension type)" -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$STUBS" \ - "-Dsocket.recordsFile=$RECORDS" \ - validate ) - -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -nodes = {r[2] for r in rows if r[0] == 'node'} -files = {r[3] for r in rows if r[0] == 'file' and r[2].startswith('demo.ext:fat:')} -failures = [r[1:] for r in rows if r[0] in ('failure', 'unscannable')] -errors = [] -if not any(n.startswith('demo.ext:fat:') for n in nodes): - errors.append(f"demo.ext:fat missing; nodes={sorted(nodes)}") -if any(n.startswith('demo.ext:inner:') for n in nodes): - errors.append("demo.ext:inner emitted, though type fat includes its dependencies") -if not any(p.endswith('fat-1.0.jar') for p in files): - errors.append(f"fat-1.0.jar not materialized; files={sorted(files)}") -if failures: - errors.append(f"no failures expected; got {failures}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print("PASS (extension type): fat emitted as a jar, inner not resolved below it") -PY diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-graph-failure.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-graph-failure.sh deleted file mode 100755 index f9c827402d..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-graph-failure.sh +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: a dependency that fails while Maven collects the graph must be reported as that -# dependency, in the module it was collected for, and never emitted as a node. It fails in its own -# scope, and an excluded scope drops it; one the graph lacks (an unsatisfiable range, or a failed POM -# on Maven 3.2) fails in the scope it is declared with. The module itself must never be reported as -# the failure. Under --with-files, every healthy dependency must still get its file, and a jar that -# cannot be fetched is reported under its full coordinate, with the cause rather than a wrapper. -# -# Runs offline: the POMs are seeded straight into the local repository, so their missing parent and -# the absent versions of ranged can only fail to resolve. -# -# Usage: smoke-test-graph-failure.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-graph-failure.sh }" -JAR="${2:?usage: smoke-test-graph-failure.sh }" -PROJECT="$HERE/graph-failure" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" - -rm -rf "$M2/demo/graphfail" -for lib in lib testlib; do - mkdir -p "$M2/demo/graphfail/$lib/1.0" - cat > "$M2/demo/graphfail/$lib/1.0/$lib-1.0.pom" < - 4.0.0 - - demo.graphfail - lib-parent - 1.0 - - $lib - -POM -done -for lib in ok nojar; do - mkdir -p "$M2/demo/graphfail/$lib/1.0" - cat > "$M2/demo/graphfail/$lib/1.0/$lib-1.0.pom" < - 4.0.0 - demo.graphfail - $lib - 1.0 - -POM -done -( cd "$M2/demo/graphfail/ok/1.0" && mkdir -p empty && jar cf ok-1.0.jar -C empty . && rm -r empty ) - -run() { - rm -f "$RECORDS" - ( cd "$PROJECT" && "$MVN" --batch-mode -q -o \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - "-Dmaven.repo.local=$M2" \ - "-Dsocket.recordsFile=$RECORDS" \ - "$@" \ - validate ) -} - -# $1: expected scope per coord (null: excluded). -check() { - python3 - "$RECORDS" "$1" <<'PY' -import json, sys -def read(path): - return [l.rstrip('\n').split('\t') for l in open(path) if l.strip()] -rows = read(sys.argv[1]) -expected = json.loads(sys.argv[2]) -emitted = {f"{r[3]}:{r[4]}:{r[5]}" for r in rows if r[0] == 'node'} -errors = [] -if 'demo.graphfail:ok:1.0' not in emitted: - errors.append(f"ok resolved, so it must be emitted; nodes={sorted(emitted)}") -failures = [r[1:] for r in rows if r[0] == 'failure'] -unscannable = [r[1:] for r in rows if r[0] == 'unscannable'] -module = 'demo:graph-failure:1.0' - -for coord, scope in expected.items(): - found = [f for f in failures if f[0] == coord] - if coord in emitted: - errors.append(f"{coord} failed to resolve, so it must not be emitted as a node") - if scope is None: - if found: - errors.append(f"{coord} is in an excluded scope and must not be reported, got {found}") - elif not found: - errors.append(f"{coord} emitted no failure record; failures={failures}") - elif any(f[2] != scope or f[3] != module for f in found): - errors.append(f"{coord} should fail in scope {scope!r} of {module}, got {found}") -invented = [f for f in failures if f[0] == module] -if invented: - errors.append(f"the module itself must not be reported as the unresolved dependency: {invented}") -if unscannable: - errors.append(f"each collection error names its artifact, so nothing is unscannable: {unscannable}") - -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (graph failure): {expected}") -PY -} - -check_files() { - python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -files = {r[2] for r in rows if r[0] == 'file'} -failures = {(r[1], r[3]) for r in rows if r[0] == 'failure'} -details = {r[2] for r in rows if r[0] == 'failure' and r[1] == 'demo.graphfail:nojar:jar:1.0'} -unfetched = {r[2] for r in rows if r[0] == 'unfetched'} -errors = [] -if 'demo.graphfail:ok:jar:1.0' not in files: - errors.append(f"ok resolved, so its jar must be materialized despite the collection errors; files={sorted(files)}") -if ('demo.graphfail:nojar:jar:1.0', 'compile') not in failures: - errors.append(f"nojar's jar cannot be fetched, so it must be reported; failures={sorted(failures)}") -if any('One or more requests failed' in d for d in details): - errors.append(f"nojar's failure must give the cause, not the batch wrapper; details={sorted(details)}") -if unfetched != {'demo.graphfail:nojar:jar:1.0'}: - errors.append(f"only nojar's jar is unfetched; unfetched={sorted(unfetched)}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print("PASS (graph failure, with files)") -PY -} - -VERSION="$("$MVN" -v 2>/dev/null | head -1)" -echo "+ $VERSION (graph failure)" -run -check '{"demo.graphfail:lib:1.0": "compile", "demo.graphfail:testlib:1.0": "test", "demo.graphfail:ranged:[1.0,2.0)": "compile"}' -run -Dsocket.excludeConfigs=test -check '{"demo.graphfail:lib:1.0": "compile", "demo.graphfail:testlib:1.0": null, "demo.graphfail:ranged:[1.0,2.0)": "compile"}' -run -Dsocket.withFiles=true -check '{"demo.graphfail:lib:1.0": "compile", "demo.graphfail:testlib:1.0": "test", "demo.graphfail:ranged:[1.0,2.0)": "compile"}' -check_files diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-repo-inheritance.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-repo-inheritance.sh deleted file mode 100755 index 2ac369689f..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-repo-inheritance.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: a dependency reachable only through a repository declared by a SIBLING reactor -# module must still be materialized under -Dsocket.withFiles. -# -# The fixture mirrors the shape that broke in the field: `liba` declares the only repository serving -# demo.scoped:widget, and `libb` reaches that artifact transitively through its reactor dependency on -# liba. Maven resolves each dependency node against the repositories that node's own descriptor -# lineage contributes, so widget resolves for libb too. Resolving instead against libb's own -# repository list — the module the walk started from — finds nothing, and (because Aether's local -# repository records which repository each cached file came from) not even an already-downloaded copy -# in ~/.m2 is considered available. -# -# Runs at `validate`, the phase the CLI's runner uses: no reactor module is packaged and none is -# installed, so this also guards that a reactor sibling's own jar is never requested. -# -# Usage: smoke-test-repo-inheritance.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-repo-inheritance.sh }" -JAR="${2:?usage: smoke-test-repo-inheritance.sh }" -PROJECT="$HERE/repo-inheritance" -RECORDS="$PROJECT/records.tsv" -STUBS="$PROJECT/localrepo" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" - -bash "$HERE/../make-stub-repo.sh" "$STUBS" 'demo.scoped:widget:1.0' -# The stub never stays cached: every run has to resolve it through the repository liba declares. -rm -rf "$M2/demo/scoped" "$RECORDS" - -echo "+ $("$MVN" -v 2>/dev/null | head -1) (repo inheritance)" -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$STUBS" \ - "-Dsocket.recordsFile=$RECORDS" \ - validate ) - -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -roots, nodes, projects, files, edges, failures = {}, {}, {}, {}, set(), [] -for r in rows: - if r[0] == 'root': roots[r[1]] = r[2] # rootId -> projectKey - elif r[0] == 'node': - # coordId to the roots that hold it. - nodes.setdefault(r[2], set()).add(r[1]) - # coordId to the build project it resolves to, if any. - if len(r) > 9 and r[9]: projects[r[2]] = r[9] - elif r[0] == 'file': files.setdefault(r[2], set()).add(r[3]) # coordId -> {path} - elif r[0] == 'edge': edges.add((r[1], r[2], r[3])) # (rootId, parent, child) - elif r[0] == 'failure': failures.append(r[1:]) - -WIDGET = 'demo.scoped:widget:jar:1.0' -LIBA = 'demo:liba:1.0' -# liba's jar, which names liba as its project. -LIBA_JAR = 'demo:liba:jar:1.0' -LIBB = 'demo:libb:1.0' -errors = [] - -if failures: - errors.append(f"expected no failure records, got {failures}") - -def roots_for(project_key): - return {rid for rid, key in roots.items() if key == project_key} - -for project_key in (LIBA, LIBB): - rids = roots_for(project_key) - if not rids: - errors.append(f"no root record for module {project_key!r}") - continue - if not (nodes.get(WIDGET, set()) & rids): - errors.append(f"{WIDGET} missing from {project_key}'s graph") - -# The point of the fixture: libb reaches widget only through the reactor module liba. -if not any(rid in roots_for(LIBB) and p == LIBA_JAR and c == WIDGET for rid, p, c in edges): - errors.append(f"no {LIBA_JAR} -> {WIDGET} edge in libb's root") - -jars = [p for p in files.get(WIDGET, ()) if p.endswith('.jar')] -if not jars: - errors.append(f"{WIDGET} jar not materialized: {files.get(WIDGET)}") - -# A reactor sibling reports its dirs through its `project` record, never a `file` record. -if projects.get(LIBA_JAR) != LIBA: - errors.append(f"{LIBA_JAR} does not name {LIBA} as its project") -liba_files = {p for c, ps in files.items() if c == LIBA_JAR or projects.get(c) == LIBA for p in ps} -if liba_files: - errors.append(f"reactor module {LIBA} should have no file records, got {sorted(liba_files)}") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS (repo inheritance): {WIDGET} resolved for liba and libb via liba's repository; jar materialized") -PY - -# Second run, the other half of the contract: fail CLOSED. With the artifact gone from every -# repository — central mirrored to the same, now widget-less, stub repo so nothing crosses a network -# — a dependency that cannot be materialized MUST surface as a failure record. A silently missing jar -# would leave the reachability analysis blind to whatever it contains and under-report reachability. -SETTINGS="$PROJECT/.mirror-settings.xml" -cat >"$SETTINGS" < - - - socket-no-network - central - file://$STUBS - - - -XML -rm -rf "$STUBS/demo/scoped" "$M2/demo/scoped" "$RECORDS" -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$STUBS" \ - -s "$SETTINGS" \ - "-Dsocket.recordsFile=$RECORDS" \ - validate ) -rm -f "$SETTINGS" - -python3 "$HERE/assert-fail-closed.py" "$RECORDS" diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-scopes.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-scopes.sh deleted file mode 100755 index 8df7881ac6..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-scopes.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: a scope outside Maven 3's five must not drop the dependency or its subtree. -# Maven 3 puts the jar of a scope it does not know (`import`, or a typo, in ) on every -# classpath, so it is prod. Maven 4's compile-only, test-only and test-runtime are dev, and its none -# is on no path: in the SBOM, but only in roots marked noClasspath. -# -# Usage: smoke-test-scopes.sh . -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-scopes.sh }" -JAR="${2:?usage: smoke-test-scopes.sh }" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" -VERSION="$("$MVN" -v 2>/dev/null | head -1)" - -# $1: fixture; then one `artifact:prod:onClasspath[:extra]` expectation per direct dependency, each -# of which has a child `-dep` expected alike, and, with `extra`, also that child. -check_fixture() { - local project="$HERE/$1" records="$HERE/$1/records.tsv" specs=() expectation artifact - shift - for expectation in "$@"; do - IFS=: read -r artifact _ _ extra <<<"$expectation" - specs+=("demo.scopes:$artifact:1.0+demo.scopes:$artifact-dep:1.0${extra:+,demo.scopes:$extra:1.0}") - specs+=("demo.scopes:$artifact-dep:1.0") - done - bash "$HERE/../make-stub-repo.sh" "$project/localrepo" "${specs[@]}" >/dev/null - rm -rf "$M2/demo/scopes" "$records" - ( cd "$project" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$project/localrepo" \ - "-Dsocket.recordsFile=$records" \ - validate ) - python3 - "$records" "$@" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -prod_roots = {r[1] for r in rows if r[0] == 'root' and r[4] == '1'} -off_classpath = {r[1] for r in rows if r[0] == 'noClasspath'} -roots_of = {} -for r in rows: - if r[0] == 'node': - roots_of.setdefault(r[2].split(':')[1], set()).add(r[1]) -edges = {(r[2].split(':')[1], r[3].split(':')[1]) for r in rows if r[0] == 'edge'} -errors = [] -for expectation in sys.argv[2:]: - artifact, prod, on_classpath, *extra = expectation.split(':') - for child in [f'{artifact}-dep', *extra]: - if (artifact, child) not in edges: - errors.append(f"edge {artifact} -> {child} missing") - for name in (artifact, f'{artifact}-dep'): - roots = roots_of.get(name) - if not roots: - errors.append(f"{name} missing") - elif bool(roots & prod_roots) != (prod == 'prod'): - errors.append(f"{name} should be {prod}") - elif bool(roots - off_classpath) != (on_classpath == 'classpath'): - errors.append(f"{name} should be on {on_classpath}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (scopes): {', '.join(sys.argv[2:])}") -PY -} - -echo "+ $VERSION (scopes)" -check_fixture unknown-scopes imported:prod:classpath mistyped:prod:classpath -case "$VERSION" in - *"Maven 4."*) - # none also depends on lib-dep, which lib keeps on the classpath. - check_fixture maven4-scopes \ - compile-only:dev:classpath test-only:dev:classpath test-runtime:dev:classpath \ - none:dev:no-classpath:lib-dep lib:prod:classpath ;; -esac diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-unsolvable-conflict.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-unsolvable-conflict.sh deleted file mode 100755 index ce8f69f681..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-unsolvable-conflict.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: when Maven's conflict resolution throws (hard version ranges no version -# satisfies), Maven resolves no graph for the module. It must be reported unscannable and none of its -# collected dependencies emitted or fetched, however their scopes were left mid-resolution. -# -# Usage: smoke-test-unsolvable-conflict.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-unsolvable-conflict.sh }" -JAR="${2:?usage: smoke-test-unsolvable-conflict.sh }" -PROJECT="$HERE/unsolvable-conflict" -RECORDS="$PROJECT/records.tsv" -STUBS="$PROJECT/localrepo" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" - -bash "$HERE/../make-stub-repo.sh" "$STUBS" \ - 'demo.unsolvable:left:1.0+demo.unsolvable:shared:[1.0]' \ - 'demo.unsolvable:right:1.0+demo.unsolvable:shared:[2.0]' \ - 'demo.unsolvable:harness:1.0+demo.unsolvable:harness-core:1.0' \ - 'demo.unsolvable:harness-core:1.0' \ - 'demo.unsolvable:shared:1.0' \ - 'demo.unsolvable:shared:2.0' -rm -rf "$M2/demo/unsolvable" "$RECORDS" - -echo "+ $("$MVN" -v 2>/dev/null | head -1) (unsolvable conflict)" -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$STUBS" \ - "-Dsocket.recordsFile=$RECORDS" \ - validate ) - -python3 - "$RECORDS" "$M2/demo/unsolvable" <<'PY' -import os, sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -module = 'demo:unsolvable-conflict:1.0' -errors = [] -if not any(r[0] == 'unscannable' and r[3] == module for r in rows): - errors.append(f"{module} must be reported unscannable; records={rows}") -nodes = sorted(r[2] for r in rows if r[0] == 'node') -if nodes: - errors.append(f"Maven resolved no graph, so nothing may be emitted; nodes={nodes}") -jars = sorted(f for _, _, fs in os.walk(sys.argv[2]) for f in fs if f.endswith('.jar')) -if jars: - errors.append(f"Maven resolved no graph, so nothing may be fetched; jars={jars}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (unsolvable conflict): {module} unscannable, nothing emitted or fetched") -PY diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh index 116e871f15..e011e03326 100755 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh +++ b/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash -# Load the Coana Maven workspaces participant (CoanaWorkspacesLifecycleParticipant, the lightweight -# sibling of the facts participant) on a given Maven binary and assert it emits exactly the -# expected reactor project records - no dependency graph at all. Guards, across the same Maven -# compat matrix as the facts extension, that the participant registers and fires correctly. +# Load the Coana Maven workspaces participant (CoanaWorkspacesLifecycleParticipant) on a given +# Maven binary and assert it emits exactly the expected reactor project records - no dependency +# graph at all. Guards, across the Maven compat matrix, that the participant registers and fires +# correctly. # # Usage: smoke-test-workspaces.sh set -euo pipefail diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test.sh deleted file mode 100755 index f2560e094b..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test.sh +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env bash -# Load the Coana Maven core extension on a given Maven binary and assert it emits the expected RECORDS -# for the multi-module smoke project (the TS assembler turns these into .socket.facts.json and is -# tested separately in `nx test utils`). Guards, across the supported Maven range, that the extension: -# - emits the external prod dep demo.ext:tool (in a prod root) and the test dep demo.ext:harness + -# its transitive demo.ext:harness-core (only in a non-prod root -> the assembler's dev flag); -# - emits a sibling module's jar and test-jar under their own coordinates, each naming the module -# as its project (the assembler merges them into the module's component); -# - marks a node prod by the scope Maven kept it with, also one whose scope dependencyManagement -# sets under a test parent; -# - records every resolved edge, pointing at the node Maven kept: onto a direct dependency, onto a -# mediated version, and from a prod node onto a provided one; -# - its records assemble into facts with no orphaned components; -# - keeps a dependency only a sibling module's test-jar brings under that test-jar, not its jar -# (mid excludes demo.ext:libdep from lib); -# - materializes resolved external jars under -Dsocket.withFiles; -# - scopes that materialization to -Dsocket.populateFilesFor (a newline-delimited GAV file). -# -# The external artifacts are stubs generated into a file-based repo at test time (see -# ../make-stub-repo.sh, shared with the Gradle fixture): the fixture only needs their graph shape, it -# never compiles against or runs them, so nothing here can age into a CVE alert or a version bump. -# -# Assertions match on groupId:artifactId and ignore the version, so changing a fixture pom needs no -# edit here. The poms are the only place a version is written. -# -# Usage: smoke-test.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test.sh }" -JAR="${2:?usage: smoke-test.sh }" -PROJECT="$HERE/project" -RECORDS="$PROJECT/records.tsv" -STUBS="$PROJECT/localrepo" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -M2="$SOCKET_COMPAT_CACHE/m2" - -bash "$HERE/../make-stub-repo.sh" "$STUBS" \ - 'demo.ext:tool:1.0' \ - 'demo.ext:harness:1.0+demo.ext:harness-core:1.0' \ - 'demo.ext:harness-core:1.0' \ - 'demo.ext:conflict-test:1.0+demo.ext:shared:1.0' \ - 'demo.ext:conflict-prod:1.0+demo.ext:shared:1.0' \ - 'demo.ext:shared:1.0' \ - 'demo.ext:libdep:1.0' \ - 'demo.ext:dup-util:1.0' \ - 'demo.ext:dup-io:1.0+demo.ext:dup-util:1.0' \ - 'demo.ext:med-util:1.0' \ - 'demo.ext:med-util:2.0' \ - 'demo.ext:med-io:1.0+demo.ext:med-util:2.0' \ - 'demo.ext:container-api:1.0' \ - 'demo.ext:container-lib:1.0+demo.ext:container-api:1.0' \ - 'demo.ext:mgd-test:1.0+demo.ext:managed:1.0' \ - 'demo.ext:managed:1.0' -# Maven's own plugin closure stays cached between runs; the stubs never do, so every run has to -# resolve them from the repo just generated. -rm -rf "$M2/demo" "$RECORDS" "$PROJECT"/*/target "$PROJECT"/target - -echo "+ $("$MVN" -v 2>/dev/null | head -1)" -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$STUBS" \ - "-Dsocket.recordsFile=$RECORDS" \ - compile ) - -python3 "$HERE/assert-records.py" "$RECORDS" -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -app = {r[1] for r in rows if r[0] == 'root' and r[2] == 'demo:app:1.0'} -def libdep_edge(parent): - return any(r[0] == 'edge' and r[1] in app and r[2].startswith(parent) - and r[3].startswith('demo.ext:libdep:') for r in rows) -if not libdep_edge('demo:lib:test-jar:'): - print("FAIL: no demo:lib test-jar -> demo.ext:libdep edge in app"); sys.exit(1) -if libdep_edge('demo:lib:jar:'): - print("FAIL: demo:lib jar -> demo.ext:libdep edge in app, though mid excludes it"); sys.exit(1) -print("PASS: demo.ext:libdep in app through lib's test-jar only") -PY -assemble_records "$RECORDS" - -# Second run: scope --with-files to a single GAV and assert ONLY that artifact is materialized. -# The GAV comes from the records the first run just emitted, so it always matches the fixture pom. -SCOPE="$PROJECT/.populate-for.txt" -python3 - "$RECORDS" > "$SCOPE" <<'PY' -import sys -for l in open(sys.argv[1]): - r = l.rstrip('\n').split('\t') - if r[0] == 'node' and r[2].startswith('demo.ext:tool:jar:'): - print(f'{r[3]}:{r[4]}:{r[5]}') # groupId:artifactId:version - break -else: - sys.exit('no demo.ext:tool node record to scope on') -PY -rm -rf "$RECORDS" "$PROJECT"/*/target "$PROJECT"/target -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-facts \ - -Dsocket.withFiles=true \ - "-Dmaven.repo.local=$M2" \ - "-Dstub.repo.url=file://$STUBS" \ - "-Dsocket.populateFilesFor=$SCOPE" \ - "-Dsocket.recordsFile=$RECORDS" \ - compile ) -rm -f "$SCOPE" - -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -files = {} -for r in rows: - if r[0] == 'file': files.setdefault(r[2], set()).add(r[3]) -errors = [] - -def jars(prefix): - return [p for c, ps in files.items() if c.startswith(prefix) for p in ps if p.endswith('.jar')] - -if not jars('demo.ext:tool:jar:'): - errors.append(f"scoped run: demo.ext:tool (in scope) not materialized: {files}") -if jars('demo.ext:harness:jar:'): - errors.append(f"scoped run: demo.ext:harness (out of scope) was materialized: {jars('demo.ext:harness:jar:')}") -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print("PASS (populateFilesFor scoping): demo.ext:tool materialized, demo.ext:harness skipped") -PY - -assemble_records "$RECORDS" diff --git a/src/commands/manifest/scripts/test/maven-compat/unknown-scopes/pom.xml b/src/commands/manifest/scripts/test/maven-compat/unknown-scopes/pom.xml deleted file mode 100644 index 73106502ed..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/unknown-scopes/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - 4.0.0 - demo - unknown-scopes - 1.0 - - file://${maven.multiModuleProjectDirectory}/localrepo - - - - socket-stubs - ${stub.repo.url} - - true - ignore - - - false - - - - - - - demo.scopes - imported - 1.0 - import - - - demo.scopes - mistyped - 1.0 - optional - - - diff --git a/src/commands/manifest/scripts/test/maven-compat/unsolvable-conflict/pom.xml b/src/commands/manifest/scripts/test/maven-compat/unsolvable-conflict/pom.xml deleted file mode 100644 index a884bbe4f0..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/unsolvable-conflict/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - demo - unsolvable-conflict - 1.0 - - file://${maven.multiModuleProjectDirectory}/localrepo - - - - socket-stubs - ${stub.repo.url} - - true - ignore - - - false - - - - - - - demo.unsolvable - left - 1.0 - - - demo.unsolvable - right - 1.0 - - - demo.unsolvable - harness - 1.0 - test - - - diff --git a/src/commands/manifest/scripts/test/run-compat.sh b/src/commands/manifest/scripts/test/run-compat.sh index 8bc6fb9e8e..72f53cb646 100755 --- a/src/commands/manifest/scripts/test/run-compat.sh +++ b/src/commands/manifest/scripts/test/run-compat.sh @@ -1,12 +1,11 @@ #!/usr/bin/env bash -# Run the manifest-script compatibility matrix LOCALLY, on demand. +# Run the workspace-enumeration compatibility matrix LOCALLY, on demand. # # GitHub Actions can't run this: SocketDev's org action allowlist forbids # `actions/setup-java` and `sbt/setup-sbt`, so the build-tool matrix has no CI -# home. Run this whenever you change the Gradle init script -# (socket-facts.init.gradle), the sbt plugin (socket-facts.plugin.scala), or the -# Maven extension (maven-extension/) — it exercises the same version matrix the -# CI workflow used and asserts the scripts still emit the expected records. +# home. Run this whenever you change socket-workspaces.init.gradle, +# socket-workspaces.plugin.scala, the Maven extension or the dotnet tool's +# workspaces mode. # # JDKs: the matrix needs several Java versions (a row's required major is shown # per run). Point JDK8 / JDK11 / JDK17 / JDK21 at JDK homes to use the right one @@ -26,17 +25,13 @@ TOOL="${1:-all}" . "$HERE/compat-cache.sh" CACHE="$SOCKET_COMPAT_CACHE" -# Same matrix as the former CI workflow. Rows: " [scala]". -# 6.2 is the oldest Gradle with dependency verification. +# Rows: " [scala]". GRADLE_MATRIX=("1.12 8" "2.14.1 8" "3.3 8" "6.2.2 8" "8.10.2 17" "9.2.1 21") -# The Maven rows span the range the extension claims to support (see maven-extension/pom.xml): -# 3.2.5 is the oldest, 4.x the newest. Resolution goes through Maven's own -# ProjectDependenciesResolver, so both ends are load-bearing, not decorative. +# The Maven rows span the range the extension claims to support (see maven-extension/pom.xml). MAVEN_MATRIX=("3.2.5 8" "3.6.3 11" "3.8.8 17" "3.9.9 17" "4.0.0-rc-6 21") -# The `ivy` row runs sbt 1.x with `useCoursier := false`, the other resolver path; failure suite only. # One SDK per supported major. DOTNET_MATRIX=("6.0.428" "7.0.410" "8.0.414" "9.0.315" "10.0.301" "11.0.100-rc.3.26522.148") -SBT_MATRIX=("0.13.18 8 2.10.7" "1.4.9 11 2.12.20" "1.6.2 17 2.12.20" "1.9.9 17 2.12.20" "1.9.9 17 2.12.20 ivy") +SBT_MATRIX=("0.13.18 8 2.10.7" "1.4.9 11 2.12.20" "1.6.2 17 2.12.20" "1.9.9 17 2.12.20") # Select a JDK for the given Java major: use $JDK if set, else current java. use_jdk() { @@ -63,7 +58,6 @@ run_dotnet() { echo "Fix: bash dotnet-install.sh --version $sdk --install-dir $CACHE/dotnet (https://dot.net/v1/dotnet-install.sh)" >&2 exit 1 fi - bash "$HERE/dotnet-compat/smoke-test.sh" "$dotnet" "$sdk" bash "$HERE/dotnet-compat/smoke-test-workspaces.sh" "$dotnet" "$sdk" bash "$HERE/dotnet-compat/smoke-test-exclude-base.sh" "$dotnet" "$sdk" done @@ -84,10 +78,8 @@ run_gradle() { echo "Fix: download https://services.gradle.org/distributions/gradle-$ver-bin.zip and unzip it into $CACHE" >&2 exit 1 fi - bash "$HERE/gradle-compat/smoke-test.sh" "$dir/bin/gradle" bash "$HERE/gradle-compat/smoke-test-workspaces.sh" "$dir/bin/gradle" bash "$HERE/gradle-compat/smoke-test-exclude-base.sh" "$dir/bin/gradle" - bash "$HERE/gradle-compat/smoke-test-failures.sh" "$dir/bin/gradle" done } @@ -110,16 +102,8 @@ run_maven() { echo "Fix: download https://archive.apache.org/dist/maven/$line/$ver/binaries/apache-maven-$ver-bin.zip and unzip it into $CACHE" >&2 exit 1 fi - bash "$HERE/maven-compat/smoke-test.sh" "$dir/bin/mvn" "$jar" bash "$HERE/maven-compat/smoke-test-workspaces.sh" "$dir/bin/mvn" "$jar" bash "$HERE/maven-compat/smoke-test-exclude-base.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-repo-inheritance.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-duplicate-failure.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-graph-failure.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-descriptor-failure.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-unsolvable-conflict.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-extension-type.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-scopes.sh" "$dir/bin/mvn" "$jar" done } @@ -131,16 +115,11 @@ run_sbt() { for row in "${SBT_MATRIX[@]}"; do # shellcheck disable=SC2086 set -- $row - local ver="$1" java="$2" scala="$3" resolver="${4:-}" - echo "== sbt $ver / scala $scala${resolver:+ / $resolver} (wants JDK $java) ==" + local ver="$1" java="$2" scala="$3" + echo "== sbt $ver / scala $scala (wants JDK $java) ==" use_jdk "$java" - if [ -z "$resolver" ]; then - bash "$HERE/sbt-compat/smoke-test.sh" "$ver" "$scala" - bash "$HERE/sbt-compat/smoke-test-workspaces.sh" "$ver" "$scala" - bash "$HERE/sbt-compat/smoke-test-exclude-base.sh" "$ver" "$scala" - fi - bash "$HERE/sbt-compat/smoke-test-failure.sh" "$ver" "$scala" ${resolver:+"$resolver"} - bash "$HERE/sbt-compat/smoke-test-relocation.sh" "$ver" "$scala" ${resolver:+"$resolver"} + bash "$HERE/sbt-compat/smoke-test-workspaces.sh" "$ver" "$scala" + bash "$HERE/sbt-compat/smoke-test-exclude-base.sh" "$ver" "$scala" done } diff --git a/src/commands/manifest/scripts/test/sbt-compat/.gitignore b/src/commands/manifest/scripts/test/sbt-compat/.gitignore index 90cf81ffc4..90ea570bb9 100644 --- a/src/commands/manifest/scripts/test/sbt-compat/.gitignore +++ b/src/commands/manifest/scripts/test/sbt-compat/.gitignore @@ -1,19 +1,5 @@ -# Generated by smoke-test.sh / sbt at test time. -project/localrepo/ +# Generated at test time. project/target/ -project/project/target/ -project/project/build.properties +project/project/ project/scala-version.sbt -project/records.tsv project/workspaces-records.tsv -project/target -failure/localrepo/ -failure/target/ -failure/project/ -failure/scala-version.sbt -failure/records.tsv -artifact-failure/target/ -artifact-failure/*/target/ -artifact-failure/project/ -artifact-failure/scala-version.sbt -artifact-failure/records.tsv diff --git a/src/commands/manifest/scripts/test/sbt-compat/artifact-failure/build.sbt b/src/commands/manifest/scripts/test/sbt-compat/artifact-failure/build.sbt deleted file mode 100644 index e7d024e3f7..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/artifact-failure/build.sbt +++ /dev/null @@ -1,20 +0,0 @@ -// Artifact-failure fixture for ../../../socket-facts.plugin.scala: every module resolves, but ok has no -// tests-classifier jar, so the only failure is an artifact that names no module. app depends on core, -// whose update sbt also runs for app. Reuses ../failure/localrepo, generated by ../smoke-test-failure.sh. -organization in ThisBuild := "demo" -version in ThisBuild := "0.1.0" - -lazy val stubs = Seq( - resolvers := Seq( - "Socket Stubs" at s"file://${(baseDirectory in ThisBuild).value.getAbsolutePath}/../failure/localrepo" - ) ++ resolvers.value -) - -lazy val core = (project in file("core")) - .settings(stubs) - .settings( - libraryDependencies += "demo.fail" % "ok" % "1.0", - libraryDependencies += "demo.fail" % "ok" % "1.0" classifier "tests" - ) - -lazy val app = (project in file("app")).settings(stubs).dependsOn(core) diff --git a/src/commands/manifest/scripts/test/sbt-compat/failure/build.sbt b/src/commands/manifest/scripts/test/sbt-compat/failure/build.sbt deleted file mode 100644 index 5f4b4aa4eb..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/failure/build.sbt +++ /dev/null @@ -1,26 +0,0 @@ -// Failure fixture for ../../../socket-facts.plugin.scala: ok resolves; lib and testlib name a parent POM -// that does not exist; ghost does not exist at all; nojar has a POM but no jar; pomonly is -// `pom`, and so is doctype, whose POM declares a DOCTYPE; pkwar is a war with no -// jar; ok has no tests-classifier jar. Generated into `localrepo` by ../smoke-test-failure.sh. Uses the -// `in ThisBuild` form so it parses on sbt 0.13 and 1.x. -organization in ThisBuild := "demo" -version in ThisBuild := "0.1.0" - -lazy val root = (project in file(".")) - .settings( - name := "sbt-compat-failure", - resolvers := Seq( - "Socket Stubs" at s"file://${baseDirectory.value.getAbsolutePath}/localrepo", - "Ivy Releases" at "https://scala.jfrog.io/artifactory/ivy-releases/", - "Maven Central" at "https://repo1.maven.org/maven2/" - ) ++ resolvers.value, - libraryDependencies += "demo.fail" % "ok" % "1.0", - libraryDependencies += "demo.fail" % "lib" % "1.0", - libraryDependencies += "demo.fail" % "testlib" % "1.0" % Test, - libraryDependencies += "demo.fail" % "ghost" % "1.0", - libraryDependencies += "demo.fail" % "nojar" % "1.0", - libraryDependencies += "demo.fail" % "pomonly" % "1.0", - libraryDependencies += "demo.fail" % "doctype" % "1.0", - libraryDependencies += "demo.fail" % "pkwar" % "1.0", - libraryDependencies += "demo.fail" % "ok" % "1.0" % Test classifier "tests" - ) diff --git a/src/commands/manifest/scripts/test/sbt-compat/project/Base.scala b/src/commands/manifest/scripts/test/sbt-compat/project/Base.scala deleted file mode 100644 index 0075bb2e32..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/project/Base.scala +++ /dev/null @@ -1 +0,0 @@ -object Base diff --git a/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt b/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt index f72bace27e..7f63095479 100644 --- a/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt +++ b/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt @@ -1,27 +1,14 @@ -// Minimal cross-sbt smoke project for ../../socket-facts.plugin.scala. Resolves prod deps (two through -// a Maven relocation) and one test dep so the smoke test can assert the prod/dev split, relocations -// and --with-files materialization. All are -// stub artifacts generated into `localrepo` at test time (../../make-stub-repo.sh): plain Java -// artifacts needing no Scala cross-version, never compiled against, so they can never age into a CVE -// alert or a version bump. Uses the `in ThisBuild` setting form (not the `/` slash form) so it parses -// on sbt 0.13 AND 1.x. scalaVersion is set by smoke-test.sh per matrix entry (scala-version.sbt: -// 2.10 for sbt 0.13, 2.12 for 1.x). +// Smoke project for ../../socket-workspaces.plugin.scala. The `in ThisBuild` form parses on sbt 0.13 +// and 1.x; smoke-test-workspaces.sh sets scalaVersion per matrix entry. organization in ThisBuild := "demo" version in ThisBuild := "0.1.0" lazy val root = (project in file(".")) .settings( name := "sbt-compat-smoke", - // Pin fast resolvers first: sbt 0.13's default chain otherwise hits slow/dead Ivy repos. The - // stub repo leads so the two declared deps resolve off disk; Central still serves sbt's own - // closure (scala-library and friends). + // sbt 0.13's default chain otherwise hits slow or dead Ivy repos. resolvers := Seq( - "Socket Stubs" at s"file://${baseDirectory.value.getAbsolutePath}/localrepo", "Ivy Releases" at "https://scala.jfrog.io/artifactory/ivy-releases/", "Maven Central" at "https://repo1.maven.org/maven2/" - ) ++ resolvers.value, - libraryDependencies += "demo.ext" % "tool" % "1.0", - // Relocated to demo.ext:moved; tool depends on demo.old:legacy, relocated to demo.ext:legacy. - libraryDependencies += "demo.old" % "moved" % "1.0", - libraryDependencies += "demo.ext" % "harness" % "1.0" % Test + ) ++ resolvers.value ) diff --git a/src/commands/manifest/scripts/test/sbt-compat/project/src/main/scala/App.scala b/src/commands/manifest/scripts/test/sbt-compat/project/src/main/scala/App.scala deleted file mode 100644 index 5c4529302c..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/project/src/main/scala/App.scala +++ /dev/null @@ -1 +0,0 @@ -object App { def main(a: Array[String]): Unit = println("hi") } diff --git a/src/commands/manifest/scripts/test/sbt-compat/relocation/build.sbt b/src/commands/manifest/scripts/test/sbt-compat/relocation/build.sbt deleted file mode 100644 index ebdb848d52..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/relocation/build.sbt +++ /dev/null @@ -1,21 +0,0 @@ -// Relocation fixture for ../../socket-facts.plugin.scala. core declares demo.old:moved, which -// relocates to demo.ext:moved, by a version range; app gets demo.ext:moved only through core, and -// overrides its version to one the relocation does not name. The -// demo.ext:wrapper POM declares demo.old:moved with the test scope, which it does not pass on, so it -// must not become demo.ext:moved's parent. Stub artifacts come from `localrepo` -// (../../make-stub-repo.sh). Uses the `in ThisBuild` setting form so it parses on sbt 0.13 and 1.x. -organization in ThisBuild := "demo" -version in ThisBuild := "0.1.0" - -lazy val stubs = Seq( - resolvers := Seq( - "Socket Stubs" at s"file://${(baseDirectory in ThisBuild).value.getAbsolutePath}/localrepo", - "Maven Central" at "https://repo1.maven.org/maven2/" - ) ++ resolvers.value -) - -lazy val core = (project in file("core")).settings(stubs, libraryDependencies += "demo.old" % "moved" % "[1.0,2.0)") - -lazy val app = (project in file("app")) - .dependsOn(core) - .settings(stubs, libraryDependencies += "demo.ext" % "wrapper" % "1.0", dependencyOverrides += "demo.ext" % "moved" % "1.1") diff --git a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-failure.sh b/src/commands/manifest/scripts/test/sbt-compat/smoke-test-failure.sh deleted file mode 100755 index f33706197d..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-failure.sh +++ /dev/null @@ -1,266 +0,0 @@ -#!/usr/bin/env bash -# Regression guard: an unresolvable dependency must be reported, never emitted, and must not take the -# rest of the project down with it. ok must still be emitted; every module named in a failure record -# must be absent from the nodes. Which modules sbt names depends on its resolver: Ivy (sbt 0.13) names -# the declared dependencies whose parent POM is missing (lib, testlib), coursier (sbt 1.3+) names the -# missing parent POM itself; both name ghost. Each failure's detail is its own module's message. -# -# A second run with files: a jar that cannot be fetched (nojar; lib/testlib's under coursier; ok's -# tests classifier, test-scoped) must be reported and marked `unfetched` under its full coordinate, -# in the configurations that requested it, while pomonly (and under coursier doctype, whose POM -# declares a DOCTYPE) stays an artifactless module and pkwar keeps its war. Coursier skips a missing -# jar silently and lists one for every Maven module whatever its packaging, without a cause; Ivy's -# own resolution report names what it failed to download, and why. -# -# Then ../artifact-failure, whose only failure is ok's missing tests jar, without and with files: an -# artifact failure names no module, yet sbt's update fails on it, so it must be reported in both runs -# and must not make core or its dependent app unscannable. -# -# Usage: smoke-test-failure.sh [coursier|ivy] (ivy: sbt 1.x only) -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -SBT_VERSION="${1:?usage: smoke-test-failure.sh }" -SCALA_VERSION="${2:?usage: smoke-test-failure.sh }" -RESOLVER="${3:-coursier}" -PLUGIN="$HERE/../../socket-facts.plugin.scala" -PROJECT="$HERE/failure" -RECORDS="$PROJECT/records.tsv" -REPO="$PROJECT/localrepo" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -IVY="$SOCKET_COMPAT_CACHE/ivy2" -export COURSIER_CACHE="$SOCKET_COMPAT_CACHE/coursier" - -bash "$HERE/../make-stub-repo.sh" "$REPO" 'demo.fail:ok:1.0' -for lib in lib testlib; do - mkdir -p "$REPO/demo/fail/$lib/1.0" - cat > "$REPO/demo/fail/$lib/1.0/$lib-1.0.pom" < - 4.0.0 - - demo.fail - missing-parent - 1.0 - - $lib - -POM -done -mkdir -p "$REPO/demo/fail/nojar/1.0" "$REPO/demo/fail/pomonly/1.0" "$REPO/demo/fail/pkwar/1.0" "$REPO/demo/fail/doctype/1.0" -cat > "$REPO/demo/fail/pkwar/1.0/pkwar-1.0.pom" <<'POM' - - 4.0.0 - demo.fail - pkwar - 1.0 - war - -POM -cp "$REPO/demo/fail/ok/1.0/ok-1.0.jar" "$REPO/demo/fail/pkwar/1.0/pkwar-1.0.war" -cat > "$REPO/demo/fail/nojar/1.0/nojar-1.0.pom" <<'POM' - - 4.0.0 - demo.fail - nojar - 1.0 - -POM -cat > "$REPO/demo/fail/pomonly/1.0/pomonly-1.0.pom" <<'POM' - - 4.0.0 - demo.fail - pomonly - 1.0 - pom - -POM -cat > "$REPO/demo/fail/doctype/1.0/doctype-1.0.pom" <<'POM' - - - - 4.0.0 - demo.fail - doctype - 1.0 - pom - -POM -rm -rf "$IVY/cache/demo.fail" - -GB="$(mktemp -d)/global-base" -mkdir -p "$GB/plugins" -cp "$PLUGIN" "$GB/plugins/SocketFactsPlugin.scala" - -mkdir -p "$PROJECT/project" -echo "sbt.version=$SBT_VERSION" > "$PROJECT/project/build.properties" -echo "scalaVersion in ThisBuild := \"$SCALA_VERSION\"" > "$PROJECT/scala-version.sbt" -if [ "$RESOLVER" = ivy ]; then - echo 'useCoursier in ThisBuild := false' >> "$PROJECT/scala-version.sbt" -fi -rm -rf "$RECORDS" "$PROJECT/target" "$PROJECT/project/target" - -run() { - local dir="$1" - shift - ( cd "$dir" && sbt -Dsbt.global.base="$GB" -Dsbt.server.autostart=false \ - -Dsbt.ivy.home="$IVY" "$@" --batch socketFacts ) -} - -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (failure)" -run "$PROJECT" -Dsocket.recordsFile="$RECORDS" - -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -nodes = {f"{r[3]}:{r[4]}:{r[5]}" for r in rows if r[0] == 'node'} -failure_rows = [r for r in rows if r[0] == 'failure'] -failed = {r[1] for r in failure_rows} -unscannable = [r[1:] for r in rows if r[0] == 'unscannable'] -errors = [] - -if 'demo.fail:ok:1.0' not in nodes: - errors.append(f"ok resolved, so it must be emitted; nodes={sorted(nodes)}") -if 'demo.fail:ghost:1.0' not in failed: - errors.append(f"ghost does not exist, so it must be reported; failures={sorted(failed)}") -if not ({'demo.fail:lib:1.0', 'demo.fail:testlib:1.0'} <= failed or 'demo.fail:missing-parent:1.0' in failed): - errors.append(f"neither lib/testlib nor their missing parent was reported; failures={sorted(failed)}") -emitted = failed & nodes -if emitted: - errors.append(f"reported failures must not be emitted as nodes: {sorted(emitted)}") -# Each failure carries its own module's message, not the whole batch. -for r in failure_rows: - for other in failed - {r[1]}: - org, name, rev = other.split(':') - if any(k in r[2] for k in (f"{org}:{name}:{rev}", f"{org}#{name};{rev}", f"/{name}/{rev}/")): - errors.append(f"{r[1]}'s detail also describes {other}: {r[2][:200]}") -if unscannable: - errors.append(f"the failures name their modules, so the project must not be unscannable: {unscannable}") - -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (failure): reported {sorted(failed)}; ok still emitted") -PY - -rm -rf "$RECORDS" "$PROJECT/target" "$PROJECT/project/target" -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (failure, with files)" -run "$PROJECT" -Dsocket.withFiles=true -Dsocket.recordsFile="$RECORDS" - -# sbt resolves with coursier by default from 1.3. -IVY_RESOLVER=false -case "$RESOLVER:$SBT_VERSION" in - ivy:*|*:0.*|*:1.[0-2].*) IVY_RESOLVER=true ;; -esac -python3 - "$RECORDS" "$IVY_RESOLVER" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -ivy = sys.argv[2] == 'true' -nodes = {r[2]: r for r in rows if r[0] == 'node'} -unfetched = {r[2] for r in rows if r[0] == 'unfetched'} -failed = {r[1] for r in rows if r[0] == 'failure'} -config_of = {r[1]: r[3] for r in rows if r[0] == 'root'} -unfetched_configs = {(r[2], config_of[r[1]]) for r in rows if r[0] == 'unfetched'} -files = {r[2] for r in rows if r[0] == 'file'} -errors = [] - -# Ivy's POM reader declares a DOCTYPE of its own, so it fails on doctype's; coursier reads it. -if ivy and 'demo.fail:doctype:1.0' not in failed: - errors.append(f"Ivy cannot read doctype's POM, so it must be reported; failures={sorted(failed)}") -for name in ('pomonly',) if ivy else ('pomonly', 'doctype'): - if f'demo.fail:{name}:1.0' not in nodes: - errors.append(f"{name} is pom-packaged, so it must be emitted without an artifact; nodes={sorted(nodes)}") - if any(name in u for u in unfetched) or f'demo.fail:{name}:1.0' in failed: - errors.append(f"{name} has no jar to fetch; unfetched={sorted(unfetched)} failures={sorted(failed)}") -for name in ('nojar', 'ok'): - if f'demo.fail:{name}:1.0' not in failed: - errors.append(f"{name}'s jar cannot be fetched, so it must be reported; failures={sorted(failed)}") -if 'demo.fail:nojar:jar:1.0' not in unfetched: - errors.append(f"nojar must be emitted as an unfetched jar; unfetched={sorted(unfetched)}") -if 'demo.fail:ok:jar:1.0' not in files: - errors.append("ok's own jar resolved, so its missing tests jar must not cost it its file") -tests_configs = {c for (u, c) in unfetched_configs if u == 'demo.fail:ok:jar:tests:1.0'} -if not tests_configs or any('test' not in c.lower() for c in tests_configs): - errors.append(f"ok's tests jar is requested only in Test, so only test configs may miss it: {sorted(tests_configs)}") -for name in ('nojar', 'lib', 'testlib'): - if f'demo.fail:{name}:1.0' in nodes: - errors.append(f"{name} has a jar-packaged POM, so it must not look artifactless") - if f'demo.fail:{name}:jar:1.0' in nodes and f'demo.fail:{name}:jar:1.0' not in unfetched: - errors.append(f"{name} is emitted without its jar, so it must be marked unfetched; unfetched={sorted(unfetched)}") -if 'demo.fail:pkwar:war:1.0' not in files: - errors.append(f"pkwar's war resolved, so it must keep its file; nodes={sorted(n for n in nodes if 'pkwar' in n)}") -if any('pkwar' in f for f in failed): - errors.append(f"pkwar's packaging is war, so a missing jar is expected; failures={sorted(failed)}") -details = [r[2] for r in rows if r[0] == 'failure' and r[1] == 'demo.fail:nojar:1.0'] -# Ivy's report names the cause; coursier's update report does not, so none may be claimed. -expected_cause = 'not found' if ivy else 'could not be fetched' -if len(set(details)) != 1 or expected_cause not in details[0]: - errors.append(f"nojar's jar is absent, so it must be reported once as {expected_cause!r}: {sorted(set(details))}") -stray = unfetched - {f'demo.fail:{n}:jar:1.0' for n in ('nojar', 'lib', 'testlib')} - {'demo.fail:ok:jar:tests:1.0'} -if stray: - errors.append(f"only the jars that are missing may be unfetched: {sorted(stray)}") - -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print(f"PASS (failure, with files): unfetched {sorted(unfetched)}; pomonly artifactless") -PY - -ARTIFACT="$HERE/artifact-failure" -mkdir -p "$ARTIFACT/project" -echo "sbt.version=$SBT_VERSION" > "$ARTIFACT/project/build.properties" -cp "$PROJECT/scala-version.sbt" "$ARTIFACT/scala-version.sbt" -rm -rf "$ARTIFACT/records.tsv" "$ARTIFACT/target" "$ARTIFACT"/*/target "$ARTIFACT/project/target" -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (artifact failure)" -run "$ARTIFACT" -Dsocket.recordsFile="$ARTIFACT/records.tsv" - -python3 - "$ARTIFACT/records.tsv" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -unscannable = [r[1:] for r in rows if r[0] == 'unscannable'] -failed = {r[1] for r in rows if r[0] == 'failure'} -errors = [] -if unscannable: - errors.append(f"a missing artifact names no module, but must not make a project unscannable: {unscannable}") -if failed != {'demo.fail:ok:1.0'}: - errors.append(f"sbt's update fails on ok's missing tests jar, so it must be reported without files too; failures={sorted(failed)}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print("PASS (artifact failure): ok's missing tests jar reported without files") -PY - -rm -rf "$ARTIFACT/records.tsv" -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (artifact failure, with files)" -run "$ARTIFACT" -Dsocket.withFiles=true -Dsocket.recordsFile="$ARTIFACT/records.tsv" - -python3 - "$ARTIFACT/records.tsv" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -unscannable = [r[1:] for r in rows if r[0] == 'unscannable'] -project_of = {r[1]: r[2] for r in rows if r[0] == 'root'} -unfetched_by = {} -for r in rows: - if r[0] == 'unfetched': - unfetched_by.setdefault(project_of[r[1]], set()).add(r[2]) -failed = {r[1] for r in rows if r[0] == 'failure'} -errors = [] -if unscannable: - errors.append(f"a missing artifact names no module, but must not make a project unscannable: {unscannable}") -for p in ('core', 'app'): - if unfetched_by.get(p) != {'demo.fail:ok:jar:tests:1.0'}: - errors.append(f"{p} reaches ok's missing tests jar, so only it may be unfetched: {sorted(unfetched_by.get(p, ()))}") -if failed != {'demo.fail:ok:1.0'}: - errors.append(f"only ok's tests jar is missing; failures={sorted(failed)}") -if errors: - print("FAIL:") - for e in errors: - print(" -", e) - sys.exit(1) -print("PASS (artifact failure, with files): ok's tests jar unfetched in core and app; nothing unscannable") -PY diff --git a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-relocation.sh b/src/commands/manifest/scripts/test/sbt-compat/smoke-test-relocation.sh deleted file mode 100755 index 05a3e6e3c1..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-relocation.sh +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env bash -# Run socket-facts.plugin.scala on the relocation fixture and assert a Maven relocation's target keeps -# the parent that declared the relocating module: the project itself (direct) or a build project it -# depends on, never a library that declares it with a scope it does not pass on. Coursier reports the -# target with a caller it leaves out of the report, and gives that caller its declared revision, here -# a version range; an override can move the target off the version the relocation names. -# -# Usage: smoke-test-relocation.sh [coursier|ivy] (ivy: sbt 1.x only) -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -SBT_VERSION="${1:?usage: smoke-test-relocation.sh }" -SCALA_VERSION="${2:?usage: smoke-test-relocation.sh }" -RESOLVER="${3:-coursier}" -PLUGIN="$HERE/../../socket-facts.plugin.scala" -PROJECT="$HERE/relocation" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -IVY="$SOCKET_COMPAT_CACHE/ivy2" -export COURSIER_CACHE="$SOCKET_COMPAT_CACHE/coursier" - -bash "$HERE/../make-stub-repo.sh" "$PROJECT/localrepo" \ - 'demo.old:moved:1.0>demo.ext:moved:1.0' \ - 'demo.ext:moved:1.0' \ - 'demo.ext:moved:1.1' \ - 'demo.ext:wrapper:1.0+demo.old:moved:1.0@test' -rm -rf "$IVY/cache/demo.ext" "$IVY/cache/demo.old" - -GB="$(mktemp -d)/global-base" -mkdir -p "$GB/plugins" -cp "$PLUGIN" "$GB/plugins/SocketFactsPlugin.scala" -mkdir -p "$PROJECT/project" -echo "sbt.version=$SBT_VERSION" > "$PROJECT/project/build.properties" -echo "scalaVersion in ThisBuild := \"$SCALA_VERSION\"" > "$PROJECT/scala-version.sbt" -if [ "$RESOLVER" = ivy ]; then - echo 'useCoursier in ThisBuild := false' >> "$PROJECT/scala-version.sbt" -fi -rm -rf "$RECORDS" "$PROJECT/target" "$PROJECT/project/target" "$PROJECT"/*/target - -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (relocation, $RESOLVER)" -( cd "$PROJECT" && sbt -Dsbt.global.base="$GB" -Dsbt.server.autostart=false \ - -Dsbt.ivy.home="$IVY" -Dsocket.recordsFile="$RECORDS" --batch socketFacts ) - -python3 - "$RECORDS" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -root_of = {r[1]: (r[2], r[3]) for r in rows if r[0] == 'root'} -# Coursier leaves the relocating module out, so the target hangs under its declarer; Ivy keeps it as -# an artifact-less node between the two, which counts as the declarer's edge. -moved = {'core': 'demo.ext:moved:jar:1.0', 'app': 'demo.ext:moved:jar:1.1'} -relocating, wrapper = 'demo.old:moved:1.0', 'demo.ext:wrapper:jar:1.0' -errors = [] -for rid, (project, config) in root_of.items(): - nodes = {r[2]: r for r in rows if r[0] == 'node' and r[1] == rid} - target = moved.get(project) - if target not in nodes: - continue - parents_of = lambda c: {r[2] for r in rows if r[0] == 'edge' and r[1] == rid and r[3] == c} - parents, direct = parents_of(target), nodes[target][8] == '1' - if relocating in parents: - parents = (parents - {relocating}) | parents_of(relocating) - direct = direct or nodes[relocating][8] == '1' - if project == 'core' and not direct: - errors.append(f"core/{config}: {target} not direct") - if project == 'app' and parents != {'core'}: - errors.append(f"app/{config}: {target} parents {sorted(parents)} != ['core']") - if wrapper in parents: - errors.append(f"{project}/{config}: {wrapper} made a parent of {target}") -for project, target in moved.items(): - if not any(r[0] == 'node' and r[2] == target and root_of[r[1]][0] == project for r in rows): - errors.append(f"{target} missing from {project}") -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS (relocation): demo.ext:moved direct in core, under core in app (overridden), never under {wrapper}") -PY - -assemble_records "$RECORDS" diff --git a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh index 8fbbcf4e01..a4f68cf5f8 100755 --- a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh +++ b/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh @@ -1,8 +1,7 @@ #!/usr/bin/env bash -# Run socket-workspaces.plugin.scala (the lightweight workspace-enumeration sibling of -# socket-facts.plugin.scala) against the smoke project on a given sbt version and assert it emits -# exactly the expected project record - no dependency resolution at all. Guards, across the same -# sbt/scala compat matrix as the facts plugin, that SocketWorkspacesPlugin registers and runs. +# Run socket-workspaces.plugin.scala against the smoke project on a given sbt version and assert it +# emits exactly the expected project record - no dependency resolution at all. Guards, across the +# sbt/scala compat matrix, that SocketWorkspacesPlugin registers and runs. # # The plugin is activated exactly as run.ts does it: dropped into a fresh sbt global base's plugins/. # Usage: smoke-test-workspaces.sh @@ -32,8 +31,7 @@ echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (workspaces)" python3 - "$RECORDS" "$SCALA_VERSION" "$(cd "$PROJECT" && pwd -P)" <<'PY' import sys rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -# CrossVersion.apply appends _ (major.minor) to the artifact name - the same -# identity computation socket-facts.plugin.scala's rootIdOf already does, so this isn't optional. +# CrossVersion.apply appends _ (major.minor) to the artifact name. binary_version = '.'.join(sys.argv[2].split('.')[:2]) expected_name = f"sbt-compat-smoke_{binary_version}" errors = [] diff --git a/src/commands/manifest/scripts/test/sbt-compat/smoke-test.sh b/src/commands/manifest/scripts/test/sbt-compat/smoke-test.sh deleted file mode 100755 index 6e509c2ae9..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/smoke-test.sh +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env bash -# Run socket-facts.plugin.scala against the smoke project on a given sbt version and assert it emits -# the expected RECORDS (the plugin's only output now — the TS assembler turns these into -# .socket.facts.json and is tested separately in `nx test utils`). Guards, across the supported sbt -# range (0.13.x .. 1.x), that the reflective version shims (ResolveException / ExclusionRule / -# ConfigRef, updateFull-vs-update) keep producing correct facts: -# - the two expected dependency nodes are present (demo.ext:tool prod, demo.ext:harness test); -# - tool appears in a prod root, harness only in non-prod roots -> the assembler's dev flag; -# - its records assemble into facts with no orphaned components; -# - both get an on-disk jar `file` record under -Dsocket.withFiles; -# - a Maven relocation's target, declared directly (demo.old:moved) or through a dependency -# (demo.old:legacy, from tool), stays in the graph although coursier leaves its caller out of the report; -# - a source in the base dir is a `projectSrc` file, never the base dir itself. -# -# Both deps are stubs generated into project/localrepo at test time (../make-stub-repo.sh, shared with -# the Gradle and Maven fixtures), so neither can age into a CVE alert or a version bump. -# -# The plugin is activated exactly as run.ts does it: dropped into a fresh sbt global base's plugins/. -# Usage: smoke-test.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -SBT_VERSION="${1:?usage: smoke-test.sh }" -SCALA_VERSION="${2:?usage: smoke-test.sh }" -PLUGIN="$HERE/../../socket-facts.plugin.scala" -PROJECT="$HERE/project" -RECORDS="$PROJECT/records.tsv" -# shellcheck source=SCRIPTDIR/../compat-cache.sh -. "$HERE/../compat-cache.sh" -IVY="$SOCKET_COMPAT_CACHE/ivy2" -export COURSIER_CACHE="$SOCKET_COMPAT_CACHE/coursier" - -bash "$HERE/../make-stub-repo.sh" "$PROJECT/localrepo" \ - 'demo.ext:tool:1.0+demo.old:legacy:1.0' \ - 'demo.old:legacy:1.0>demo.ext:legacy:1.0' \ - 'demo.ext:legacy:1.0' \ - 'demo.old:moved:1.0>demo.ext:moved:1.0' \ - 'demo.ext:moved:1.0' \ - 'demo.ext:harness:1.0' -# scala-library and friends stay cached between runs; the stubs never do, so every run has to -# resolve them from the repo just generated. Only Ivy caches them — coursier reads a `file:` -# repository in place. -rm -rf "$IVY/cache/demo.ext" - -GB="$(mktemp -d)/global-base" -mkdir -p "$GB/plugins" -cp "$PLUGIN" "$GB/plugins/SocketFactsPlugin.scala" - -# Pin the sbt + scala versions for this matrix entry (the launcher downloads the sbt version). -# `project/` (the meta-build dir) is an empty dir in git, so it's absent on a fresh checkout. -mkdir -p "$PROJECT/project" -echo "sbt.version=$SBT_VERSION" > "$PROJECT/project/build.properties" -echo "scalaVersion in ThisBuild := \"$SCALA_VERSION\"" > "$PROJECT/scala-version.sbt" -rm -rf "$RECORDS" "$PROJECT/target" "$PROJECT/project/target" - -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION)" -( cd "$PROJECT" && sbt -Dsbt.global.base="$GB" -Dsbt.server.autostart=false \ - -Dsbt.ivy.home="$IVY" \ - -Dsocket.withFiles=true -Dsocket.recordsFile="$RECORDS" --batch socketFacts ) - -python3 - "$RECORDS" "$PROJECT" <<'PY' -import os, sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -base = os.path.realpath(sys.argv[2]) -roots, nodes, files, srcs = {}, {}, {}, set() -for r in rows: - if r[0] == 'root': roots[r[1]] = (r[4] == '1') - elif r[0] == 'node': nodes.setdefault(r[2], set()).add(r[1]) - elif r[0] == 'file': files.setdefault(r[2], set()).add(r[3]) - elif r[0] == 'projectSrc': srcs.add(os.path.realpath(r[2])) -errors = [] - -tool = 'demo.ext:tool:jar:1.0' -harness = 'demo.ext:harness:jar:1.0' -for cid in (tool, harness): - if cid not in nodes: errors.append(f"expected node missing: {cid}") -if tool in nodes and not any(roots.get(rid) for rid in nodes[tool]): - errors.append("demo.ext:tool not present in any prod root") -if harness in nodes and any(roots.get(rid) for rid in nodes[harness]): - errors.append("test dep demo.ext:harness wrongly present in a prod root") -def has_jar(cid): return any(p.endswith('.jar') for p in files.get(cid, ())) -for cid in (tool, harness): - if not has_jar(cid): errors.append(f"{cid} missing materialized jar under --with-files: {files.get(cid)}") -for cid in ('demo.ext:legacy:jar:1.0', 'demo.ext:moved:jar:1.0'): - if cid not in nodes: errors.append(f"relocation target missing: {cid}") - elif not any(roots.get(rid) for rid in nodes[cid]): errors.append(f"relocation target {cid} not in a prod root") -if os.path.join(base, 'Base.scala') not in srcs: errors.append(f"base-dir source Base.scala not a projectSrc: {sorted(srcs)}") -if base in srcs: errors.append("base dir emitted as a projectSrc root") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS: demo.ext:tool prod+jar; demo.ext:harness dev+jar ({len(nodes)} nodes)") -PY - -assemble_records "$RECORDS" diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index c2759f1f03..fc632c4eee 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -29,8 +29,8 @@ import { resolveEcosystemConfig, } from './generate-recursive-manifests.mts' import { loadBuild, withModules } from './load-build.mts' +import { DSI_SETUP_COMMAND } from './run-manifest-facts.mts' import { BUILD_FILES, ECOSYSTEM_LABELS } from './scripts/build-tool.mts' -import { DSI_SETUP_COMMAND } from './scripts/resolution-report-render.mts' import { setupDotnet, setupGradle, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index d13c8a38e3..b958148fb2 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -33,14 +33,13 @@ import { socketDocsLink } from '../../utils/terminal-link.mts' import { detectManifestActions } from '../manifest/detect-manifest-actions.mts' import { generateAutoManifest } from '../manifest/generate_auto_manifest.mts' import { buildToolsFor } from '../manifest/scripts/build-tool.mts' -import { mergeResolvedPathsSidecars } from '../manifest/scripts/sidecar.mts' import type { ReachabilityFallback } from './output-create-new-scan.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' import type { REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' -import type { ResolvedPathsSidecar } from '../manifest/scripts/sidecar.mts' +import type { SocketFactsContext } from '../manifest/run-manifest-facts.mts' import type { Remap } from '@socketsecurity/registry/lib/objects' import type { SocketSdkSuccessResult } from '@socketsecurity/sdk' @@ -161,17 +160,23 @@ async function createNewScan( workspace, }) - // Sidecar forwarded to reachability; populated only when reach runs. - let resolvedPathsSidecar: ResolvedPathsSidecar | undefined let factsOnlyTypes: FactsOnlyTypes | undefined let discardedFactsPaths: string[] | undefined - // sbt provisions its Scala toolchain under the directory passed as its - // isolated global base; reach's artifactPaths point into it, so it must - // stay on disk until the reachability analysis below has consumed those - // paths. Always allocated (even when unused) to keep this uniform rather - // than conditional on autoManifest/reach. + // Coana's reachability run reads what facts generation keeps in the work + // dir, so it lives until the analysis below is done. await withTmpDir('socket-auto-manifest-', async manifestTmpDir => { + const factsContext: SocketFactsContext = { + coanaVersion: reach.reachVersion, + orgSlug, + workDir: reach.runReachabilityAnalysis + ? { + dir: path.join(manifestTmpDir, 'socket-facts-work'), + entries: [], + withFiles: true, + } + : undefined, + } if (autoManifest || reach.dynamicSbomInference) { logger.info('Auto-generating manifest files ...') debugFn('notice', 'Manifest auto-generation enabled') @@ -183,20 +188,14 @@ async function createNewScan( // ecosystems is generated unless --auto-manifest also asked for it. const dynamicResult = await runDynamicSbomInference({ consumer: reach.runReachabilityAnalysis ? 'reach' : 'upload', + context: factsContext, cwd, excludePaths: reach.excludePaths, purlTypes: reach.dynamicSbomInference, - // sbt's Scala toolchain lives under its shared global base; - // reach's artifactPaths point into it, so when reachability - // will consume them afterward, reuse manifestTmpDir (kept alive - // until reach finishes below) instead of letting the call clean - // its own ephemeral base up before reach ever reads those paths. - sbtTmpDir: manifestTmpDir, }) scanTargets = Array.from( new Set([...scanTargets, ...dynamicResult.factsPaths]), ) - resolvedPathsSidecar = dynamicResult.resolvedPathsSidecar factsOnlyTypes = dynamicResult.factsOnlyTypes discardedFactsPaths = dynamicResult.discardedFactsPaths } @@ -215,22 +214,13 @@ async function createNewScan( } const autoManifestResult = await generateAutoManifest({ - computeArtifactsSidecar: reach.runReachabilityAnalysis, + context: factsContext, cwd, detected, excludePaths: reach.excludePaths, outputKind, - tmpDir: manifestTmpDir, verbose: false, }) - if (autoManifestResult.resolvedPathsSidecar) { - resolvedPathsSidecar = resolvedPathsSidecar - ? mergeResolvedPathsSidecars( - resolvedPathsSidecar, - autoManifestResult.resolvedPathsSidecar, - ) - : autoManifestResult.resolvedPathsSidecar - } if (autoManifestResult.generatedFiles.length) { scanTargets = Array.from( new Set([...scanTargets, ...autoManifestResult.generatedFiles]), @@ -345,7 +335,7 @@ async function createNewScan( packagePaths, reachabilityOptions: mergedReachabilityOptions, repoName, - resolvedPathsSidecar, + socketFactsSidecar: factsContext.workDir?.entries, spinner, target: targets[0]!, }) diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index 628711d004..acb6ecf6b1 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -390,9 +390,8 @@ describe('handleCreateNewScan excludePaths', () => { expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( expect.objectContaining({ + context: expect.objectContaining({ workDir: undefined }), cwd: '/repo', - sbtTmpDir: undefined, - withFiles: false, }), ) expect(mockGenerateAutoManifest).toHaveBeenCalledWith( @@ -490,24 +489,14 @@ describe('handleCreateNewScan excludePaths', () => { expect(mockGetPackageFilesForScan).toHaveBeenCalled() }) - it('accumulates a sidecar across recursively discovered build roots and forwards it to reachability analysis', async () => { + it('collects what Coana kept of each build root and forwards it to reachability analysis', async () => { + const entry = { + factsFile: '/repo/service-a/.socket.facts.json', + stateDir: '/work/a', + } mockGenerateRecursiveManifests.mockImplementationOnce( - async ({ sidecarAcc }) => { - sidecarAcc?.set('/repo/service-a/.socket.facts.json', { - projects: [ - { - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: '.', - dependencies: [], - targets: ['/repo/service-a/build/classes'], - sources: ['/repo/service-a/src/main/java'], - }, - ], - components: [], - }) + async ({ context }) => { + context.workDir.entries.push(entry) return [ { dir: '/repo/service-a', @@ -527,19 +516,14 @@ describe('handleCreateNewScan excludePaths', () => { expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( expect.objectContaining({ - sbtTmpDir: expect.any(String), - withFiles: true, + context: expect.objectContaining({ + orgSlug: config.orgSlug, + workDir: expect.objectContaining({ withFiles: true }), + }), }), ) expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( - expect.objectContaining({ - resolvedPathsSidecar: { - '/repo/service-a/.socket.facts.json': { - projects: [expect.objectContaining({ name: 'app' })], - components: [], - }, - }, - }), + expect.objectContaining({ socketFactsSidecar: [entry] }), ) }) diff --git a/src/commands/scan/handle-scan-reach.mts b/src/commands/scan/handle-scan-reach.mts index 1e54d6e5d4..7e72993954 100644 --- a/src/commands/scan/handle-scan-reach.mts +++ b/src/commands/scan/handle-scan-reach.mts @@ -19,6 +19,7 @@ import { getPackageFilesForScan } from '../../utils/path-resolve.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' import type { DynamicSbomInferenceResult } from './run-dynamic-sbom-inference.mts' import type { OutputKind } from '../../types.mts' +import type { SocketFactsWorkDir } from '../manifest/run-manifest-facts.mts' export type HandleScanReachConfig = { cwd: string @@ -40,7 +41,7 @@ async function runScanReach( reachabilityOptions, targets, }: HandleScanReachConfig, - sbtTmpDir: string | undefined, + workDir: SocketFactsWorkDir | undefined, ) { const { spinner } = constants @@ -53,10 +54,14 @@ async function runScanReach( logger.info('Generating Socket facts for each build root ...') dynamicResult = await runDynamicSbomInference({ consumer: 'reach', + context: { + coanaVersion: reachabilityOptions.reachVersion, + orgSlug, + workDir, + }, cwd, excludePaths: reachabilityOptions.excludePaths, purlTypes: reachabilityOptions.dynamicSbomInference, - sbtTmpDir, }) scanTargets = Array.from( new Set([...scanTargets, ...dynamicResult.factsPaths]), @@ -134,7 +139,7 @@ async function runScanReach( outputPath, packagePaths, reachabilityOptions: mergedReachabilityOptions, - resolvedPathsSidecar: dynamicResult?.resolvedPathsSidecar, + socketFactsSidecar: workDir?.entries, spinner, target: targets[0]!, }) @@ -163,12 +168,10 @@ async function runScanReach( export async function handleScanReach( config: HandleScanReachConfig, ): Promise { - // sbt provisions its Scala toolchain under the directory passed as its - // isolated global base; the sidecar's artifactPaths point into it, so it - // must stay on disk until the reachability analysis has consumed them. + // Coana's run reads what facts generation keeps in the work dir. return config.reachabilityOptions.dynamicSbomInference - ? await withTmpDir('socket-dynamic-sbom-inference-', tmpDir => - runScanReach(config, tmpDir), + ? await withTmpDir('socket-dynamic-sbom-inference-', dir => + runScanReach(config, { dir, entries: [], withFiles: true }), ) : await runScanReach(config, undefined) } diff --git a/src/commands/scan/handle-scan-reach.test.mts b/src/commands/scan/handle-scan-reach.test.mts index 22c8b0afa3..9d7dac0743 100644 --- a/src/commands/scan/handle-scan-reach.test.mts +++ b/src/commands/scan/handle-scan-reach.test.mts @@ -112,10 +112,7 @@ describe('handleScanReach', () => { tier1ReachabilityScanId: undefined, }, }) - mockRunDynamicSbomInference.mockResolvedValue({ - factsPaths: [], - resolvedPathsSidecar: undefined, - }) + mockRunDynamicSbomInference.mockResolvedValue({ factsPaths: [] }) }) it('applies excludePaths to manifest discovery and reachability analysis', async () => { @@ -353,20 +350,23 @@ describe('handleScanReach', () => { excludePaths: ['vendor/**'], } - it('generates per-build-root facts, merges them into manifest discovery, and forwards the sidecar', async () => { - mockRunDynamicSbomInference.mockResolvedValueOnce({ - factsOnlyTypes: ['maven'], - factsPaths: [ - '/repo/service-a/.socket.facts.json', - '/repo/service-b/.socket.facts.json', - ], - resolvedPathsSidecar: { - '/repo/service-a/.socket.facts.json': { - projects: [], - components: [], - }, + it('generates per-build-root facts, merges them into manifest discovery, and forwards what Coana kept of them', async () => { + const entry = { + factsFile: '/repo/service-a/.socket.facts.json', + stateDir: '/work/a', + } + mockRunDynamicSbomInference.mockImplementationOnce( + async ({ context }) => { + context.workDir.entries.push(entry) + return { + factsOnlyTypes: ['maven'], + factsPaths: [ + '/repo/service-a/.socket.facts.json', + '/repo/service-b/.socket.facts.json', + ], + } }, - }) + ) await handleScanReach({ cwd: '/repo', @@ -380,11 +380,19 @@ describe('handleScanReach', () => { expect(mockRunDynamicSbomInference).toHaveBeenCalledWith({ consumer: 'reach', + context: { + coanaVersion: baseReachabilityOptions.reachVersion, + orgSlug: 'fakeOrg', + // A caller-owned dir that outlives the analysis reading it. + workDir: { + dir: expect.any(String), + entries: [entry], + withFiles: true, + }, + }, cwd: '/repo', excludePaths: ['vendor/**'], purlTypes: ['maven', 'nuget'], - // A caller-owned dir that outlives the analysis consuming its paths. - sbtTmpDir: expect.any(String), }) expect(mockGetPackageFilesForScan).toHaveBeenCalledWith( [ @@ -398,12 +406,7 @@ describe('handleScanReach', () => { expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( expect.objectContaining({ factsOnlyTypes: ['maven'], - resolvedPathsSidecar: { - '/repo/service-a/.socket.facts.json': { - projects: [], - components: [], - }, - }, + socketFactsSidecar: [entry], // The reachability target stays the user's own, never a facts file. target: '/repo', }), @@ -475,7 +478,7 @@ describe('handleScanReach', () => { expect(mockRunDynamicSbomInference).not.toHaveBeenCalled() expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( - expect.objectContaining({ resolvedPathsSidecar: undefined }), + expect.objectContaining({ socketFactsSidecar: undefined }), ) }) }) diff --git a/src/commands/scan/perform-reachability-analysis.mts b/src/commands/scan/perform-reachability-analysis.mts index 9e57bc1a0a..db744543c5 100644 --- a/src/commands/scan/perform-reachability-analysis.mts +++ b/src/commands/scan/perform-reachability-analysis.mts @@ -17,13 +17,12 @@ import { import { hasEnterpriseOrgPlan } from '../../utils/organization.mts' import { setupSdk } from '../../utils/sdk.mts' import { socketDevLink } from '../../utils/terminal-link.mts' -import { hasResolvedPathsSidecarEntries } from '../manifest/scripts/sidecar.mts' import { fetchOrganization } from '../organization/fetch-organization-list.mts' import type { CResult, OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' -import type { ResolvedPathsSidecar } from '../manifest/scripts/sidecar.mts' +import type { SocketFactsSidecarEntry } from '../manifest/run-manifest-facts.mts' import type { Spinner } from '@socketsecurity/registry/lib/spinner' import type { StdioOptions } from 'node:child_process' @@ -66,10 +65,9 @@ export type ReachabilityAnalysisOptions = { outputPath?: string | undefined packagePaths: string[] reachabilityOptions: ReachabilityOptions - // Resolved-paths sidecar from the auto-manifest run; passed to coana so it - // reuses these paths instead of re-resolving the build. - resolvedPathsSidecar?: ResolvedPathsSidecar | undefined repoName?: string | undefined + // What facts generation kept of each build root, for Coana to read back. + socketFactsSidecar?: SocketFactsSidecarEntry[] | undefined spinner?: Spinner | undefined target: string } @@ -92,7 +90,7 @@ export async function performReachabilityAnalysis( packagePaths, reachabilityOptions, repoName, - resolvedPathsSidecar, + socketFactsSidecar, spinner, target, } = { __proto__: null, ...options } as ReachabilityAnalysisOptions @@ -193,20 +191,16 @@ export async function performReachabilityAnalysis( spinner?.start() spinner?.infoAndStop('Running reachability analysis with Coana...') - // Temp file for --compute-artifacts-sidecar, removed in the finally below. + // Temp file for --socket-facts-sidecar, removed in the finally below. // Written even when empty with factsOnlyTypes: `coana run` rejects the // facts-only flag without one. let sidecarPath: string | undefined - if ( - factsOnlyTypes || - (resolvedPathsSidecar && - hasResolvedPathsSidecarEntries(resolvedPathsSidecar)) - ) { + if (factsOnlyTypes || socketFactsSidecar?.length) { sidecarPath = path.join( tmpdir(), - `socket-compute-artifacts-sidecar-${randomUUID()}.json`, + `socket-facts-sidecar-${randomUUID()}.json`, ) - await fs.writeFile(sidecarPath, JSON.stringify(resolvedPathsSidecar ?? {})) + await fs.writeFile(sidecarPath, JSON.stringify(socketFactsSidecar ?? [])) } // Build Coana arguments. @@ -273,7 +267,7 @@ export async function performReachabilityAnalysis( ...(reachabilityOptions.reachUseOnlyPregeneratedSboms ? ['--use-only-pregenerated-sboms'] : []), - ...(sidecarPath ? ['--compute-artifacts-sidecar', sidecarPath] : []), + ...(sidecarPath ? ['--socket-facts-sidecar', sidecarPath] : []), ] // Build environment variables. diff --git a/src/commands/scan/perform-reachability-analysis.test.mts b/src/commands/scan/perform-reachability-analysis.test.mts index 82add0f187..76fa1faf30 100644 --- a/src/commands/scan/perform-reachability-analysis.test.mts +++ b/src/commands/scan/perform-reachability-analysis.test.mts @@ -356,29 +356,29 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', rmSync(scanCwd, { force: true, recursive: true }) }) - const sidecar = { - '/repo/reactor/.socket.facts.json': { components: [], projects: [] }, - } + const sidecar = [ + { factsFile: '/repo/reactor/.socket.facts.json', stateDir: '/work/r' }, + ] it.for([ { name: 'names every facts-only type next to the sidecar', factsOnlyTypes: ['maven', 'nuget'], - resolvedPathsSidecar: sidecar, + socketFactsSidecar: sidecar, expected: ['--use-only-socket-facts-artifacts', 'maven,nuget'], expectedSidecar: sidecar, }, { name: 'keeps the Maven-only flag older Coana releases know, with an empty sidecar', factsOnlyTypes: ['maven'], - resolvedPathsSidecar: undefined, + socketFactsSidecar: undefined, expected: ['--maven-use-only-socket-facts'], - expectedSidecar: {}, + expectedSidecar: [], }, { name: 'passes no facts-only flag without facts-only types, even with a sidecar', factsOnlyTypes: undefined, - resolvedPathsSidecar: sidecar, + socketFactsSidecar: sidecar, expected: [], expectedSidecar: sidecar, }, @@ -388,12 +388,11 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', expected, expectedSidecar, factsOnlyTypes, - resolvedPathsSidecar, + socketFactsSidecar, }) => { let sidecarAtSpawn: unknown mockSpawnCoana.mockImplementationOnce(async (args: string[]) => { - const sidecarPath = - args[args.indexOf('--compute-artifacts-sidecar') + 1]! + const sidecarPath = args[args.indexOf('--socket-facts-sidecar') + 1]! sidecarAtSpawn = JSON.parse(readFileSync(sidecarPath, 'utf8')) return { ok: true, data: '' } }) @@ -401,7 +400,7 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', const args = await coanaArgsFor( scanCwd, {}, - { factsOnlyTypes, resolvedPathsSidecar }, + { factsOnlyTypes, socketFactsSidecar }, ) expect(factsOnlyArgs(args)).toEqual(expected) @@ -413,7 +412,7 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', const args = await coanaArgsFor(scanCwd, { dynamicSbomInference: ['maven', 'nuget'], }) - expect(args).not.toContain('--compute-artifacts-sidecar') + expect(args).not.toContain('--socket-facts-sidecar') }) }) diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index b49dc75bd7..28095c8356 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -7,29 +7,22 @@ import { isFactsOnlyTypes } from '../../utils/coana.mts' import { InputError } from '../../utils/errors.mts' import { realpathOrResolved } from '../../utils/fs.mts' import { generateRecursiveManifests } from '../manifest/generate-recursive-manifests.mts' +import { DSI_SETUP_COMMAND } from '../manifest/run-manifest-facts.mts' import { PURL_TYPE_BY_TOOL, buildToolLabelsFor, } from '../manifest/scripts/build-tool.mts' -import { DSI_SETUP_COMMAND } from '../manifest/scripts/resolution-report-render.mts' -import { - hasSidecarEntries, - serializeSidecar, -} from '../manifest/scripts/sidecar.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { RecursiveManifestOutcome } from '../manifest/generate-recursive-manifests.mts' -import type { - ResolvedPathsSidecar, - SidecarAccumulator, -} from '../manifest/scripts/sidecar.mts' +import type { SocketFactsContext } from '../manifest/run-manifest-facts.mts' const DSI_SETTINGS_DOCS_URL = 'https://github.com/SocketDev/socket-cli/blob/v1.x/docs/dynamic-sbom-inference-settings.md' -// Who consumes the facts: Coana for `fix` and `reach` (which also resolves -// artifact paths), or only the scan upload. +// Who consumes the facts: Coana for `fix` and `reach`, or only the scan +// upload. export type FactsConsumer = 'fix' | 'reach' | 'upload' export type DynamicSbomInferenceResult = { @@ -39,7 +32,6 @@ export type DynamicSbomInferenceResult = { // these types' artifacts only from facts files. factsOnlyTypes: FactsOnlyTypes factsPaths: string[] - resolvedPathsSidecar: ResolvedPathsSidecar | undefined } // Coana takes the discovered ecosystems' artifacts only from facts files, so a @@ -74,38 +66,28 @@ function checkFactsForCoana( } // Recursively discovers and generates Socket facts for every independent -// build root of the selected ecosystems under `cwd`, returning the generated -// facts paths plus the resolved-paths sidecar that reachability forwards to -// Coana. +// build root of the selected ecosystems under `cwd`. For `fix` and `reach`, +// `context.workDir` collects what the Coana run after it reads. export async function runDynamicSbomInference({ consumer, + context, cwd, excludePaths, purlTypes, - sbtTmpDir, }: { consumer: FactsConsumer + context: SocketFactsContext cwd: string excludePaths: string[] purlTypes: readonly PURL_Type[] - // sbt provisions its Scala toolchain under this directory and reach's - // artifactPaths point into it, so it must outlive whoever consumes them. - // Only meaningful for `reach`. - sbtTmpDir: string | undefined }): Promise { - const withFiles = consumer === 'reach' const coanaReadsFacts = consumer === 'fix' || consumer === 'reach' - const sidecarAcc: SidecarAccumulator | undefined = coanaReadsFacts - ? new Map() - : undefined const outcomes = await generateRecursiveManifests({ + context, cwd, excludePaths, purlTypes, - sbtTmpDir: withFiles ? sbtTmpDir : undefined, - sidecarAcc, verbose: false, - withFiles, }) const factsOnlyTypes = [ ...new Set(outcomes.map(o => PURL_TYPE_BY_TOOL[o.ecosystem])), @@ -147,10 +129,6 @@ export async function runDynamicSbomInference({ ), factsOnlyTypes, factsPaths, - resolvedPathsSidecar: - sidecarAcc && hasSidecarEntries(sidecarAcc) - ? serializeSidecar(sidecarAcc) - : undefined, } } diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index 15f85a220c..5f08f517c0 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -32,16 +32,21 @@ const generated = { status: 'generated', } +const context = { + coanaVersion: '1.2.3', + workDir: { dir: '/work', entries: [], withFiles: true }, +} + function run( consumer: FactsConsumer, purlTypes: readonly PURL_Type[] = ['maven', 'nuget'], ) { return runDynamicSbomInference({ consumer, + context, cwd: '/repo', excludePaths: ['vendor/**'], purlTypes, - sbtTmpDir: '/tmp/sbt', }) } @@ -50,45 +55,19 @@ describe('runDynamicSbomInference', () => { vi.clearAllMocks() }) - it.for([ - // sbtTmpDir only matters for reach; withheld otherwise so the callee - // allocates and cleans up its own ephemeral base. - { - consumer: 'upload', - sbtTmpDir: undefined, - sidecar: false, - withFiles: false, - }, - { - consumer: 'fix', - sbtTmpDir: undefined, - sidecar: true, - withFiles: false, - }, - { - consumer: 'reach', - sbtTmpDir: '/tmp/sbt', - sidecar: true, - withFiles: true, - }, - ] as const)( - 'generates for $consumer', - async ({ consumer, sbtTmpDir, sidecar, withFiles }) => { - mockGenerateRecursiveManifests.mockResolvedValueOnce([generated]) - - await run(consumer) - - expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith({ - cwd: '/repo', - excludePaths: ['vendor/**'], - purlTypes: ['maven', 'nuget'], - sbtTmpDir, - sidecarAcc: sidecar ? expect.any(Map) : undefined, - verbose: false, - withFiles, - }) - }, - ) + it('generates every build root with the given context', async () => { + mockGenerateRecursiveManifests.mockResolvedValueOnce([generated]) + + await run('reach') + + expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith({ + context, + cwd: '/repo', + excludePaths: ['vendor/**'], + purlTypes: ['maven', 'nuget'], + verbose: false, + }) + }) it('returns only the generated facts paths, ignoring empty and skipped roots', async () => { mockGenerateRecursiveManifests.mockResolvedValueOnce([ @@ -102,26 +81,6 @@ describe('runDynamicSbomInference', () => { discardedFactsPaths: [], factsOnlyTypes: ['maven'], factsPaths: ['/repo/a/.socket.facts.json'], - resolvedPathsSidecar: undefined, - }) - }) - - it('serializes the accumulated sidecar', async () => { - mockGenerateRecursiveManifests.mockImplementationOnce( - async ({ sidecarAcc }) => { - sidecarAcc.set('/repo/a/.socket.facts.json', { - projects: [{ name: 'app' }], - components: [], - }) - return [generated] - }, - ) - - expect((await run('reach')).resolvedPathsSidecar).toEqual({ - '/repo/a/.socket.facts.json': { - projects: [{ name: 'app' }], - components: [], - }, }) }) diff --git a/src/commands/scan/warn-socket-json-only-flags.mts b/src/commands/scan/warn-socket-json-only-flags.mts index 26e2857969..15ec3f228a 100644 --- a/src/commands/scan/warn-socket-json-only-flags.mts +++ b/src/commands/scan/warn-socket-json-only-flags.mts @@ -1,7 +1,7 @@ import { logger } from '@socketsecurity/registry/lib/logger' import { camelToKebab } from '../../utils/strings.mts' -import { DSI_SETUP_COMMAND } from '../manifest/scripts/resolution-report-render.mts' +import { DSI_SETUP_COMMAND } from '../manifest/run-manifest-facts.mts' // Build options that `socket manifest ` takes as flags but the scan // commands read from each build's socket.json, so passing them does nothing. diff --git a/test/maven-compat-smoke-assertions.test.mts b/test/maven-compat-smoke-assertions.test.mts deleted file mode 100644 index dcbbbccb62..0000000000 --- a/test/maven-compat-smoke-assertions.test.mts +++ /dev/null @@ -1,366 +0,0 @@ -/** - * Unit tests for the maven-compat fixture's record assertions. - * - * The fixture proves the Maven extension emits a sibling module's jar and - * test-jar under their own coordinates, each naming the module as its project, - * that it records every resolved edge, and that it marks a node prod by the - * scope Maven kept it with. - * The fixture itself needs Maven and a JDK, so these run its assertions over - * synthetic records instead. - * - * Implementation: src/commands/manifest/scripts/test/maven-compat/assert-records.py - */ - -import { spawnSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { fileURLToPath } from 'node:url' - -import { afterEach, beforeEach, describe, expect, it } from 'vitest' - -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - -const ASSERT_RECORDS_PATH = path.join( - __dirname, - '../src/commands/manifest/scripts/test/maven-compat/assert-records.py', -) - -/** A `root` row: the assertions read the id (field 2), project (field 3) and prod-ness (field 5). */ -function rootRow( - rootId: string, - projectKey: string, - options: { prod: boolean }, -): string { - return ['root', rootId, projectKey, '', options.prod ? '1' : '0'].join('\t') -} - -/** - * A `node` row: root id in field 2, coordinate in field 3, directness in field - * 9, the build project it resolves to in field 10. - */ -function nodeRow( - rootId: string, - coordId: string, - options: { direct: boolean; project: string }, -): string { - return [ - 'node', - rootId, - coordId, - '', - '', - '', - '', - '', - options.direct ? '1' : '0', - options.project, - ].join('\t') -} - -/** A `file` row: coordinate in field 3, materialized path in field 4. */ -function fileRow(rootId: string, coordId: string, filePath: string): string { - return ['file', rootId, coordId, filePath].join('\t') -} - -/** An `edge` row: root id in field 2, parent coord in field 3, child coord in field 4. */ -function edgeRow(rootId: string, parent: string, child: string): string { - return ['edge', rootId, parent, child].join('\t') -} - -const TOOL = 'demo.ext:tool:jar:1.0' -const HARNESS = 'demo.ext:harness:jar:1.0' -const HARNESS_CORE = 'demo.ext:harness-core:jar:1.0' -const SHARED = 'demo.ext:shared:jar:1.0' -const CONFLICT_PROD = 'demo.ext:conflict-prod:jar:1.0' -const CONFLICT_TEST = 'demo.ext:conflict-test:jar:1.0' -const DUP_IO = 'demo.ext:dup-io:jar:1.0' -const DUP_UTIL = 'demo.ext:dup-util:jar:1.0' -const MED_IO = 'demo.ext:med-io:jar:1.0' -const MED_UTIL = 'demo.ext:med-util:jar:1.0' -const CONTAINER_LIB = 'demo.ext:container-lib:jar:1.0' -const CONTAINER_API = 'demo.ext:container-api:jar:1.0' -const MID_JAR = 'demo:mid:jar:1.0' -// The reactor module each sibling artifact's coordinate resolves to, by artifactId. -const SIBLING_PROJECTS: Record = { - __proto__: null, - lib: 'demo:lib:1.0', - mid: 'demo:mid:1.0', -} as unknown as Record -const LIB_JAR = 'demo:lib:jar:1.0' -const LIB_TESTS = 'demo:lib:test-jar:tests:1.0' -const MGD_TEST = 'demo.ext:mgd-test:jar:1.0' -const MANAGED = 'demo.ext:managed:jar:1.0' - -const DEV_NODES = new Set([ - CONFLICT_TEST, - CONTAINER_API, - HARNESS, - HARNESS_CORE, - LIB_TESTS, - MGD_TEST, -]) - -type Edge = { child: string; module: string; parent: string } - -const EDGES = { - conflictProdShared: { module: 'app', parent: CONFLICT_PROD, child: SHARED }, - conflictTestShared: { module: 'app', parent: CONFLICT_TEST, child: SHARED }, - containerLibApi: { - module: 'app', - parent: CONTAINER_LIB, - child: CONTAINER_API, - }, - dupIoUtil: { module: 'app', parent: DUP_IO, child: DUP_UTIL }, - harnessCore: { module: 'app', parent: HARNESS, child: HARNESS_CORE }, - medIoUtil: { module: 'mid', parent: MED_IO, child: MED_UTIL }, - mgdTestManaged: { module: 'app', parent: MGD_TEST, child: MANAGED }, - midLib: { module: 'app', parent: MID_JAR, child: LIB_JAR }, -} satisfies Record - -function rootIdOf(module: string, prodRoot: boolean): string { - return `${module}-${prodRoot ? 'compile' : 'test'}` -} - -type RecordsOptions = { - dev?: string[] - extraNodes?: string[] - libProject?: string - omitEdges?: Edge[] - omitNodes?: string[] - prod?: string[] - toggleDirect?: string[] -} - -/** - * Records in the extension's root layout: per module, a compile root with the - * nodes Maven kept with a prod scope and a test root with the whole - * resolution. `dev`, `extraNodes`, `libProject`, `omitEdges`, `omitNodes`, - * `prod` and `toggleDirect` alter it into outputs the assertions must reject. - */ -function buildRecords({ - dev = [], - extraNodes = [], - libProject = 'demo:lib:1.0', - omitEdges = [], - omitNodes = [], - prod = [], - toggleDirect = [], -}: RecordsOptions = {}): string { - // Coordinate and directness of each module's nodes. - const modules: Array<[string, Array<[string, boolean]>]> = [ - [ - 'app', - [ - [TOOL, true], - [HARNESS, true], - [HARNESS_CORE, false], - [CONFLICT_TEST, true], - [CONFLICT_PROD, true], - [SHARED, false], - [DUP_UTIL, true], - [DUP_IO, true], - [CONTAINER_API, true], - [CONTAINER_LIB, true], - [MGD_TEST, true], - [MANAGED, false], - [MID_JAR, true], - [LIB_JAR, false], - [LIB_TESTS, true], - ...extraNodes.map(coord => [coord, true] as [string, boolean]), - ], - ], - [ - 'mid', - [ - [MED_UTIL, true], - [MED_IO, true], - [LIB_JAR, true], - ], - ], - ] - const isProd = (coord: string) => - prod.includes(coord) || (!DEV_NODES.has(coord) && !dev.includes(coord)) - const rows = [['meta', 'maven'].join('\t')] - for (const { 0: module, 1: nodes } of modules) { - for (const prodRoot of [true, false]) { - const rootId = rootIdOf(module, prodRoot) - const inRoot = (coord: string) => - !omitNodes.includes(coord) && (!prodRoot || isProd(coord)) - rows.push(rootRow(rootId, `demo:${module}:1.0`, { prod: prodRoot })) - for (const { 0: coord, 1: direct } of nodes) { - if (inRoot(coord)) { - const project = coord.startsWith('demo:lib:') - ? libProject - : (SIBLING_PROJECTS[coord.split(':')[1] ?? ''] ?? '') - rows.push( - nodeRow(rootId, coord, { - direct: direct !== toggleDirect.includes(coord), - project, - }), - ) - } - } - for (const edge of Object.values(EDGES)) { - if ( - edge.module === module && - !omitEdges.includes(edge) && - inRoot(edge.parent) && - inRoot(edge.child) - ) { - rows.push(edgeRow(rootId, edge.parent, edge.child)) - } - } - } - } - rows.push(fileRow(rootIdOf('app', true), TOOL, '/repo/tool-1.0.jar')) - rows.push(fileRow(rootIdOf('app', false), HARNESS, '/repo/harness-1.0.jar')) - return `${rows.join('\n')}\n` -} - -describe('maven-compat assert-records.py', () => { - let workDir: string - - beforeEach(() => { - workDir = mkdtempSync(path.join(os.tmpdir(), 'maven-compat-assert-')) - }) - - afterEach(() => { - rmSync(workDir, { force: true, recursive: true }) - }) - - function assertRecords(options?: RecordsOptions): { - status: number | null - output: string - } { - const recordsPath = path.join(workDir, 'records.tsv') - writeFileSync(recordsPath, buildRecords(options)) - - const result = spawnSync('python3', [ASSERT_RECORDS_PATH, recordsPath], { - cwd: workDir, - encoding: 'utf8', - }) - return { output: `${result.stdout}${result.stderr}`, status: result.status } - } - - it('accepts the extension output', () => { - const { output, status } = assertRecords() - - expect(output).toContain('PASS') - expect(status).toBe(0) - }) - - it.for([ - { - name: 'a sibling emitted under its bare id', - options: { extraNodes: ['demo:lib:1.0'] }, - message: 'sibling demo:lib emitted under its bare id', - }, - { - name: "a missing edge onto the sibling's jar", - options: { omitEdges: [EDGES.midLib] }, - message: "edge demo:mid -> demo:lib's jar missing from app", - }, - { - name: 'a missing sibling jar', - options: { omitNodes: [LIB_JAR] }, - message: "sibling demo:lib's jar or test-jar missing", - }, - { - name: 'a missing sibling test-jar', - options: { omitNodes: [LIB_TESTS] }, - message: "sibling demo:lib's jar or test-jar missing", - }, - { - name: 'sibling artifacts that do not name their project', - options: { libProject: '' }, - message: - "sibling demo:lib's artifacts do not name demo:lib:1.0 as their project", - }, - { - name: 'a sibling jar left dev', - options: { dev: [LIB_JAR] }, - message: "sibling demo:lib's jar not in app's prod root", - }, - { - name: 'a sibling test-jar in a prod root', - options: { prod: [LIB_TESTS] }, - message: "sibling demo:lib's test-jar wrongly in a prod root", - }, - { - name: 'a sibling jar marked direct', - options: { toggleDirect: [LIB_JAR] }, - message: "sibling demo:lib's jar wrongly direct in app", - }, - { - name: 'a sibling test-jar not marked direct', - options: { toggleDirect: [LIB_TESTS] }, - message: "sibling demo:lib's test-jar not direct in app", - }, - { - name: 'a compile-scoped node kept under a test parent left dev', - options: { dev: [SHARED] }, - message: 'scope-conflict demo.ext:shared not in a prod root', - }, - { - name: 'a missing edge onto a node kept under another parent', - options: { omitEdges: [EDGES.conflictProdShared] }, - message: - 'edge demo.ext:conflict-prod -> demo.ext:shared missing from a prod root', - }, - { - name: 'a missing edge onto a direct dependency', - options: { omitEdges: [EDGES.dupIoUtil] }, - message: 'edge demo.ext:dup-io -> demo.ext:dup-util missing', - }, - { - name: 'a missing mediated edge', - options: { omitEdges: [EDGES.medIoUtil] }, - message: 'edge demo.ext:med-io -> demo.ext:med-util missing from mid', - }, - { - name: 'a missing edge from a prod node onto a provided one', - options: { omitEdges: [EDGES.containerLibApi] }, - message: 'edge demo.ext:container-lib -> demo.ext:container-api missing', - }, - { - name: 'a missing end of an edge', - options: { omitNodes: [CONFLICT_PROD] }, - message: 'missing demo.ext:conflict-prod:jar', - }, - { - name: 'a test parent of a managed-scope node in a prod root', - options: { prod: [MGD_TEST] }, - message: 'test dep demo.ext:mgd-test wrongly in a prod root', - }, - { - name: 'a missing edge onto a managed-scope node', - options: { omitEdges: [EDGES.mgdTestManaged] }, - message: 'edge demo.ext:mgd-test -> demo.ext:managed missing', - }, - { - name: 'a managed-scope node left dev', - options: { dev: [MANAGED] }, - message: 'managed-scope demo.ext:managed not in a prod root', - }, - { - name: 'a provided dependency in a prod root', - options: { prod: [CONTAINER_API] }, - message: 'provided demo.ext:container-api wrongly in a prod root', - }, - { - name: 'a compile dependency of a provided one left dev', - options: { dev: [CONTAINER_LIB] }, - message: 'demo.ext:container-lib not in a prod root', - }, - ] satisfies Array<{ - name: string - options: RecordsOptions - message: string - }>)('rejects $name', ({ message, options }) => { - const { output, status } = assertRecords(options) - - expect(output).toContain(message) - expect(status).not.toBe(0) - }) -}) From 65cf8cbe9787cbfe1b9eef12db225e092b44ec5f Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 05:56:43 +0100 Subject: [PATCH 02/23] Take what each build loads from Coana's projects Discovery decides which builds to keep from what each build loads: its projects' directories as well as their build files, anywhere in the scan root. A Gradle or sbt build of its own nested in another is covered only by a build that loads all of its project directories, and a project without a build file is loaded only through its directory. coveredBuildFiles carries neither the directories nor the build files outside the build root, so socket-cli now reads the generated result's `projects`, each with its absolute `dir` and `buildFiles`, and keeps what lies in the scan root. This needs a Coana that reports `projects` in place of coveredBuildFiles. --- .../manifest/discover-manifest-roots.mts | 39 ++--- .../manifest/discover-manifest-roots.test.mts | 26 ++-- .../manifest/generate-recursive-manifests.mts | 9 +- .../generate-recursive-manifests.test.mts | 138 +++++++++++++++++- src/commands/manifest/load-build.mts | 15 +- src/commands/manifest/run-manifest-facts.mts | 11 +- .../manifest/run-manifest-facts.test.mts | 9 +- 7 files changed, 180 insertions(+), 67 deletions(-) diff --git a/src/commands/manifest/discover-manifest-roots.mts b/src/commands/manifest/discover-manifest-roots.mts index 3e3660d263..f056086290 100644 --- a/src/commands/manifest/discover-manifest-roots.mts +++ b/src/commands/manifest/discover-manifest-roots.mts @@ -18,9 +18,11 @@ import { getOrInsert } from '../../utils/get-or-insert.mts' import { globWithGitIgnore } from '../../utils/glob.mts' import { excludePathToScanIgnores } from '../scan/exclude-paths.mts' -import type { SocketFactsContext } from './run-manifest-facts.mts' +import type { + SocketFactsContext, + SocketFactsProject, +} from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { SocketJson } from '../../utils/socket-json.mts' import type { SocketYml } from '@socketsecurity/config' @@ -131,26 +133,19 @@ export function isPathInside(dir: string, file: string): boolean { return file === dir || file.startsWith(`${dir}${path.sep}`) } -// Paths are relative to `buildRoot`. Only what lies inside `scanRoot` (when -// given) counts, as only that can be a candidate. +// Only what lies inside `scanRoot` (when given) counts, as only that can be a +// candidate. export async function membershipOf( - buildRoot: string, - projects: readonly SocketFactsSbomProject[], + projects: readonly SocketFactsProject[], scanRoot?: string | undefined, ): Promise { const realScanRoot = scanRoot ? await realpathOrResolved(scanRoot) : undefined const inScan = (p: string) => !realScanRoot || isPathInside(realScanRoot, p) const membership = emptyMembership() const [dirs, files] = await Promise.all([ + Promise.all(projects.map(({ dir }) => realpathOrResolved(dir))), Promise.all( - projects.map(({ subprojectDir }) => - realpathOrResolved(path.resolve(buildRoot, subprojectDir)), - ), - ), - Promise.all( - projects - .flatMap(project => project.manifestFiles ?? []) - .map(({ file }) => realFilePath(path.resolve(buildRoot, file))), + projects.flatMap(({ buildFiles }) => buildFiles).map(realFilePath), ), ]) for (const dir of dirs) { @@ -166,22 +161,6 @@ export async function membershipOf( return membership } -// Coana reports the realpath-resolved build files a build covers. -export async function membershipOfBuildFiles( - files: readonly string[], - scanRoot?: string | undefined, -): Promise { - const realScanRoot = scanRoot ? await realpathOrResolved(scanRoot) : undefined - return { - dirs: new Set(), - files: new Set( - realScanRoot - ? files.filter(file => isPathInside(realScanRoot, file)) - : files, - ), - } -} - const rootMarkerByDir = new Map() export function hasRootMarker(tool: BuildTool, root: BuildRoot): boolean { diff --git a/src/commands/manifest/discover-manifest-roots.test.mts b/src/commands/manifest/discover-manifest-roots.test.mts index 231085c529..697842d963 100644 --- a/src/commands/manifest/discover-manifest-roots.test.mts +++ b/src/commands/manifest/discover-manifest-roots.test.mts @@ -311,17 +311,6 @@ describe('isBuildRootCovered', () => { ) }) -function mavenProject(subprojectDir: string, file: string) { - return { - type: 'maven' as const, - name: subprojectDir, - id: subprojectDir, - subprojectDir, - manifestFiles: [{ file }], - children: [], - } -} - describe('membershipOf', () => { let scanRoot = '' @@ -341,14 +330,17 @@ describe('membershipOf', () => { await fs.rm(scanRoot, { recursive: true, force: true }) }) - it('takes project dirs and existing build files anywhere in the scan root, relative to the build root', async () => { + it('takes project dirs and existing build files in the scan root', async () => { + const at = (rel: string) => path.resolve(scanRoot, rel) const membership = await membershipOf( - path.join(scanRoot, 'build'), [ - mavenProject('member', 'member/pom.xml'), - mavenProject('../sibling', '../sibling/pom.xml'), - mavenProject('absent', 'absent/build.gradle'), - mavenProject('../../outside', '../../outside/pom.xml'), + { buildFiles: [at('build/member/pom.xml')], dir: at('build/member') }, + { buildFiles: [at('sibling/pom.xml')], dir: at('sibling') }, + { + buildFiles: [at('build/absent/build.gradle')], + dir: at('build/absent'), + }, + { buildFiles: [at('../outside/pom.xml')], dir: at('../outside') }, ], scanRoot, ) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 4ad8be7d8a..9e4f830d4f 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -21,7 +21,7 @@ import { isBuildRootCovered, isPathInside, isRootCovered, - membershipOfBuildFiles, + membershipOf, realpathOrResolved, unionMemberships, withoutDisabledFlags, @@ -728,7 +728,7 @@ async function runCandidate( ...candidate, factsKey, membership: result - ? await membershipOfBuildFiles(result.coveredBuildFiles, ctx.realCwd) + ? await membershipOf(result.projects, ctx.realCwd) : emptyMembership(), output, result: result ?? undefined, @@ -824,10 +824,7 @@ export async function buildUncoveredRoot({ verbose: config.verbose, }) if (result) { - addMembership( - covered, - await membershipOfBuildFiles(result.coveredBuildFiles), - ) + addMembership(covered, await membershipOf(result.projects)) } return result } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index c150a6ec1b..b9215482f6 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -54,11 +54,13 @@ type TestFacts = { factsPath: string; projects: TestProject[] } function reported({ factsPath, projects }: TestFacts) { const buildRoot = path.dirname(factsPath) return { - coveredBuildFiles: projects - .flatMap(project => project.manifestFiles ?? []) - .map(({ file }) => path.resolve(buildRoot, file)) - .filter(file => existsSync(file)), factsPath, + projects: projects.map(project => ({ + buildFiles: (project.manifestFiles ?? []).map(({ file }) => + path.resolve(buildRoot, file), + ), + dir: path.resolve(buildRoot, project.subprojectDir), + })), } } @@ -261,6 +263,70 @@ describe('generateRecursiveManifests', () => { }, ) + it.for([ + // The build that redirects Gradle with `-p` runs second, then first. + ['a-main', 'z-alias'], + ['z-main', 'a-alias'], + ])( + 'keeps the facts and sidecar entry of the kept run together when two runs write one facts file (%s, %s)', + async ([mainName, aliasName]) => { + const outer = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'shared-facts-')), + ) + const main = path.join(outer, mainName!) + const alias = path.join(outer, aliasName!) + const workDir = newWorkDir() + try { + for (const dir of [main, alias]) { + for (const file of ['settings.gradle', 'build.gradle']) { + // eslint-disable-next-line no-await-in-loop + await fs.mkdir(dir, { recursive: true }) + // eslint-disable-next-line no-await-in-loop + await fs.writeFile(path.join(dir, file), '') + } + } + mockFacts(async ({ cwd }) => { + const factsPath = path.join(main, 'gradle.socket.facts.json') + await fs.writeFile(factsPath, cwd) + setSidecarEntry(workDir, factsPath, { + factsFile: factsPath, + stateDir: cwd, + }) + return { + factsPath, + projects: [ + { + type: 'maven' as const, + name: 'root', + id: 'root', + subprojectDir: '.', + children: [], + }, + ], + } + }) + + const outcomes = await generateRecursiveManifests({ + context: { workDir }, + cwd: outer, + verbose: false, + }) + + const generated = outcomes.filter(o => o.status === 'generated') + expect(generated).toHaveLength(1) + const { factsPath } = generated[0]! + expect(generated[0]!.discardedFactsPath).toBeUndefined() + // The kept build's own facts and sidecar entry, whichever ran last. + expect(await fs.readFile(factsPath!, 'utf8')).toBe(generated[0]!.dir) + expect(workDir.entries).toEqual([ + { factsFile: factsPath, stateDir: generated[0]!.dir }, + ]) + } finally { + await fs.rm(outer, { recursive: true, force: true }) + } + }, + ) + it('removes the facts file of a dropped run when none existed before it', async () => { const outer = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'dropped-run-')), @@ -1268,6 +1334,70 @@ describe('generateRecursiveManifests', () => { await fs.rm(outer, { recursive: true, force: true }) }) + it.for([ + // sub's own settings include `a`, which the outer build does not load. + [['.', 'a'], 'generated'], + // Everything sub loads, the outer build loads too. + [['.'], 'skippedCovered'], + ] as const)( + 'runs the nested build and keeps it only when it loads more (%j)', + async ({ 0: subProjects, 1: subStatus }) => { + const sub = path.join(outer, 'sub') + mockFacts(async ({ cwd }) => + cwd === outer + ? gradleFacts(cwd, [ + '.', + 'sub', + ...(subProjects.length > 1 ? [] : ['sub/a']), + ]) + : gradleFacts(cwd, [...subProjects]), + ) + + const outcomes = await generateRecursiveManifests({ + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }) + + const byDir = new Map( + outcomes + .filter(o => o.ecosystem === 'gradle') + .map(o => [path.relative(outer, o.dir) || '.', o.status]), + ) + expect(byDir.get('.')).toBe('generated') + expect(byDir.get('sub')).toBe(subStatus) + expect(byDir.get('sub/a')).toBe('skippedCovered') + expect( + vi + .mocked(runManifestFacts) + .mock.calls.map(([o]) => path.relative(outer, o.cwd) || '.'), + ).toEqual(['.', 'sub']) + }, + ) + + it('ignores the failure of a nested build of its own when the build that includes its directory succeeds', async () => { + mockFacts(async ({ cwd }) => { + if (cwd === path.join(outer, 'sub')) { + process.exitCode = 1 + return null + } + return gradleFacts(cwd, ['.', 'sub', 'sub/a']) + }) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + + const outcomes = await generateRecursiveManifests({ + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }) + + expect( + outcomes.find(o => o.dir === path.join(outer, 'sub'))?.status, + ).toBe('skippedCovered') + expect(outcomes.some(o => o.status === 'failed')).toBe(false) + expect(process.exitCode).toBeUndefined() + }) + it.for([ // `a` is a project of sub: skipped with what sub loads. [['.', 'a'], 'and its 1 module'], diff --git a/src/commands/manifest/load-build.mts b/src/commands/manifest/load-build.mts index c65d48ee75..c7ebb9906b 100644 --- a/src/commands/manifest/load-build.mts +++ b/src/commands/manifest/load-build.mts @@ -1,3 +1,5 @@ +import path from 'node:path' + import { pluralize } from '@socketsecurity/registry/lib/words' import { membershipOf } from './discover-manifest-roots.mts' @@ -43,9 +45,18 @@ export async function loadBuild({ if (!result) { return undefined } + const { buildRoot, projects } = result return { - membership: await membershipOf(result.buildRoot, result.projects, scanRoot), - modules: Math.max(0, result.projects.length - 1), + membership: await membershipOf( + projects.map(({ manifestFiles, subprojectDir }) => ({ + buildFiles: (manifestFiles ?? []).map(({ file }) => + path.resolve(buildRoot, file), + ), + dir: path.resolve(buildRoot, subprojectDir), + })), + scanRoot, + ), + modules: Math.max(0, projects.length - 1), } } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 3a14c91514..e179ff8500 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -92,10 +92,13 @@ export type SocketFactsContext = { workDir?: SocketFactsWorkDir | undefined } +// A project the build loaded, with absolute paths. Gradle reports a project's +// build file even when absent. +export type SocketFactsProject = { buildFiles: string[]; dir: string } + export type RunManifestFactsResult = { - // Realpath-resolved build files the build covers. - coveredBuildFiles: string[] factsPath: string + projects: SocketFactsProject[] } // `null` = a real failure (crash, missing config, blocking unresolved @@ -128,8 +131,8 @@ type SocketFactsRequest = { type SocketFactsResult = | { - coveredBuildFiles: string[] factsPath: string + projects: SocketFactsProject[] sidecarEntry?: SocketFactsSidecarEntry | undefined status: 'generated' } @@ -383,7 +386,7 @@ export async function runManifestFacts({ setSidecarEntry(workDir, result.factsPath, result.sidecarEntry) } return { - coveredBuildFiles: result.coveredBuildFiles, factsPath: result.factsPath, + projects: result.projects, } } diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 6e8beeae46..de9ac5b119 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -71,9 +71,10 @@ afterEach(async () => { describe('runManifestFacts', () => { it('asks Coana for one build root with its options as written', async () => { + const projects = [{ buildFiles: [path.join(cwd, 'pom.xml')], dir: cwd }] coanaAnswers({ - coveredBuildFiles: [path.join(cwd, 'pom.xml')], factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + projects, status: 'generated', }) const result = await runManifestFacts({ @@ -86,8 +87,8 @@ describe('runManifestFacts', () => { javaHome: '$JAVA11_HOME', }) expect(result).toEqual({ - coveredBuildFiles: [path.join(cwd, 'pom.xml')], factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + projects, }) expect(calls[0]!.args.slice(0, 1)).toEqual(['generate-socket-facts']) expect(calls[0]!.args).not.toContain('--work-dir') @@ -133,8 +134,8 @@ describe('runManifestFacts', () => { stateDir: '/w/x', } coanaAnswers({ - coveredBuildFiles: [], factsPath: entry.factsFile, + projects: [], sidecarEntry: entry, status: 'generated', }) @@ -154,8 +155,8 @@ describe('runManifestFacts', () => { it('keeps state without installing files for socket fix', async () => { coanaAnswers({ - coveredBuildFiles: [], factsPath: '/r/f', + projects: [], sidecarEntry: { factsFile: '/r/f', stateDir: '/w/y' }, status: 'generated', }) From 25a8ed097f69167326fad759c386972340f6fd4a Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 13 Nov 2026 18:12:10 +0100 Subject: [PATCH 03/23] List the setup wizard's workspaces with Coana `socket manifest setup --dynamic-sbom-inference` skips the build roots a parent build already declares. It now learns which build files a build covers from `coana generate-socket-facts --list-projects`, which lists the build's projects without resolving it (`sparjvm workspaces` for Gradle, Maven and sbt, the dotnet tool's workspaces mode for .NET). That was the last use of socket-cli's own build-tool machinery, so it goes: the workspace enumeration runner, the Gradle init script and sbt plugin, the Maven extension, the dotnet tool, the records parser and assembler, the exclude-path glob compiler, the javaHome expander, their tests and compat suites, the Rollup copy step, the build:dotnet-tool and build:maven-extension scripts, and the steps that built them for npm, the package matrix and the standalone build. The standalone build no longer embeds the .NET facts helper or lists manifest-dotnet-facts as available. --- .config/rollup.dist.config.mjs | 57 -- .github/workflows/ci.yml | 4 - .github/workflows/publish-npm.yml | 22 - .gitignore | 208 ------ package.json | 2 - scripts/build-package-matrix.mts | 4 - socket.yml | 5 - .../manifest/enumerate-workspaces.mts | 113 --- .../manifest/enumerate-workspaces.test.mts | 122 ---- src/commands/manifest/expand-env-var-refs.mts | 33 - .../manifest/expand-env-var-refs.test.mts | 67 -- .../generate-recursive-manifests.test.mts | 64 +- src/commands/manifest/load-build.mts | 19 +- src/commands/manifest/run-manifest-facts.mts | 66 ++ .../manifest/run-manifest-facts.test.mts | 51 ++ src/commands/manifest/scripts/assemble.mts | 670 ------------------ .../manifest/scripts/assemble.test.mts | 647 ----------------- src/commands/manifest/scripts/build-tool.mts | 3 - .../manifest/scripts/build-tool.test.mts | 31 - .../manifest/scripts/dotnet-tool/.gitignore | 3 - .../scripts/dotnet-tool/FactsRunner.cs | 344 --------- .../manifest/scripts/dotnet-tool/NuGetShim.cs | 23 - .../manifest/scripts/dotnet-tool/Patterns.cs | 140 ---- .../manifest/scripts/dotnet-tool/Program.cs | 23 - .../manifest/scripts/dotnet-tool/Reader.cs | 662 ----------------- .../scripts/dotnet-tool/RecordsWriter.cs | 81 --- .../manifest/scripts/dotnet-tool/Restorer.cs | 89 --- .../scripts/dotnet-tool/SolutionContext.cs | 101 --- .../scripts/dotnet-tool/ToolOptions.cs | 167 ----- .../scripts/dotnet-tool/build-tool.sh | 18 - .../scripts/dotnet-tool/packages.lock.json | 281 -------- .../dotnet-tool/socket-facts-dotnet.csproj | 48 -- .../manifest/scripts/exclude-paths-glob.mts | 156 ---- .../scripts/exclude-paths-glob.test.mts | 196 ----- src/commands/manifest/scripts/facts.mts | 113 --- .../scripts/maven-extension/.gitignore | 3 - .../.mvn/wrapper/maven-wrapper.properties | 3 - .../scripts/maven-extension/build-jar.sh | 10 - .../manifest/scripts/maven-extension/mvnw | 295 -------- .../manifest/scripts/maven-extension/mvnw.cmd | 189 ----- .../manifest/scripts/maven-extension/pom.xml | 89 --- .../CoanaWorkspacesLifecycleParticipant.java | 58 -- .../java/tech/coana/socket/SocketSupport.java | 93 --- .../socket/SocketWorkspacesRecordsEngine.java | 70 -- src/commands/manifest/scripts/records.mts | 415 ----------- .../manifest/scripts/resolution-report.mts | 33 - src/commands/manifest/scripts/run.mts | 407 ----------- src/commands/manifest/scripts/run.test.mts | 191 ----- .../scripts/socket-workspaces.init.gradle | 121 ---- .../scripts/socket-workspaces.plugin.scala | 145 ---- src/commands/manifest/scripts/test/README.md | 29 - .../manifest/scripts/test/compat-cache.sh | 6 - .../scripts/test/dotnet-compat/.gitignore | 2 - .../test/dotnet-compat/basic/Basic.sln | 82 --- .../test/dotnet-compat/basic/shared/Linked.cs | 1 - .../dotnet-compat/basic/src/App/App.csproj | 8 - .../dotnet-compat/basic/src/App/Program.cs | 1 - .../test/dotnet-compat/basic/src/Extra/E.cs | 1 - .../basic/src/Extra/Extra.csproj | 4 - .../test/dotnet-compat/basic/src/Lib/L.cs | 1 - .../dotnet-compat/basic/src/Lib/Lib.csproj | 11 - .../basic/test/App.Tests/App.Tests.csproj | 8 - .../dotnet-compat/basic/test/App.Tests/T.cs | 1 - .../basic/tools/Nuke/Nuke.csproj | 5 - .../dotnet-compat/exclude-base/app/App.csproj | 7 - .../dotnet-compat/exclude-base/app/App.sln | 67 -- .../exclude-base/app/core/Core.csproj | 3 - .../exclude-base/shared/Shared.csproj | 3 - .../scripts/test/dotnet-compat/lib.sh | 35 - .../dotnet-compat/smoke-test-exclude-base.sh | 56 -- .../dotnet-compat/smoke-test-workspaces.sh | 68 -- .../scripts/test/gradle-compat/.gitignore | 4 - .../exclude-base/app/build.gradle | 1 - .../exclude-base/app/core/build.gradle | 1 - .../exclude-base/app/settings.gradle | 4 - .../exclude-base/shared/build.gradle | 1 - .../test/gradle-compat/project/build.gradle | 4 - .../gradle-compat/project/settings.gradle | 1 - .../gradle-compat/smoke-test-exclude-base.sh | 38 - .../gradle-compat/smoke-test-workspaces.sh | 61 -- .../scripts/test/maven-compat/.gitignore | 4 - .../exclude-base/app/core/pom.xml | 11 - .../maven-compat/exclude-base/app/pom.xml | 12 - .../maven-compat/exclude-base/shared/pom.xml | 11 - .../test/maven-compat/project/app/pom.xml | 10 - .../test/maven-compat/project/lib/pom.xml | 10 - .../test/maven-compat/project/mid/pom.xml | 10 - .../scripts/test/maven-compat/project/pom.xml | 13 - .../maven-compat/smoke-test-exclude-base.sh | 41 -- .../maven-compat/smoke-test-workspaces.sh | 64 -- .../manifest/scripts/test/run-compat.sh | 143 ---- .../scripts/test/sbt-compat/.gitignore | 5 - .../sbt-compat/exclude-base/app/build.sbt | 2 - .../scripts/test/sbt-compat/project/build.sbt | 14 - .../sbt-compat/smoke-test-exclude-base.sh | 43 -- .../test/sbt-compat/smoke-test-workspaces.sh | 73 -- .../setup-recursive-manifest-config.test.mts | 48 +- src/sea/README.md | 4 +- src/sea/build-sea.mts | 49 +- src/sea/capabilities.mts | 1 - test/release-workflow.test.mts | 17 +- test/unit/sea/build-sea.test.mts | 2 +- 102 files changed, 184 insertions(+), 7672 deletions(-) delete mode 100644 src/commands/manifest/enumerate-workspaces.mts delete mode 100644 src/commands/manifest/enumerate-workspaces.test.mts delete mode 100644 src/commands/manifest/expand-env-var-refs.mts delete mode 100644 src/commands/manifest/expand-env-var-refs.test.mts delete mode 100644 src/commands/manifest/scripts/assemble.mts delete mode 100644 src/commands/manifest/scripts/assemble.test.mts delete mode 100644 src/commands/manifest/scripts/build-tool.test.mts delete mode 100644 src/commands/manifest/scripts/dotnet-tool/.gitignore delete mode 100644 src/commands/manifest/scripts/dotnet-tool/FactsRunner.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/NuGetShim.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/Patterns.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/Program.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/Reader.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/RecordsWriter.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/Restorer.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/SolutionContext.cs delete mode 100644 src/commands/manifest/scripts/dotnet-tool/ToolOptions.cs delete mode 100755 src/commands/manifest/scripts/dotnet-tool/build-tool.sh delete mode 100644 src/commands/manifest/scripts/dotnet-tool/packages.lock.json delete mode 100644 src/commands/manifest/scripts/dotnet-tool/socket-facts-dotnet.csproj delete mode 100644 src/commands/manifest/scripts/exclude-paths-glob.mts delete mode 100644 src/commands/manifest/scripts/exclude-paths-glob.test.mts delete mode 100644 src/commands/manifest/scripts/facts.mts delete mode 100644 src/commands/manifest/scripts/maven-extension/.gitignore delete mode 100644 src/commands/manifest/scripts/maven-extension/.mvn/wrapper/maven-wrapper.properties delete mode 100755 src/commands/manifest/scripts/maven-extension/build-jar.sh delete mode 100755 src/commands/manifest/scripts/maven-extension/mvnw delete mode 100644 src/commands/manifest/scripts/maven-extension/mvnw.cmd delete mode 100644 src/commands/manifest/scripts/maven-extension/pom.xml delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java delete mode 100644 src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java delete mode 100644 src/commands/manifest/scripts/records.mts delete mode 100644 src/commands/manifest/scripts/resolution-report.mts delete mode 100644 src/commands/manifest/scripts/run.mts delete mode 100644 src/commands/manifest/scripts/run.test.mts delete mode 100644 src/commands/manifest/scripts/socket-workspaces.init.gradle delete mode 100644 src/commands/manifest/scripts/socket-workspaces.plugin.scala delete mode 100644 src/commands/manifest/scripts/test/README.md delete mode 100755 src/commands/manifest/scripts/test/compat-cache.sh delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/.gitignore delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/Basic.sln delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/shared/Linked.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/App.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/Program.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/E.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/Extra.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/L.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/Lib.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/App.Tests.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/T.cs delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/Nuke.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.sln delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/Core.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/Shared.csproj delete mode 100644 src/commands/manifest/scripts/test/dotnet-compat/lib.sh delete mode 100755 src/commands/manifest/scripts/test/dotnet-compat/smoke-test-exclude-base.sh delete mode 100755 src/commands/manifest/scripts/test/dotnet-compat/smoke-test-workspaces.sh delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/.gitignore delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/settings.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/project/build.gradle delete mode 100644 src/commands/manifest/scripts/test/gradle-compat/project/settings.gradle delete mode 100755 src/commands/manifest/scripts/test/gradle-compat/smoke-test-exclude-base.sh delete mode 100755 src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh delete mode 100644 src/commands/manifest/scripts/test/maven-compat/.gitignore delete mode 100644 src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/exclude-base/app/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml delete mode 100644 src/commands/manifest/scripts/test/maven-compat/project/pom.xml delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-exclude-base.sh delete mode 100755 src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh delete mode 100755 src/commands/manifest/scripts/test/run-compat.sh delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/.gitignore delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/build.sbt delete mode 100644 src/commands/manifest/scripts/test/sbt-compat/project/build.sbt delete mode 100755 src/commands/manifest/scripts/test/sbt-compat/smoke-test-exclude-base.sh delete mode 100755 src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh diff --git a/.config/rollup.dist.config.mjs b/.config/rollup.dist.config.mjs index 7ef22943f0..e530391e46 100644 --- a/.config/rollup.dist.config.mjs +++ b/.config/rollup.dist.config.mjs @@ -38,7 +38,6 @@ import { const { CONSTANTS, INLINED_SOCKET_CLI_LEGACY_BUILD, - INLINED_SOCKET_CLI_PUBLISHED_BUILD, INLINED_SOCKET_CLI_SENTRY_BUILD, INSTRUMENT_WITH_SENTRY, NODE_MODULES, @@ -109,61 +108,6 @@ async function copyInitGradle() { await fs.copyFile(filepath, destPath) } -// Copy the workspace-enumeration assets (Gradle init script, sbt plugin, Maven -// extension jar, dotnet tool) into dist/manifest-scripts, where run.mts resolves them -// at runtime. The Maven jar is compiled by maven-extension/build-jar.sh. Local -// dev builds may omit it; published builds fail here if it is missing. -async function copyManifestScripts() { - const srcDir = path.join(constants.srcPath, 'commands/manifest/scripts') - const destDir = path.join(constants.distPath, 'manifest-scripts') - await fs.mkdir(path.join(destDir, 'maven-extension'), { recursive: true }) - await Promise.all([ - fs.copyFile( - path.join(srcDir, 'socket-workspaces.init.gradle'), - path.join(destDir, 'socket-workspaces.init.gradle'), - ), - fs.copyFile( - path.join(srcDir, 'socket-workspaces.plugin.scala'), - path.join(destDir, 'socket-workspaces.plugin.scala'), - ), - ]) - // The dotnet tool's publish output (scripts/dotnet-tool/build-tool.sh), - // like the Maven jar absent from a fresh checkout. - const dotnetToolDir = path.join(srcDir, 'dotnet-tool', 'publish') - if (existsSync(path.join(dotnetToolDir, 'socket-facts-dotnet.dll'))) { - await fs.cp(dotnetToolDir, path.join(destDir, 'dotnet-tool'), { - recursive: true, - }) - } else if (constants.ENV[INLINED_SOCKET_CLI_PUBLISHED_BUILD]) { - throw new Error( - 'dotnet manifest tool not found at ' + - dotnetToolDir + - ' for a published build. Build it first: pnpm run build:dotnet-tool', - ) - } - const jarPath = path.join( - srcDir, - 'maven-extension', - 'coana-maven-extension.jar', - ) - if (existsSync(jarPath)) { - await fs.copyFile( - jarPath, - path.join(destDir, 'maven-extension', 'coana-maven-extension.jar'), - ) - } else if (constants.ENV[INLINED_SOCKET_CLI_PUBLISHED_BUILD]) { - // Fail closed: a published build without the jar would ship a package whose - // `socket manifest setup` cannot list Maven projects. Run - // `pnpm run build:maven-extension` before `build:dist`. (A local dev build - // tolerates a missing jar; run.mts surfaces a hint at runtime.) - throw new Error( - 'Maven manifest extension jar not found at ' + - jarPath + - ' for a published build. Build it first: pnpm run build:maven-extension', - ) - } -} - async function copyBashCompletion() { const filepath = path.join( constants.srcPath, @@ -571,7 +515,6 @@ export default async () => { await Promise.all([ copyCoanaCache(), copyInitGradle(), - copyManifestScripts(), copyBashCompletion(), ...(updatePackageMetadata ? [updatePackageJson()] : []), // Remove dist/vendor.js.map file. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 73cfc03e68..ed95fadd9b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -757,10 +757,6 @@ jobs: pnpm exec vitest run --config .config/vitest.config.mts test/unit/scripts/test/apple-signing.test.mts pnpm exec vitest run --config .config/vitest.terminal.config.mts - - name: Verify .NET SDK - shell: bash - run: dotnet --list-sdks | awk -F. '$1 >= 8 { found=1 } END { exit !found }' - - name: Build prototype native executable env: NODE_OPTIONS: ${{ matrix.target == 'darwin-arm64' && '--max-old-space-size=4096' || '' }} diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 64f01860c0..4f4dbb061f 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -366,28 +366,6 @@ jobs: exit 1 fi - # Compile the Maven manifest extension jar so the dist build bundles it - # into dist/manifest-scripts (the jar is never committed; it ships only in - # the published package). Invoke build-jar.sh directly, NOT via `pnpm run`: - # Socket Firewall wraps the package managers (npm/pnpm/...) it shims, so a - # `pnpm run` would route the Maven wrapper's download through sfw, which - # fails on the non-package fetch. Running bash directly keeps the Maven - # download outside the shimmed process tree. The org action allowlist forbids - # actions/setup-java, so use a JDK pre-installed on the runner image - # (JAVA_HOME_17_X64), falling back to the runner's default `java`. - - name: Build Maven manifest extension jar - run: | - if [ -n "${JAVA_HOME_17_X64:-}" ]; then - export JAVA_HOME="$JAVA_HOME_17_X64" - fi - bash src/commands/manifest/scripts/maven-extension/build-jar.sh - - # Same for the dotnet manifest tool: built here, bundled into - # dist/manifest-scripts, never committed. The runner image's preinstalled - # .NET SDK builds it (actions/setup-dotnet is not on the org allowlist). - - name: Build dotnet manifest tool - run: bash src/commands/manifest/scripts/dotnet-tool/build-tool.sh - # PACK ONCE, PUBLISH THOSE BYTES. Each variant is built, packed to a # tarball, and smoke-tested from that tarball; the three tarballs are # uploaded as an artifact and the publish job stages those exact files. diff --git a/.gitignore b/.gitignore index 2c1bda539a..902c9807e0 100644 --- a/.gitignore +++ b/.gitignore @@ -60,110 +60,6 @@ !/src/commands/manifest/ !/src/commands/manifest/bazel/ !/src/commands/manifest/scripts/ -!/src/commands/manifest/scripts/dotnet-tool/ -!/src/commands/manifest/scripts/maven-extension/ -!/src/commands/manifest/scripts/maven-extension/.mvn/ -!/src/commands/manifest/scripts/maven-extension/.mvn/wrapper/ -!/src/commands/manifest/scripts/maven-extension/src/ -!/src/commands/manifest/scripts/maven-extension/src/main/ -!/src/commands/manifest/scripts/maven-extension/src/main/java/ -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/ -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/ -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/ -!/src/commands/manifest/scripts/test/ -!/src/commands/manifest/scripts/test/dotnet-compat/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/shared/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/test/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/ -!/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/ -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/ -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/ -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Api/ -!/src/commands/manifest/scripts/test/dotnet-compat/cpm/src/Core/ -!/src/commands/manifest/scripts/test/dotnet-compat/dev/ -!/src/commands/manifest/scripts/test/dotnet-compat/evaluation/ -!/src/commands/manifest/scripts/test/dotnet-compat/evaluation/Lib/ -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/ -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/ -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/ -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/ -!/src/commands/manifest/scripts/test/dotnet-compat/failures/ -!/src/commands/manifest/scripts/test/dotnet-compat/failures/broken/ -!/src/commands/manifest/scripts/test/dotnet-compat/failures/missing/ -!/src/commands/manifest/scripts/test/dotnet-compat/langs/ -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Fs/ -!/src/commands/manifest/scripts/test/dotnet-compat/langs/Vb/ -!/src/commands/manifest/scripts/test/dotnet-compat/multi/ -!/src/commands/manifest/scripts/test/dotnet-compat/multi/One/ -!/src/commands/manifest/scripts/test/dotnet-compat/multi/Two/ -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/ -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/ -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Legacy/Properties/ -!/src/commands/manifest/scripts/test/dotnet-compat/packages-config/Modern/ -!/src/commands/manifest/scripts/test/dotnet-compat/pair/ -!/src/commands/manifest/scripts/test/dotnet-compat/rid/ -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/ -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/sln/ -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/ -!/src/commands/manifest/scripts/test/dotnet-compat/sibling/src/A/ -!/src/commands/manifest/scripts/test/gradle-compat/ -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/ -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/ -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/ -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/ -!/src/commands/manifest/scripts/test/gradle-compat/failures/ -!/src/commands/manifest/scripts/test/gradle-compat/failures/app/ -!/src/commands/manifest/scripts/test/gradle-compat/failures/gradle/ -!/src/commands/manifest/scripts/test/gradle-compat/failures/lib/ -!/src/commands/manifest/scripts/test/gradle-compat/project/ -!/src/commands/manifest/scripts/test/maven-compat/ -!/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/ -!/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/a/ -!/src/commands/manifest/scripts/test/maven-compat/descriptor-failure/b/ -!/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/ -!/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m1/ -!/src/commands/manifest/scripts/test/maven-compat/duplicate-failure/m2/ -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/ -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/ -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/ -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/ -!/src/commands/manifest/scripts/test/maven-compat/graph-failure/ -!/src/commands/manifest/scripts/test/maven-compat/project/ -!/src/commands/manifest/scripts/test/maven-compat/project/app/ -!/src/commands/manifest/scripts/test/maven-compat/project/app/src/ -!/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/ -!/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/ -!/src/commands/manifest/scripts/test/maven-compat/project/app/src/main/java/demo/ -!/src/commands/manifest/scripts/test/maven-compat/project/lib/ -!/src/commands/manifest/scripts/test/maven-compat/project/lib/src/ -!/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/ -!/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/ -!/src/commands/manifest/scripts/test/maven-compat/project/lib/src/main/java/demo/ -!/src/commands/manifest/scripts/test/maven-compat/project/mid/ -!/src/commands/manifest/scripts/test/maven-compat/project/mid/src/ -!/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/ -!/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/ -!/src/commands/manifest/scripts/test/maven-compat/project/mid/src/main/java/demo/ -!/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/ -!/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/liba/ -!/src/commands/manifest/scripts/test/maven-compat/repo-inheritance/libb/ -!/src/commands/manifest/scripts/test/sbt-compat/ -!/src/commands/manifest/scripts/test/sbt-compat/artifact-failure/ -!/src/commands/manifest/scripts/test/sbt-compat/exclude-base/ -!/src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/ -!/src/commands/manifest/scripts/test/sbt-compat/failure/ -!/src/commands/manifest/scripts/test/sbt-compat/project/ -!/src/commands/manifest/scripts/test/sbt-compat/project/src/ -!/src/commands/manifest/scripts/test/sbt-compat/project/src/main/ -!/src/commands/manifest/scripts/test/sbt-compat/project/src/main/scala/ -!/src/commands/manifest/scripts/test/sbt-compat/relocation/ !/src/commands/npm/ !/src/commands/npx/ !/src/commands/oops/ @@ -593,10 +489,6 @@ !/src/commands/manifest/detect-manifest-actions.test.mts !/src/commands/manifest/discover-manifest-roots.mts !/src/commands/manifest/discover-manifest-roots.test.mts -!/src/commands/manifest/enumerate-workspaces.mts -!/src/commands/manifest/enumerate-workspaces.test.mts -!/src/commands/manifest/expand-env-var-refs.mts -!/src/commands/manifest/expand-env-var-refs.test.mts !/src/commands/manifest/generate-recursive-manifests.mts !/src/commands/manifest/generate-recursive-manifests.test.mts !/src/commands/manifest/generate_auto_manifest.mts @@ -616,88 +508,7 @@ !/src/commands/manifest/run-cdxgen.mts !/src/commands/manifest/run-manifest-facts.mts !/src/commands/manifest/run-manifest-facts.test.mts -!/src/commands/manifest/scripts/assemble.mts -!/src/commands/manifest/scripts/assemble.test.mts !/src/commands/manifest/scripts/build-tool.mts -!/src/commands/manifest/scripts/build-tool.test.mts -!/src/commands/manifest/scripts/dotnet-tool/.gitignore -!/src/commands/manifest/scripts/dotnet-tool/FactsRunner.cs -!/src/commands/manifest/scripts/dotnet-tool/NuGetShim.cs -!/src/commands/manifest/scripts/dotnet-tool/Patterns.cs -!/src/commands/manifest/scripts/dotnet-tool/Program.cs -!/src/commands/manifest/scripts/dotnet-tool/Reader.cs -!/src/commands/manifest/scripts/dotnet-tool/RecordsWriter.cs -!/src/commands/manifest/scripts/dotnet-tool/Restorer.cs -!/src/commands/manifest/scripts/dotnet-tool/SolutionContext.cs -!/src/commands/manifest/scripts/dotnet-tool/ToolOptions.cs -!/src/commands/manifest/scripts/dotnet-tool/build-tool.sh -!/src/commands/manifest/scripts/dotnet-tool/packages.lock.json -!/src/commands/manifest/scripts/dotnet-tool/socket-facts-dotnet.csproj -!/src/commands/manifest/scripts/exclude-paths-glob.mts -!/src/commands/manifest/scripts/exclude-paths-glob.test.mts -!/src/commands/manifest/scripts/facts.mts -!/src/commands/manifest/scripts/maven-extension/.gitignore -!/src/commands/manifest/scripts/maven-extension/.mvn/wrapper/maven-wrapper.properties -!/src/commands/manifest/scripts/maven-extension/build-jar.sh -!/src/commands/manifest/scripts/maven-extension/mvnw -!/src/commands/manifest/scripts/maven-extension/mvnw.cmd -!/src/commands/manifest/scripts/maven-extension/pom.xml -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java -!/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java -!/src/commands/manifest/scripts/records.mts -!/src/commands/manifest/scripts/resolution-report.mts -!/src/commands/manifest/scripts/run.mts -!/src/commands/manifest/scripts/run.test.mts -!/src/commands/manifest/scripts/socket-workspaces.init.gradle -!/src/commands/manifest/scripts/socket-workspaces.plugin.scala -!/src/commands/manifest/scripts/test/README.md -!/src/commands/manifest/scripts/test/assert-reachability.py -!/src/commands/manifest/scripts/test/compat-cache.sh -!/src/commands/manifest/scripts/test/dotnet-compat/.gitignore -!/src/commands/manifest/scripts/test/dotnet-compat/basic/Basic.sln -!/src/commands/manifest/scripts/test/dotnet-compat/basic/shared/Linked.cs -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/App.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/Program.cs -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/E.cs -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/Extra.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/L.cs -!/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/Lib.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/App.Tests.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/T.cs -!/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/Nuke.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.sln -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/Core.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/Shared.csproj -!/src/commands/manifest/scripts/test/dotnet-compat/lib.sh -!/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/gradle-compat/.gitignore -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/settings.gradle -!/src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle -!/src/commands/manifest/scripts/test/gradle-compat/project/settings.gradle -!/src/commands/manifest/scripts/test/gradle-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/maven-compat/.gitignore -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/project/pom.xml -!/src/commands/manifest/scripts/test/maven-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh -!/src/commands/manifest/scripts/test/run-compat.sh -!/src/commands/manifest/scripts/test/sbt-compat/.gitignore -!/src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/build.sbt -!/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt -!/src/commands/manifest/scripts/test/sbt-compat/smoke-test-exclude-base.sh -!/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh !/src/commands/manifest/setup-manifest-config.mts !/src/commands/manifest/setup-manifest-config.test.mts !/src/commands/manifest/setup-recursive-manifest-config.mts @@ -1289,25 +1100,6 @@ /.claude/ops/ /.claude/worktrees/ /.github/copilot-instructions.md -/src/commands/manifest/scripts/test/gradle-compat/.gradle-home/ -/src/commands/manifest/scripts/test/gradle-compat/**/.gradle/ -/src/commands/manifest/scripts/test/gradle-compat/project/build/ -/src/commands/manifest/scripts/test/gradle-compat/project/localrepo/ -/src/commands/manifest/scripts/test/gradle-compat/project/records.tsv -/src/commands/manifest/scripts/test/gradle-compat/project/workspaces-records.tsv -/src/commands/manifest/scripts/test/maven-compat/project/localrepo/ -/src/commands/manifest/scripts/test/maven-compat/project/records.tsv -/src/commands/manifest/scripts/test/maven-compat/project/target/ -/src/commands/manifest/scripts/test/maven-compat/project/*/target/ -/src/commands/manifest/scripts/test/sbt-compat/project/localrepo/ -/src/commands/manifest/scripts/test/sbt-compat/project/records.tsv -/src/commands/manifest/scripts/test/sbt-compat/project/target/ -/src/commands/manifest/scripts/test/sbt-compat/relocation/*/target/ -/src/commands/manifest/scripts/test/sbt-compat/relocation/localrepo/ -/src/commands/manifest/scripts/test/sbt-compat/relocation/project/ -/src/commands/manifest/scripts/test/sbt-compat/relocation/records.tsv -/src/commands/manifest/scripts/test/sbt-compat/relocation/scala-version.sbt -/src/commands/manifest/scripts/test/sbt-compat/relocation/target/ /test/fixtures/commands/manifest/dynamic-sbom-inference/**/.gradle/ /test/fixtures/commands/manifest/dynamic-sbom-inference/**/build/ /test/fixtures/commands/manifest/dynamic-sbom-inference/**/target/ diff --git a/package.json b/package.json index e18571658a..4af0a3e649 100644 --- a/package.json +++ b/package.json @@ -42,8 +42,6 @@ "build:dist": "pnpm build:dist:src && pnpm build:dist:types", "build:dist:src": "run-p -c clean:dist clean:external && dotenvx -q run -f .env.local -- rollup -c .config/rollup.dist.config.mjs", "build:dist:types": "pnpm clean:dist:types && tsgo --project .config/tsconfig.dts.json", - "build:dotnet-tool": "bash src/commands/manifest/scripts/dotnet-tool/build-tool.sh", - "build:maven-extension": "bash src/commands/manifest/scripts/maven-extension/build-jar.sh", "build:sea": "node src/sea/build-sea.mts", "build:package-matrix": "node scripts/build-package-matrix.mts", "test:native": "node scripts/test/native.mts", diff --git a/scripts/build-package-matrix.mts b/scripts/build-package-matrix.mts index 4e7f558a2e..6bfe19487c 100644 --- a/scripts/build-package-matrix.mts +++ b/scripts/build-package-matrix.mts @@ -320,10 +320,6 @@ async function main(): Promise { privateEnv, ) await verifyPrivateVirtualStore(workspace) - run(workspace, 'pnpm', ['run', 'build:dotnet-tool'], privateEnv) - await verifyPrivateVirtualStore(workspace) - run(workspace, 'pnpm', ['run', 'build:maven-extension'], privateEnv) - await verifyPrivateVirtualStore(workspace) for (const variant of variants) { await fs.writeFile( packagePath, diff --git a/socket.yml b/socket.yml index 3d684efe60..ad9c526bf5 100644 --- a/socket.yml +++ b/socket.yml @@ -2,8 +2,3 @@ version: 2 projectIgnorePaths: - "test/fixtures/" - # Build-tooling and test fixtures for the JVM manifest scripts, not socket-cli's - # own supply chain: the Maven extension's build pom and the compat-test - # projects' pom.xml / build.gradle / build.sbt. - - "src/commands/manifest/scripts/maven-extension/" - - "src/commands/manifest/scripts/test/" diff --git a/src/commands/manifest/enumerate-workspaces.mts b/src/commands/manifest/enumerate-workspaces.mts deleted file mode 100644 index 120b1998e5..0000000000 --- a/src/commands/manifest/enumerate-workspaces.mts +++ /dev/null @@ -1,113 +0,0 @@ -import { logger } from '@socketsecurity/registry/lib/logger' - -import { - expandEnvVarRefs, - formatMissingEnvVarRefs, -} from './expand-env-var-refs.mts' -import { enumerateWorkspaces as enumerateWorkspacesScript } from './scripts/run.mts' -import { getErrorMessageOr } from '../../utils/errors.mts' - -import type { BuildTool } from './scripts/build-tool.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' - -const MAX_FAILURE_OUTPUT_LINES = 40 - -// Last N non-empty lines of the captured build output, for diagnosing a crash -// without forcing a --verbose rebuild. -function tailBuildOutput(stdout: string, stderr: string): string { - const combined = [stdout, stderr] - .map(s => s.trimEnd()) - .filter(Boolean) - .join('\n') - return combined.split('\n').slice(-MAX_FAILURE_OUTPUT_LINES).join('\n') -} - -export type EnumerateWorkspacesResult = { - buildRoot: string - projects: SocketFactsSbomProject[] -} - -// Cheap subproject discovery (no dependency resolution), for builds that are -// not resolved: the setup wizard's, and skipped ones. Callers decide whether -// a failure fails the command. -export async function enumerateWorkspaces({ - bin, - buildOpts, - cwd, - ecosystem, - entryFile, - excludeBase, - excludePaths, - javaHome, - verbose, -}: { - bin: string - buildOpts: string[] - cwd: string - ecosystem: BuildTool - // See ManifestScriptOptions.entryFile. - entryFile?: string | undefined - // See ManifestScriptOptions.excludeBase. - excludeBase?: string | undefined - excludePaths?: string[] | undefined - javaHome?: string | undefined - verbose: boolean -}): Promise { - let resolvedJavaHome: string | undefined - if (javaHome) { - const expanded = expandEnvVarRefs(javaHome) - if (expanded.missing) { - logger.fail( - `javaHome (\`${javaHome}\`) ${formatMissingEnvVarRefs(expanded.missing)}.`, - ) - return - } - resolvedJavaHome = expanded.value - } - - const scriptOpts = { - bin: bin || undefined, - entryFile, - excludeBase, - excludePaths: excludePaths?.length ? excludePaths : undefined, - // `env` replaces the spawned process's whole environment, not just JAVA_HOME. - env: resolvedJavaHome - ? { ...process.env, JAVA_HOME: resolvedJavaHome } - : undefined, - projectDir: cwd, - stdio: verbose ? ('inherit' as const) : ('pipe' as const), - toolOpts: buildOpts, - } - - let result - try { - result = await enumerateWorkspacesScript(ecosystem, scriptOpts) - } catch (e) { - logger.fail( - `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, - ) - return - } - - if (!result.projects.length) { - logger.fail( - `The ${ecosystem} build produced no workspace records (exit code ${result.code}); every build reports at least its own root project, so the enumeration task did not run.`, - ) - const tail = verbose ? '' : tailBuildOutput(result.stdout, result.stderr) - if (tail) { - logger.group('Build output:') - logger.error(tail) - logger.groupEnd() - } - return - } - - if (!result.buildRoot) { - logger.fail( - `The ${ecosystem} build did not report its build root, so its projects' paths cannot be located.`, - ) - return - } - - return { buildRoot: result.buildRoot, projects: result.projects } -} diff --git a/src/commands/manifest/enumerate-workspaces.test.mts b/src/commands/manifest/enumerate-workspaces.test.mts deleted file mode 100644 index 28209f538f..0000000000 --- a/src/commands/manifest/enumerate-workspaces.test.mts +++ /dev/null @@ -1,122 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('./scripts/run.mts', () => ({ - enumerateWorkspaces: vi.fn(), -})) - -import { enumerateWorkspaces } from './enumerate-workspaces.mts' -import { enumerateWorkspaces as enumerateWorkspacesScript } from './scripts/run.mts' - -import type { WorkspaceEnumerationResult } from './scripts/run.mts' - -const ENV_VAR = 'SOCKET_TEST_ENUMERATE_JAVA_HOME' - -function okResult(): WorkspaceEnumerationResult { - return { - buildRoot: '/tmp/some-project', - code: 0, - projects: [ - { - type: 'maven', - name: 'root', - subprojectDir: '.', - children: [], - }, - ], - stderr: '', - stdout: '', - } -} - -const baseArgs = { - bin: 'gradle', - buildOpts: [], - cwd: '/tmp/some-project', - ecosystem: 'gradle' as const, - verbose: false, -} - -describe('enumerateWorkspaces', () => { - beforeEach(() => { - vi.mocked(enumerateWorkspacesScript).mockReset() - delete process.env[ENV_VAR] - process.exitCode = undefined - }) - - it('returns the build root and projects from a successful run', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - const result = await enumerateWorkspaces(baseArgs) - expect(result?.buildRoot).toBe(okResult().buildRoot) - expect(result?.projects).toEqual(okResult().projects) - }) - - it('passes a literal javaHome straight through as JAVA_HOME', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - await enumerateWorkspaces({ ...baseArgs, javaHome: '/opt/jdk-17' }) - const opts = vi.mocked(enumerateWorkspacesScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-17') - }) - - it('expands $VAR and ${VAR} references against the CLI process env', async () => { - process.env[ENV_VAR] = '/opt/jdk-11' - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - await enumerateWorkspaces({ ...baseArgs, javaHome: `\${${ENV_VAR}}` }) - const opts = vi.mocked(enumerateWorkspacesScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-11') - delete process.env[ENV_VAR] - }) - - it('fails closed without invoking the build tool when the referenced var is unset', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - const result = await enumerateWorkspaces({ - ...baseArgs, - javaHome: `$${ENV_VAR}`, - }) - expect(result).toBeUndefined() - expect(enumerateWorkspacesScript).not.toHaveBeenCalled() - expect(process.exitCode).toBeUndefined() - }) - - it('leaves the environment untouched when javaHome is unset', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - await enumerateWorkspaces(baseArgs) - const opts = vi.mocked(enumerateWorkspacesScript).mock.calls[0]?.[1] - expect(opts?.env).toBeUndefined() - }) - - it('fails when the build crashed before producing any workspace records', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue({ - buildRoot: undefined, - code: 1, - projects: [], - stderr: '', - stdout: '', - }) - const result = await enumerateWorkspaces(baseArgs) - expect(result).toBeUndefined() - expect(process.exitCode).toBeUndefined() - }) - - it('fails even on a clean exit if no workspace records were produced - every real run reports at least its own root project', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue({ - buildRoot: undefined, - code: 0, - projects: [], - stderr: '', - stdout: '', - }) - const result = await enumerateWorkspaces(baseArgs) - expect(result).toBeUndefined() - expect(process.exitCode).toBeUndefined() - }) - - it('fails when the build did not report its build root', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue({ - ...okResult(), - buildRoot: undefined, - }) - const result = await enumerateWorkspaces(baseArgs) - expect(result).toBeUndefined() - expect(process.exitCode).toBeUndefined() - }) -}) diff --git a/src/commands/manifest/expand-env-var-refs.mts b/src/commands/manifest/expand-env-var-refs.mts deleted file mode 100644 index c72ef53b3d..0000000000 --- a/src/commands/manifest/expand-env-var-refs.mts +++ /dev/null @@ -1,33 +0,0 @@ -const ENV_VAR_REF = /\$\$|\$\{(\w+)\}|\$(\w+)/g - -// Expands `$VAR`/`${VAR}` references (e.g. a team-shared `javaHome: -// "$JAVA11_HOME"`) against the CLI process's own environment, so a socket.json -// value works across machines instead of hardcoding one developer's path. -// `$$` is a literal `$`, for a value that must contain a literal `$WORD`. -export function expandEnvVarRefs(value: string): { - missing?: string[] - value: string -} { - const missing: string[] = [] - const expanded = value.replace(ENV_VAR_REF, (match, braced, bare) => { - if (match === '$$') { - return '$' - } - const name = braced ?? bare - const resolved = process.env[name] - if (resolved === undefined) { - if (!missing.includes(name)) { - missing.push(name) - } - return '' - } - return resolved - }) - return missing.length ? { missing, value: expanded } : { value: expanded } -} - -export function formatMissingEnvVarRefs(missing: readonly string[]): string { - const names = missing.map(name => `\`${name}\``).join(', ') - const verb = missing.length > 1 ? 'are' : 'is' - return `references ${names}, which ${verb} not set in this environment` -} diff --git a/src/commands/manifest/expand-env-var-refs.test.mts b/src/commands/manifest/expand-env-var-refs.test.mts deleted file mode 100644 index f2db002784..0000000000 --- a/src/commands/manifest/expand-env-var-refs.test.mts +++ /dev/null @@ -1,67 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' - -import { - expandEnvVarRefs, - formatMissingEnvVarRefs, -} from './expand-env-var-refs.mts' - -const VAR_A = 'SOCKET_TEST_EXPAND_ENV_VAR_A' -const VAR_B = 'SOCKET_TEST_EXPAND_ENV_VAR_B' - -describe('expandEnvVarRefs', () => { - beforeEach(() => { - delete process.env[VAR_A] - delete process.env[VAR_B] - }) - afterEach(() => { - delete process.env[VAR_A] - delete process.env[VAR_B] - }) - - it('expands a bare $VAR reference', () => { - process.env[VAR_A] = '/opt/jdk-17' - expect(expandEnvVarRefs(`$${VAR_A}`)).toEqual({ value: '/opt/jdk-17' }) - }) - - it('expands a braced ${VAR} reference', () => { - process.env[VAR_A] = '/opt/jdk-17' - expect(expandEnvVarRefs(`\${${VAR_A}}`)).toEqual({ value: '/opt/jdk-17' }) - }) - - it('reports every distinct missing variable, not just the first', () => { - const result = expandEnvVarRefs(`$${VAR_A}/$${VAR_B}`) - expect(result.missing).toEqual([VAR_A, VAR_B]) - expect(result.value).toBe('/') - }) - - it('reports a missing variable only once even if referenced twice', () => { - const result = expandEnvVarRefs(`$${VAR_A}:$${VAR_A}`) - expect(result.missing).toEqual([VAR_A]) - }) - - it('treats $$ as an escaped literal $, leaving the following text untouched', () => { - expect(expandEnvVarRefs('$$HOME')).toEqual({ value: '$HOME' }) - }) - - it('treats $$ as an escaped literal $ ahead of a braced-looking reference', () => { - expect(expandEnvVarRefs('$${HOME}')).toEqual({ value: '${HOME}' }) - }) - - it('does not report a missing variable for an escaped $$ reference', () => { - expect(expandEnvVarRefs(`$$${VAR_A}`).missing).toBeUndefined() - }) -}) - -describe('formatMissingEnvVarRefs', () => { - it('uses singular wording for one missing variable', () => { - expect(formatMissingEnvVarRefs(['FOO'])).toBe( - 'references `FOO`, which is not set in this environment', - ) - }) - - it('uses plural wording for multiple missing variables', () => { - expect(formatMissingEnvVarRefs(['FOO', 'BAR'])).toBe( - 'references `FOO`, `BAR`, which are not set in this environment', - ) - }) -}) diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index b9215482f6..6b1d3beaaf 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -14,17 +14,15 @@ vi.mock('../../utils/socket-json.mts', async importOriginal => ({ })) vi.mock('./run-manifest-facts.mts', async importOriginal => ({ ...(await importOriginal()), + listBuildProjects: vi.fn(), listDotnetSolutionMembers: vi.fn(async () => undefined), runManifestFacts: vi.fn(), })) -vi.mock('./enumerate-workspaces.mts', () => ({ - enumerateWorkspaces: vi.fn(), -})) import { buildRootPath } from './discover-manifest-roots.mts' -import { enumerateWorkspaces } from './enumerate-workspaces.mts' import { generateRecursiveManifests } from './generate-recursive-manifests.mts' import { + listBuildProjects, listDotnetSolutionMembers, runManifestFacts, setSidecarEntry, @@ -49,19 +47,19 @@ type TestProject = { type TestFacts = { factsPath: string; projects: TestProject[] } -// What Coana reports of a build whose tool lists `projects`, relative to the -// facts file's directory. +// What Coana reports of `projects`, as the build tool at `buildRoot` lists +// them. +function listed(buildRoot: string, projects: readonly TestProject[]) { + return projects.map(project => ({ + buildFiles: (project.manifestFiles ?? []).map(({ file }) => + path.resolve(buildRoot, file), + ), + dir: path.resolve(buildRoot, project.subprojectDir), + })) +} + function reported({ factsPath, projects }: TestFacts) { - const buildRoot = path.dirname(factsPath) - return { - factsPath, - projects: projects.map(project => ({ - buildFiles: (project.manifestFiles ?? []).map(({ file }) => - path.resolve(buildRoot, file), - ), - dir: path.resolve(buildRoot, project.subprojectDir), - })), - } + return { factsPath, projects: listed(path.dirname(factsPath), projects) } } function newWorkDir(): SocketFactsWorkDir { @@ -1414,10 +1412,9 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: sub, - projects: gradleFacts(sub, [...subProjects]).projects, - }) + vi.mocked(listBuildProjects).mockResolvedValue( + listed(sub, gradleFacts(sub, [...subProjects]).projects), + ) mockFacts(async ({ cwd }) => gradleFacts(cwd, ['.'])) const warnSpy = vi .spyOn(logger, 'warn') @@ -1578,14 +1575,13 @@ describe('generateRecursiveManifests', () => { }) it('loads it without resolving, and skips what it loads with it, wherever that is', async () => { - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: path.join(outer, 'legacy'), - projects: [ + vi.mocked(listBuildProjects).mockResolvedValue( + listed(path.join(outer, 'legacy'), [ mavenProject('.'), mavenProject('old'), mavenProject('../aaa-module'), - ], - }) + ]), + ) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1608,7 +1604,7 @@ describe('generateRecursiveManifests', () => { expect( existsSync(path.join(outer, 'aaa-module/pom.xml.socket.facts.json')), ).toBe(false) - expect(enumerateWorkspaces).toHaveBeenCalledWith( + expect(listBuildProjects).toHaveBeenCalledWith( expect.objectContaining({ cwd: path.join(outer, 'legacy'), entryFile: 'pom.xml', @@ -1627,10 +1623,9 @@ describe('generateRecursiveManifests', () => { it('reports a skipped build that another build includes as part of that build, warning that the skip does not apply', async () => { await fs.mkdir(path.join(outer, 'zzz-reactor'), { recursive: true }) await fs.writeFile(pom('zzz-reactor'), '') - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: path.join(outer, 'legacy'), - projects: [mavenProject('.')], - }) + vi.mocked(listBuildProjects).mockResolvedValue( + listed(path.join(outer, 'legacy'), [mavenProject('.')]), + ) mockFacts(async ({ cwd, entryFile }) => ({ factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), projects: @@ -1670,7 +1665,7 @@ describe('generateRecursiveManifests', () => { }) it('fails, without building what lies beneath it, when it cannot be loaded', async () => { - vi.mocked(enumerateWorkspaces).mockImplementation(async () => { + vi.mocked(listBuildProjects).mockImplementation(async () => { process.exitCode = 1 return undefined }) @@ -1746,10 +1741,9 @@ describe('generateRecursiveManifests', () => { vi.mocked(listDotnetSolutionMembers).mockImplementation( async ({ entryFile }) => members[entryFile ?? ''], ) - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: at('skip'), - projects: [projectRecord('../p/a/A.csproj')], - }) + vi.mocked(listBuildProjects).mockResolvedValue( + listed(at('skip'), [projectRecord('../p/a/A.csproj')]), + ) mockFacts(async ({ cwd, entryFile }) => ({ factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), projects: diff --git a/src/commands/manifest/load-build.mts b/src/commands/manifest/load-build.mts index c7ebb9906b..1ff150d75e 100644 --- a/src/commands/manifest/load-build.mts +++ b/src/commands/manifest/load-build.mts @@ -1,9 +1,7 @@ -import path from 'node:path' - import { pluralize } from '@socketsecurity/registry/lib/words' import { membershipOf } from './discover-manifest-roots.mts' -import { enumerateWorkspaces } from './enumerate-workspaces.mts' +import { listBuildProjects } from './run-manifest-facts.mts' import type { BuildRoot, Membership } from './discover-manifest-roots.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' @@ -31,7 +29,7 @@ export async function loadBuild({ scanRoot: string verbose: boolean }): Promise { - const result = await enumerateWorkspaces({ + const projects = await listBuildProjects({ bin: config.bin, buildOpts: config.buildOpts, cwd: root.dir, @@ -42,20 +40,11 @@ export async function loadBuild({ javaHome: config.javaHome, verbose: verbose || config.verbose, }) - if (!result) { + if (!projects) { return undefined } - const { buildRoot, projects } = result return { - membership: await membershipOf( - projects.map(({ manifestFiles, subprojectDir }) => ({ - buildFiles: (manifestFiles ?? []).map(({ file }) => - path.resolve(buildRoot, file), - ), - dir: path.resolve(buildRoot, subprojectDir), - })), - scanRoot, - ), + membership: await membershipOf(projects, scanRoot), modules: Math.max(0, projects.length - 1), } } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index e179ff8500..5147a4e115 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -141,6 +141,10 @@ type SocketFactsResult = type SolutionMembers = { members: string[] | null } +type ProjectList = + | { projects: SocketFactsProject[]; status: 'listed' } + | { status: 'failed' } + let defaultOrgSlug: Promise | undefined // Resolved once: each build root is its own Coana run. @@ -275,6 +279,68 @@ export function listDotnetSolutionMembers({ }) } +// The projects a build loads, as the build reports them, without resolving its +// dependencies; undefined when the build cannot list them, which Coana +// reports. +export async function listBuildProjects({ + bin, + buildOpts, + cwd, + ecosystem, + entryFile, + excludeBase, + excludePaths, + javaHome, + verbose, +}: { + bin: string + buildOpts: string[] + cwd: string + ecosystem: BuildTool + entryFile?: string | undefined + excludeBase?: string | undefined + excludePaths?: string[] | undefined + javaHome?: string | undefined + verbose: boolean +}): Promise { + let resolvedBin: string + try { + resolvedBin = requestBin(ecosystem, cwd, bin) + } catch (e) { + logger.fail( + `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, + ) + return undefined + } + const request: SocketFactsRequest = { + buildRoot: path.resolve(cwd), + config: { + bin: resolvedBin, + buildOpts, + ignoreUnresolved: false, + ...(javaHome ? { javaHome } : {}), + verbose, + }, + ...(entryFile ? { entryFile } : {}), + excludeBase: path.resolve(excludeBase ?? cwd), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: toRequestHints(FLAG_HINTS), + tool: ecosystem, + } + const { message, result } = await runGenerateSocketFacts( + request, + ['--list-projects'], + {}, + ) + if (!result) { + logger.fail( + `Could not list the projects of the ${ecosystem} build at \`${cwd}\`${message ? `: ${message}` : '.'}`, + ) + return undefined + } + return result.status === 'listed' ? result.projects : undefined +} + // Generates one build root's `.socket.facts.json` with Coana. With a // work dir in `context`, also collects what a later Coana run reads of it. A // failure sets a non-zero exit code; Coana reports why. diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index de9ac5b119..3555eedd6b 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -12,6 +12,7 @@ vi.mock('../ci/fetch-default-org-slug.mts', () => ({ })) import { + listBuildProjects, listDotnetSolutionMembers, runManifestFacts, } from './run-manifest-facts.mts' @@ -236,3 +237,53 @@ describe('listDotnetSolutionMembers', () => { ).toEqual([]) }) }) + +describe('listBuildProjects', () => { + const listArgs = { + bin: 'mvn', + buildOpts: ['-Pci'], + ecosystem: 'maven' as const, + verbose: false, + } + + it('asks Coana to list the build root, unresolved, with its options as written', async () => { + const projects = [{ buildFiles: [path.join(cwd, 'pom.xml')], dir: cwd }] + coanaAnswers({ buildRoot: cwd, projects, status: 'listed' }) + expect( + await listBuildProjects({ + ...listArgs, + cwd: path.join(cwd, 'reactor'), + entryFile: 'pom.xml', + excludeBase: cwd, + excludePaths: ['reactor/moduleB'], + javaHome: '$JAVA11_HOME', + }), + ).toEqual(projects) + expect(calls[0]!.args).toContain('--list-projects') + expect(calls[0]!.args).not.toContain('--work-dir') + expect(calls[0]!.request).toMatchObject({ + buildRoot: path.join(cwd, 'reactor'), + config: { + bin: 'mvn', + buildOpts: ['-Pci'], + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + entryFile: 'pom.xml', + excludeBase: cwd, + excludePaths: ['reactor/moduleB'], + tool: 'maven', + }) + }) + + it('lists nothing when the build cannot list its projects', async () => { + coanaAnswers({ status: 'failed' }, false) + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + }) + + it('lists nothing when Coana writes no result', async () => { + coanaAnswers(undefined, false) + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + }) +}) diff --git a/src/commands/manifest/scripts/assemble.mts b/src/commands/manifest/scripts/assemble.mts deleted file mode 100644 index fae409ec91..0000000000 --- a/src/commands/manifest/scripts/assemble.mts +++ /dev/null @@ -1,670 +0,0 @@ -import { existsSync } from 'node:fs' - -import { NAMESPACELESS_PURL_TYPES, PURL_TYPE_BY_TOOL } from './build-tool.mts' -import { - type ProjectFramework, - type ResolvedArtifactPaths, - type SocketFactsSbom, - type SocketFactsSbomComponent, - type SocketFactsSbomDependency, - type SocketFactsSbomMetadata, - type SocketFactsSbomProject, -} from './facts.mts' -import { moduleKey } from './resolution-report.mts' -import { getOrInsert } from '../../../utils/get-or-insert.mts' - -import type { - ParsedRecords, - RawCoord, - RawProject, - RawTarget, -} from './records.mts' -import type { ResolutionReport } from './resolution-report.mts' - -function purlBase( - type: string, - group: string, - name: string, -): { type: string; namespace?: string; name: string } { - return NAMESPACELESS_PURL_TYPES.has(type) - ? { type, name } - : { type, namespace: group, name } -} - -export type AssembleResult = { - facts: SocketFactsSbom - report: ResolutionReport - artifactPaths: ResolvedArtifactPaths -} - -export type AssembleOptions = { - // Injectable for tests; an uncompiled module's output dir is dropped (module - // stays resolvable via its sources). - fileExists?: ((path: string) => boolean) | undefined -} - -type MergedNode = { - coord: RawCoord - prod: boolean - direct: boolean - // projectKey when this node is a build project, else empty. - project: string - // One per resolution root that recorded files or failed to fetch them. - resolutions: Array<{ targets: string[]; unfetched: boolean }> -} - -type SubprojectGraph = { - children: Map> - // The nodes of the roots on a classpath: reachability analyses only these. - classpath: Set - direct: Set -} - -type PerRoot = { - projectKey: string - prod: boolean - onClasspath: boolean - target?: RawTarget | undefined - nodes: Map -} - -type RootNode = { - coord: RawCoord - children: string[] - compileTargets: string[] - direct: boolean - project: string - targets: string[] - unfetched: boolean -} - -export function assembleFacts( - parsed: ParsedRecords, - opts: AssembleOptions = {}, -): AssembleResult { - // Every root that fetched an artifact lists its file, so check each path once. - const fileExists = opts.fileExists ?? existsSync - const existing = new Map() - const exists = (p: string) => { - let e = existing.get(p) - if (e === undefined) { - e = fileExists(p) - existing.set(p, e) - } - return e - } - const perRoot = buildPerRoot(parsed) - const finalNodes = mergeById(perRoot) - const graphs = buildSubprojectGraphs(perRoot) - - const tool = (parsed.tool || 'gradle') as SocketFactsSbomMetadata['tool'] - const purlType = PURL_TYPE_BY_TOOL[tool] - const components = buildComponents(finalNodes, purlType) - const { dependencies, projects } = buildDependencyGraph( - parsed, - graphs, - components, - purlType, - ) - - const metadata: SocketFactsSbomMetadata = { - format: 'socket-facts-sbom', - tool, - toolVersion: parsed.toolVersion, - ...(parsed.javaVersion ? { javaVersion: parsed.javaVersion } : {}), - } - - const facts: SocketFactsSbom = projects.length - ? { metadata, projects, components, dependencies } - : { metadata, components } - - return { - facts, - report: buildReport(parsed), - artifactPaths: { - ...buildArtifactPaths( - finalNodes, - [...parsed.projects.values()], - [...parsed.excludedProjects.values()], - graphs, - exists, - ), - ...buildFrameworks(parsed, perRoot, exists), - }, - } -} - -// A node resolving to a build project takes that project's id, so projects -// sharing a coordinate stay apart and the project's variants collapse into it. -function componentId(coordId: string, project: string): string { - return project || coordId -} - -function buildPerRoot(parsed: ParsedRecords): Map { - const out = new Map() - for (const [rootId, r] of parsed.roots) { - const idOf = (coordId: string) => - componentId(coordId, r.nodes.get(coordId)?.project ?? '') - const nodes = new Map() - for (const [coordId, n] of r.nodes) { - const id = idOf(coordId) - let node = nodes.get(id) - if (!node) { - node = { - coord: n.project ? { ...n.coord, classifier: '', ext: '' } : n.coord, - children: [], - compileTargets: [], - direct: false, - project: n.project, - targets: [], - unfetched: false, - } - nodes.set(id, node) - } - node.direct ||= n.direct - node.unfetched ||= n.unfetched - node.targets.push(...n.targets) - node.compileTargets.push(...n.compileTargets) - } - for (const [p, c] of r.edges) { - if (!r.nodes.has(p) || !r.nodes.has(c)) { - continue - } - const parentId = idOf(p) - const childId = idOf(c) - const parent = nodes.get(parentId)! - if (childId !== parentId && !parent.children.includes(childId)) { - parent.children.push(childId) - } - } - out.set(rootId, { - projectKey: r.projectKey, - prod: r.prod, - onClasspath: r.onClasspath, - target: r.target, - nodes, - }) - } - return out -} - -// Components are merged by id across every resolution root; which ids belong -// to which subproject is kept separately (classpathByProject) for -// reachability, which needs each subproject's exact classpath. -function mergeById(perRoot: Map): Map { - const finalNodes = new Map() - for (const { nodes, prod } of perRoot.values()) { - for (const [coordId, node] of nodes) { - let fn = finalNodes.get(coordId) - if (!fn) { - fn = { - coord: node.coord, - prod: false, - direct: false, - project: node.project, - resolutions: [], - } - finalNodes.set(coordId, fn) - } - if (prod) { - fn.prod = true - } - if (node.direct) { - fn.direct = true - } - if (node.unfetched || node.targets.length) { - fn.resolutions.push({ - targets: node.targets, - unfetched: node.unfetched, - }) - } - } - } - return finalNodes -} - -function buildComponents( - finalNodes: Map, - purlType: string, -): SocketFactsSbomComponent[] { - return [...finalNodes.keys()].sort().map(id => { - const fn = finalNodes.get(id)! - const c = fn.coord - const qualifiers: Record = { - __proto__: null, - } as unknown as Record - if (c.classifier) { - qualifiers['classifier'] = c.classifier - } - if (c.ext) { - qualifiers['ext'] = c.ext - } - const comp: SocketFactsSbomComponent = { - ...purlBase(purlType, c.group, c.name), - ...(c.version ? { version: c.version } : {}), - ...(Object.keys(qualifiers).length ? { qualifiers } : {}), - id, - } - if (fn.direct) { - comp.direct = true - } - if (!fn.prod) { - comp.dev = true - } - if (fn.project) { - comp.firstParty = true - } - return comp - }) -} - -// One graph per subproject, its configurations merged. -function buildSubprojectGraphs( - perRoot: Map, -): Map { - const graphs = new Map() - for (const { nodes, onClasspath, projectKey } of perRoot.values()) { - let g = graphs.get(projectKey) - if (!g) { - g = { children: new Map(), classpath: new Set(), direct: new Set() } - graphs.set(projectKey, g) - } - for (const [coordId, node] of nodes) { - if (onClasspath) { - g.classpath.add(coordId) - } - let set = g.children.get(coordId) - if (!set) { - set = new Set() - g.children.set(coordId, set) - } - for (const c of node.children) { - set.add(c) - } - if (node.direct) { - g.direct.add(coordId) - } - } - } - return graphs -} - -// Equal subtrees share an entry; partition refinement (coarsest bisimulation) -// keeps that exact on cycles too. -function buildDependencyGraph( - parsed: ParsedRecords, - graphs: Map, - components: SocketFactsSbomComponent[], - purlType: string, -): { - dependencies: SocketFactsSbomDependency[] - projects: SocketFactsSbomProject[] -} { - const componentIndex = new Map(components.map((c, i) => [c.id, i])) - - const vertexIds = new Map() - const labels: number[] = [] - const edges: number[][] = [] - const vertex = (projectKey: string, coordId: string): number => { - const key = `${projectKey}\t${coordId}` - let v = vertexIds.get(key) - if (v === undefined) { - v = labels.length - vertexIds.set(key, v) - labels.push(componentIndex.get(coordId)!) - edges.push([]) - } - return v - } - for (const [projectKey, { children }] of graphs) { - for (const [coordId, kids] of children) { - const v = vertex(projectKey, coordId) - for (const c of kids) { - edges[v]!.push(vertex(projectKey, c)) - } - } - } - - // Each round splits blocks by their children's blocks; a round that splits - // nothing is stable. - let block = [...labels] - let blockCount = new Set(block).size - for (;;) { - const ids = new Map() - block = block.map((b, v) => { - const childBlocks = [...new Set(edges[v]!.map(c => block[c]!))].sort( - (x, y) => x - y, - ) - const sig = `${b}:${childBlocks.join(',')}` - let id = ids.get(sig) - if (id === undefined) { - id = ids.size - ids.set(sig, id) - } - return id - }) - if (ids.size === blockCount) { - break - } - blockCount = ids.size - } - - const byComponent = (a: string, b: string) => - componentIndex.get(a)! - componentIndex.get(b)! - const projects = [...parsed.projects.values()] - .map(p => ({ - p, - roots: treeRoots(p.projectKey, graphs.get(p.projectKey), byComponent), - })) - .sort((a, b) => { - const ka = `${a.p.dir} ${a.p.group}:${a.p.name}` - const kb = `${b.p.dir} ${b.p.group}:${b.p.name}` - return ka < kb ? -1 : ka > kb ? 1 : 0 - }) - - // Post-order over the sorted projects, so the numbering is stable. - const indexOfBlock = new Map() - const vertexOfBlock = new Map() - const dependencies: SocketFactsSbomDependency[] = [] - const visit = (v: number): void => { - const b = block[v]! - if (vertexOfBlock.has(b)) { - return - } - vertexOfBlock.set(b, v) - for (const c of [...edges[v]!].sort((x, y) => labels[x]! - labels[y]!)) { - visit(c) - } - indexOfBlock.set(b, dependencies.length) - dependencies.push({ component: labels[v]! }) - } - const indexOf = (v: number) => indexOfBlock.get(block[v]!)! - for (const { p, roots } of projects) { - for (const coordId of roots) { - visit(vertex(p.projectKey, coordId)) - } - } - for (const [b, v] of vertexOfBlock) { - const children = [...new Set(edges[v]!.map(indexOf))].sort((x, y) => x - y) - if (children.length) { - dependencies[indexOfBlock.get(b)!]!.children = children - } - } - - return { - dependencies, - projects: projects.map(({ p, roots }) => { - const entry: SocketFactsSbomProject = { - id: p.projectKey, - ...purlBase(purlType, p.group, p.name), - ...(p.version ? { version: p.version } : {}), - subprojectDir: p.dir, - children: roots - .map(coordId => indexOf(vertex(p.projectKey, coordId))) - .sort((x, y) => x - y), - } - if (p.buildFiles.length) { - entry.manifestFiles = sortedUnique(p.buildFiles).map(file => ({ file })) - } - return entry - }), - } -} - -function treeRoots( - projectKey: string, - graph: SubprojectGraph | undefined, - byComponent: (a: string, b: string) => number, -): string[] { - if (!graph) { - return [] - } - const roots = [...graph.direct].sort(byComponent) - const reached = new Set() - const stack = [...roots] - while (stack.length) { - const id = stack.pop()! - if (!reached.has(id)) { - reached.add(id) - stack.push(...graph.children.get(id)!) - } - } - const unreached = [...graph.children.keys()].filter(id => !reached.has(id)) - if (unreached.length) { - throw new Error( - `Resolved dependencies of ${projectKey} are not reachable from its direct dependencies: ${unreached.sort(byComponent).join(', ')}`, - ) - } - return roots -} - -function byProject( - projects: RawProject[], - graphs: Map, - ids: (graph: SubprojectGraph) => Iterable, -): Map { - return new Map( - projects.map(p => { - const g = graphs.get(p.projectKey) - return [p.projectKey, g ? [...ids(g)].sort() : []] - }), - ) -} - -function buildArtifactPaths( - finalNodes: Map, - projects: RawProject[], - excludedProjects: RawProject[], - graphs: Map, - exists: (path: string) => boolean, -): ResolvedArtifactPaths { - const pathsById: ResolvedArtifactPaths['pathsById'] = new Map() - for (const [id, fn] of finalNodes) { - if (!fn.project) { - const complete = completeResolutions( - fn.resolutions, - exists, - r => r.targets, - ) - pathsById.set( - id, - complete - ? { - sources: [], - targets: sortedUnique(complete.flatMap(r => r.targets)), - } - : { sources: [] }, - ) - } - } - // A project's own component shares its id, so this also covers dependency - // edges onto a sibling project. - for (const p of [...projects, ...excludedProjects]) { - pathsById.set(p.projectKey, { - sources: sortedUnique(p.sources).filter(exists), - targets: sortedUnique(p.targets).filter(exists), - }) - } - return { - pathsById, - classpathByProject: byProject(projects, graphs, g => g.classpath), - directDependenciesByProject: byProject(projects, graphs, g => - [...g.direct].filter(id => g.classpath.has(id)), - ), - } -} - -// Only a root that fetched every file of the artifact, all still on disk, -// resolved it: a partial list would claim it resolved whole. Undefined when -// every root that fetched it failed. -function completeResolutions( - resolutions: readonly R[], - exists: (path: string) => boolean, - files: (resolution: R) => string[], -): R[] | undefined { - const complete = resolutions.filter( - r => !r.unfetched && files(r).every(exists), - ) - return resolutions.length && !complete.length ? undefined : complete -} - -function frameworkKey(framework: string, runtime: string): string { - return `${framework}\t${runtime}` -} - -function sortedUnique(ids: Iterable): string[] { - return [...new Set(ids)].sort() -} - -// Per target framework, for builds that resolve per framework (dotnet): what -// each project's build compiles against and each package contributes to it. -function buildFrameworks( - parsed: ParsedRecords, - perRoot: Map, - exists: (path: string) => boolean, -): Pick { - const roots = [...perRoot.values()].filter( - (r): r is PerRoot & { target: RawTarget } => !!r.target, - ) - const projects = [...parsed.projects.values()] - if (!roots.length && !projects.some(p => p.builds.size)) { - return {} - } - - const projectBuilds = new Map>() - const projectFramework = ( - projectKey: string, - { alias, framework, runtime }: RawTarget, - ): ProjectFramework => - getOrInsert( - getOrInsert(projectBuilds, projectKey, () => new Map()), - frameworkKey(alias, runtime), - () => { - const build = parsed.projects.get(projectKey)?.builds.get(alias) - return { - ...build, - alias, - framework: framework || build?.framework || alias, - ...(runtime ? { runtime } : {}), - frameworkReferences: sortedUnique(build?.frameworkReferences ?? []), - defineConstants: [...new Set(build?.defineConstants)], - usings: (build?.usings ?? []).map(u => ({ - namespace: u.namespace, - ...(u.alias ? { alias: u.alias } : {}), - ...(u.static ? { static: true as const } : {}), - })), - // In compiler order, which F# depends on. - sources: [...new Set(build?.sources)].filter(exists), - targets: sortedUnique(build?.targets ?? []).filter(exists), - dependencies: [], - classpath: [], - } - }, - ) - - // Per component and framework: the roots' resolutions. - const componentBuilds = new Map< - string, - Map - >() - for (const { nodes, projectKey, target } of roots) { - const pf = projectFramework(projectKey, target) - for (const { 0: id, 1: node } of nodes) { - pf.classpath.push(id) - if (node.direct) { - pf.dependencies.push(id) - } - if (node.project) { - continue - } - const cb = getOrInsert( - getOrInsert(componentBuilds, id, () => new Map()), - frameworkKey(target.framework, target.runtime), - () => ({ target, resolutions: [] }), - ) - if (node.unfetched || node.targets.length || node.compileTargets.length) { - cb.resolutions.push(node) - } - } - } - // A build with nothing to resolve has no root, yet still compiles. - for (const p of projects) { - for (const alias of p.builds.keys()) { - projectFramework(p.projectKey, { alias, framework: '', runtime: '' }) - } - } - - const frameworksByProject = new Map( - [...projectBuilds].map(({ 0: projectKey, 1: builds }) => [ - projectKey, - [...builds.values()].map(pf => ({ - ...pf, - dependencies: sortedUnique(pf.dependencies), - classpath: sortedUnique(pf.classpath.filter(id => id !== projectKey)), - })), - ]), - ) - const frameworksById = new Map( - [...componentBuilds].map(({ 0: id, 1: byFramework }) => [ - id, - [...byFramework.values()].map( - ({ resolutions, target: { framework, runtime } }) => { - const complete = completeResolutions(resolutions, exists, r => [ - ...r.targets, - ...r.compileTargets, - ]) - return { - framework, - ...(runtime ? { runtime } : {}), - ...(complete - ? { - targets: sortedUnique(complete.flatMap(r => r.targets)), - compile: sortedUnique( - complete.flatMap(r => r.compileTargets), - ), - } - : {}), - } - }, - ), - ]), - ) - return { frameworksByProject, frameworksById } -} - -function buildReport(parsed: ParsedRecords): ResolutionReport { - const seen = new Set() - const failures = parsed.failures.filter(f => { - const key = `${f.coord}|${f.detail}|${f.config}|${f.project}` - if (seen.has(key)) { - return false - } - seen.add(key) - return true - }) - const seenUnscannable = new Set() - const unscannable = parsed.unscannable.filter(u => { - const key = `${u.config}|${u.detail}|${u.project}` - if (seenUnscannable.has(key)) { - return false - } - seenUnscannable.add(key) - return true - }) - const resolvedModules = new Set() - if (failures.length) { - for (const r of parsed.roots.values()) { - for (const n of r.nodes.values()) { - resolvedModules.add( - moduleKey(r.projectKey, `${n.coord.group}:${n.coord.name}`), - ) - } - } - } - return { - failures, - resolvedModules, - scannedConfigs: parsed.scannedConfigs, - unscannable, - } -} diff --git a/src/commands/manifest/scripts/assemble.test.mts b/src/commands/manifest/scripts/assemble.test.mts deleted file mode 100644 index 6c246b221c..0000000000 --- a/src/commands/manifest/scripts/assemble.test.mts +++ /dev/null @@ -1,647 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { assembleFacts } from './assemble.mts' -import { parseRecords } from './records.mts' - -import type { SocketFactsSbom } from './facts.mts' - -// Each project's tree, written out with component ids; a repeat on the current -// path (a cycle) is written without its children. -function trees(facts: SocketFactsSbom): Record { - const deps = facts.dependencies ?? [] - const render = (i: number, path: number[]): string => { - const id = facts.components[deps[i]!.component]!.id - const children = deps[i]!.children ?? [] - if (path.includes(i) || !children.length) { - return id - } - return `${id}(${children.map(c => render(c, [...path, i])).join(', ')})` - } - return Object.fromEntries( - (facts.projects ?? []).map(p => [p.id, p.children.map(i => render(i, []))]), - ) -} - -// Minimal line-protocol records for a one-module Gradle build (--with-files): -// - first-party module `:app` (a project, NOT a dependency node) with source + -// output roots, -// - an external dep `lib` resolved to a jar, -// - a `bom` resolved as a constraints-only artifact (no file). -const RECORDS = [ - 'meta\tgradle\t8.0\t17', - 'project\t:app\tcom.example\tapp\t1.0\t/abs/app', - 'projectSrc\t:app\t/abs/app/src/main/java', - 'projectTgt\t:app\t/abs/app/build/classes', - 'root\tr1\t:app\truntimeClasspath\t1', - 'node\tr1\tcom.example:lib:jar:1.0\tcom.example\tlib\t1.0\tjar\t\t1', - 'node\tr1\tcom.example:bom:2.0\tcom.example\tbom\t2.0\t\t\t1', - 'file\tr1\tcom.example:lib:jar:1.0\t/abs/lib.jar', - 'scanned\truntimeClasspath', -].join('\n') - -function chain(root: string, project: string, version: string): string[] { - return [ - `root\t${root}\t${project}\tcompile\t1`, - `node\t${root}\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1`, - `node\t${root}\tg:mid:jar:1\tg\tmid\t1\tjar\t\t0`, - `node\t${root}\tg:dep:jar:${version}\tg\tdep\t${version}\tjar\t\t0`, - `edge\t${root}\tg:lib:jar:1\tg:mid:jar:1`, - `edge\t${root}\tg:mid:jar:1\tg:dep:jar:${version}`, - ] -} - -function cycle(root: string, project: string, extra: boolean): string[] { - return [ - `root\t${root}\t${project}\tcompile\t1`, - `node\t${root}\tg:x:jar:1\tg\tx\t1\tjar\t\t1`, - `node\t${root}\tg:y:jar:1\tg\ty\t1\tjar\t\t0`, - `edge\t${root}\tg:x:jar:1\tg:y:jar:1`, - `edge\t${root}\tg:y:jar:1\tg:x:jar:1`, - ...(extra - ? [ - `node\t${root}\tg:z:jar:1\tg\tz\t1\tjar\t\t0`, - `edge\t${root}\tg:y:jar:1\tg:z:jar:1`, - ] - : []), - ] -} - -describe('records → assemble', () => { - it("carries an excluded module's paths into the kept project that depends on it", () => { - const records = [ - 'meta\tgradle\t8.10\t17', - 'project\t:app\tg\tapp\t1\tapp', - 'projectSrc\t:app\t/abs/app/src', - 'projectTgt\t:app\t/abs/app/classes', - 'excludedProject\t:lib', - 'projectSrc\t:lib\t/abs/lib/src', - 'projectTgt\t:lib\t/abs/lib/classes', - 'root\t0\t:app\tcompileClasspath\t1', - 'node\t0\t:lib\tg\tlib\t1\tjar\t\t1\t:lib', - ].join('\n') - const { artifactPaths, facts } = assembleFacts(parseRecords(records), { - fileExists: () => true, - }) - - expect(facts.projects?.map(p => p.id)).toEqual([':app']) - expect(artifactPaths.pathsById.get(':lib')).toEqual({ - sources: ['/abs/lib/src'], - targets: ['/abs/lib/classes'], - }) - expect([...artifactPaths.classpathByProject.keys()]).toEqual([':app']) - }) - it('keeps the targets of an artifact that another root fetched', () => { - const records = [ - 'meta\tmaven\t3.9.6\t17', - 'project\tg:a:1\tg\ta\t1\ta', - 'project\tg:b:1\tg\tb\t1\tb', - 'root\t0\tg:a:1\tcompile\t1', - 'root\t1\tg:b:1\tcompile\t1', - 'node\t0\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\t1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\t0\tg:moved:jar:1\tg\tmoved\t1\tjar\t\t1', - 'node\t1\tg:moved:jar:1\tg\tmoved\t1\tjar\t\t1', - 'unfetched\t0\tg:lib:jar:1', - 'file\t1\tg:lib:jar:1\t/abs/lib.jar', - 'file\t0\tg:moved:jar:1\t/abs/gone.jar', - 'file\t1\tg:moved:jar:1\t/abs/moved.jar', - ].join('\n') - const { artifactPaths } = assembleFacts(parseRecords(records), { - fileExists: p => p !== '/abs/gone.jar', - }) - - expect(artifactPaths.pathsById.get('g:lib:jar:1')?.targets).toEqual([ - '/abs/lib.jar', - ]) - expect(artifactPaths.pathsById.get('g:moved:jar:1')?.targets).toEqual([ - '/abs/moved.jar', - ]) - }) - it('keeps a coordinate with divergent subtrees as one component with a dependency entry per subtree', () => { - // :a and :b both depend on `lib`, which pulls a different `dep` version in - // each subproject. - const records = [ - 'meta\tgradle\t8.0\t17', - 'project\t:a\tcom.example\ta\t1.0\ta', - 'project\t:b\tcom.example\tb\t1.0\tb', - 'root\tr1\t:a\truntimeClasspath\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'edge\tr1\tg:lib:jar:1\tg:dep:jar:1', - 'root\tr2\t:b\truntimeClasspath\t1', - 'node\tr2\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr2\tg:dep:jar:2\tg\tdep\t2\tjar\t\t0', - 'edge\tr2\tg:lib:jar:1\tg:dep:jar:2', - 'root\tr3\t:b\ttestRuntimeClasspath\t0', - 'node\tr3\tg:junit:jar:4\tg\tjunit\t4\tjar\t\t1', - ].join('\n') - const { artifactPaths, facts } = assembleFacts(parseRecords(records), { - fileExists: () => true, - }) - - expect(facts.components.map(c => c.id)).toEqual([ - 'g:dep:jar:1', - 'g:dep:jar:2', - 'g:junit:jar:4', - 'g:lib:jar:1', - ]) - expect(facts.components[3]).not.toHaveProperty('dependencies') - expect(facts.dependencies).toEqual([ - { component: 0 }, - { component: 3, children: [0] }, - { component: 2 }, - { component: 1 }, - { component: 3, children: [3] }, - ]) - expect(trees(facts)).toEqual({ - ':a': ['g:lib:jar:1(g:dep:jar:1)'], - ':b': ['g:junit:jar:4', 'g:lib:jar:1(g:dep:jar:2)'], - }) - - const { classpathByProject, directDependenciesByProject } = artifactPaths - expect([...classpathByProject.get(':a')!]).toEqual([ - 'g:dep:jar:1', - 'g:lib:jar:1', - ]) - expect([...classpathByProject.get(':b')!]).toEqual([ - 'g:dep:jar:2', - 'g:junit:jar:4', - 'g:lib:jar:1', - ]) - expect([...directDependenciesByProject.get(':b')!]).toEqual([ - 'g:junit:jar:4', - 'g:lib:jar:1', - ]) - }) - it('shares one dependency entry between identical subtrees across subprojects', () => { - const records = [ - 'meta\tmaven\t3.9.6\t17', - 'project\ta\tg\ta\t1\ta', - 'project\tb\tg\tb\t1\tb', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'edge\tr1\tg:lib:jar:1\tg:dep:jar:1', - 'root\tr2\tb\tcompile\t1', - 'node\tr2\tg:other:jar:1\tg\tother\t1\tjar\t\t1', - 'node\tr2\tg:lib:jar:1\tg\tlib\t1\tjar\t\t0', - 'node\tr2\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'edge\tr2\tg:other:jar:1\tg:lib:jar:1', - 'edge\tr2\tg:lib:jar:1\tg:dep:jar:1', - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - expect(facts.dependencies).toHaveLength(3) - expect(trees(facts)).toEqual({ - a: ['g:lib:jar:1(g:dep:jar:1)'], - b: ['g:other:jar:1(g:lib:jar:1(g:dep:jar:1))'], - }) - }) - it('tells apart subtrees that differ only further down', () => { - const records = [ - 'meta\tmaven\t3.9.6\t17', - 'project\ta\tg\ta\t1\ta', - 'project\tb\tg\tb\t1\tb', - ...chain('r1', 'a', '1'), - ...chain('r2', 'b', '2'), - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - expect(trees(facts)).toEqual({ - a: ['g:lib:jar:1(g:mid:jar:1(g:dep:jar:1))'], - b: ['g:lib:jar:1(g:mid:jar:1(g:dep:jar:2))'], - }) - }) - it('merges the configurations of a subproject into one tree', () => { - const records = [ - 'meta\tgradle\t8.0\t17', - 'project\t:a\tg\ta\t1\ta', - 'root\tr1\t:a\tcompileClasspath\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:api:jar:1\tg\tapi\t1\tjar\t\t0', - 'edge\tr1\tg:lib:jar:1\tg:api:jar:1', - 'root\tr2\t:a\truntimeClasspath\t1', - 'node\tr2\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr2\tg:api:jar:1\tg\tapi\t1\tjar\t\t0', - 'node\tr2\tg:impl:jar:1\tg\timpl\t1\tjar\t\t0', - 'edge\tr2\tg:lib:jar:1\tg:api:jar:1', - 'edge\tr2\tg:lib:jar:1\tg:impl:jar:1', - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - expect(trees(facts)).toEqual({ - ':a': ['g:lib:jar:1(g:api:jar:1, g:impl:jar:1)'], - }) - }) - it('merges equal cycles and keeps different ones apart', () => { - const records = [ - 'meta\tsbt\t1.10.7\t17', - 'project\ta\tg\ta\t1\ta', - 'project\tb\tg\tb\t1\tb', - 'project\tc\tg\tc\t1\tc', - ...cycle('r1', 'a', false), - ...cycle('r2', 'b', false), - ...cycle('r3', 'c', true), - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - // x and y once for a and b together, and once more for c, plus z. - expect(facts.dependencies).toHaveLength(5) - const [a, b, c] = facts.projects! - expect(a!.children).toEqual(b!.children) - expect(c!.children).not.toEqual(a!.children) - expect(trees(facts)).toEqual({ - a: ['g:x:jar:1(g:y:jar:1(g:x:jar:1))'], - b: ['g:x:jar:1(g:y:jar:1(g:x:jar:1))'], - c: ['g:x:jar:1(g:y:jar:1(g:z:jar:1, g:x:jar:1))'], - }) - }) - it('rejects a resolved dependency that no direct dependency reaches', () => { - const records = [ - 'meta\tsbt\t1.10.7\t17', - 'project\ta\tg\ta\t1\ta', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:loose:jar:1\tg\tloose\t1\tjar\t\t0', - 'node\tr1\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'edge\tr1\tg:loose:jar:1\tg:dep:jar:1', - ].join('\n') - - expect(() => assembleFacts(parseRecords(records))).toThrow( - 'Resolved dependencies of a are not reachable from its direct dependencies: g:dep:jar:1, g:loose:jar:1', - ) - }) - it.for([ - { - name: 'an edge through a node its root does not hold', - records: [ - 'project\ta\tg\ta\t1\ta', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'edge\tr1\tg:lib:jar:1\tg:ghost:jar:1', - 'edge\tr1\tg:ghost:jar:1\tg:dep:jar:1', - ], - unreached: - 'a are not reachable from its direct dependencies: g:dep:jar:1', - }, - { - name: "an edge in another project's root", - records: [ - 'project\ta\tg\ta\t1\ta', - 'project\tb\tg\tb\t1\tb', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'root\tr2\tb\tcompile\t1', - 'node\tr2\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr2\tg:dep:jar:1\tg\tdep\t1\tjar\t\t0', - 'edge\tr2\tg:lib:jar:1\tg:dep:jar:1', - ], - unreached: - 'a are not reachable from its direct dependencies: g:dep:jar:1', - }, - { - // Maven: dependencyManagement makes `managed` compile under a test parent, - // so the compile root holds it without a parent. - name: "a node whose parent edge only the project's other root holds", - records: [ - 'project\ta\tg\ta\t1\ta', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:managed:jar:1\tg\tmanaged\t1\tjar\t\t0', - 'root\tr2\ta\ttest\t0', - 'node\tr2\tg:harness:jar:1\tg\tharness\t1\tjar\t\t1', - 'node\tr2\tg:managed:jar:1\tg\tmanaged\t1\tjar\t\t0', - 'edge\tr2\tg:harness:jar:1\tg:managed:jar:1', - ], - unreached: undefined, - }, - { - name: "a build project's artifacts, direct in one root only", - records: [ - 'project\ta\tg\ta\t1\ta', - 'project\tg:lib:1\tg\tlib\t1\tlib', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1\tg:lib:1', - 'root\tr2\ta\ttest\t0', - 'node\tr2\tg:lib:test-jar:tests:1\tg\tlib\t1\ttest-jar\ttests\t0\tg:lib:1', - ], - unreached: undefined, - }, - ])('checks reachability for $name', ({ records, unreached }) => { - const assemble = () => - assembleFacts( - parseRecords(['meta\tmaven\t3.9.9\t17', ...records].join('\n')), - ) - if (unreached) { - expect(assemble).toThrow(`Resolved dependencies of ${unreached}`) - } else { - expect(assemble).not.toThrow() - } - }) - it('keeps the nodes of a root on no classpath in the SBOM but off every classpath', () => { - // Maven 4: `none` is declared, and resolved with its subtree, but on no - // path. Its child x is also on the classpath through lib. - const records = [ - 'meta\tmaven\t4.0.0\t21', - 'project\ta\tg\ta\t1\ta', - 'root\tr1\ta\tcompile\t1', - 'node\tr1\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr1\tg:x:jar:1\tg\tx\t1\tjar\t\t0', - 'edge\tr1\tg:lib:jar:1\tg:x:jar:1', - 'root\tr2\ta\tnone\t0', - 'noClasspath\tr2', - 'node\tr2\tg:lib:jar:1\tg\tlib\t1\tjar\t\t1', - 'node\tr2\tg:x:jar:1\tg\tx\t1\tjar\t\t0', - 'node\tr2\tg:none:jar:1\tg\tnone\t1\tjar\t\t1', - 'node\tr2\tg:none-dep:jar:1\tg\tnone-dep\t1\tjar\t\t0', - 'edge\tr2\tg:lib:jar:1\tg:x:jar:1', - 'edge\tr2\tg:none:jar:1\tg:x:jar:1', - 'edge\tr2\tg:none:jar:1\tg:none-dep:jar:1', - ].join('\n') - - const { artifactPaths, facts } = assembleFacts(parseRecords(records)) - - expect(trees(facts)).toEqual({ - a: [ - 'g:lib:jar:1(g:x:jar:1)', - 'g:none:jar:1(g:x:jar:1, g:none-dep:jar:1)', - ], - }) - expect(facts.components.filter(c => c.dev).map(c => c.id)).toEqual([ - 'g:none-dep:jar:1', - 'g:none:jar:1', - ]) - expect(artifactPaths.classpathByProject.get('a')).toEqual([ - 'g:lib:jar:1', - 'g:x:jar:1', - ]) - expect(artifactPaths.directDependenciesByProject.get('a')).toEqual([ - 'g:lib:jar:1', - ]) - }) - it("gives a dependency on a build project that project's id, and marks only it firstParty", () => { - const records = [ - 'meta\tgradle\t8.0\t17', - 'project\t:a\tg\ta\t1.0-SNAPSHOT\ta', - 'project\t:b\tg\tb\t1.0-SNAPSHOT\tb', - 'root\tr1\t:a\truntimeClasspath\t1', - 'node\tr1\tg:ext:jar:2\tg\text\t2\tjar\t\t1\t', - 'root\tr2\t:b\truntimeClasspath\t1', - 'node\tr2\tg:a:jar:1.0-SNAPSHOT\tg\ta\t1.0-SNAPSHOT\tjar\t\t1\t:a', - 'node\tr2\tg:ext:jar:2\tg\text\t2\tjar\t\t0\t', - 'edge\tr2\tg:a:jar:1.0-SNAPSHOT\tg:ext:jar:2', - // Same name as a build project, but a published artifact, not the project. - 'node\tr2\tg:b:jar:0.9\tg\tb\t0.9\tjar\t\t1\t', - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - expect(facts.components.map(c => [c.id, c.firstParty ?? 'absent'])).toEqual( - [ - [':a', true], - ['g:b:jar:0.9', 'absent'], - ['g:ext:jar:2', 'absent'], - ], - ) - expect(trees(facts)).toEqual({ - ':a': ['g:ext:jar:2'], - ':b': [':a(g:ext:jar:2)', 'g:b:jar:0.9'], - }) - for (const project of facts.projects ?? []) { - expect(project).not.toHaveProperty('firstParty') - } - }) - it("keeps projects that share a coordinate apart, collapsing each project's variants into it", () => { - const records = [ - 'meta\tgradle\t8.0\t17', - 'project\t:a:util\tex\tutil\t1\ta/util', - 'projectSrc\t:a:util\t/abs/a/util/src', - 'project\t:b:util\tex\tutil\t1\tb/util', - 'projectSrc\t:b:util\t/abs/b/util/src', - 'project\t:app\tex\tapp\t1\tapp', - 'root\tr1\t:app\truntimeClasspath\t1', - 'node\tr1\tex:util:jar:1\tex\tutil\t1\tjar\t\t1\t:b:util', - 'node\tr1\tex:util:jar:test-fixtures:1\tex\tutil\t1\tjar\ttest-fixtures\t1\t:b:util', - 'node\tr1\tg:ext:jar:2\tg\text\t2\tjar\t\t0\t', - 'edge\tr1\tex:util:jar:test-fixtures:1\tex:util:jar:1', - 'edge\tr1\tex:util:jar:1\tg:ext:jar:2', - 'root\tr2\t:b:util\truntimeClasspath\t1', - 'node\tr2\tex:util:jar:1\tex\tutil\t1\tjar\t\t1\t:a:util', - ].join('\n') - const { artifactPaths, facts } = assembleFacts(parseRecords(records), { - fileExists: () => true, - }) - - expect(facts.components.map(c => [c.id, c.qualifiers])).toEqual([ - [':a:util', undefined], - [':b:util', undefined], - ['g:ext:jar:2', { ext: 'jar' }], - ]) - expect(trees(facts)).toEqual({ - ':a:util': [], - ':app': [':b:util(g:ext:jar:2)'], - ':b:util': [':a:util'], - }) - expect(artifactPaths.classpathByProject.get(':app')).toEqual([ - ':b:util', - 'g:ext:jar:2', - ]) - expect(artifactPaths.classpathByProject.get(':b:util')).toEqual([':a:util']) - expect(artifactPaths.pathsById.get(':a:util')?.sources).toEqual([ - '/abs/a/util/src', - ]) - expect(artifactPaths.pathsById.get(':b:util')?.sources).toEqual([ - '/abs/b/util/src', - ]) - }) - - it('marks each subproject with its own build files and no component with any', () => { - const records = [ - 'meta\tmaven\t3.9.6\t17', - 'project\ta\tg\ta\t1\ta', - 'projectBuild\ta\ta/pom.xml', - 'project\tb\tg\tb\t1\tb', - 'projectBuild\tb\tb/pom.xml', - // No build file of its own, e.g. configured from the root build. - 'project\tc\tg\tc\t1\tc', - 'root\tr1\ta\truntimeClasspath\t1', - 'node\tr1\tg:ext:jar:2\tg\text\t2\tjar\t\t1', - 'node\tr1\tg:dep:jar:3\tg\tdep\t3\tjar\t\t0', - 'edge\tr1\tg:ext:jar:2\tg:dep:jar:3', - 'root\tr2\tb\ttestRuntimeClasspath\t0', - 'node\tr2\tg:a:jar:1\tg\ta\t1\tjar\t\t1', - 'node\tr2\tg:ext:jar:2\tg\text\t2\tjar\t\t1', - 'edge\tr2\tg:a:jar:1\tg:ext:jar:2', - 'root\tr3\tc\truntimeClasspath\t1', - 'node\tr3\tg:solo:jar:1\tg\tsolo\t1\tjar\t\t1', - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - expect( - Object.fromEntries( - facts.projects!.map(p => [p.name, p.manifestFiles ?? 'absent']), - ), - ).toEqual({ - a: [{ file: 'a/pom.xml' }], - b: [{ file: 'b/pom.xml' }], - c: 'absent', - }) - for (const c of facts.components) { - expect(c).not.toHaveProperty('manifestFiles') - } - }) - it("records each project's own build files, relative to the build root", () => { - const records = [ - 'meta\tmaven\t3.9.6\t17', - 'buildRoot\t/repo/sub', - 'project\tg:agg:1\tg\tagg\t1\t.', - 'projectBuild\tg:agg:1\tother-pom.xml', - 'project\tg:mod-a:1\tg\tmod-a\t1\tmod', - 'projectBuild\tg:mod-a:1\tmod/a.xml', - 'project\tg:mod-b:1\tg\tmod-b\t1\tmod', - 'projectBuild\tg:mod-b:1\tmod/b.xml', - 'project\tg:bare:1\tg\tbare\t1\tbare', - ].join('\n') - const parsed = parseRecords(records) - const { facts } = assembleFacts(parsed) - - expect(parsed.buildRoot).toBe('/repo/sub') - expect( - Object.fromEntries( - facts.projects!.map(p => [p.id, p.manifestFiles ?? 'absent']), - ), - ).toEqual({ - 'g:agg:1': [{ file: 'other-pom.xml' }], - 'g:bare:1': 'absent', - 'g:mod-a:1': [{ file: 'mod/a.xml' }], - 'g:mod-b:1': [{ file: 'mod/b.xml' }], - }) - }) - it('marks each Gradle project with its configured build file, even when absent', () => { - const records = [ - 'meta\tgradle\t9.2.1\t21', - 'buildRoot\t/repo', - 'project\t:\tg\troot\t1\t.', - 'projectBuild\t:\tbuild.gradle.kts', - // Configured from the root build, no script of its own. - 'project\t:a\tg\ta\t1\ta', - 'projectBuild\t:a\ta/build.gradle.kts', - 'root\tr1\t:a\truntimeClasspath\t1', - 'node\tr1\tx:from-root:jar:1\tx\tfrom-root\t1\tjar\t\t1', - ].join('\n') - const { facts } = assembleFacts(parseRecords(records)) - - expect( - Object.fromEntries( - facts.projects!.map(p => [p.id, p.manifestFiles?.map(m => m.file)]), - ), - ).toEqual({ - ':': ['build.gradle.kts'], - ':a': ['a/build.gradle.kts'], - }) - }) -}) - -describe('dotnet records → assemble', () => { - const DOTNET = [ - 'meta\tdotnet\t8.0.414\t', - 'buildRoot\t/abs', - 'entry\tApp.sln', - 'project\tsrc/App/App.csproj\t\tApp\t1.0.0\tsrc/App', - 'projectBuild\tsrc/App/App.csproj\tsrc/App/App.csproj', - 'projectBuild\tsrc/App/App.csproj\tDirectory.Packages.props', - 'project\tsrc/Lib/Lib.csproj\t\tAcme.Lib\t2.0.0\tsrc/Lib', - 'root\tsrc/App/App.csproj|net8.0|prod\tsrc/App/App.csproj\tnet8.0\t1', - 'node\tsrc/App/App.csproj|net8.0|prod\tacme.lib:2.0.0\t\tAcme.Lib\t2.0.0\t\t\t1\tsrc/Lib/Lib.csproj', - 'node\tsrc/App/App.csproj|net8.0|prod\tnewtonsoft.json:13.0.3\t\tNewtonsoft.Json\t13.0.3\t\t\t0\t', - 'edge\tsrc/App/App.csproj|net8.0|prod\tacme.lib:2.0.0\tnewtonsoft.json:13.0.3', - 'root\tsrc/Lib/Lib.csproj|net8.0|prod\tsrc/Lib/Lib.csproj\tnet8.0\t1', - 'node\tsrc/Lib/Lib.csproj|net8.0|prod\tnewtonsoft.json:13.0.3\t\tNewtonsoft.Json\t13.0.3\t\t\t1\t', - 'scanned\tnet8.0', - ].join('\r\n') - - it('assembles nuget purls without a namespace, with project-path ids', () => { - const { facts } = assembleFacts(parseRecords(DOTNET)) - expect(facts.metadata?.tool).toBe('dotnet') - expect(facts.components).toEqual([ - { - type: 'nuget', - name: 'Newtonsoft.Json', - version: '13.0.3', - id: 'newtonsoft.json:13.0.3', - direct: true, - }, - { - type: 'nuget', - name: 'Acme.Lib', - version: '2.0.0', - id: 'src/Lib/Lib.csproj', - direct: true, - firstParty: true, - }, - ]) - expect(facts.projects?.map(p => ({ ...p, children: undefined }))).toEqual([ - { - id: 'src/App/App.csproj', - type: 'nuget', - name: 'App', - version: '1.0.0', - subprojectDir: 'src/App', - manifestFiles: [ - { file: 'Directory.Packages.props' }, - { file: 'src/App/App.csproj' }, - ], - children: undefined, - }, - { - id: 'src/Lib/Lib.csproj', - type: 'nuget', - name: 'Acme.Lib', - version: '2.0.0', - subprojectDir: 'src/Lib', - children: undefined, - }, - ]) - expect(trees(facts)).toEqual({ - 'src/App/App.csproj': ['src/Lib/Lib.csproj(newtonsoft.json:13.0.3)'], - 'src/Lib/Lib.csproj': ['newtonsoft.json:13.0.3'], - }) - }) -}) - -describe('dotnet build without dependencies', () => { - it('still gets its compile context', () => { - const records = [ - 'meta\tdotnet\t8.0.414\t', - 'project\tLeaf.csproj\t\tLeaf\t1.0.0\t.', - 'projectSrc\tLeaf.csproj\t/abs/Leaf.cs\tnet8.0', - 'projectInfo\tLeaf.csproj\tnet8.0\tFramework\tnet8.0', - 'projectInfo\tLeaf.csproj\tnet8.0\tFrameworkReference\tMicrosoft.NETCore.App', - ].join('\n') - const { artifactPaths } = assembleFacts(parseRecords(records), { - fileExists: () => true, - }) - expect(artifactPaths.frameworksByProject?.get('Leaf.csproj')).toMatchObject( - [ - { - alias: 'net8.0', - framework: 'net8.0', - frameworkReferences: ['Microsoft.NETCore.App'], - sources: ['/abs/Leaf.cs'], - dependencies: [], - classpath: [], - }, - ], - ) - }) -}) - -describe('parseRecords', () => { - it('reads the build root the build reports', () => { - expect( - parseRecords( - ['meta\tmaven\t3.9.6\t17', 'buildRoot\t/repo/sub'].join('\n'), - ).buildRoot, - ).toBe('/repo/sub') - }) -}) diff --git a/src/commands/manifest/scripts/build-tool.mts b/src/commands/manifest/scripts/build-tool.mts index 20c4a5651b..0b1fe65290 100644 --- a/src/commands/manifest/scripts/build-tool.mts +++ b/src/commands/manifest/scripts/build-tool.mts @@ -45,9 +45,6 @@ export function buildToolLabelsFor(purlTypes: readonly PURL_Type[]): string[] { return buildToolsFor(purlTypes).map(tool => ECOSYSTEM_LABELS[tool]) } -// Purl types whose packages have no namespace (NuGet ids are flat). -export const NAMESPACELESS_PURL_TYPES: ReadonlySet = new Set(['nuget']) - const BUILD_TOOL_PATH_ENV: Record = { __proto__: null, gradle: 'SOCKET_CLI_GRADLE_PATH', diff --git a/src/commands/manifest/scripts/build-tool.test.mts b/src/commands/manifest/scripts/build-tool.test.mts deleted file mode 100644 index 7e8fb7a0fc..0000000000 --- a/src/commands/manifest/scripts/build-tool.test.mts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { socketFactsFileName } from './build-tool.mts' -import { parseRecords } from './records.mts' - -describe('socketFactsFileName', () => { - it('names a directory-addressed build after its tool', () => { - expect(socketFactsFileName('gradle', undefined)).toBe( - 'gradle.socket.facts.json', - ) - expect(socketFactsFileName('sbt', undefined)).toBe('sbt.socket.facts.json') - }) - - it('names a file-addressed build after the entry file it reported', () => { - expect( - socketFactsFileName('maven', parseRecords('entry\tpom.xml').entry), - ).toBe('pom.xml.socket.facts.json') - expect( - socketFactsFileName('maven', parseRecords('entry\tother-pom.xml').entry), - ).toBe('other-pom.xml.socket.facts.json') - }) - - it('cannot name a file-addressed build that reported no entry file', () => { - expect( - socketFactsFileName( - 'maven', - parseRecords('meta\tmaven\t3.9.6\t17').entry || undefined, - ), - ).toBeUndefined() - }) -}) diff --git a/src/commands/manifest/scripts/dotnet-tool/.gitignore b/src/commands/manifest/scripts/dotnet-tool/.gitignore deleted file mode 100644 index 7538de6140..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -bin/ -obj/ -publish/ diff --git a/src/commands/manifest/scripts/dotnet-tool/FactsRunner.cs b/src/commands/manifest/scripts/dotnet-tool/FactsRunner.cs deleted file mode 100644 index a3f874a33f..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/FactsRunner.cs +++ /dev/null @@ -1,344 +0,0 @@ -using System.Text.Json; -using Microsoft.Build.Definition; -using Microsoft.Build.Evaluation; -using Microsoft.Build.Evaluation.Context; -using Microsoft.Build.Exceptions; - -namespace Socket.Facts.Dotnet; - -internal enum RestoreStyle { - PackageReference, - PackagesConfig, - ProjectJson, - Unknown, -} - -internal sealed class ProjectInfo { - public string FullPath = ""; - public string Key = ""; - public Dictionary GlobalProperties = new(); - public bool Excluded; - public RestoreStyle Style = RestoreStyle.Unknown; -} - -// Evaluate -> `dotnet restore` -> re-evaluate and read. Never throws for a -// project-level problem: those become failure/unscannable records, which the -// CLI renders and turns into the exit code. -internal static class FactsRunner { - public static int Run(ToolOptions opts, string sdkVersion) { - using var records = new RecordsWriter(opts.RecordsPath); - try { - records.Meta(sdkVersion); - new Session(opts, records).Execute(); - return 0; - } catch (Exception e) { - // The record keeps a partially written run from reading as complete. - records.Failure( - Path.GetFileName(opts.EntryPath), - $"socket-facts-dotnet failed: {e.GetType().Name}: {Text.FirstLine(e.Message)}", - "", - "" - ); - Console.Error.WriteLine($"socket-facts-dotnet: {e}"); - return 1; - } - } -} - -internal sealed partial class Session { - private readonly ToolOptions _opts; - private readonly RecordsWriter _records; - private readonly string _buildRoot; - private readonly string _excludeBase; - private readonly Globs _configs; - private readonly PathExcludes _excludes; - private readonly HashSet _scanned = new(StringComparer.Ordinal); - private readonly Dictionary _projects = new(StringComparer.Ordinal); - private SolutionContext? _solution; - private RestoreOutcome? _restore; - - public Session(ToolOptions opts, RecordsWriter records) { - _opts = opts; - _records = records; - _buildRoot = Path.GetDirectoryName(opts.EntryPath)!; - _excludeBase = string.IsNullOrEmpty(opts.ExcludeBase) ? _buildRoot : opts.ExcludeBase; - _configs = new Globs(opts.IncludeConfigs, opts.ExcludeConfigs); - _excludes = new PathExcludes(opts.ExcludePaths); - } - - public void Execute() { - _records.BuildRoot(_buildRoot); - _records.Entry(Path.GetFileName(_opts.EntryPath)); - if (!File.Exists(_opts.EntryPath)) { - _records.Failure(Path.GetFileName(_opts.EntryPath), "entry file does not exist", ""); - return; - } - - var entryProjects = EntryProjects(); - if (entryProjects == null) return; - if (_opts.Mode == ToolMode.Members) { - foreach (var path in entryProjects) { - if (!IsExcludedProject(path)) _records.Member(Rel(path)); - } - return; - } - - // Listing workspaces evaluates the projects as they are before restore; - // a scan leaves finding them to restore, which follows every reference, - // conditional per target framework or not. - if (_opts.Mode == ToolMode.Workspaces) { - var preRestore = new ProjectCollection(); - _evaluation = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared); - var queue = new Queue(entryProjects); - while (queue.Count > 0) { - var path = queue.Dequeue(); - if (_projects.ContainsKey(path)) continue; - var info = Register(path); - if (info.Excluded) continue; - var project = Evaluate(info, preRestore); - if (project == null) continue; - info.Style = StyleOf(project, out _); - EmitProject(info, project); - foreach (var reference in ProjectReferences(project, innerBuilds: true)) queue.Enqueue(reference); - } - return; - } - - RunRestore(); - - // One evaluation context for every project read: its file-system and SDK - // resolution caches are shared, and it starts after restore wrote the - // files evaluation imports. - var postRestore = new ProjectCollection(); - _evaluation = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared); - var read = new HashSet(StringComparer.Ordinal); - var pending = new Queue( - entryProjects.Concat(_projects.Keys).Distinct(StringComparer.Ordinal).OrderBy(p => p, StringComparer.Ordinal) - ); - while (pending.Count > 0) { - var path = pending.Dequeue(); - if (!read.Add(path)) continue; - var info = _projects.TryGetValue(path, out var known) ? known : Register(path); - foreach (var reference in ReadProject(info, postRestore)) { - if (!read.Contains(reference)) pending.Enqueue(reference); - } - foreach (var loaded in postRestore.GetLoadedProjects(path).ToList()) postRestore.UnloadProject(loaded); - } - ReportRestoreErrors(); - } - - private ProjectInfo Register(string path) { - var info = new ProjectInfo { - FullPath = path, - Key = Rel(path), - GlobalProperties = PropertiesFor(path), - }; - info.Excluded = IsExcludedProject(path); - _projects[path] = info; - return info; - } - - // Relative to --exclude-base when given; a project outside it, including on - // another Windows drive (which GetRelativePath returns as is), never matches. - private bool IsExcludedProject(string path) { - var rel = RelTo(_excludeBase, Path.GetDirectoryName(path)!); - return rel != ".." && !rel.StartsWith("../", StringComparison.Ordinal) && !Path.IsPathRooted(rel) - && _excludes.IsExcluded(rel); - } - - // The solution's members its active configuration builds, or the entry - // project itself. - private List? EntryProjects() { - var entry = _opts.EntryPath; - if (!IsSolution(entry)) return new List { entry }; - try { - _solution = new SolutionContext(entry, _opts.GlobalProperties); - return _solution.Members.Keys.OrderBy(p => p, StringComparer.Ordinal).ToList(); - } catch (Exception e) when (e is InvalidProjectFileException or IOException or JsonException) { - _records.Failure(Rel(entry), $"could not read the solution: {ErrorText(e)}", ""); - return null; - } - } - - private Dictionary PropertiesFor(string projectPath) { - var props = new Dictionary(_opts.GlobalProperties, StringComparer.OrdinalIgnoreCase); - _solution?.Apply(projectPath, props); - return props; - } - - // NuGet's GetRestoreProjectStyleTask (fed by NuGet.targets' - // _GetRestoreProjectStyle): an explicit RestoreProjectStyle wins (the .NET - // SDK sets PackageReference), then PackageReference items, then - // project.json, then a packages config file. - private static RestoreStyle StyleOf(Project project, out string? packagesConfig) { - packagesConfig = FindPackagesConfig(project); - var explicitStyle = project.GetPropertyValue("RestoreProjectStyle"); - if (!string.IsNullOrEmpty(explicitStyle)) { - return Enum.TryParse(explicitStyle, ignoreCase: true, out var style) - ? style - : RestoreStyle.Unknown; - } - if (project.GetItems("PackageReference").Count > 0) return RestoreStyle.PackageReference; - var dir = project.DirectoryPath; - if (File.Exists(Path.Combine(dir, "project.json")) - || File.Exists(Path.Combine(dir, $"{project.GetPropertyValue("MSBuildProjectName")}.project.json"))) { - return RestoreStyle.ProjectJson; - } - return packagesConfig != null ? RestoreStyle.PackagesConfig : RestoreStyle.Unknown; - } - - // packages.config wins over packages..config, as in - // GetRestoreProjectStyleTask and NuGet.targets' _GenerateRestoreProjectSpec. - private static string? FindPackagesConfig(Project project) { - var dir = project.DirectoryPath; - var shared = Path.Combine(dir, "packages.config"); - if (File.Exists(shared)) return shared; - var named = Path.Combine(dir, $"packages.{project.GetPropertyValue("MSBuildProjectName")}.config"); - return File.Exists(named) ? named : null; - } - - // As MSBuild's static graph finds them: a multi-targeting project's - // references are those of each of its inner builds, which may differ by - // target framework. - private IEnumerable ProjectReferences(Project project, bool innerBuilds) { - var builds = new List { project }; - if (innerBuilds) { - foreach (var tfm in Frameworks(project)) { - try { - builds.Add(LoadInnerBuild(project, tfm)); - } catch (InvalidProjectFileException) { - // Its references surface from restore output instead. - } - } - } - return FullPaths(builds.SelectMany(b => b.GetItems("ProjectReference"))).Where(File.Exists).ToList(); - } - - private void RunRestore() { - // The entry exactly as the user restores it, or a solution filter of the - // members --exclude-paths keeps, restored in the solution's own context. - var target = _opts.EntryPath; - string? filter = null; - if (_solution != null) { - var kept = _solution.Members.Keys - .Where(m => !IsExcludedProject(m)) - .ToList(); - if (kept.Count == 0) return; - if (kept.Count != _solution.Members.Count) { - filter = _solution.WriteFilter(kept); - target = filter; - } - } - try { - _restore = Restorer.Run(_opts, target, Log); - } finally { - if (filter != null) Text.TryDelete(filter); - } - if (_restore.TimedOut) { - _records.Failure(Rel(_opts.EntryPath), $"`dotnet restore` did not finish within {Restorer.TimeoutSec}s and was stopped", ""); - } - } - - // As `dotnet restore` evaluates: a project it reads despite a bad import (a - // web application's Visual Studio-only targets) is read here too. - private const ProjectLoadSettings RestoreLoadSettings = - ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports; - - private EvaluationContext? _evaluation; - - private Project Load(ProjectCollection collection, string path, IDictionary properties) { - foreach (var loaded in collection.GetLoadedProjects(path)) { - if (loaded.GlobalProperties.Count == properties.Count - && properties.All(kv => loaded.GlobalProperties.TryGetValue(kv.Key, out var v) && v == kv.Value)) { - return loaded; - } - } - return Project.FromFile(path, new ProjectOptions { - EvaluationContext = _evaluation, - GlobalProperties = properties, - LoadSettings = RestoreLoadSettings, - ProjectCollection = collection, - }); - } - - private Project LoadInnerBuild(Project project, string targetFramework) { - var props = new Dictionary(project.GlobalProperties, StringComparer.OrdinalIgnoreCase) { - ["TargetFramework"] = targetFramework, - }; - return Load(project.ProjectCollection, project.FullPath, props); - } - - // An excluded project's failure is not reported: it is only read for the - // paths of the kept projects depending on it. - private Project? Evaluate(ProjectInfo info, ProjectCollection collection) { - try { - return Load(collection, info.FullPath, info.GlobalProperties); - } catch (InvalidProjectFileException e) { - if (!info.Excluded) { - _records.Unscannable("", $"could not evaluate the project: {ErrorText(e)}", info.Key); - } - return null; - } - } - - // MSBuild keeps an error's code out of its message. - private static string ErrorText(Exception e) { - var line = Text.FirstLine(e.Message); - return e is InvalidProjectFileException { ErrorCode: { Length: > 0 } code } ? $"{code}: {line}" : line; - } - - // Restore errors not already reported from an assets file, then the projects - // left without current assets and without errors of their own. - private void ReportRestoreErrors() { - if (_restore == null || _restore.Succeeded) return; - var withErrors = new HashSet(_assetsReportedErrors, StringComparer.Ordinal); - if (!_restore.TimedOut) { - var reported = 0; - foreach (var error in _restore.Errors) { - var key = string.IsNullOrEmpty(error.ProjectFile) ? "" : Rel(Path.GetFullPath(error.ProjectFile)); - if (key.Length > 0 && _assetsReportedErrors.Contains(key)) continue; - if (key.Length > 0) withErrors.Add(key); - var code = string.IsNullOrEmpty(error.Code) ? "" : $"{error.Code}: "; - _records.Failure(key.Length > 0 ? key : Rel(_opts.EntryPath), $"{code}{error.Message}", "", key); - reported += 1; - } - if (reported == 0 && _assetsReportedErrors.Count == 0) { - _records.Failure( - Rel(_opts.EntryPath), - $"`dotnet restore` failed with exit code {_restore.ExitCode}; run with --verbose to see its output", - "" - ); - } - } - foreach (var key in _notRestored.Where(k => !withErrors.Contains(k))) { - _records.Unscannable("", "the failed `dotnet restore` may have skipped this project as up to date, or never reached it, so its dependencies are unknown", key); - } - } - - private void Log(string message) { - if (_opts.Verbose) Console.Error.WriteLine($"socket-facts-dotnet: {message}"); - } - - // Build-root-relative with `/`, the shape every record path takes. - private string Rel(string path) => RelTo(_buildRoot, path); - - private static string RelTo(string root, string path) { - var rel = Path.GetRelativePath(root, Path.GetFullPath(path)).Replace('\\', '/'); - return string.IsNullOrEmpty(rel) ? "." : rel; - } - - private static bool SamePath(string a, string b) { - return string.Equals( - RealPaths.Of(a), - RealPaths.Of(b), - OperatingSystem.IsLinux() ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase - ); - } - - private static bool IsSolution(string path) { - var ext = Path.GetExtension(path); - return ext.Equals(".sln", StringComparison.OrdinalIgnoreCase) - || ext.Equals(".slnx", StringComparison.OrdinalIgnoreCase) - || ext.Equals(".slnf", StringComparison.OrdinalIgnoreCase); - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/NuGetShim.cs b/src/commands/manifest/scripts/dotnet-tool/NuGetShim.cs deleted file mode 100644 index 97d0c2306b..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/NuGetShim.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections; -using System.Collections.Concurrent; -using System.Reflection; - -namespace Socket.Facts.Dotnet; - -// NuGet changed collection members' declared types across the SDKs the tool -// runs on (IList -> ImmutableArray), which a compiled getter cannot bind. -internal static class NuGetShim { - private static readonly ConcurrentDictionary<(Type, string), PropertyInfo?> Properties = new(); - - public static IEnumerable Seq(object? owner, string member) { - if (owner == null) yield break; - var prop = Properties.GetOrAdd( - (owner.GetType(), member), - key => key.Item1.GetProperty(key.Item2, BindingFlags.Public | BindingFlags.Instance) - ); - if (prop?.GetValue(owner) is not IEnumerable items) yield break; - foreach (var item in items) { - if (item is T typed) yield return typed; - } - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/Patterns.cs b/src/commands/manifest/scripts/dotnet-tool/Patterns.cs deleted file mode 100644 index 294b5e41a7..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/Patterns.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System.Text; -using System.Text.RegularExpressions; - -namespace Socket.Facts.Dotnet; - -// Target-framework name filters with the semantics of the JVM scripts' -// config globs: case-sensitive `*`, `?` and `[...]` (with `[!..]` negation); -// a malformed glob matches literally. -internal sealed class Globs { - private readonly List _includes; - private readonly List _excludes; - - public Globs(string includes, string excludes) { - _includes = Parse(includes); - _excludes = Parse(excludes); - } - - // Matches when any of `names` matches an include (or there are none) and - // none matches an exclude. - public bool Matches(IReadOnlyCollection names) { - if (_excludes.Any(p => names.Any(p.IsMatch))) return false; - return _includes.Count == 0 || _includes.Any(p => names.Any(p.IsMatch)); - } - - public bool Matches(string name) => Matches(new[] { name }); - - private static List Parse(string csv) { - return csv - .Split(',') - .Select(s => s.Trim()) - .Where(s => s.Length > 0) - .Select(ToRegex) - .ToList(); - } - - private static Regex ToRegex(string glob) { - var sb = new StringBuilder("^(?:"); - var i = 0; - while (i < glob.Length) { - var ch = glob[i]; - if (ch == '*') { - sb.Append(".*"); - i += 1; - } else if (ch == '?') { - sb.Append('.'); - i += 1; - } else if (ch == '[') { - var j = glob.IndexOf(']', i + 1); - if (j <= i + 1) { - sb.Append("\\["); - i += 1; - } else { - var body = glob.Substring(i + 1, j - i - 1); - var negated = body.StartsWith('!'); - if (negated) body = body.Substring(1); - body = body.Replace("\\", "\\\\").Replace("[", "\\["); - sb.Append('[').Append(negated ? "^" : "").Append(body).Append(']'); - i = j + 1; - } - } else { - sb.Append(Regex.Escape(ch.ToString())); - i += 1; - } - } - sb.Append(")\\z"); - try { - return new Regex(sb.ToString(), RegexOptions.CultureInvariant); - } catch (ArgumentException) { - return new Regex($"^{Regex.Escape(glob)}\\z", RegexOptions.CultureInvariant); - } - } -} - -// --exclude-paths, pre-compiled by the CLI (exclude-paths-glob.mts) into -// anchored regex sources over build-root-relative directories; each already -// means "this directory or anything below it". -internal sealed class PathExcludes { - private readonly List _patterns = new(); - - public PathExcludes(string csv) { - foreach (var raw in csv.Split(',')) { - var p = raw.Trim(); - if (p.Length == 0) continue; - try { - _patterns.Add(new Regex(p, RegexOptions.CultureInvariant)); - } catch (ArgumentException) { - // The CLI only emits valid sources; this guards a broken transport. - } - } - } - - // `rel` is build-root-relative with `/`; the build root itself (`.`) is - // never excluded. - public bool IsExcluded(string rel) => rel != "." && _patterns.Any(p => p.IsMatch(rel)); -} - -internal static class Text { - // An MSBuild project file: .csproj, .fsproj, .vbproj and the like. - public static bool IsProjectFile(string path) => path.EndsWith("proj", StringComparison.OrdinalIgnoreCase); - - public static string FirstLine(string s) { - var idx = s.IndexOfAny(new[] { '\n', '\r' }); - return idx < 0 ? s : s.Substring(0, idx); - } - - public static void TryDelete(string path) { - try { - File.Delete(path); - } catch (IOException) { - // Left in the temp dir. - } catch (UnauthorizedAccessException) { - // Left in the temp dir. - } - } -} - -// Restore reports some paths through a symlinked directory's target (macOS's -// /var -> /private/var); the last segment keeps the name it was given. -internal static class RealPaths { - private static readonly Dictionary Dirs = new(StringComparer.Ordinal); - - public static string Of(string path) { - var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); - var dir = Path.GetDirectoryName(full); - return dir == null ? full : Path.Combine(Dir(dir), Path.GetFileName(full)); - } - - public static string Dir(string dir) { - if (Dirs.TryGetValue(dir, out var known)) return known; - var parent = Path.GetDirectoryName(dir); - var real = parent == null ? dir : Path.Combine(Dir(parent), Path.GetFileName(dir)); - try { - if (new DirectoryInfo(real).ResolveLinkTarget(returnFinalTarget: true) is { } target) real = Dir(target.FullName); - } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { - // Unresolvable links stay as written. - } - Dirs[dir] = real; - return real; - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/Program.cs b/src/commands/manifest/scripts/dotnet-tool/Program.cs deleted file mode 100644 index f2a096a9a6..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/Program.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.Build.Locator; - -namespace Socket.Facts.Dotnet; - -internal static class Program { - private static int Main(string[] args) { - ToolOptions opts; - try { - opts = ToolOptions.Parse(args); - } catch (ArgumentException e) { - Console.Error.WriteLine(e.Message); - Console.Error.WriteLine(ToolOptions.Usage); - return 2; - } - // Resolves the SDK the way the dotnet CLI does from the entry's directory - // (the caller's cwd), so a global.json pin selects the same SDK that - // `dotnet restore` runs. - var instance = MSBuildLocator.RegisterDefaults(); - // MSBuild types must not be JITed before the locator has registered the - // SDK assemblies, hence the separate class. - return FactsRunner.Run(opts, instance.Version.ToString()); - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/Reader.cs b/src/commands/manifest/scripts/dotnet-tool/Reader.cs deleted file mode 100644 index ce38350b92..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/Reader.cs +++ /dev/null @@ -1,662 +0,0 @@ -using System.Xml.Linq; -using Microsoft.Build.Construction; -using Microsoft.Build.Evaluation; -using Microsoft.Build.Exceptions; -using NuGet.Common; -using NuGet.Frameworks; -using NuGet.LibraryModel; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.ProjectModel; -using NuGet.Versioning; - -namespace Socket.Facts.Dotnet; - -// What every target of one project.assets.json shares. -internal sealed record Assets( - // NuGet's own choice of a package's directory among the package folders; - // null when a fallback folder restore used is gone. - FallbackPackagePathResolver? Resolver, - // Package libraries by lowercased name and version. - Dictionary<(string Name, NuGetVersion? Version), LockFileLibrary> Libraries, - // Lowercased project library name -> the project's key, and back. - Dictionary ProjectKeys, - Dictionary ProjectNames -); - -internal sealed partial class Session { - // The project type GUID in the ProjectTypeGuids of Visual Studio unit test - // projects. - private const string TestProjectTypeGuid = "3AC096D0-A1C2-E12C-1390-A8335801FDAB"; - - // Package and project identities NuGet compares case-insensitively. - private static string CoordId(string name, string version) => - $"{name.ToLowerInvariant()}:{version}"; - - // Keys of projects whose assets file recorded restore errors of its own, - // which say more than the restore's console errors for that project. - private readonly HashSet _assetsReportedErrors = new(StringComparer.Ordinal); - // Read without current assets after a failed restore; see ReportRestoreErrors. - private readonly List _notRestored = new(); - - private IEnumerable ReadProject(ProjectInfo info, ProjectCollection collection) { - var references = new List(); - var project = Evaluate(info, collection); - if (project == null) return references; - info.Style = StyleOf(project, out var packagesConfig); - if (info.Excluded) { - // Not resolved, but kept projects depending on it still need its paths. - if (_opts.WithFiles) { - EmitProject(info, project); - _records.ExcludedProject(info.Key); - EmitPaths(info, project); - } - return references; - } - references.AddRange(ProjectReferences(project, innerBuilds: false)); - switch (info.Style) { - case RestoreStyle.PackageReference: - references.AddRange(ReadAssets(info, project)); - break; - case RestoreStyle.PackagesConfig when packagesConfig != null: - ReadPackagesConfig(info, project, packagesConfig); - break; - case RestoreStyle.ProjectJson: - EmitProject(info, project); - _records.Unscannable("", "project.json projects are not supported; migrate the project to PackageReference", info.Key); - break; - default: - // No NuGet dependencies; still a module whose sources matter. - EmitProject(info, project); - if (_opts.WithFiles) EmitPaths(info, project); - break; - } - return references; - } - - // NuGet.targets' _RestoreProjectName: PackageId, then AssemblyName, for - // the PackageReference style; the project name otherwise. - private static string RestoreName(Project project, RestoreStyle style) { - if (style == RestoreStyle.PackageReference) { - foreach (var property in new[] { "PackageId", "AssemblyName" }) { - var value = project.GetPropertyValue(property); - if (!string.IsNullOrEmpty(value)) return value; - } - } - return project.GetPropertyValue("MSBuildProjectName"); - } - - // NuGet.targets' _RestoreProjectVersion. - private static string RestoreVersion(Project project) { - var v = project.GetPropertyValue("PackageVersion"); - if (string.IsNullOrEmpty(v)) v = project.GetPropertyValue("Version"); - return string.IsNullOrEmpty(v) ? "1.0.0" : v; - } - - // Named as restore names the project, unless its restore spec says. - private void EmitProject(ProjectInfo info, Project project, string? name = null, string? version = null) { - _records.Project( - info.Key, - name ?? RestoreName(project, info.Style), - version ?? RestoreVersion(project), - Rel(project.DirectoryPath) - ); - EmitBuildFiles(info, project); - } - - private IEnumerable ReadAssets(ProjectInfo info, Project project) { - var assetsPath = project.GetPropertyValue("ProjectAssetsFile"); - if (string.IsNullOrEmpty(assetsPath)) { - assetsPath = Path.Combine(project.GetPropertyValue("MSBuildProjectExtensionsPath"), "project.assets.json"); - } - assetsPath = Path.GetFullPath(assetsPath, project.DirectoryPath); - // Null detail: ReportRestoreErrors reports the project with the failed restore. - string[] Unscannable(string? detail) { - EmitProject(info, project); - if (detail == null) { - _notRestored.Add(info.Key); - } else { - _records.Unscannable("", detail, info.Key); - } - return Array.Empty(); - } - if (!RestoredByThisRun(info, assetsPath) || !File.Exists(assetsPath)) { - return Unscannable( - _restore == null || _restore.Succeeded ? "`dotnet restore` wrote no project.assets.json for this project" : null - ); - } - - var lockFile = LockFileUtilities.GetLockFile(assetsPath, NullLogger.Instance); - var spec = lockFile?.PackageSpec; - if (lockFile == null || spec == null) return Unscannable($"could not read {Rel(assetsPath)}"); - var owner = spec.RestoreMetadata?.ProjectPath; - if (!string.IsNullOrEmpty(owner) && !SamePath(owner, info.FullPath)) { - return Unscannable( - $"{Rel(assetsPath)} belongs to {Rel(owner)}: the projects share an intermediate output directory, so each overwrites the other's restore output; give each its own, e.g. obj/$(MSBuildProjectName)/ in Directory.Build.props" - ); - } - - EmitProject(info, project, spec.Name, spec.Version?.ToNormalizedString()); - var lockFilePath = PackagesLockFileUtilities.GetNuGetLockFilePath(spec); - if (!string.IsNullOrEmpty(lockFilePath) && File.Exists(lockFilePath)) { - _records.ProjectBuild(info.Key, Rel(lockFilePath)); - } - ReportLogErrors(info, lockFile); - - // Project libraries are ProjectReferences as restore resolved them. - var projectKeys = new Dictionary(StringComparer.Ordinal); - var projectNames = new Dictionary(StringComparer.Ordinal); - var references = new List(); - var libraries = new Dictionary<(string, NuGetVersion?), LockFileLibrary>(); - foreach (var library in NuGetShim.Seq(lockFile, "Libraries")) { - if (string.IsNullOrEmpty(library.Name)) continue; - libraries[(library.Name.ToLowerInvariant(), library.Version)] = library; - if (!IsProject(library.Type)) continue; - if (string.IsNullOrEmpty(library.MSBuildProject)) continue; - var path = Path.GetFullPath(library.MSBuildProject, project.DirectoryPath); - var key = Rel(path); - projectKeys[library.Name.ToLowerInvariant()] = key; - projectNames[key] = library.Name.ToLowerInvariant(); - references.Add(path); - } - var assets = new Assets(PackageResolver(lockFile), libraries, projectKeys, projectNames); - - var isTest = IsTestProject(project); - foreach (var target in NuGetShim.Seq(lockFile, "Targets")) { - EmitTarget(info, spec, target, assets, isTest); - } - if (_opts.WithFiles) EmitPaths(info, project); - return references; - } - - // The resolver the .NET SDK builds from an assets file's package folders: - // the first is the user's, the rest fallbacks. - private static FallbackPackagePathResolver? PackageResolver(LockFile lockFile) { - var folders = NuGetShim.Seq(lockFile, "PackageFolders") - .Select(f => f.Path) - .Where(p => !string.IsNullOrEmpty(p)) - .ToList(); - if (folders.Count == 0) return null; - try { - return new FallbackPackagePathResolver(folders[0], folders.Skip(1)); - } catch (PackagingException) { - // A fallback folder restore used no longer exists. - return null; - } - } - - // An assets or cache file's error-level restore messages, as failures of the - // package they name. - private void ReportLogErrors(ProjectInfo info, object owner) { - foreach (var message in NuGetShim.Seq(owner, "LogMessages")) { - if (message.Level != LogLevel.Error) continue; - _assetsReportedErrors.Add(info.Key); - _records.Failure( - string.IsNullOrEmpty(message.LibraryId) ? info.Key : message.LibraryId, - $"{message.Code}: {message.Message}", - "", - info.Key - ); - } - } - - // FAT records write times to 2 s. - // https://learn.microsoft.com/en-us/windows/win32/sysinfo/file-times - private static readonly TimeSpan MtimeResolution = TimeSpan.FromSeconds(2); - - // NuGet rewrites project.nuget.cache on every restore it performs but not an - // unchanged assets file, so only the cache says whether this run restored it. - // It skips the cache of a project it found up to date too, so after a failed - // restore an older cache cannot tell such a project from one the restore - // never reached: both count as not restored. - // https://github.com/NuGet/NuGet.Client/blob/aa539166b2ff5abf970ee44281d73c96e3dbaa1a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/NoOpRestoreResult.cs#L34-L35 - private bool RestoredByThisRun(ProjectInfo info, string assetsPath) { - if (_restore == null || _restore.Succeeded) return true; - var cachePath = Path.Combine(Path.GetDirectoryName(assetsPath)!, "project.nuget.cache"); - if (!File.Exists(cachePath) || File.GetLastWriteTimeUtc(cachePath) < _restore.StartedUtc - MtimeResolution) return false; - using (var stream = File.OpenRead(cachePath)) { - ReportLogErrors(info, CacheFileFormat.Read(stream, NullLogger.Instance, cachePath)); - } - return true; - } - - private static bool IsTestProject(Project project) { - return string.Equals(project.GetPropertyValue("IsTestProject"), "true", StringComparison.OrdinalIgnoreCase) - || project.GetPropertyValue("ProjectTypeGuids").Contains(TestProjectTypeGuid, StringComparison.OrdinalIgnoreCase); - } - - // One resolution root per (target framework [/ runtime], prod|dev). - private void EmitTarget(ProjectInfo info, PackageSpec spec, LockFileTarget target, Assets assets, bool isTest) { - var framework = NuGetShim.Seq(spec, "TargetFrameworks") - .FirstOrDefault(f => f.FrameworkName.Equals(target.TargetFramework)); - var alias = framework?.TargetAlias; - if (string.IsNullOrEmpty(alias)) alias = target.TargetFramework.GetShortFolderName(); - var rid = target.RuntimeIdentifier; - var config = string.IsNullOrEmpty(rid) ? alias : $"{alias}/{rid}"; - // A runtime-specific target also answers to its framework's name, so a - // filter on `net8.0` covers `net8.0/win-x64`. - var names = string.IsNullOrEmpty(rid) ? new[] { config } : new[] { config, alias }; - if (!_configs.Matches(names)) return; - if (_scanned.Add(config)) _records.Scanned(config); - - var libraries = new Dictionary(StringComparer.Ordinal); - var idByName = new Dictionary(StringComparer.Ordinal); - foreach (var lib in NuGetShim.Seq(target, "Libraries")) { - if (string.IsNullOrEmpty(lib.Name)) continue; - var id = CoordId(lib.Name, lib.Version?.ToNormalizedString() ?? ""); - libraries[id] = lib; - idByName[lib.Name.ToLowerInvariant()] = id; - } - var children = new Dictionary>(StringComparer.Ordinal); - foreach (var (id, lib) in libraries) { - var kids = new List(); - foreach (var dep in NuGetShim.Seq(lib, "Dependencies")) { - if (idByName.TryGetValue(dep.Id.ToLowerInvariant(), out var child) && child != id && !kids.Contains(child)) { - kids.Add(child); - } - } - children[id] = kids; - } - - // Direct dependencies are the project's own PackageReferences and - // ProjectReferences. - var direct = new HashSet(StringComparer.Ordinal); - foreach (var dep in NuGetShim.Seq(framework, "Dependencies")) { - if (!string.IsNullOrEmpty(dep.Name) && idByName.TryGetValue(dep.Name.ToLowerInvariant(), out var id)) direct.Add(id); - } - var restoreFramework = NuGetShim.Seq(spec.RestoreMetadata, "TargetFrameworks") - .FirstOrDefault(f => f.FrameworkName.Equals(target.TargetFramework)); - foreach (var reference in NuGetShim.Seq(restoreFramework, "ProjectReferences")) { - if (string.IsNullOrEmpty(reference.ProjectPath)) continue; - var key = Rel(Path.GetFullPath(reference.ProjectPath, Path.GetDirectoryName(info.FullPath)!)); - if (assets.ProjectNames.TryGetValue(key, out var name) && idByName.TryGetValue(name, out var id)) direct.Add(id); - } - - var reached = Reach(direct, children); - var unreached = libraries.Keys.Where(k => !reached.Contains(k)).OrderBy(k => k).ToList(); - if (unreached.Count > 0) { - _records.Failure( - info.Key, - $"restore resolved packages no direct dependency leads to: {string.Join(", ", unreached)}", - config, - info.Key - ); - } - - // Prod is what reaches the build output after the include flags, plus - // metapackages and packages that bring a shipped one in. - var parents = new Dictionary>(StringComparer.Ordinal); - foreach (var (id, kids) in children) { - foreach (var kid in kids) { - if (!parents.TryGetValue(kid, out var list)) parents[kid] = list = new List(); - list.Add(id); - } - } - var shipped = new HashSet(reached.Where(id => Delivers(assets, libraries[id])), StringComparer.Ordinal); - for (var grew = true; grew;) { - grew = false; - foreach (var id in reached) { - if (!shipped.Contains(id) && children[id].Any(shipped.Contains) && IsMetapackage(assets, libraries[id])) { - grew |= shipped.Add(id); - } - } - } - var shippedChildren = children.ToDictionary( - kv => kv.Key, kv => kv.Value.Where(shipped.Contains).ToList(), StringComparer.Ordinal - ); - var viaShipped = Reach(new HashSet(direct.Where(shipped.Contains), StringComparer.Ordinal), shippedChildren); - shipped.UnionWith(Reach(new HashSet(shipped.Except(viaShipped), StringComparer.Ordinal), parents)); - shipped.IntersectWith(reached); - - void EmitRoot(string kind, bool prod, HashSet ids, bool withFiles) { - if (ids.Count == 0) return; - var rootId = $"{info.Key}|{config}|{kind}"; - _records.Root(rootId, info.Key, config, prod, target.TargetFramework.GetShortFolderName(), rid ?? "", alias); - foreach (var id in ids.OrderBy(k => k, StringComparer.Ordinal)) { - var lib = libraries[id]; - var isProject = IsProject(lib.Type); - var projectKey = isProject && assets.ProjectKeys.TryGetValue(lib.Name!.ToLowerInvariant(), out var k) ? k : ""; - _records.Node(rootId, id, lib.Name!, lib.Version?.ToNormalizedString() ?? "", direct.Contains(id), projectKey); - if (withFiles && !isProject) EmitPackageAssemblies(info, rootId, id, config, assets, lib); - foreach (var child in children[id]) { - if (ids.Contains(child)) _records.Edge(rootId, id, child); - } - } - } - // The whole graph once as dev, its shipped part again as prod: a package - // is prod when any build of any project ships it. Everything a test - // project resolves is dev. - EmitRoot("all", false, reached, _opts.WithFiles); - if (!isTest) EmitRoot("prod", true, shipped, false); - } - - // Runtime assemblies (lib/, runtimes//lib/) carry the method bodies an - // analysis follows; compile-time ones (often ref/) are what the project's - // own sources compile against. - private void EmitPackageAssemblies( - ProjectInfo info, string rootId, string id, string config, Assets assets, LockFileTargetLibrary lib - ) { - var runtime = AssetPaths(NuGetShim.Seq(lib, "RuntimeAssemblies") - .Concat(NuGetShim.Seq(lib, "RuntimeTargets") - .Where(t => string.Equals(t.AssetType, "runtime", StringComparison.OrdinalIgnoreCase)))) - .ToList(); - var compile = AssetPaths(NuGetShim.Seq(lib, "CompileTimeAssemblies")).ToList(); - if (runtime.Count == 0 && compile.Count == 0) return; - var packageDir = assets.Resolver != null && lib.Version != null - ? assets.Resolver.GetPackageDirectory(lib.Name!, lib.Version) - : null; - var missing = new List(); - string? Resolve(string item) { - var path = packageDir == null ? null : Path.GetFullPath(Path.Combine(packageDir, item)); - if (path != null && File.Exists(path)) return path; - missing.Add(item); - return null; - } - foreach (var item in runtime) { - if (Resolve(item) is { } path) _records.File(rootId, id, path); - } - // Without its runtime assemblies the package is not installed; a missing - // compile-time one still fails the run but leaves those in place. - if (missing.Count > 0) _records.Unfetched(rootId, id); - foreach (var item in compile) { - if (Resolve(item) is { } path) _records.CompileFile(rootId, id, path); - } - if (missing.Count > 0) { - _records.Failure( - $"{lib.Name}:{lib.Version?.ToNormalizedString()}", - $"assemblies restore listed are missing from the package folders ({missing[0]}{(missing.Count > 1 ? $" and {missing.Count - 1} more" : "")}); re-run `dotnet restore`", - config, - info.Key - ); - } - } - - private static HashSet Reach(HashSet seeds, Dictionary> edges) { - var seen = new HashSet(seeds, StringComparer.Ordinal); - var stack = new Stack(seen); - while (stack.Count > 0) { - if (!edges.TryGetValue(stack.Pop(), out var next)) continue; - foreach (var n in next) { - if (seen.Add(n)) stack.Push(n); - } - } - return seen; - } - - private static readonly string[] OutputAssets = - { "RuntimeAssemblies", "RuntimeTargets", "NativeLibraries", "ResourceAssemblies", "ContentFiles" }; - - // An asset restore excluded through the include flags is listed as `_._`. - private static IEnumerable AssetPaths(IEnumerable items) => items - .Select(i => i.Path) - .Where(p => !string.IsNullOrEmpty(p) && Path.GetFileName(p) != "_._") - .Distinct(StringComparer.Ordinal); - - private static bool IsProject(string? libraryType) => - string.Equals(libraryType, "project", StringComparison.OrdinalIgnoreCase); - - private static readonly string[] BuildAssets = { "Build", "BuildMultiTargeting" }; - - // Active build files can copy anything into the output, as SqlClient.SNI's - // copy its native DLLs; only a developmentDependency declaration rules it out. - private bool Delivers(Assets assets, LockFileTargetLibrary lib) => - IsProject(lib.Type) - || AssetPaths(OutputAssets.SelectMany(member => NuGetShim.Seq(lib, member))).Any() - || (AssetPaths(BuildAssets.SelectMany(member => NuGetShim.Seq(lib, member))).Any() - && !IsDevelopmentDependency(assets, lib)); - - private readonly Dictionary _developmentDependency = new(StringComparer.Ordinal); - - // Unreadable counts as not declared, which keeps the package prod. - private bool IsDevelopmentDependency(Assets assets, LockFileTargetLibrary lib) { - if (assets.Resolver == null || lib.Version == null || string.IsNullOrEmpty(lib.Name)) return false; - var nuspec = assets.Resolver.GetPackageInfo(lib.Name, lib.Version)?.PathResolver.GetManifestFilePath(lib.Name, lib.Version); - if (nuspec == null) return false; - if (_developmentDependency.TryGetValue(nuspec, out var known)) return known; - var result = false; - try { - result = File.Exists(nuspec) && new NuspecReader(nuspec).GetDevelopmentDependency(); - } catch (Exception e) when (e is System.Xml.XmlException or PackagingException or IOException) { - Log($"{nuspec}: {Text.FirstLine(e.Message)}"); - } - _developmentDependency[nuspec] = result; - return result; - } - - // A package with no content of its own: every file it holds is package - // metadata at its root (nuspec, signature, readme, licence). - private static bool IsMetapackage(Assets assets, LockFileTargetLibrary lib) { - if (IsProject(lib.Type)) return false; - if (!assets.Libraries.TryGetValue((lib.Name!.ToLowerInvariant(), lib.Version), out var library)) return false; - return NuGetShim.Seq(library, "Files").All(file => !file.Contains('/') && !file.Contains('\\')); - } - - // packages.config holds the pinned closure NuGet installed, without edges - // or a direct/transitive split, so every package is a direct dependency of - // a flat graph. developmentDependency="true" marks dev packages. - private void ReadPackagesConfig(ProjectInfo info, Project project, string packagesConfig) { - EmitProject(info, project); - _records.ProjectBuild(info.Key, Rel(packagesConfig)); - if (_opts.WithFiles) EmitPaths(info, project); - - List packages; - try { - packages = new NuGet.Packaging.PackagesConfigReader(XDocument.Load(packagesConfig)) - .GetPackages(allowDuplicatePackageIds: true) - .ToList(); - } catch (Exception e) when (e is System.Xml.XmlException or PackagingException or ArgumentException) { - _records.Unscannable("", $"could not read {Rel(packagesConfig)}: {Text.FirstLine(e.Message)}", info.Key); - return; - } - if (packages.Count == 0) return; - var config = LegacyFrameworkName(project); - if (!_configs.Matches(config)) return; - if (_scanned.Add(config)) _records.Scanned(config); - - var isTest = IsTestProject(project); - var hintPaths = _opts.WithFiles ? HintPaths(project) : new List(); - foreach (var dev in new[] { false, true }) { - var selected = packages.Where(p => p.IsDevelopmentDependency == dev).ToList(); - if (selected.Count == 0) continue; - var rootId = $"{info.Key}|{config}|{(dev ? "dev" : "prod")}"; - _records.Root(rootId, info.Key, config, !dev && !isTest, config, "", config); - foreach (var pkg in selected.OrderBy(p => p.PackageIdentity.Id, StringComparer.OrdinalIgnoreCase)) { - var identity = pkg.PackageIdentity; - var version = identity.Version?.ToNormalizedString() ?? ""; - _records.Node(rootId, CoordId(identity.Id, version), identity.Id, version, direct: true, project: ""); - if (_opts.WithFiles) EmitHintPathAssemblies(info, rootId, config, identity, hintPaths); - } - } - } - - // A packages.config project consumes a package's assemblies only through - // its Reference HintPaths into `/./`. - private void EmitHintPathAssemblies( - ProjectInfo info, string rootId, string config, PackageIdentity identity, List hintPaths - ) { - var version = identity.Version?.ToNormalizedString() ?? ""; - var id = CoordId(identity.Id, version); - var missing = new List(); - foreach (var path in hintPaths.Where(p => InPackageFolder(p, identity))) { - if (File.Exists(path)) { - // A HintPath reference is both what compiles and what runs. - _records.File(rootId, id, path); - _records.CompileFile(rootId, id, path); - } else { - missing.Add(path); - } - } - if (missing.Count > 0) { - _records.Unfetched(rootId, id); - _records.Failure( - $"{identity.Id}:{version}", - $"referenced assembly is not installed ({Rel(missing[0])}); restore the packages.config packages (`nuget restore`, or `msbuild -t:restore -p:RestorePackagesConfig=true`)", - config, - info.Key - ); - } - } - - private static bool InPackageFolder(string path, PackageIdentity identity) { - var prefix = identity.Id + "."; - foreach (var segment in path.Split(Path.DirectorySeparatorChar)) { - if (segment.Length <= prefix.Length || !segment.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; - if (NuGetVersion.TryParse(segment.Substring(prefix.Length), out var v) && v.Equals(identity.Version)) return true; - } - return false; - } - - private static List HintPaths(Project project) { - return project.GetItems("Reference") - .Select(item => NormalizeSlashes(item.GetMetadataValue("HintPath"))) - .Where(h => !string.IsNullOrEmpty(h)) - .Select(h => Path.GetFullPath(h, project.DirectoryPath)) - .Distinct(StringComparer.Ordinal) - .ToList(); - } - - // MSBuild only turns `\` into `/` on Unix when a value's first segment is - // an existing directory, so a HintPath into a missing packages folder keeps - // its backslashes. - private static string NormalizeSlashes(string path) { - return Path.DirectorySeparatorChar == '/' ? path.Replace('\\', '/') : path; - } - - // NuGet's short folder name of a build's framework, as restore derives it - // from the two monikers; null when unrecognized. - private static string? ShortFrameworkName(Project build) { - var moniker = build.GetPropertyValue("TargetFrameworkMoniker"); - if (string.IsNullOrEmpty(moniker)) return null; - try { - return NuGetFramework.ParseComponents(moniker, build.GetPropertyValue("TargetPlatformMoniker")).GetShortFolderName(); - } catch (ArgumentException) { - return null; - } - } - - // Short folder name of a legacy project's single framework, e.g. net48. - private static string LegacyFrameworkName(Project project) { - if (ShortFrameworkName(project) is { } name) return name; - var version = project.GetPropertyValue("TargetFrameworkVersion"); - return string.IsNullOrEmpty(version) ? "unknown" : $"net{version.TrimStart('v').Replace(".", "")}"; - } - - // Split as Microsoft.Common.CrossTargeting.targets does: trimmed, distinct - // ignoring case. Empty for a single-framework project. - private static List Frameworks(Project project) { - var multi = project.GetPropertyValue("TargetFrameworks"); - if (string.IsNullOrEmpty(project.GetPropertyValue("TargetFramework")) && !string.IsNullOrEmpty(multi)) { - return multi.Split(';').Select(f => f.Trim()).Where(f => f.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); - } - return new List(); - } - - // Per inner build of a multi-targeting project, whose outer evaluation has - // no Compile items or TargetPath, or of the project's single framework. - private void EmitPaths(ProjectInfo info, Project project) { - var multi = Frameworks(project); - if (multi.Count == 0) { - var single = project.GetPropertyValue("TargetFramework"); - var config = string.IsNullOrEmpty(single) ? LegacyFrameworkName(project) : single; - if (_configs.Matches(config)) EmitBuild(info, project, config); - return; - } - foreach (var tfm in multi.Where(_configs.Matches)) { - Project build; - try { - build = LoadInnerBuild(project, tfm); - } catch (InvalidProjectFileException e) { - _records.Unscannable(tfm, $"could not evaluate the {tfm} build: {ErrorText(e)}", info.Key); - continue; - } - EmitBuild(info, build, tfm); - } - } - - // As evaluation leaves it: sources that targets generate are absent. - private void EmitBuild(ProjectInfo info, Project build, string config) { - var language = build.GetPropertyValue("Language"); - var isFSharp = string.Equals(language, "F#", StringComparison.OrdinalIgnoreCase); - var isVb = string.Equals(language, "VB", StringComparison.OrdinalIgnoreCase); - var sources = isFSharp ? FSharpCompileOrder(build) : build.GetItems("Compile"); - foreach (var source in FullPaths(sources)) _records.ProjectSrc(info.Key, source, config); - var targetPath = NormalizeSlashes(build.GetPropertyValue("TargetPath")); - if (!string.IsNullOrEmpty(targetPath)) { - _records.ProjectTgt(info.Key, Path.GetFullPath(targetPath, build.DirectoryPath), config); - } - foreach (var property in new[] { "TargetFrameworkMoniker", "Language", "LangVersion", "AssemblyName", "Nullable" }) { - var value = build.GetPropertyValue(property); - if (!string.IsNullOrEmpty(value)) _records.ProjectInfo(info.Key, config, property, value); - } - // Unrecognized, the alias stands in. - if (ShortFrameworkName(build) is { } framework) { - _records.ProjectInfo(info.Key, config, "Framework", framework); - } - foreach (var reference in build.GetItems("FrameworkReference").Select(i => i.EvaluatedInclude).Distinct()) { - _records.ProjectInfo(info.Key, config, "FrameworkReference", reference); - } - foreach (var item in build.GetItems("Using")) { - _records.ProjectUsing( - info.Key, config, item.EvaluatedInclude, item.GetMetadataValue("Alias"), - string.Equals(item.GetMetadataValue("Static"), "true", StringComparison.OrdinalIgnoreCase) - ); - } - // Vbc takes FinalDefineConstants, Csc and Fsc DefineConstants. - var finalDefines = isVb ? build.GetPropertyValue("FinalDefineConstants") : ""; - var defines = finalDefines.Length > 0 ? finalDefines : build.GetPropertyValue("DefineConstants"); - foreach (var symbol in defines - .Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(s => s.Trim()) - .Where(s => s.Length > 0) - .Distinct(StringComparer.Ordinal)) { - _records.ProjectInfo(info.Key, config, "DefineConstant", symbol); - } - } - - private static IEnumerable FullPaths(IEnumerable items) => items - .Select(item => item.GetMetadataValue("FullPath")) - .Where(full => !string.IsNullOrEmpty(full)) - .Select(full => Path.GetFullPath(full)) - .Distinct(StringComparer.Ordinal); - - // As the F# SDK's FSharpSourceCodeCompileOrder target orders them for Fsc. - private static IEnumerable FSharpCompileOrder(Project build) { - IEnumerable Ordered(string order) => - build.GetItems("Compile").Where(item => item.GetMetadataValue("CompileOrder") == order); - return Ordered("CompileFirst") - .Concat(build.GetItems("CompileBefore")) - .Concat(Ordered("CompileBefore")) - .Concat(Ordered("")) - .Concat(Ordered("CompileAfter")) - .Concat(build.GetItems("CompileAfter")) - .Concat(Ordered("CompileLast")); - } - - // The repository files declaring the project's dependencies; SDK- and - // package-provided definitions are not the user's to change. - private void EmitBuildFiles(ProjectInfo info, Project project) { - _records.ProjectBuild(info.Key, info.Key); - var foreign = new[] { - "NetCoreRoot", "MSBuildExtensionsPath", "MSBuildSDKsPath", "MSBuildToolsPath", "NuGetPackageRoot", - } - .Select(project.GetPropertyValue) - .Where(p => !string.IsNullOrEmpty(p)) - .Select(p => Path.TrimEndingDirectorySeparator(Path.GetFullPath(p)) + Path.DirectorySeparatorChar) - .ToList(); - var definedIn = new HashSet(); - foreach (var itemType in new[] { "PackageReference", "PackageVersion", "GlobalPackageReference" }) { - foreach (var item in project.GetItems(itemType)) { - if (string.Equals(item.GetMetadataValue("IsImplicitlyDefined"), "true", StringComparison.OrdinalIgnoreCase)) continue; - if (item.Xml?.ContainingProject is { } file) definedIn.Add(file); - } - } - var files = new SortedSet(StringComparer.Ordinal); - foreach (var element in definedIn) { - var file = element.FullPath; - if (string.IsNullOrEmpty(file) || SamePath(file, info.FullPath)) continue; - if (foreign.Any(root => file.StartsWith(root, StringComparison.OrdinalIgnoreCase))) continue; - files.Add(Path.GetFullPath(file)); - } - foreach (var file in files) _records.ProjectBuild(info.Key, Rel(file)); - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/RecordsWriter.cs b/src/commands/manifest/scripts/dotnet-tool/RecordsWriter.cs deleted file mode 100644 index 6db32cfce5..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/RecordsWriter.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Text; - -namespace Socket.Facts.Dotnet; - -// Writes the TSV records line protocol shared with the JVM build-tool scripts -// (grammar in records.mts). -internal sealed class RecordsWriter : IDisposable { - private readonly StreamWriter _writer; - - public RecordsWriter(string path) { - var dir = Path.GetDirectoryName(Path.GetFullPath(path)); - if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); - // No BOM, and `\n` on every OS: the parser splits on `\n` and reads the - // first tag verbatim. - _writer = new StreamWriter(path, append: false, new UTF8Encoding(false)) { NewLine = "\n" }; - } - - private void Rec(params string[] fields) { - var sb = new StringBuilder(); - for (var i = 0; i < fields.Length; i += 1) { - if (i > 0) sb.Append('\t'); - sb.Append(Escape(fields[i])); - } - _writer.WriteLine(sb.ToString()); - } - - public void Meta(string sdkVersion) => Rec("meta", "dotnet", sdkVersion, ""); - - public void BuildRoot(string path) => Rec("buildRoot", path); - - public void Entry(string path) => Rec("entry", path); - - public void Project(string projectKey, string name, string version, string dir) => - Rec("project", projectKey, "", name, version, dir); - - public void ProjectSrc(string projectKey, string path, string config) => Rec("projectSrc", projectKey, path, config); - - public void ProjectTgt(string projectKey, string path, string config) => Rec("projectTgt", projectKey, path, config); - - public void ProjectInfo(string projectKey, string config, string name, string value) => - Rec("projectInfo", projectKey, config, name, value); - - public void ProjectUsing(string projectKey, string config, string ns, string alias, bool isStatic) => - Rec("projectUsing", projectKey, config, ns, alias, isStatic ? "1" : "0"); - - public void ProjectBuild(string projectKey, string path) => Rec("projectBuild", projectKey, path); - - public void Member(string path) => Rec("member", path); - - public void ExcludedProject(string projectKey) => Rec("excludedProject", projectKey); - - public void Root(string rootId, string projectKey, string config, bool prod, string framework, string runtime, string alias) => - Rec("root", rootId, projectKey, config, prod ? "1" : "0", framework, runtime, alias); - - public void Node(string rootId, string coordId, string name, string version, bool direct, string project) => - Rec("node", rootId, coordId, "", name, version, "", "", direct ? "1" : "0", project); - - public void Edge(string rootId, string parentCoordId, string childCoordId) => - Rec("edge", rootId, parentCoordId, childCoordId); - - public void File(string rootId, string coordId, string path) => Rec("file", rootId, coordId, path); - - public void CompileFile(string rootId, string coordId, string path) => Rec("compileFile", rootId, coordId, path); - - public void Unfetched(string rootId, string coordId) => Rec("unfetched", rootId, coordId); - - public void Scanned(string config) => Rec("scanned", config); - - public void Failure(string coord, string detail, string config, string projectKey = "") => - Rec("failure", coord, detail, config, projectKey); - - public void Unscannable(string config, string detail, string projectKey) => - Rec("unscannable", config, detail, projectKey); - - public void Dispose() => _writer.Dispose(); - - private static string Escape(string? v) { - if (string.IsNullOrEmpty(v)) return ""; - return v.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\n", "\\n").Replace("\r", "\\r"); - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/Restorer.cs b/src/commands/manifest/scripts/dotnet-tool/Restorer.cs deleted file mode 100644 index e1c8a227a2..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/Restorer.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Diagnostics; -using System.Text.RegularExpressions; - -namespace Socket.Facts.Dotnet; - -internal sealed record RestoreError(string Code, string Message, string ProjectFile); - -// No exit code when the restore timed out and was stopped. -internal sealed record RestoreOutcome( - int? ExitCode, - DateTime StartedUtc, - List Errors -) { - public bool TimedOut => ExitCode == null; - public bool Succeeded => ExitCode == 0; -} - -// Runs the user's own `dotnet restore`: the same host, SDK selection -// (global.json), environment, nuget.config hierarchy and credential providers -// as when they run it themselves, so whatever restores for them restores here. -internal static class Restorer { - // Bounds a restore that hangs, e.g. on an unreachable feed. - public const int TimeoutSec = 1800; - - // MSBuild's canonical error format: `origin: error CODE: text [project]`, - // which the file logger prefixes with the building node's id (`1>`). - private static readonly Regex ErrorLine = new( - @"^(?.*?):\s*error\s*(?[A-Za-z]+\d+)?\s*:\s*(?.*?)(?:\s+\[(?[^\[\]]+)\])?\s*$", - RegexOptions.Compiled - ); - - public static RestoreOutcome Run(ToolOptions opts, string target, Action log) { - var errorLog = Path.Combine(Path.GetTempPath(), $"socket-facts-restore-{Guid.NewGuid():N}.log"); - var psi = new ProcessStartInfo(opts.Dotnet) { - UseShellExecute = false, - // Inherit stdout/stderr: the output reaches the user as their own - // restore output would, and no pipe can be held open by a child. - RedirectStandardInput = true, - WorkingDirectory = Path.GetDirectoryName(opts.EntryPath)!, - }; - psi.ArgumentList.Add("restore"); - psi.ArgumentList.Add(target); - // Socket reports advisories itself; auditing only adds network calls and - // NU190x warnings a project may promote to errors. - psi.ArgumentList.Add("-p:NuGetAudit=false"); - // No lingering MSBuild nodes holding this process's handles. - psi.ArgumentList.Add("-nodeReuse:false"); - psi.ArgumentList.Add("-fileLogger"); - psi.ArgumentList.Add($"-fileLoggerParameters:LogFile={errorLog};ErrorsOnly;Encoding=UTF-8"); - foreach (var arg in opts.RestoreArgs) psi.ArgumentList.Add(arg); - log($"running: {opts.Dotnet} {string.Join(' ', psi.ArgumentList)}"); - - var started = DateTime.UtcNow; - using var process = Process.Start(psi) - ?? throw new InvalidOperationException($"could not start `{opts.Dotnet}`"); - process.StandardInput.Close(); - var timedOut = !process.WaitForExit(TimeoutSec * 1000); - if (timedOut) { - try { - process.Kill(entireProcessTree: true); - } catch (InvalidOperationException) { - // Exited between the timeout and the kill. - } - process.WaitForExit(); - } - var errors = ReadErrors(errorLog); - Text.TryDelete(errorLog); - return new RestoreOutcome(timedOut ? null : process.ExitCode, started, errors); - } - - private static List ReadErrors(string path) { - var errors = new List(); - if (!File.Exists(path)) return errors; - foreach (var line in File.ReadAllLines(path)) { - var m = ErrorLine.Match(Regex.Replace(line.Trim().TrimStart('\uFEFF'), @"^\d+>", "")); - if (!m.Success) continue; - // The error's origin is the file it points into, the project for a - // NuGet error; the bracketed file is what was being built, which for a - // solution restore is the solution. - var origin = Regex.Replace(m.Groups["origin"].Value.Trim(), @"\(\d+(,\d+)*\)$", ""); - var built = m.Groups["project"].Value; - var project = Text.IsProjectFile(origin) && File.Exists(origin) - ? origin - : Text.IsProjectFile(built) && File.Exists(built) ? built : ""; - errors.Add(new RestoreError(m.Groups["code"].Value, m.Groups["text"].Value, project)); - } - return errors; - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/SolutionContext.cs b/src/commands/manifest/scripts/dotnet-tool/SolutionContext.cs deleted file mode 100644 index 1f42af6de2..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/SolutionContext.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Text.Json; -using Microsoft.Build.Construction; - -namespace Socket.Facts.Dotnet; - -// A solution entry: its MSBuild-format members, and the global properties -// MSBuild's solution metaproject passes each of them (Solution* properties -// and the project configuration the active solution configuration maps to). -internal sealed class SolutionContext { - public readonly Dictionary Members = new(StringComparer.Ordinal); - private readonly string _solutionPath; - private readonly string _configurationKey; - - public SolutionContext(string entry, IReadOnlyDictionary globalProperties) { - // A filter (.slnf) names its solution; the Solution* properties describe - // that solution, as when MSBuild builds the filter. - HashSet? filtered = null; - _solutionPath = entry; - if (entry.EndsWith(".slnf", StringComparison.OrdinalIgnoreCase)) { - (_solutionPath, filtered) = ReadFilter(entry); - } - var solution = SolutionFile.Parse(_solutionPath); - var configuration = globalProperties.TryGetValue("Configuration", out var c) && c.Length > 0 - ? c - : solution.GetDefaultConfigurationName(); - var platform = globalProperties.TryGetValue("Platform", out var p) && p.Length > 0 - ? p - : solution.GetDefaultPlatformName(); - _configurationKey = $"{configuration}|{platform}"; - // Like the solution's own build, restore covers only the projects the - // active solution configuration builds; a solution without - // configurations builds them all. - var configured = solution.SolutionConfigurations.Count > 0; - foreach (var project in solution.ProjectsInOrder) { - if (!IsMSBuildProject(project)) continue; - if (configured - && !(project.ProjectConfigurations.TryGetValue(_configurationKey, out var mapping) && mapping.IncludeInBuild)) { - continue; - } - var full = Path.GetFullPath(project.AbsolutePath); - if (filtered != null && !filtered.Contains(full)) continue; - if (File.Exists(full)) Members[full] = project; - } - } - - public void Apply(string projectPath, Dictionary props) { - props["SolutionDir"] = Path.GetDirectoryName(_solutionPath) + Path.DirectorySeparatorChar; - props["SolutionExt"] = Path.GetExtension(_solutionPath); - props["SolutionFileName"] = Path.GetFileName(_solutionPath); - props["SolutionName"] = Path.GetFileNameWithoutExtension(_solutionPath); - props["SolutionPath"] = _solutionPath; - if (Members.TryGetValue(projectPath, out var member) - && member.ProjectConfigurations.TryGetValue(_configurationKey, out var mapped)) { - props["Configuration"] = mapped.ConfigurationName; - props["Platform"] = mapped.PlatformName; - } - } - - // A temporary solution filter over `members`, for restoring a subset of the - // solution with the solution's own context. - public string WriteFilter(IReadOnlyList members) { - var path = Path.Combine(Path.GetTempPath(), $"socket-facts-{Guid.NewGuid():N}.slnf"); - var doc = new { - solution = new { - path = _solutionPath, - projects = members - .Select(m => Members[m].RelativePath) - .ToArray(), - }, - }; - File.WriteAllText(path, JsonSerializer.Serialize(doc)); - return path; - } - - // Solution folders, website folders and shared projects (.shproj, imported - // into others) are not projects MSBuild builds on their own. - private static bool IsMSBuildProject(ProjectInSolution project) { - return project.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat - || (project.ProjectType == SolutionProjectType.Unknown && Text.IsProjectFile(project.AbsolutePath)); - } - - // A solution filter: {"solution": {"path": , "projects": []}}. - private static (string Solution, HashSet Projects) ReadFilter(string filter) { - using var doc = JsonDocument.Parse(File.ReadAllText(filter)); - var solution = doc.RootElement.GetProperty("solution"); - var solutionPath = FullPath(Path.GetDirectoryName(filter)!, solution.GetProperty("path").GetString() ?? ""); - var solutionDir = Path.GetDirectoryName(solutionPath)!; - var projects = new HashSet(StringComparer.Ordinal); - if (solution.TryGetProperty("projects", out var list)) { - foreach (var p in list.EnumerateArray()) { - if (p.GetString() is { Length: > 0 } rel) projects.Add(FullPath(solutionDir, rel)); - } - } - return (solutionPath, projects); - } - - private static string FullPath(string dir, string rel) { - return Path.GetFullPath(Path.Combine(dir, rel.Replace('\\', Path.DirectorySeparatorChar))); - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/ToolOptions.cs b/src/commands/manifest/scripts/dotnet-tool/ToolOptions.cs deleted file mode 100644 index 744da70f8b..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/ToolOptions.cs +++ /dev/null @@ -1,167 +0,0 @@ -namespace Socket.Facts.Dotnet; - -internal enum ToolMode { - Facts, - Members, - Workspaces, -} - -internal sealed class ToolOptions { - public const string Usage = """ - Usage: socket-facts-dotnet --records --entry [options] [-- ] - - Options: - --records Records output file (TSV line protocol). Required. - --entry Solution (.sln/.slnx/.slnf) or project file to scan. Required. - --dotnet dotnet executable that runs `dotnet restore` (default: dotnet). - --with-files Also emit resolved artifact and source paths. - --include-configs Target framework globs; only matching ones are read. - --exclude-configs Target framework globs to skip (applied after includes). - --exclude-paths Anchored regex sources over build-root-relative project dirs. - --exclude-base

Directory --exclude-paths is relative to (default: the build root). - --workspaces Only list the projects (no restore, no dependencies). - --members Only list the projects the entry builds (no evaluation). - --verbose Log progress to stderr. - - Arguments after `--` go to `dotnet restore` verbatim. MSBuild properties among - them (-p:K=V, --property:K=V, /p:K=V) and --runtime/-r also apply to project - evaluation, so evaluation and restore see the same build. - """; - - public string RecordsPath = ""; - public string EntryPath = ""; - public string Dotnet = "dotnet"; - public bool WithFiles; - public string IncludeConfigs = ""; - public string ExcludeConfigs = ""; - public string ExcludePaths = ""; - public string ExcludeBase = ""; - public ToolMode Mode = ToolMode.Facts; - public bool Verbose; - public List RestoreArgs = new(); - public Dictionary GlobalProperties = new(StringComparer.OrdinalIgnoreCase); - - public static ToolOptions Parse(string[] args) { - var opts = new ToolOptions(); - var i = 0; - for (; i < args.Length; i += 1) { - var arg = args[i]; - if (arg == "--") { - i += 1; - break; - } - switch (arg) { - case "--records": - opts.RecordsPath = Next(args, ref i, arg); - break; - case "--entry": - opts.EntryPath = Next(args, ref i, arg); - break; - case "--dotnet": - opts.Dotnet = Next(args, ref i, arg); - break; - case "--with-files": - opts.WithFiles = true; - break; - case "--include-configs": - opts.IncludeConfigs = Next(args, ref i, arg); - break; - case "--exclude-configs": - opts.ExcludeConfigs = Next(args, ref i, arg); - break; - case "--exclude-paths": - opts.ExcludePaths = Next(args, ref i, arg); - break; - case "--exclude-base": - opts.ExcludeBase = RealPaths.Dir(Path.GetFullPath(Next(args, ref i, arg))); - break; - case "--workspaces": - opts.SetMode(ToolMode.Workspaces, arg); - break; - case "--members": - opts.SetMode(ToolMode.Members, arg); - break; - case "--verbose": - opts.Verbose = true; - break; - default: - throw new ArgumentException($"Unknown argument `{arg}`"); - } - } - var runtimes = new List(); - for (; i < args.Length; i += 1) { - var arg = args[i]; - opts.RestoreArgs.Add(arg); - if (TryParseProperty(arg, out var props)) { - foreach (var (key, value) in props) opts.GlobalProperties[key] = value; - continue; - } - string? rid = null; - if ((arg == "--runtime" || arg == "-r") && i + 1 < args.Length) { - i += 1; - rid = args[i]; - opts.RestoreArgs.Add(rid); - } else if (arg.StartsWith("--runtime=", StringComparison.Ordinal)) { - rid = arg.Substring("--runtime=".Length); - } - if (!string.IsNullOrEmpty(rid)) runtimes.Add(rid); - } - // What `dotnet restore --runtime` forwards: the RuntimeIdentifiers property. - if (runtimes.Count > 0) opts.GlobalProperties["RuntimeIdentifiers"] = string.Join(';', runtimes); - if (string.IsNullOrEmpty(opts.RecordsPath) || string.IsNullOrEmpty(opts.EntryPath)) { - throw new ArgumentException("--records and --entry are required"); - } - opts.EntryPath = RealPaths.Of(opts.EntryPath); - return opts; - } - - private void SetMode(ToolMode mode, string arg) { - if (Mode != ToolMode.Facts) throw new ArgumentException($"{arg} cannot be combined with another mode"); - Mode = mode; - } - - private static string Next(string[] args, ref int i, string arg) { - i += 1; - if (i >= args.Length) throw new ArgumentException($"{arg} expects a value"); - return args[i]; - } - - // MSBuild's property switch: `-p:A=1;B=2`, also spelled /p:, -property:, - // --property: (case-insensitive). Per the MSBuild command-line reference, - // `;` or `,` separates properties; a quoted value keeps its separators. - private static bool TryParseProperty(string arg, out List<(string Key, string Value)> props) { - props = new(); - string? rest = null; - foreach (var prefix in new[] { "-p:", "/p:", "--property:", "-property:", "/property:" }) { - if (arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { - rest = arg.Substring(prefix.Length); - break; - } - } - if (rest == null) return false; - foreach (var part in SplitUnquoted(rest)) { - var eq = part.IndexOf('='); - if (eq <= 0) continue; - props.Add((part.Substring(0, eq).Trim(), Unquote(part.Substring(eq + 1).Trim()))); - } - return props.Count > 0; - } - - private static IEnumerable SplitUnquoted(string s) { - var start = 0; - var quoted = false; - for (var i = 0; i < s.Length; i += 1) { - if (s[i] == '"') { - quoted = !quoted; - } else if (!quoted && (s[i] == ';' || s[i] == ',')) { - yield return s.Substring(start, i - start); - start = i + 1; - } - } - yield return s.Substring(start); - } - - private static string Unquote(string v) { - return v.Length >= 2 && v[0] == '"' && v[^1] == '"' ? v.Substring(1, v.Length - 2) : v; - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/build-tool.sh b/src/commands/manifest/scripts/dotnet-tool/build-tool.sh deleted file mode 100755 index 8b65e0af87..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/build-tool.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -# Builds the socket-facts-dotnet tool into ./publish, which the rollup dist -# build copies to dist/manifest-scripts/dotnet-tool. Requires a .NET 8+ SDK. -set -euo pipefail - -cd "$(dirname "$0")" -# Publish into a fresh dir and swap it in, so no stale file survives. -staging="$(mktemp -d "${TMPDIR:-/tmp}/socket-facts-dotnet.XXXXXX")" -# Vulnerability-feed auditing runs in the dedicated security workflow; restore -# this locked build input without making the helper build depend on that feed. -dotnet restore socket-facts-dotnet.csproj --locked-mode -p:NuGetAudit=false --nologo -v quiet -dotnet publish socket-facts-dotnet.csproj -c Release -o "$staging" --no-restore --nologo -v quiet -rm -f "$staging"/*.pdb -if [ -d publish ]; then - mv publish "$staging.old" -fi -mv "$staging" publish -echo "socket-facts-dotnet tool: $(pwd)/publish/socket-facts-dotnet.dll" diff --git a/src/commands/manifest/scripts/dotnet-tool/packages.lock.json b/src/commands/manifest/scripts/dotnet-tool/packages.lock.json deleted file mode 100644 index e4d3badc95..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/packages.lock.json +++ /dev/null @@ -1,281 +0,0 @@ -{ - "version": 1, - "dependencies": { - "net6.0": { - "Microsoft.Build": { - "type": "Direct", - "requested": "[17.3.2, )", - "resolved": "17.3.2", - "contentHash": "k5+7CfF/aM/hykfnrF93VhbUnhGfpJkGaD+ce8VlhLnOqDyts7WV+8Up3YCP6qmXMZFeeH/Cp23w2wSliP0mBw==", - "dependencies": { - "Microsoft.Build.Framework": "17.3.2", - "Microsoft.NET.StringTools": "17.3.2", - "System.Collections.Immutable": "6.0.0", - "System.Configuration.ConfigurationManager": "6.0.0", - "System.Reflection.Metadata": "6.0.0", - "System.Reflection.MetadataLoadContext": "6.0.0", - "System.Security.Principal.Windows": "5.0.0", - "System.Text.Encoding.CodePages": "6.0.0", - "System.Text.Json": "6.0.0", - "System.Threading.Tasks.Dataflow": "6.0.0" - } - }, - "Microsoft.Build.Framework": { - "type": "Direct", - "requested": "[17.3.2, )", - "resolved": "17.3.2", - "contentHash": "iGfJt6rm/vIEowBG6qNX2Udn7UagI6MzalDwwdkDUkSwhvvrGCnDLphyRABAwrrsWHTD/LJlUAJsbW1SkC4CUQ==", - "dependencies": { - "System.Security.Permissions": "6.0.0" - } - }, - "Microsoft.Build.Locator": { - "type": "Direct", - "requested": "[1.7.8, )", - "resolved": "1.7.8", - "contentHash": "sPy10x527Ph16S2u0yGME4S6ohBKJ69WfjeGG/bvELYeZVmJdKjxgnlL8cJJJLGV/cZIRqSfB12UDB8ICakOog==" - }, - "Newtonsoft.Json": { - "type": "Direct", - "requested": "[13.0.1, )", - "resolved": "13.0.1", - "contentHash": "ppPFpBcvxdsfUonNcvITKqLl3bqxWbDCZIzDWHzjpdAHRFfZe0Dw9HmA0+za13IdyrgJwpkDTDA9fHaxOrt20A==" - }, - "NuGet.Common": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "EZulYMsyoMAkJjyKQfoUc0mEJ5D+cto/uoAgnNtHEVAFFNieToRuL3rLI3We+0tr63XfF0iOND8hAVCwkgiDag==", - "dependencies": { - "NuGet.Frameworks": "6.0.6" - } - }, - "NuGet.Configuration": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "yNqg6DmSF65DotTcKpT2f6kFygI8Oi6dHi0jggk+jT+LHTQBiQauVuLOj4VRyEDeKchrltsGjU841tzHuCjiHQ==", - "dependencies": { - "NuGet.Common": "6.0.6", - "System.Security.Cryptography.ProtectedData": "4.4.0" - } - }, - "NuGet.DependencyResolver.Core": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "blOZghvcf23rh66rX6A6Ct7qHlALjrTce1KlGtFiq1uhU/qsbkzzySv3ZN/A13aUFpH8lRvd8C4oHcFwgr/WjQ==", - "dependencies": { - "NuGet.Configuration": "6.0.6", - "NuGet.LibraryModel": "6.0.6", - "NuGet.Protocol": "6.0.6" - } - }, - "NuGet.Frameworks": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "Cntffs4It+LZpNWT14s5IVSCooTVGOlnSuO/wV097H/n1Uws0b+22+I/tO7lt8ivyvm2RckeXXO6IgCztovWlQ==" - }, - "NuGet.LibraryModel": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "nUq9/tpOYrtpqFvqy6vhQKsP52JHIT0V7InbZq+SucvuApR1Qm7liktVCJCRWUsyY0ASGfTgV3XyjaYkH/ZInw==", - "dependencies": { - "NuGet.Common": "6.0.6", - "NuGet.Versioning": "6.0.6" - } - }, - "NuGet.Packaging": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "oWk8ZCmAnljB5A1gshZNEHtR0/D04yXp5fDd8qWGcWtnFUIiYLzQvrRHQ73bGDxRNXX+VRSc3r/jphh4im0FTw==", - "dependencies": { - "Newtonsoft.Json": "13.0.1", - "NuGet.Configuration": "6.0.6", - "NuGet.Versioning": "6.0.6", - "System.Security.Cryptography.Cng": "5.0.0", - "System.Security.Cryptography.Pkcs": "5.0.0" - } - }, - "NuGet.ProjectModel": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "3PnngLphRDLUGPIEpYkU1J4TWe+bxTYtT0XV990gy3CCcott4SaBwpihUBwDb5mdZOf5aoYbjFp9KZh9mZnOeA==", - "dependencies": { - "NuGet.DependencyResolver.Core": "6.0.6" - } - }, - "NuGet.Protocol": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "qq9uzbRITI9CogNkTZ9Hqooca79gDeLdrELWvQfAj6LUHyE0ihOaeOSYi6o6U1wUxilFytX0se+noAony4gucQ==", - "dependencies": { - "NuGet.Packaging": "6.0.6" - } - }, - "NuGet.Versioning": { - "type": "Direct", - "requested": "[6.0.6, )", - "resolved": "6.0.6", - "contentHash": "9Y2fBEDbR6VRVsXUP5UJQYTsUNHyROguhJR2JGGg6lbahzBKnV5oJjtAxYafA5ffbCE7szNRLwQzDvj3CgPLmw==" - }, - "System.Formats.Asn1": { - "type": "Direct", - "requested": "[6.0.1, )", - "resolved": "6.0.1", - "contentHash": "glgtKqWJpH9GDw0m9I5xFiF6WDIQqi/eZXU6MkMRPzAWEERGGAJh+qztkrlWSDbokQ1jalj5NcBNIvVoSDpSSA==" - }, - "System.Text.Json": { - "type": "Direct", - "requested": "[6.0.10, )", - "resolved": "6.0.10", - "contentHash": "NSB0kDipxn2ychp88NXWfFRFlmi1bst/xynOutbnpEfRCT9JZkZ7KOmF/I/hNKo2dILiMGnqblm+j1sggdLB9g==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.0.0", - "System.Text.Encodings.Web": "6.0.0" - } - }, - "Microsoft.NET.StringTools": { - "type": "Transitive", - "resolved": "17.3.2", - "contentHash": "3sIZECEDSY9kP7BqPLOSIHLsiqv0TSU5cIGAMung+NrefIooo1tBMVRt598CGz+kUF1xlbOsO8nPAYpgfokx/Q==", - "dependencies": { - "System.Memory": "4.5.5", - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "Microsoft.Win32.SystemEvents": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "hqTM5628jSsQiv+HGpiq3WKBl2c8v1KZfby2J6Pr7pEPlK9waPdgEO6b8A/+/xn/yZ9ulv8HuqK71ONy2tg67A==" - }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "l4zZJ1WU2hqpQQHXz1rvC3etVZN+2DLmQMO79FhOTZHMn8tDRr+WU287sbomD0BETlmKDn0ygUgVy9k5xkkJdA==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "System.Configuration.ConfigurationManager": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "7T+m0kDSlIPTHIkPMIu6m6tV6qsMqJpvQWW2jIc2qi7sn40qxFo0q+7mEQAhMPXZHMKnWrnv47ntGlM/ejvw3g==", - "dependencies": { - "System.Security.Cryptography.ProtectedData": "6.0.0", - "System.Security.Permissions": "6.0.0" - } - }, - "System.Drawing.Common": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "NfuoKUiP2nUWwKZN6twGqXioIe1zVD0RIj2t976A+czLHr2nY454RwwXs6JU9Htc6mwqL6Dn/nEL3dpVf2jOhg==", - "dependencies": { - "Microsoft.Win32.SystemEvents": "6.0.0" - } - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.5.5", - "contentHash": "XIWiDvKPXaTveaB7HVganDlOCRoj03l+jrwNvcge/t8vhGYKvqV+dMv6G4SAX2NoNmN0wZfVPTAlFwZcZvVOUw==" - }, - "System.Reflection.Metadata": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "sffDOcex1C3HO5kDolOYcWXTwRpZY/LvJujM6SMjn63fWMJWchYAAmkoAJXlbpZ5yf4d+KMgxd+LeETa4gD9sQ==", - "dependencies": { - "System.Collections.Immutable": "6.0.0" - } - }, - "System.Reflection.MetadataLoadContext": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "SuK8qTHbmG3PToLo1TEq8YSfY31FiKhASBmjozUTAleDgiX4H2X4jm0VPFb+K2soSSmYPyHTpHp35TctfNtDzQ==", - "dependencies": { - "System.Collections.Immutable": "6.0.0", - "System.Reflection.Metadata": "6.0.0" - } - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "/iUeP3tq1S0XdNNoMz5C9twLSrM/TH+qElHkXWaPvuNOt+99G75NrV0OS2EqHx5wMN7popYjpc8oTjC1y16DLg==" - }, - "System.Security.AccessControl": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "AUADIc0LIEQe7MzC+I0cl0rAT8RrTAKFHl53yHjEUzNVIaUlhFY11vc2ebiVJzVBuOzun6F7FBA+8KAbGTTedQ==" - }, - "System.Security.Cryptography.Cng": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "jIMXsKn94T9JY7PvPq/tMfqa6GAaHpElRDpmG+SuL+D3+sTw2M8VhnibKnN8Tq+4JqbPJ/f+BwtLeDMEnzAvRg==", - "dependencies": { - "System.Formats.Asn1": "5.0.0" - } - }, - "System.Security.Cryptography.Pkcs": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "9TPLGjBCGKmNvG8pjwPeuYy0SMVmGZRwlTZvyPHDbYv/DRkoeumJdfumaaDNQzVGMEmbWtg07zUpSW9q70IlDQ==", - "dependencies": { - "System.Formats.Asn1": "5.0.0", - "System.Security.Cryptography.Cng": "5.0.0" - } - }, - "System.Security.Cryptography.ProtectedData": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "rp1gMNEZpvx9vP0JW0oHLxlf8oSiQgtno77Y4PLUBjSiDYoD77Y8uXHr1Ea5XG4/pIKhqAdxZ8v8OTUtqo9PeQ==" - }, - "System.Security.Permissions": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "T/uuc7AklkDoxmcJ7LGkyX1CcSviZuLCa4jg3PekfJ7SU0niF0IVTXwUiNVP9DSpzou2PpxJ+eNY2IfDM90ZCg==", - "dependencies": { - "System.Security.AccessControl": "6.0.0", - "System.Windows.Extensions": "6.0.0" - } - }, - "System.Security.Principal.Windows": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "t0MGLukB5WAVU9bO3MGzvlGnyJPgUlcwerXn1kzBRjwLKixT96XV0Uza41W49gVd8zEMFu9vQEFlv0IOrytICA==" - }, - "System.Text.Encoding.CodePages": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "ZFCILZuOvtKPauZ/j/swhvw68ZRi9ATCfvGbk1QfydmcXBkIWecWKn/250UH7rahZ5OoDBaiAudJtPvLwzw85A==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "System.Text.Encodings.Web": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "Vg8eB5Tawm1IFqj4TVK1czJX89rhFxJo9ELqc/Eiq0eXy13RK00eubyU6TJE6y+GQXjyV5gSfiewDUZjQgSE0w==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, - "System.Threading.Tasks.Dataflow": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "+tyDCU3/B1lDdOOAJywHQoFwyXIUghIaP2BxG79uvhfTnO+D9qIgjVlL/JV2NTliYbMHpd6eKDmHp2VHpij7MA==" - }, - "System.Windows.Extensions": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "IXoJOXIqc39AIe+CIR7koBtRGMiCt/LPM3lI+PELtDIy9XdyeSrwXFdWV9dzJ2Awl0paLWUaknLxFQ5HpHZUog==", - "dependencies": { - "System.Drawing.Common": "6.0.0" - } - } - } - } -} diff --git a/src/commands/manifest/scripts/dotnet-tool/socket-facts-dotnet.csproj b/src/commands/manifest/scripts/dotnet-tool/socket-facts-dotnet.csproj deleted file mode 100644 index 376def0284..0000000000 --- a/src/commands/manifest/scripts/dotnet-tool/socket-facts-dotnet.csproj +++ /dev/null @@ -1,48 +0,0 @@ - - - - Exe - - net6.0 - LatestMajor - 12 - enable - enable - socket-facts-dotnet - Socket.Facts.Dotnet - true - en - - false - - true - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/commands/manifest/scripts/exclude-paths-glob.mts b/src/commands/manifest/scripts/exclude-paths-glob.mts deleted file mode 100644 index 33e5b0a9b6..0000000000 --- a/src/commands/manifest/scripts/exclude-paths-glob.mts +++ /dev/null @@ -1,156 +0,0 @@ -// Single source of truth for --exclude-paths glob semantics against a JVM -// build root's subproject dirs: anchored, relative, case-sensitive; `*` -// within one path segment, `**` across zero or more segments, `?` within one -// segment, and `[...]` character classes with `[!..]`/`[^..]` negation. -// Entries are assumed pre-validated by assertValidExcludePaths (relative, no -// negation, no `..`, balanced brackets, comma-free). A malformed entry falls -// back to a literal match, never throws. -// -// Compiled HERE, once, and handed to every producer (the gradle/sbt/maven -// facts and workspaces scripts) pre-compiled, so there is exactly one -// implementation and one test suite instead of the same algorithm -// re-implemented per language. -// -// Portability contract: gradle/sbt/maven all run on the JVM and share the -// exact same regex engine (java.util.regex), so the same emitted subset -// (`.*`, `[^/]*`, `[^/]`, `[...]`, `[^...]`, backslash-escaped -// metacharacters) is authoritative for every producer - this compiler and JS -// RegExp agree on the identical subset. Class bodies escape `&` because Java -// classes support `&&` intersection (JS treats it literally). Each compiled -// pattern already means "this path OR its whole subtree", matching the -// documented --exclude-paths contract, so a producer never needs its own -// "self + /**" expansion. Patterns transport comma-joined: an input glob can -// never contain a comma, since --exclude-paths is comma-split before glob -// parsing reaches this module. - -function literalSource(glob: string): string { - const escaped = glob.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - return `^(?:${escaped})(?:/.*)?$` -} - -// Strips a trailing `/**` (and trailing slashes) so `dir` and `dir/**` both -// compile to the same base pattern - the "self OR subtree" wrap below is -// what actually encodes matching the subtree, not the user's own suffix. -function stripTrailingGlobstar(glob: string): string { - let g = glob - while (g.endsWith('/')) { - g = g.slice(0, -1) - } - while (g.endsWith('/**')) { - g = g.slice(0, -3) - while (g.endsWith('/')) { - g = g.slice(0, -1) - } - } - return g -} - -// Translates one path segment's `*`/`?`/`[...]` - never crosses a `/`. -function translateSegment(segment: string): string { - let sb = '' - let i = 0 - const n = segment.length - while (i < n) { - const ch = segment.charAt(i) - if (ch === '*') { - sb += '[^/]*' - i += 1 - } else if (ch === '?') { - sb += '[^/]' - i += 1 - } else if (ch === '[') { - const j = segment.indexOf(']', i + 1) - // Treat as a class only with a non-empty body; else a literal `[`. - if (j <= i + 1) { - sb += '\\[' - i += 1 - } else { - let body = segment.slice(i + 1, j) - const neg = body.startsWith('!') || body.startsWith('^') - if (neg) { - body = body.slice(1) - } - if (!body) { - // `[!]`/`[^]` would emit `[^]`, which JS accepts but Java rejects; - // signal the caller to fall back to a whole-glob literal match. - throw new Error('empty-class') - } - // Only literal chars and `-` ranges are meaningful; neutralize - // regex-class tricks (`&` guards Java's `&&` class intersection). - body = body - .replace(/\\/g, '\\\\') - .replace(/\[/g, '\\[') - .replace(/\]/g, '\\]') - .replace(/&/g, '\\&') - sb += `[${neg ? '^' : ''}${body}]` - i = j + 1 - } - } else if ('.\\^$|+(){}]'.includes(ch)) { - sb += `\\${ch}` - i += 1 - } else { - sb += ch - i += 1 - } - } - return sb -} - -export function excludePathGlobToRegexSource(glob: string): string { - const stripped = stripTrailingGlobstar(glob) - if (!stripped) { - // Defensive only: assertValidExcludePaths already rejects a pattern that - // reduces to "match everything". - return literalSource(glob) - } - try { - const segments = stripped.split('/') - let base = '' - segments.forEach((segment, i) => { - const isLast = i === segments.length - 1 - if (segment === '**') { - // Zero or more whole segments: mid-pattern, each consumed segment - // carries its own trailing slash; as the last segment, anything - // (including nothing) for the rest of the path. - base += isLast ? '.*' : '(?:[^/]+/)*' - } else { - base += translateSegment(segment) - if (!isLast) { - base += '/' - } - } - }) - const source = `^(?:${base})(?:/.*)?$` - // eslint-disable-next-line no-new - new RegExp(source) - return source - } catch { - return literalSource(glob) - } -} - -// A Windows-style `foo\bar` means the path `foo/bar`. -export function compileExcludePathPatterns( - paths: readonly string[] | undefined, -): string[] { - return (paths ?? []).map(p => - excludePathGlobToRegexSource(p.replaceAll('\\', '/')), - ) -} - -// Transport form handed to the build-tool scripts: comma-joined pattern -// sources. Empty string when there are no patterns. -export function serializeExcludePathPatterns( - paths: readonly string[] | undefined, -): string { - return compileExcludePathPatterns(paths).join(',') -} - -export type ExcludePathFilter = (relPath: string) => boolean - -export function createExcludePathFilter( - paths: readonly string[] | undefined, -): ExcludePathFilter { - const patterns = compileExcludePathPatterns(paths).map(s => new RegExp(s)) - return relPath => patterns.some(p => p.test(relPath)) -} diff --git a/src/commands/manifest/scripts/exclude-paths-glob.test.mts b/src/commands/manifest/scripts/exclude-paths-glob.test.mts deleted file mode 100644 index ba21e26453..0000000000 --- a/src/commands/manifest/scripts/exclude-paths-glob.test.mts +++ /dev/null @@ -1,196 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - createExcludePathFilter, - excludePathGlobToRegexSource, - serializeExcludePathPatterns, -} from './exclude-paths-glob.mts' - -// Vector table for the cross-language --exclude-paths contract. Globs are -// compiled to regex pattern sources here (the ONLY implementation) and handed -// pre-compiled to the gradle/sbt/maven facts and workspaces scripts, so these -// vectors define the semantics every producer sees. Every entry means "this -// path AND its whole subtree", whether or not the user wrote a trailing -// `/**` themselves. -const MATCH_VECTORS: Array<{ - glob: string - matches: string[] - rejects: string[] -}> = [ - // A bare entry excludes itself and its whole subtree, without needing an - // explicit trailing `/**`. - { - glob: 'legacy', - matches: ['legacy', 'legacy/sub', 'legacy/sub/deeper'], - rejects: ['legacyx', 'xlegacy', 'a/legacy'], - }, - // An explicit trailing `/**` (or `/`) compiles to the identical pattern. - { - glob: 'legacy/**', - matches: ['legacy', 'legacy/sub'], - rejects: ['legacyx'], - }, - { - glob: 'legacy/', - matches: ['legacy', 'legacy/sub'], - rejects: ['legacyx'], - }, - // `*` spans one path segment, never crossing `/`. - { - glob: 'leg*cy', - matches: ['legacy', 'legcy'], - rejects: ['leg/acy', 'legacyx'], - }, - // `?` matches exactly one character, never `/`. - { - glob: 'a?c', - matches: ['abc'], - rejects: ['ac', 'a/c', 'abbc'], - }, - // Leading `**/` matches at any depth, including root-level (the NIO - // zero-depth gap this compiler exists to close without per-language - // variant expansion). - { - glob: '**/legacy', - matches: ['legacy', 'a/legacy', 'a/b/legacy', 'a/legacy/sub'], - rejects: ['legacyx', 'a/legacyx'], - }, - // A mid-pattern `**` spans zero or more whole segments. - { - glob: 'src/**/legacy', - matches: ['src/legacy', 'src/a/legacy', 'src/a/b/legacy'], - rejects: ['xsrc/legacy', 'src/legacyx', 'legacy'], - }, - // Character classes: enumerations, ranges, and `[!..]`/`[^..]` negation. - { - glob: '[lL]egacy', - matches: ['legacy', 'Legacy'], - rejects: ['regacy'], - }, - { - glob: 'v[1-3]', - matches: ['v1', 'v2', 'v3'], - rejects: ['v4'], - }, - { - glob: '[!x]legacy', - matches: ['ylegacy'], - rejects: ['xlegacy'], - }, - { - glob: '[^x]legacy', - matches: ['ylegacy'], - rejects: ['xlegacy'], - }, - // Regex metacharacters in globs are literals. - { - glob: 'a.b', - matches: ['a.b'], - rejects: ['axb'], - }, - // An unterminated `[` is a literal bracket. - { - glob: 'a[bc', - matches: ['a[bc'], - rejects: ['ab', 'ac'], - }, - // An empty (possibly negated) class would emit `[^]`, valid in JS but - // rejected by Java - the whole glob falls back to a literal match. - { - glob: '[!]legacy', - matches: ['[!]legacy'], - rejects: ['xlegacy', 'legacy'], - }, - // `&` inside a class is a literal (Java classes support `&&` intersection; - // the emitted pattern escapes it so both engines agree). - { - glob: '[a&]x', - matches: ['ax', '&x'], - rejects: ['bx'], - }, - // A Windows path separator. - { - glob: 'app\\core', - matches: ['app/core', 'app/core/x'], - rejects: ['app', 'core'], - }, -] - -describe('exclude-paths-glob vectors (cross-language contract)', () => { - for (const { glob, matches, rejects } of MATCH_VECTORS) { - it(`\`${glob}\``, () => { - const filter = createExcludePathFilter([glob]) - for (const relPath of matches) { - expect(filter(relPath), `${glob} should match ${relPath}`).toBe(true) - } - for (const relPath of rejects) { - expect(filter(relPath), `${glob} should reject ${relPath}`).toBe(false) - } - }) - } -}) - -describe('multiple entries', () => { - it('matches if any entry matches', () => { - const filter = createExcludePathFilter(['legacy', 'vendor']) - expect(filter('legacy')).toBe(true) - expect(filter('vendor/pkg')).toBe(true) - expect(filter('src')).toBe(false) - }) - - it('an empty/undefined list matches nothing', () => { - expect(createExcludePathFilter([])('legacy')).toBe(false) - expect(createExcludePathFilter(undefined)('legacy')).toBe(false) - }) -}) - -describe('emitted pattern sources (transport format)', () => { - it('wraps every entry in a self-or-subtree suffix', () => { - expect(excludePathGlobToRegexSource('legacy')).toBe('^(?:legacy)(?:/.*)?$') - }) - - it('translates * and ? to segment-bounded classes', () => { - expect(excludePathGlobToRegexSource('a*b')).toBe('^(?:a[^/]*b)(?:/.*)?$') - expect(excludePathGlobToRegexSource('a?b')).toBe('^(?:a[^/]b)(?:/.*)?$') - }) - - it('translates a leading ** to zero-or-more full segments', () => { - expect(excludePathGlobToRegexSource('**/legacy')).toBe( - '^(?:(?:[^/]+/)*legacy)(?:/.*)?$', - ) - }) - - it('escapes regex metacharacters as literals', () => { - expect(excludePathGlobToRegexSource('a.b')).toBe('^(?:a\\.b)(?:/.*)?$') - }) - - it('escapes `&` in class bodies (Java `&&` intersection guard)', () => { - expect(excludePathGlobToRegexSource('[a&]x')).toBe('^(?:[a\\&]x)(?:/.*)?$') - }) - - it('normalizes `[!..]` negation to `[^..]`', () => { - expect(excludePathGlobToRegexSource('[!x]legacy')).toBe( - '^(?:[^x]legacy)(?:/.*)?$', - ) - }) - - it('never emits `[^]` (Java-invalid); empty classes go literal', () => { - expect(excludePathGlobToRegexSource('[!]legacy')).toBe( - '^(?:\\[!\\]legacy)(?:/.*)?$', - ) - }) - - it('emits nothing a comma-join could break on', () => { - // The transport comma-joins patterns; globs cannot contain commas (the - // comma-split precedes glob parsing), so emitted patterns cannot either. - const serialized = serializeExcludePathPatterns(['legacy', '[a&]x']) - for (const pattern of serialized.split(',')) { - expect(() => new RegExp(pattern)).not.toThrow() - } - }) - - it('serializes an empty/undefined list to the empty string', () => { - expect(serializeExcludePathPatterns([])).toBe('') - expect(serializeExcludePathPatterns(undefined)).toBe('') - }) -}) diff --git a/src/commands/manifest/scripts/facts.mts b/src/commands/manifest/scripts/facts.mts deleted file mode 100644 index 06c09a06ec..0000000000 --- a/src/commands/manifest/scripts/facts.mts +++ /dev/null @@ -1,113 +0,0 @@ -export type AnyPURL = { - type: string - namespace?: string | undefined - name: string - version?: string | undefined - qualifiers?: Record | undefined -} - -// No sources/targets here: those are local absolute paths, returned in-memory -// as ResolvedArtifactPaths, never serialized into the SBOM. -export type SocketFactsSbom = { - metadata?: SocketFactsSbomMetadata | undefined - projects?: SocketFactsSbomProject[] | undefined - components: SocketFactsSbomComponent[] - dependencies?: SocketFactsSbomDependency[] | undefined -} - -export type SocketFactsSbomMetadata = { - format: 'socket-facts-sbom' - tool: 'dotnet' | 'gradle' | 'maven' | 'sbt' - toolVersion: string - javaVersion?: string | undefined - // Lets a facts file be traced back to the generator release that produced it. - socketCliVersion?: string | undefined -} - -export type SocketFactsSbomComponent = AnyPURL & { - id: string - direct?: boolean | undefined - dev?: boolean | undefined - // A module of the scanned build itself (same GAV as a projects[] entry). - firstParty?: true | undefined -} - -// Relative to the facts file's directory. -export type SocketFactsManifestReference = { - file: string -} - -// A component with one exact subtree, shared by every position whose subtree -// is identical. -export type SocketFactsSbomDependency = { - // Index into components[]. - component: number - // Indices into dependencies[]. - children?: number[] | undefined -} - -export type SocketFactsSbomProject = AnyPURL & { - // The build tool's own project identity, unique within the facts file: - // Maven's GAV, Gradle's project path, sbt's project id, the project file's - // build-root-relative path for dotnet. - id: string - subprojectDir: string - // The build files the tool reports for the project, e.g. a POM other than - // `/pom.xml`, or a Gradle build file absent on disk. - manifestFiles?: SocketFactsManifestReference[] | undefined - // Indices into dependencies[]: this subproject's direct dependencies. - children: number[] -} - -// One dotnet build of a project: a target framework, and a runtime where -// restore resolved one. `framework` is the NuGet short folder name, `alias` the -// project's own name for it; ids are those of the facts file's components. -export type ProjectFramework = { - alias: string - framework: string - runtime?: string | undefined - targetFrameworkMoniker?: string | undefined - language?: string | undefined - langVersion?: string | undefined - nullable?: string | undefined - assemblyName?: string | undefined - frameworkReferences: string[] - // As evaluated: the SDK's implicit framework symbols (NET8_0_OR_GREATER, - // ...) are absent. - defineConstants: string[] - usings: Array<{ namespace: string; alias?: string; static?: true }> - // In compiler order, as evaluated: sources that build targets generate - // are absent. - sources: string[] - targets: string[] - dependencies: string[] - classpath: string[] -} - -// A package's runtime assemblies in one target framework (and runtime); no -// `targets` when restore's assemblies for it are missing. -export type ComponentFramework = { - framework: string - runtime?: string | undefined - targets?: string[] | undefined - // What the project's sources compile against (often reference assemblies). - compile?: string[] | undefined -} - -// Resolved on-disk paths for a --with-files run, keyed by component or project -// id (a project and its own component share one). `targets` = classpath -// entries (jars / module output dirs), absent when the component's artifact -// did not resolve; `sources` = module source roots. -export type ResolvedArtifactPaths = { - pathsById: Map - // Component ids on each project's resolved classpath (union over its - // configurations), keyed by project id. A component on no classpath, such as - // a Maven 4 `none` dependency, is in the SBOM but not here. - classpathByProject: Map - // Component ids of each project's direct dependencies on its classpath, keyed - // by project id. - directDependenciesByProject: Map - // dotnet only: the same per target framework. - frameworksByProject?: Map | undefined - frameworksById?: Map | undefined -} diff --git a/src/commands/manifest/scripts/maven-extension/.gitignore b/src/commands/manifest/scripts/maven-extension/.gitignore deleted file mode 100644 index b8d44bdaca..0000000000 --- a/src/commands/manifest/scripts/maven-extension/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Build artifacts — the jar is compiled from source (build-jar.sh), never committed. -target/ -coana-maven-extension.jar diff --git a/src/commands/manifest/scripts/maven-extension/.mvn/wrapper/maven-wrapper.properties b/src/commands/manifest/scripts/maven-extension/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index ffcab66aa2..0000000000 --- a/src/commands/manifest/scripts/maven-extension/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,3 +0,0 @@ -wrapperVersion=3.3.4 -distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/src/commands/manifest/scripts/maven-extension/build-jar.sh b/src/commands/manifest/scripts/maven-extension/build-jar.sh deleted file mode 100755 index eeaef2f672..0000000000 --- a/src/commands/manifest/scripts/maven-extension/build-jar.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# Compile the Coana Maven core extension to a self-contained jar and place it at the path the TS -# runner resolves: manifest-scripts/maven-extension/coana-maven-extension.jar. Run by the npm-package -# build and the manifest-maven CI job. Uses the bundled Maven wrapper, so it needs only a JDK. -set -euo pipefail - -here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -( cd "$here" && ./mvnw -q --batch-mode package ) -cp -f "$here/target/coana-maven-extension.jar" "$here/coana-maven-extension.jar" -echo "Coana Maven extension jar: $here/coana-maven-extension.jar" diff --git a/src/commands/manifest/scripts/maven-extension/mvnw b/src/commands/manifest/scripts/maven-extension/mvnw deleted file mode 100755 index bd8896bf22..0000000000 --- a/src/commands/manifest/scripts/maven-extension/mvnw +++ /dev/null @@ -1,295 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.4 -# -# Optional ENV vars -# ----------------- -# JAVA_HOME - location of a JDK home dir, required when download maven via java source -# MVNW_REPOURL - repo url base for downloading maven distribution -# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output -# ---------------------------------------------------------------------------- - -set -euf -[ "${MVNW_VERBOSE-}" != debug ] || set -x - -# OS specific support. -native_path() { printf %s\\n "$1"; } -case "$(uname)" in -CYGWIN* | MINGW*) - [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" - native_path() { cygpath --path --windows "$1"; } - ;; -esac - -# set JAVACMD and JAVACCMD -set_java_home() { - # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched - if [ -n "${JAVA_HOME-}" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - JAVACCMD="$JAVA_HOME/jre/sh/javac" - else - JAVACMD="$JAVA_HOME/bin/java" - JAVACCMD="$JAVA_HOME/bin/javac" - - if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then - echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 - echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 - return 1 - fi - fi - else - JAVACMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v java - )" || : - JAVACCMD="$( - 'set' +e - 'unset' -f command 2>/dev/null - 'command' -v javac - )" || : - - if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then - echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 - return 1 - fi - fi -} - -# hash string like Java String::hashCode -hash_string() { - str="${1:-}" h=0 - while [ -n "$str" ]; do - char="${str%"${str#?}"}" - h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) - str="${str#?}" - done - printf %x\\n $h -} - -verbose() { :; } -[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - -die() { - printf %s\\n "$1" >&2 - exit 1 -} - -trim() { - # MWRAPPER-139: - # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. - # Needed for removing poorly interpreted newline sequences when running in more - # exotic environments such as mingw bash on Windows. - printf "%s" "${1}" | tr -d '[:space:]' -} - -scriptDir="$(dirname "$0")" -scriptName="$(basename "$0")" - -# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties -while IFS="=" read -r key value; do - case "${key-}" in - distributionUrl) distributionUrl=$(trim "${value-}") ;; - distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; - esac -done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" - -case "${distributionUrl##*/}" in -maven-mvnd-*bin.*) - MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ - case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in - *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; - :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; - :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; - :Linux*x86_64*) distributionPlatform=linux-amd64 ;; - *) - echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 - distributionPlatform=linux-amd64 - ;; - esac - distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" - ;; -maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; -*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" -distributionUrlName="${distributionUrl##*/}" -distributionUrlNameMain="${distributionUrlName%.*}" -distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" -MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" - -exec_maven() { - unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : - exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" -} - -if [ -d "$MAVEN_HOME" ]; then - verbose "found existing MAVEN_HOME at $MAVEN_HOME" - exec_maven "$@" -fi - -case "${distributionUrl-}" in -*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; -*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; -esac - -# prepare tmp dir -if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then - clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } - trap clean HUP INT TERM EXIT -else - die "cannot create temp dir" -fi - -mkdir -p -- "${MAVEN_HOME%/*}" - -# Download and Install Apache Maven -verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -verbose "Downloading from: $distributionUrl" -verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -# select .zip or .tar.gz -if ! command -v unzip >/dev/null; then - distributionUrl="${distributionUrl%.zip}.tar.gz" - distributionUrlName="${distributionUrl##*/}" -fi - -# verbose opt -__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' -[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v - -# normalize http auth -case "${MVNW_PASSWORD:+has-password}" in -'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; -has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; -esac - -if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then - verbose "Found wget ... using wget" - wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" -elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then - verbose "Found curl ... using curl" - curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" -elif set_java_home; then - verbose "Falling back to use Java to download" - javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" - targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" - cat >"$javaSource" <<-END - public class Downloader extends java.net.Authenticator - { - protected java.net.PasswordAuthentication getPasswordAuthentication() - { - return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); - } - public static void main( String[] args ) throws Exception - { - setDefault( new Downloader() ); - java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); - } - } - END - # For Cygwin/MinGW, switch paths to Windows format before running javac and java - verbose " - Compiling Downloader.java ..." - "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" - verbose " - Running Downloader.java ..." - "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" -fi - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -if [ -n "${distributionSha256Sum-}" ]; then - distributionSha256Result=false - if [ "$MVN_CMD" = mvnd.sh ]; then - echo "Checksum validation is not supported for maven-mvnd." >&2 - echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - elif command -v sha256sum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then - distributionSha256Result=true - fi - elif command -v shasum >/dev/null; then - if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then - distributionSha256Result=true - fi - else - echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 - echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 - exit 1 - fi - if [ $distributionSha256Result = false ]; then - echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 - echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 - exit 1 - fi -fi - -# unzip and move -if command -v unzip >/dev/null; then - unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" -else - tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" -fi - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -actualDistributionDir="" - -# First try the expected directory name (for regular distributions) -if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then - if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then - actualDistributionDir="$distributionUrlNameMain" - fi -fi - -# If not found, search for any directory with the Maven executable (for snapshots) -if [ -z "$actualDistributionDir" ]; then - # enable globbing to iterate over items - set +f - for dir in "$TMP_DOWNLOAD_DIR"/*; do - if [ -d "$dir" ]; then - if [ -f "$dir/bin/$MVN_CMD" ]; then - actualDistributionDir="$(basename "$dir")" - break - fi - fi - done - set -f -fi - -if [ -z "$actualDistributionDir" ]; then - verbose "Contents of $TMP_DOWNLOAD_DIR:" - verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" - die "Could not find Maven distribution directory in extracted archive" -fi - -verbose "Found extracted Maven distribution directory: $actualDistributionDir" -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/src/commands/manifest/scripts/maven-extension/mvnw.cmd b/src/commands/manifest/scripts/maven-extension/mvnw.cmd deleted file mode 100644 index 92450f9327..0000000000 --- a/src/commands/manifest/scripts/maven-extension/mvnw.cmd +++ /dev/null @@ -1,189 +0,0 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.4 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' - -$MAVEN_M2_PATH = "$HOME/.m2" -if ($env:MAVEN_USER_HOME) { - $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" -} - -if (-not (Test-Path -Path $MAVEN_M2_PATH)) { - New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null -} - -$MAVEN_WRAPPER_DISTS = $null -if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { - $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" -} else { - $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" -} - -$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" -$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -$actualDistributionDir = "" - -# First try the expected directory name (for regular distributions) -$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" -$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" -if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { - $actualDistributionDir = $distributionUrlNameMain -} - -# If not found, search for any directory with the Maven executable (for snapshots) -if (!$actualDistributionDir) { - Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { - $testPath = Join-Path $_.FullName "bin/$MVN_CMD" - if (Test-Path -Path $testPath -PathType Leaf) { - $actualDistributionDir = $_.Name - } - } -} - -if (!$actualDistributionDir) { - Write-Error "Could not find Maven distribution directory in extracted archive" -} - -Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/src/commands/manifest/scripts/maven-extension/pom.xml b/src/commands/manifest/scripts/maven-extension/pom.xml deleted file mode 100644 index 502c724fc9..0000000000 --- a/src/commands/manifest/scripts/maven-extension/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - - tech.coana - coana-maven-extension - 1.0 - - jar - Coana Maven extension - Core extension that emits a reactor's projects as records without a local-repo install. - - - 8 - 8 - UTF-8 - - 3.9.6 - - - - - coana-maven-extension - - - - org.eclipse.sisu - sisu-maven-plugin - 0.9.0.M3 - - - index-project - - main-index - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.5.1 - - - package - - shade - - - false - - - META-INF/sisu/javax.inject.Named - - - - - - - - - - - - - javax.inject - javax.inject - 1 - provided - - - - - org.apache.maven - maven-core - ${maven.version} - provided - - - diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java deleted file mode 100644 index 0e63312600..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/ext/CoanaWorkspacesLifecycleParticipant.java +++ /dev/null @@ -1,58 +0,0 @@ -package tech.coana.ext; - -import org.apache.maven.AbstractMavenLifecycleParticipant; -import org.apache.maven.MavenExecutionException; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.rtinfo.RuntimeInformation; -import tech.coana.socket.SocketWorkspacesRecordsEngine; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -/** - * Gated by {@code -Dcoana.task=socket-workspaces}. Hooks {@code afterProjectsRead} (fires once the reactor project list is known, before any - * lifecycle phase runs) since it only needs that list, never a dependency graph. - */ -@Named("coana-workspaces") -@Singleton -public class CoanaWorkspacesLifecycleParticipant extends AbstractMavenLifecycleParticipant { - - private final RuntimeInformation runtimeInformation; - - @Inject - public CoanaWorkspacesLifecycleParticipant(RuntimeInformation runtimeInformation) { - this.runtimeInformation = runtimeInformation; - } - - @Override - public void afterProjectsRead(MavenSession session) throws MavenExecutionException { - if (!"socket-workspaces".equals(opt(session, "coana.task"))) { - return; - } - String recordsFile = opt(session, "socket.recordsFile"); - if (recordsFile == null || recordsFile.isEmpty()) { - throw new MavenExecutionException("socket-workspaces requires -Dsocket.recordsFile", new IllegalStateException()); - } - SocketWorkspacesRecordsEngine.Options opts = new SocketWorkspacesRecordsEngine.Options(); - opts.recordsFile = recordsFile; - opts.excludePaths = opt(session, "socket.excludePaths"); - opts.excludeBase = opt(session, "socket.excludeBase"); - File rootDir = new File(session.getExecutionRootDirectory()); - try { - SocketWorkspacesRecordsEngine.run(session.getProjects(), rootDir, opts, runtimeInformation.getMavenVersion()); - } catch (IOException exception) { - throw new MavenExecutionException("Cannot write socket workspace records", exception); - } - } - - // -D values arrive as both session user-properties and JVM system properties; prefer the former. - private static String opt(MavenSession session, String key) { - Properties user = session.getUserProperties(); - if (user != null && user.getProperty(key) != null) return user.getProperty(key); - return System.getProperty(key); - } -} diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java deleted file mode 100644 index 2710de9640..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketSupport.java +++ /dev/null @@ -1,93 +0,0 @@ -package tech.coana.socket; - -import java.io.File; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -/** - * Shared helpers kept byte-compatible with the Gradle/SBT scripts and the TS parsers: the - * build-root-relative workspace path, path exclusion and record-field escaping. - */ -public final class SocketSupport { - private SocketSupport() {} - - /** The module dir relative to the reactor (build) root; "." for the root. */ - public static String workspace(Path rootDir, Path projectDir) { - return rootDir.equals(projectDir) ? "." : rootDir.relativize(projectDir).toString(); - } - - public static String relativePath(Path rootDir, Path file) { - return rootDir.relativize(file).toString().replace(File.separatorChar, '/'); - } - - /** - * Compile a comma-separated list of PRE-COMPILED {@code --exclude-paths} regex pattern sources - * into {@link Pattern}s, used only to skip whole excluded reactor modules. The CLI compiles the - * user-facing globs in {@code exclude-paths-glob.mts} (the single glob implementation, tested in - * CI); this only {@code Pattern.compile()}s what it receives. A pattern that doesn't compile is - * dropped, never thrown: the CLI emits a dialect-portable subset, so this only guards against a - * broken transport. - */ - public static List parseExcludePatterns(String csv) { - List out = new ArrayList<>(); - if (csv == null || csv.trim().isEmpty()) return out; - for (String raw : csv.split(",")) { - String p = raw.trim(); - if (p.isEmpty()) continue; - try { - out.add(Pattern.compile(p)); - } catch (java.util.regex.PatternSyntaxException ignored) { - } - } - return out; - } - - /** - * Whether a module directory is covered by an {@code --exclude-paths} pattern, which is relative - * to {@code base} (the scan root). A module outside it, such as a {@code ../x} - * beyond the scan root, never is. - */ - public static boolean isExcludedDir(Path base, Path dir, List patterns) { - if (patterns == null || patterns.isEmpty()) return false; - Path path = canonical(dir); - // On another Windows drive than the scan root, so outside it. - if (!java.util.Objects.equals(path.getRoot(), base.getRoot())) return false; - String rel = base.relativize(path).toString().replace(File.separatorChar, '/'); - return !rel.equals("..") && !rel.startsWith("../") && isExcludedPath(rel.isEmpty() ? "." : rel, patterns); - } - - /** The canonical {@code isExcludedDir} base: {@code socket.excludeBase}, else the build root. */ - public static Path excludeBase(String excludeBase, File rootDir) { - return canonical((excludeBase != null && !excludeBase.isEmpty() ? new File(excludeBase) : rootDir).toPath()); - } - - private static Path canonical(Path p) { - try { - return p.toRealPath(); - } catch (java.io.IOException e) { - return p.toAbsolutePath().normalize(); - } - } - - /** Whether a scan-root-relative POSIX path is covered by any {@code --exclude-paths} pattern. */ - public static boolean isExcludedPath(String rel, List patterns) { - if (patterns == null || patterns.isEmpty()) return false; - String c = (rel == null ? "" : rel).replace("\\", "/"); - while (c.startsWith("./")) c = c.substring(2); - while (c.startsWith("/")) c = c.substring(1); - while (c.endsWith("/")) c = c.substring(0, c.length() - 1); - if (c.isEmpty()) return false; - for (Pattern p : patterns) { - if (p.matcher(c).matches()) return true; - } - return false; - } - - /** Backslash-escape a record field so it can never break line/field framing (see records.ts). */ - public static String escapeField(String v) { - if (v == null) return ""; - return v.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r"); - } -} diff --git a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java b/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java deleted file mode 100644 index d1bdafb3c0..0000000000 --- a/src/commands/manifest/scripts/maven-extension/src/main/java/tech/coana/socket/SocketWorkspacesRecordsEngine.java +++ /dev/null @@ -1,70 +0,0 @@ -package tech.coana.socket; - -import org.apache.maven.project.MavenProject; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -/** - * Emits only `meta`/`buildRoot`/`project`/`projectBuild` records from the already-populated reactor - * list, building no dependency graph - cheap workspace discovery for - * `socket manifest setup --dynamic-sbom-inference`. - */ -public final class SocketWorkspacesRecordsEngine { - - public static final class Options { - // `--exclude-paths` (CSV) relative to excludeBase: a wholly excluded reactor module is skipped. - public String excludePaths; - // The directory excludePaths are relative to; the build root when unset. - public String excludeBase; - public String recordsFile; - } - - private SocketWorkspacesRecordsEngine() {} - - public static void run(List reactor, File rootDir, Options opts, String mavenVersion) - throws IOException { - List excludes = SocketSupport.parseExcludePatterns(opts.excludePaths); - java.nio.file.Path excludeBase = SocketSupport.excludeBase(opts.excludeBase, rootDir); - - List lines = new ArrayList<>(); - rec(lines, "meta", "maven", mavenVersion, System.getProperty("java.version")); - rec(lines, "buildRoot", rootDir.getAbsolutePath()); - - for (MavenProject module : reactor) { - // No basedir: Maven's stand-in project for a directory without a POM. Skipping it lets Maven's - // own "no POM in this directory" error surface instead of an NPE. - if (module.getBasedir() == null) continue; - String ws = SocketSupport.workspace(rootDir.toPath(), module.getBasedir().toPath()); - if (SocketSupport.isExcludedDir(excludeBase, module.getBasedir().toPath(), excludes)) continue; - rec(lines, "project", ws, module.getGroupId(), module.getArtifactId(), module.getVersion(), ws); - File pom = module.getFile(); - if (pom != null && pom.isFile()) rec(lines, "projectBuild", ws, SocketSupport.relativePath(rootDir.toPath(), pom.toPath())); - } - - write(opts.recordsFile, lines); - } - - private static void rec(List lines, String... fields) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < fields.length; i++) { - if (i > 0) sb.append('\t'); - sb.append(SocketSupport.escapeField(fields[i])); - } - lines.add(sb.toString()); - } - - private static void write(String recordsFile, List lines) throws IOException { - File out = new File(recordsFile); - if (out.getParentFile() != null) Files.createDirectories(out.getParentFile().toPath()); - try (PrintWriter writer = new PrintWriter(out, StandardCharsets.UTF_8.name())) { - for (String line : lines) writer.print(line + "\n"); - } - } -} diff --git a/src/commands/manifest/scripts/records.mts b/src/commands/manifest/scripts/records.mts deleted file mode 100644 index 6b60106e54..0000000000 --- a/src/commands/manifest/scripts/records.mts +++ /dev/null @@ -1,415 +0,0 @@ -import type { ResolutionFailure, Unscannable } from './resolution-report.mts' - -// Line-protocol the build-tool scripts emit to a records file (NOT stdout — sbt -// prints unsilenceable resolution noise there). One record per line, fields -// backslash-escaped (\\, \t, \n, \r) so a value can't break framing: -// -// \t\t... -// -// meta tool toolVersion javaVersion (dotnet: the SDK version; no javaVersion) -// buildRoot path (absolute; the facts file's directory) -// entry path (file-addressed builds; build-root-relative) -// member path (dotnet --members: a project the entry builds; build-root-relative) -// project projectKey group name version dir -// projectSrc projectKey path [config] (--with-files only) -// projectTgt projectKey path [config] (--with-files only) -// projectInfo projectKey config name value (dotnet, --with-files only; a name may repeat) -// projectUsing projectKey config namespace alias static(0|1) (dotnet, --with-files only) -// projectBuild projectKey path (build-root-relative; may be absent on disk) -// excludedProject projectKey (--with-files only; paths without a project) -// root rootId projectKey config prod(0|1) [framework runtime alias] (dotnet: NuGet short folder name, RID, TargetFrameworks entry) -// noClasspath rootId (its nodes are on no classpath: in the SBOM, not on a reachability classpath) -// node rootId coordId group name version ext classifier direct(0|1) project -// edge rootId parentCoordId childCoordId -// file rootId coordId path (--with-files only) -// compileFile rootId coordId path (dotnet, --with-files only; what sources compile against) -// unfetched rootId coordId (--with-files only; requested artifact not fetched) -// scanned config -// failure coord detail config projectKey (config empty: not placeable in one) -// unscannable config detail projectKey (config empty: whole project) -// -// `projectKey` is the tool's unique project identity (Maven: GAV; Gradle: -// project path; sbt: project id), emitted as the project id; a `node` whose -// `project` names one resolves to that build project. -// A `root` is one (subproject, configuration) resolution root; `coordId` is the -// coordinate key (`group:name:ext:classifier:version`, empty segments dropped), -// used opaquely as the per-root node key. Unknown tags are ignored. - -export type RawCoord = { - group: string - name: string - version: string - ext: string - classifier: string -} - -export type RawNode = { - coordId: string - coord: RawCoord - direct: boolean - // projectKey of the build project this node resolves to; empty for an - // external artifact. - project: string - // --with-files only. - targets: string[] - // dotnet, --with-files only. - compileTargets: string[] - unfetched: boolean -} - -// dotnet: the target framework's NuGet short folder name, the runtime -// identifier of a runtime-specific target (empty when none), and the -// framework's alias in the project. -export type RawTarget = { alias: string; framework: string; runtime: string } - -export type RawRoot = { - rootId: string - projectKey: string - prod: boolean - onClasspath: boolean - target?: RawTarget | undefined - nodes: Map - edges: Array<[string, string]> -} - -export type RawUsing = { namespace: string; alias: string; static: boolean } - -// One dotnet target framework build of a project, by its alias. -export type RawBuild = { - assemblyName?: string | undefined - defineConstants: string[] - framework?: string | undefined - frameworkReferences: string[] - langVersion?: string | undefined - language?: string | undefined - nullable?: string | undefined - sources: string[] - targetFrameworkMoniker?: string | undefined - targets: string[] - usings: RawUsing[] -} - -type RawBuildList = { - [K in keyof RawBuild]-?: RawBuild[K] extends string[] ? K : never -}[keyof RawBuild] - -type RawBuildValue = { - [K in keyof RawBuild]-?: RawBuild[K] extends string | undefined ? K : never -}[keyof RawBuild] - -// projectInfo names, as the dotnet tool's Reader.cs writes them. -const PROJECT_INFO_LISTS = { - __proto__: null, - DefineConstant: 'defineConstants', - FrameworkReference: 'frameworkReferences', -} as unknown as Record - -const PROJECT_INFO_VALUES = { - __proto__: null, - AssemblyName: 'assemblyName', - Framework: 'framework', - LangVersion: 'langVersion', - Language: 'language', - Nullable: 'nullable', - TargetFrameworkMoniker: 'targetFrameworkMoniker', -} as unknown as Record - -export type RawProject = { - projectKey: string - group: string - name: string - version: string - dir: string - sources: string[] - targets: string[] - // The project's build files, build-root-relative. - buildFiles: string[] - builds: Map -} - -export type ParsedRecords = { - tool: string - toolVersion: string - javaVersion: string - // Absolute directory the build is rooted at; the facts file is written there. - buildRoot: string - // The file the build was invoked on (Maven's top-level POM); empty for a - // directory-addressed build. - entry: string - projects: Map - members: string[] - // Excluded from the scan: not projects of their own, but their paths serve - // the kept projects depending on them. - excludedProjects: Map - roots: Map - scannedConfigs: string[] - failures: ResolutionFailure[] - unscannable: Unscannable[] -} - -export function unescapeField(s: string): string { - if (!s.includes('\\')) { - return s - } - let out = '' - for (let i = 0; i < s.length; i += 1) { - const c = s[i] - if (c === '\\' && i + 1 < s.length) { - const n = s[++i] - out += n === 't' ? '\t' : n === 'n' ? '\n' : n === 'r' ? '\r' : n - } else { - out += c - } - } - return out -} - -function bool(s: string | undefined): boolean { - return s === '1' || s === 'true' -} - -export function parseRecords(text: string): ParsedRecords { - const result: ParsedRecords = { - tool: '', - toolVersion: '', - javaVersion: '', - buildRoot: '', - entry: '', - projects: new Map(), - members: [], - excludedProjects: new Map(), - roots: new Map(), - scannedConfigs: [], - failures: [], - unscannable: [], - } - const scanned = new Set() - const excluded = new Set() - - const root = (id: string): RawRoot => { - let r = result.roots.get(id) - if (!r) { - r = { - rootId: id, - projectKey: '', - prod: false, - onClasspath: true, - nodes: new Map(), - edges: [], - } - result.roots.set(id, r) - } - return r - } - const project = (key: string): RawProject => { - let p = result.projects.get(key) - if (!p) { - p = { - projectKey: key, - group: '', - name: '', - version: '', - dir: '', - sources: [], - targets: [], - buildFiles: [], - builds: new Map(), - } - result.projects.set(key, p) - } - return p - } - - const build = (key: string, config: string): RawBuild => { - const builds = project(key).builds - let b = builds.get(config) - if (!b) { - b = { - defineConstants: [], - frameworkReferences: [], - sources: [], - targets: [], - usings: [], - } - builds.set(config, b) - } - return b - } - - for (const line of text.split('\n')) { - // Tolerates an emitter that writes CRLF line endings. - const rawLine = line.endsWith('\r') ? line.slice(0, -1) : line - if (!rawLine) { - continue - } - const f = rawLine.split('\t').map(unescapeField) - switch (f[0]) { - case 'meta': - result.tool = f[1] ?? '' - result.toolVersion = f[2] ?? '' - result.javaVersion = f[3] ?? '' - break - case 'buildRoot': - result.buildRoot = f[1] ?? '' - break - case 'entry': - result.entry = f[1] ?? '' - break - case 'member': - if (f[1]) { - result.members.push(f[1]) - } - break - case 'project': { - const p = project(f[1] ?? '') - p.group = f[2] ?? '' - p.name = f[3] ?? '' - p.version = f[4] ?? '' - p.dir = f[5] ?? '' - break - } - case 'projectSrc': - if (f[2]) { - project(f[1] ?? '').sources.push(f[2]) - if (f[3]) { - build(f[1] ?? '', f[3]).sources.push(f[2]) - } - } - break - case 'projectTgt': - if (f[2]) { - project(f[1] ?? '').targets.push(f[2]) - if (f[3]) { - build(f[1] ?? '', f[3]).targets.push(f[2]) - } - } - break - case 'projectInfo': - if (f[2] && f[3] && f[4]) { - const b = build(f[1] ?? '', f[2]) - const list = PROJECT_INFO_LISTS[f[3]] - const value = PROJECT_INFO_VALUES[f[3]] - if (list) { - b[list].push(f[4]) - } else if (value) { - b[value] ??= f[4] - } - } - break - case 'projectUsing': - if (f[2] && f[3]) { - build(f[1] ?? '', f[2]).usings.push({ - namespace: f[3], - alias: f[4] ?? '', - static: bool(f[5]), - }) - } - break - case 'excludedProject': - excluded.add(f[1] ?? '') - break - case 'projectBuild': - if (f[2]) { - project(f[1] ?? '').buildFiles.push(f[2]) - } - break - case 'root': { - const r = root(f[1] ?? '') - r.projectKey = f[2] ?? '' - r.prod = bool(f[4]) - if (f[5]) { - r.target = { alias: f[7] ?? '', framework: f[5], runtime: f[6] ?? '' } - } - break - } - case 'node': { - const r = root(f[1] ?? '') - const coordId = f[2] ?? '' - r.nodes.set(coordId, { - coordId, - coord: { - group: f[3] ?? '', - name: f[4] ?? '', - version: f[5] ?? '', - ext: f[6] ?? '', - classifier: f[7] ?? '', - }, - direct: bool(f[8]), - project: f[9] ?? '', - targets: [], - compileTargets: [], - unfetched: false, - }) - break - } - case 'edge': { - const parent = f[2] ?? '' - const child = f[3] ?? '' - if (parent !== child) { - root(f[1] ?? '').edges.push([parent, child]) - } - break - } - case 'noClasspath': { - root(f[1] ?? '').onClasspath = false - break - } - case 'unfetched': { - const node = root(f[1] ?? '').nodes.get(f[2] ?? '') - if (node) { - node.unfetched = true - } - break - } - case 'file': { - const node = root(f[1] ?? '').nodes.get(f[2] ?? '') - if (node && f[3]) { - node.targets.push(f[3]) - } - break - } - case 'compileFile': { - const node = root(f[1] ?? '').nodes.get(f[2] ?? '') - if (node && f[3]) { - node.compileTargets.push(f[3]) - } - break - } - case 'scanned': - if (f[1]) { - scanned.add(f[1]) - } - break - case 'failure': - if (f[1]) { - result.failures.push({ - coord: f[1], - detail: f[2] ?? '', - config: f[3] ?? '', - project: f[4] ?? '', - }) - } - break - case 'unscannable': - if (f[1] || f[3]) { - result.unscannable.push({ - config: f[1] ?? '', - detail: f[2] ?? '', - project: f[3] ?? '', - }) - } - break - default: - break - } - } - for (const key of excluded) { - const p = result.projects.get(key) - if (p) { - result.projects.delete(key) - result.excludedProjects.set(key, p) - } - } - result.scannedConfigs = [...scanned].sort() - return result -} diff --git a/src/commands/manifest/scripts/resolution-report.mts b/src/commands/manifest/scripts/resolution-report.mts deleted file mode 100644 index 37244f828e..0000000000 --- a/src/commands/manifest/scripts/resolution-report.mts +++ /dev/null @@ -1,33 +0,0 @@ -export type ResolutionFailure = { - coord: string - // Build tool's own failure message (deepest cause; may be multi-line). - // Classified on; first line shown by default, whole thing at --verbose. - detail: string - // Empty when the failure cannot be placed in a configuration; it then counts - // against every configuration of its project. - config: string - // projectKey of the subproject being resolved. - project: string -} - -// A resolution that threw without naming a dependency: one configuration, or -// with an empty `config` the whole project. -export type Unscannable = { - config: string - detail: string - project: string -} - -// A module (`group:name`, from any longer coordinate) within one project. -export function moduleKey(project: string, coord: string): string { - return `${project}\t${coord.split(':').slice(0, 2).join(':')}` -} - -export type ResolutionReport = { - failures: ResolutionFailure[] - // moduleKey of every module a project resolved in some configuration; empty - // when nothing failed. - resolvedModules: ReadonlySet - scannedConfigs: string[] - unscannable: Unscannable[] -} diff --git a/src/commands/manifest/scripts/run.mts b/src/commands/manifest/scripts/run.mts deleted file mode 100644 index 9500a82066..0000000000 --- a/src/commands/manifest/scripts/run.mts +++ /dev/null @@ -1,407 +0,0 @@ -import { existsSync, promises as fs } from 'node:fs' -import path from 'node:path' - -import { spawn } from '@socketsecurity/registry/lib/spawn' - -import { assembleFacts } from './assemble.mts' -import { resolveBuildToolBin } from './build-tool.mts' -import { serializeExcludePathPatterns } from './exclude-paths-glob.mts' -import { parseRecords } from './records.mts' -import constants from '../../../constants.mts' -import { isStandaloneSea } from '../../../sea/runtime.mts' -import { withTmpDir } from '../../../utils/fs.mts' -import { getOrInsert } from '../../../utils/get-or-insert.mts' -import { camelToKebab } from '../../../utils/strings.mts' - -import type { BuildTool } from './build-tool.mts' -import type { SocketFactsSbomProject } from './facts.mts' - -export type ManifestScriptOptions = { - projectDir: string - // Unset ⇒ resolved to the project wrapper, else PATH (resolveBuildToolBin). - bin?: string | undefined - // The file in projectDir to build: Maven's POM (unset leaves Maven's - // default), dotnet's solution or project (required). - entryFile?: string | undefined - // `--exclude-paths`, relative to excludeBase. Passed to the build script, - // which skips a wholly excluded subproject. - excludePaths?: string[] | undefined - // The scan root, which a build's modules can lie outside of (Maven `../x` - // modules); projectDir when unset. - excludeBase?: string | undefined - toolOpts?: string[] | undefined - stdio?: 'inherit' | 'pipe' | undefined - env?: NodeJS.ProcessEnv | undefined - signal?: AbortSignal | undefined -} - -type RunOutput = { code: number; stdout: string; stderr: string } - -const WORKSPACES_TASK = 'socketWorkspaces' -// Destination filename inside sbt's isolated plugins/ dir. -const SBT_WORKSPACES_PLUGIN_FILENAME = 'SocketWorkspacesPlugin.scala' - -export type WorkspaceEnumerationResult = { - // Absolute; what each project's subprojectDir and manifestFiles are relative to. - buildRoot: string | undefined - code: number - projects: SocketFactsSbomProject[] - stderr: string - stdout: string -} - -// Bundled emitter assets, copied into dist by the rollup build. -function manifestScriptsPath(...parts: string[]): string { - return path.join(constants.distPath, 'manifest-scripts', ...parts) -} - -// Streamed build output is a diagnostic: it goes to stderr so the command's own -// stdout (e.g. --json) stays machine-readable. -const STREAM_TO_STDERR = ['inherit', 2, 'inherit'] as const - -// Don't throw on a non-zero exit: the script may still have written records. A -// non-exit spawn error (e.g. missing executable) propagates. -async function runNeverThrow( - bin: string, - args: string[], - opts: ManifestScriptOptions, -): Promise { - try { - const result = await spawn(bin, args, { - cwd: opts.projectDir, - stdio: opts.stdio === 'pipe' ? 'pipe' : [...STREAM_TO_STDERR], - ...(opts.env ? { env: opts.env } : {}), - ...(opts.signal ? { signal: opts.signal } : {}), - }) - return { - code: result.code, - stdout: typeof result.stdout === 'string' ? result.stdout : '', - stderr: typeof result.stderr === 'string' ? result.stderr : '', - } - } catch (e) { - // A build tool that exits non-zero rejects with the spawn-result shape: a - // numeric exit `code` plus captured stdout/stderr. Anything else — e.g. a - // missing executable, whose `code` is a string like 'ENOENT' — propagates. - // This mirrors how utils/dlx.mts classifies spawn failures (a numeric `code` - // is a real process exit); the registry's isSpawnError is avoided here - // because it is currently broken and never matches. - if ( - e !== null && - typeof e === 'object' && - typeof (e as { code?: unknown }).code === 'number' - ) { - const err = e as { code: number; stdout?: unknown; stderr?: unknown } - return { - code: err.code, - stdout: typeof err.stdout === 'string' ? err.stdout : '', - stderr: typeof err.stderr === 'string' ? err.stderr : '', - } - } - throw e - } -} - -async function writeSbtPlugin(globalBase: string): Promise { - const src = await fs.readFile( - manifestScriptsPath('socket-workspaces.plugin.scala'), - 'utf8', - ) - const pluginsDir = path.join(globalBase, 'plugins') - await fs.mkdir(pluginsDir, { recursive: true }) - await fs.writeFile(path.join(pluginsDir, SBT_WORKSPACES_PLUGIN_FILENAME), src) -} - -async function readRecordsFile(recordsFile: string): Promise { - return existsSync(recordsFile) ? await fs.readFile(recordsFile, 'utf8') : '' -} - -function enumerationResult( - out: RunOutput, - text: string, -): WorkspaceEnumerationResult { - const parsed = parseRecords(text) - return { - buildRoot: parsed.buildRoot || undefined, - code: out.code, - projects: assembleFacts(parsed).facts.projects ?? [], - stderr: out.stderr, - stdout: out.stdout, - } -} - -// Missing only in an unbuilt local checkout. Fail loudly: without the -// extension, Maven silently records nothing. -function assertBundledAssetBuilt( - assetPath: string, - description: string, - // The package.json script that builds it, as the dist build names it too. - buildScript: string, -): void { - if (existsSync(assetPath)) { - return - } - throw new Error( - `${description} not found at ${assetPath}. It is bundled in the published CLI; for local dev build it with: pnpm run ${buildScript}`, - ) -} - -// Emits only `project` records, never resolving dependencies. -export async function enumerateWorkspaces( - tool: BuildTool, - opts: ManifestScriptOptions, -): Promise { - switch (tool) { - case 'dotnet': - return await enumerateDotnetWorkspaces(opts) - case 'gradle': - return await enumerateGradleWorkspaces(opts) - case 'sbt': - return await enumerateSbtWorkspaces(opts) - case 'maven': - return await enumerateMavenWorkspaces(opts) - } -} - -// The options every build script reads, each in its own argument syntax. -function scriptOptions(opts: ManifestScriptOptions): Array<[string, string]> { - const options: Array<[string, string]> = [] - // Globs compile to regex pattern sources HERE (exclude-paths-glob.mts is - // the single glob implementation); the scripts just compile what they - // receive. - const excludePatterns = serializeExcludePathPatterns(opts.excludePaths) - if (excludePatterns) { - options.push(['excludePaths', excludePatterns]) - options.push(['excludeBase', opts.excludeBase ?? opts.projectDir]) - } - return options -} - -function commonProps( - opts: ManifestScriptOptions, - prefix: '-D' | '-P', -): string[] { - return scriptOptions(opts).map( - ({ 0: name, 1: value }) => `${prefix}socket.${name}=${value}`, - ) -} - -// The dotnet tool's flags are the kebab-cased script option names. -function dotnetToolArgs(opts: ManifestScriptOptions): string[] { - return scriptOptions(opts).flatMap(({ 0: name, 1: value }) => [ - `--${camelToKebab(name)}`, - value, - ]) -} - -async function enumerateGradleWorkspaces( - opts: ManifestScriptOptions, -): Promise { - const bin = resolveBuildToolBin( - 'gradle', - opts.projectDir, - opts.bin, - isStandaloneSea(), - ) - const initScript = manifestScriptsPath('socket-workspaces.init.gradle') - return await withTmpDir('socket-gradle-workspaces-', async tmp => { - const recordsFile = path.join(tmp, 'records.tsv') - // Disable the configuration cache: the init script's shared accumulator - // isn't cache-safe. - const args = [ - '--init-script', - initScript, - '-Dorg.gradle.configuration-cache=false', - `-Psocket.recordsFile=${recordsFile}`, - ...commonProps(opts, '-P'), - ...(opts.toolOpts ?? []), - WORKSPACES_TASK, - '--no-daemon', - '--console=plain', - ] - const out = await runNeverThrow(bin, args, opts) - return enumerationResult(out, await readRecordsFile(recordsFile)) - }) -} - -async function invokeSbtIn( - globalBase: string, - opts: ManifestScriptOptions, -): Promise { - const bin = resolveBuildToolBin( - 'sbt', - opts.projectDir, - opts.bin, - isStandaloneSea(), - ) - await writeSbtPlugin(globalBase) - const recordsFile = path.join(globalBase, 'records.tsv') - // Fresh per-run global base (not ~/.sbt): sbt executes everything under - // plugins/, so a shared path is a code-injection surface. BSP off for this - // run. - const props = [ - `-Dsbt.global.base=${globalBase}`, - '-Dsbt.server.autostart=false', - `-Dsocket.recordsFile=${recordsFile}`, - ...commonProps(opts, '-D'), - ] - // sbt's launcher doesn't always honor JAVA_HOME; never override a - // caller-supplied --java-home. - const javaHome = opts.env?.['JAVA_HOME'] ?? process.env['JAVA_HOME'] - const javaHomeOpt = - javaHome && !(opts.toolOpts ?? []).includes('--java-home') - ? ['--java-home', javaHome] - : [] - const args = [ - ...javaHomeOpt, - ...props, - ...(opts.toolOpts ?? []), - '--batch', - WORKSPACES_TASK, - ] - const out = await runNeverThrow(bin, args, opts) - return enumerationResult(out, await readRecordsFile(recordsFile)) -} - -async function enumerateSbtWorkspaces( - opts: ManifestScriptOptions, -): Promise { - return await withTmpDir('socket-sbt-workspaces-', globalBase => - invokeSbtIn(globalBase, opts), - ) -} - -async function enumerateMavenWorkspaces( - opts: ManifestScriptOptions, -): Promise { - const bin = resolveBuildToolBin( - 'maven', - opts.projectDir, - opts.bin, - isStandaloneSea(), - ) - const jarPath = manifestScriptsPath( - 'maven-extension', - 'coana-maven-extension.jar', - ) - assertBundledAssetBuilt( - jarPath, - 'Maven manifest extension jar', - 'build:maven-extension', - ) - return await withTmpDir('socket-maven-workspaces-', async tmp => { - const recordsFile = path.join(tmp, 'records.tsv') - // `validate` is the cheapest phase that triggers the extension. - const props = [ - `-Dmaven.ext.class.path=${jarPath}`, - '-Dcoana.task=socket-workspaces', - `-Dsocket.recordsFile=${recordsFile}`, - ...commonProps(opts, '-D'), - ] - const fileOpts = opts.entryFile ? ['--file', opts.entryFile] : [] - const args = [ - ...props, - ...fileOpts, - ...(opts.toolOpts ?? []), - '--batch-mode', - 'validate', - ] - const out = await runNeverThrow(bin, args, opts) - return enumerationResult(out, await readRecordsFile(recordsFile)) - }) -} - -// The global.json the dotnet host applies in `dir`: the first one in it or -// any parent directory, the filesystem root included, which findUp skips. -// https://github.com/dotnet/runtime/blob/b4548da6edfce1996a1d6ffe1521c9ce6128be2e/src/native/corehost/fxr/sdk_resolver.cpp#L296-L321 -function nearestGlobalJson(dir: string): string { - for (let current = path.resolve(dir); ; ) { - const file = path.join(current, 'global.json') - if (existsSync(file)) { - return file - } - const parent = path.dirname(current) - if (parent === current) { - return '' - } - current = parent - } -} - -// Keyed by the nearest global.json, the only per-directory input to the -// host's SDK selection; a failed probe is shared too. -const sdkVersionByPin = new Map>() - -function dotnetSdkVersion( - bin: string, - opts: ManifestScriptOptions, -): Promise { - // A relative path names a different host in each directory. - const host = - path.isAbsolute(bin) || path.basename(bin) === bin - ? bin - : path.resolve(opts.projectDir, bin) - const key = `${host}\0${nearestGlobalJson(opts.projectDir)}` - return getOrInsert(sdkVersionByPin, key, () => - readDotnetSdkVersion(bin, opts), - ) -} - -async function readDotnetSdkVersion( - bin: string, - opts: ManifestScriptOptions, -): Promise { - const out = await runNeverThrow(bin, ['--version'], { - ...opts, - stdio: 'pipe', - }) - if (out.code !== 0) { - throw new Error( - out.stderr.trim() || - out.stdout.trim() || - `\`${bin} --version\` exited with code ${out.code}`, - ) - } - return out.stdout.trim() -} - -// Runs the bundled tool against the build's own dotnet in its restore-free -// workspaces mode. -async function enumerateDotnetWorkspaces( - opts: ManifestScriptOptions, -): Promise { - if (!opts.entryFile) { - throw new Error('A dotnet build needs a solution or project file.') - } - const toolDll = manifestScriptsPath('dotnet-tool', 'socket-facts-dotnet.dll') - assertBundledAssetBuilt(toolDll, 'dotnet manifest tool', 'build:dotnet-tool') - const bin = resolveBuildToolBin('dotnet', opts.projectDir, opts.bin) - const sdkVersion = await dotnetSdkVersion(bin, opts) - // The tool runs on the newest installed runtime (RollForward=LatestMajor), - // which must be able to load the selected SDK's MSBuild; a preview SDK - // needs a preview runtime, which roll-forward only picks when told to. - const env = sdkVersion.includes('-') - ? { - ...(opts.env ?? process.env), - DOTNET_ROLL_FORWARD_TO_PRERELEASE: '1', - } - : opts.env - return await withTmpDir('socket-dotnet-workspaces-', async tmp => { - const recordsFile = path.join(tmp, 'records.tsv') - const args = [ - toolDll, - '--records', - recordsFile, - '--entry', - opts.entryFile!, - '--dotnet', - bin, - '--workspaces', - ...dotnetToolArgs(opts), - ...(opts.stdio === 'inherit' ? ['--verbose'] : []), - '--', - ...(opts.toolOpts ?? []), - ] - const out = await runNeverThrow(bin, args, { ...opts, env }) - return enumerationResult(out, await readRecordsFile(recordsFile)) - }) -} diff --git a/src/commands/manifest/scripts/run.test.mts b/src/commands/manifest/scripts/run.test.mts deleted file mode 100644 index ab3a7d7d33..0000000000 --- a/src/commands/manifest/scripts/run.test.mts +++ /dev/null @@ -1,191 +0,0 @@ -import { promises as fs } from 'node:fs' -import os from 'node:os' -import path from 'node:path' - -import { beforeEach, describe, expect, it, vi } from 'vitest' - -import { spawn } from '@socketsecurity/registry/lib/spawn' - -import { enumerateWorkspaces } from './run.mts' - -vi.mock('@socketsecurity/registry/lib/spawn', () => ({ - spawn: vi.fn(async () => ({ code: 0, stderr: '', stdout: '' })), -})) -// The Maven extension jar and the dotnet tool exist only in a built checkout. -// Each dotnetDir() case pins its own SDK, so cases never share a probe. -vi.mock('node:fs', async importOriginal => { - const actual = await importOriginal() - return { - ...actual, - existsSync: (p: string) => - p.endsWith('.jar') || - p.endsWith('.dll') || - /[\\/]repo[\\/]dotnet-\d+[\\/]global\.json$/.test(p) || - actual.existsSync(p), - } -}) - -beforeEach(() => { - vi.mocked(spawn).mockReset() -}) - -describe('build tool output', () => { - it.each([ - ['inherit', ['inherit', 2, 'inherit']], - ['pipe', 'pipe'], - ] as const)( - 'maps stdio %s so stdout stays free of build logs', - async (stdio, expected) => { - vi.mocked(spawn).mockClear() - await enumerateWorkspaces('gradle', { - bin: 'gradle', - projectDir: process.cwd(), - stdio, - }).catch(() => {}) - expect(vi.mocked(spawn).mock.calls[0]?.[2]?.stdio).toEqual(expected) - }, - ) -}) - -describe('maven entry file', () => { - it.each([ - ['app-dev.pom.xml', ['--file', 'app-dev.pom.xml', '-P', 'ci']], - ['pom.xml', ['--file', 'pom.xml', '-P', 'ci']], - [undefined, ['-P', 'ci']], - ] as const)( - 'builds %s, ahead of the given options', - async (entryFile, expected) => { - vi.mocked(spawn).mockClear() - await enumerateWorkspaces('maven', { - bin: 'mvn', - entryFile, - projectDir: process.cwd(), - stdio: 'pipe', - toolOpts: ['-P', 'ci'], - }) - const args = vi.mocked(spawn).mock.calls[0]?.[1] ?? [] - expect(args.filter(a => !a.startsWith('-D'))).toEqual([ - ...expected, - '--batch-mode', - 'validate', - ]) - }, - ) -}) - -async function excludeProps(excludeBase: string | undefined) { - vi.mocked(spawn).mockClear() - await enumerateWorkspaces('gradle', { - bin: 'gradle', - excludeBase, - excludePaths: ['shared'], - projectDir: path.join(path.sep, 'repo', 'app'), - stdio: 'pipe', - }).catch(() => {}) - const args = (vi.mocked(spawn).mock.calls[0]?.[1] ?? []) as string[] - return args.filter(a => a.startsWith('-Psocket.exclude')) -} - -describe('--exclude-paths anchoring', () => { - it('tells the build script the scan root the patterns are relative to', async () => { - expect(await excludeProps(path.join(path.sep, 'repo'))).toEqual([ - expect.stringMatching(/^-Psocket\.excludePaths=/), - `-Psocket.excludeBase=${path.join(path.sep, 'repo')}`, - ]) - }) - - it('defaults the base to projectDir', async () => { - expect(await excludeProps(undefined)).toEqual([ - expect.stringMatching(/^-Psocket\.excludePaths=/), - `-Psocket.excludeBase=${path.join(path.sep, 'repo', 'app')}`, - ]) - }) -}) - -// The SDK version is cached per bin and directory, so each case gets its own. -let dotnetCase = 0 -function dotnetDir(): string { - dotnetCase += 1 - return path.join(path.sep, 'repo', `dotnet-${dotnetCase}`) -} - -// Answers `dotnet --version` with `sdk`, then runs the tool, which writes -// `records` to its --records file. -function mockDotnet(sdk: string, records = '', code = 0): void { - vi.mocked(spawn).mockImplementation((async ( - _bin: string, - args: readonly string[], - ) => { - if (args[0] === '--version') { - return { code: 0, stderr: '', stdout: `${sdk}\n` } - } - const at = args.indexOf('--records') - if (at < 0) { - throw new Error('the dotnet tool was run without --records') - } - await fs.writeFile(args[at + 1]!, records) - return { code, stderr: '', stdout: '' } - }) as any) -} - -function toolCall() { - return vi.mocked(spawn).mock.calls.filter(c => c[1]?.[0] !== '--version')[0] -} - -describe('dotnet tool invocation', () => { - it('lists workspaces of the build entry with the given options', async () => { - const projectDir = dotnetDir() - mockDotnet('8.0.414', 'buildRoot\t/repo\nentry\tApp.sln\n') - const result = await enumerateWorkspaces('dotnet', { - bin: '/opt/dotnet/dotnet', - entryFile: 'App.sln', - excludeBase: path.join(path.sep, 'repo'), - excludePaths: ['test'], - projectDir, - stdio: 'pipe', - toolOpts: ['-p:Configuration=Release', '--locked-mode'], - }) - const { 0: bin, 1: args = [], 2: opts } = toolCall()! - expect(bin).toBe('/opt/dotnet/dotnet') - expect(args[0]).toMatch(/socket-facts-dotnet\.dll$/) - expect(args.slice(args.indexOf('--entry'))).toEqual([ - '--entry', - 'App.sln', - '--dotnet', - '/opt/dotnet/dotnet', - '--workspaces', - '--exclude-paths', - '^(?:test)(?:/.*)?$', - '--exclude-base', - path.join(path.sep, 'repo'), - '--', - '-p:Configuration=Release', - '--locked-mode', - ]) - expect(opts?.cwd).toBe(projectDir) - expect(opts?.env).toBeUndefined() - expect(result.buildRoot).toBe('/repo') - }) - - it('lets a preview SDK roll the tool forward onto a preview runtime', async () => { - mockDotnet('11.0.100-rc.3.26522.148') - await enumerateWorkspaces('dotnet', { - bin: 'dotnet', - entryFile: 'App.csproj', - env: { NUGET_PACKAGES: '/cache', PATH: '/bin' }, - projectDir: dotnetDir(), - stdio: 'pipe', - }) - expect(toolCall()?.[2]?.env).toEqual({ - DOTNET_ROLL_FORWARD_TO_PRERELEASE: '1', - NUGET_PACKAGES: '/cache', - PATH: '/bin', - }) - }) - - it('needs an entry file', async () => { - await expect( - enumerateWorkspaces('dotnet', { bin: 'dotnet', projectDir: dotnetDir() }), - ).rejects.toThrow(/solution or project file/) - }) -}) diff --git a/src/commands/manifest/scripts/socket-workspaces.init.gradle b/src/commands/manifest/scripts/socket-workspaces.init.gradle deleted file mode 100644 index edf2c79536..0000000000 --- a/src/commands/manifest/scripts/socket-workspaces.init.gradle +++ /dev/null @@ -1,121 +0,0 @@ -// Invoke via: -// ./gradlew --init-script socket-workspaces.init.gradle socketWorkspaces - -// Emits only `meta`/`buildRoot`/`project`/`projectBuild` records, no dependency resolution, for -// the setup wizard; Coana generates the facts themselves. - -// `Project.findProperty` only exists since Gradle 2.13; fall back to hasProperty/property for older Gradle. -gradle.ext.socketProp = { proj, name -> proj.hasProperty(name) ? proj.property(name) : null } - -// `-Psocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only -// to skip whole excluded subprojects. The CLI compiles the user-facing globs in -// exclude-paths-glob.mts (the single glob implementation, tested in CI); this script only -// Pattern.compile()s what it receives. -gradle.ext.socketExcludeMatchersCache = null -gradle.ext.socketExcludeMatchers = { - if (gradle.ext.socketExcludeMatchersCache != null) return gradle.ext.socketExcludeMatchersCache - def raw = gradle.socketProp.call(gradle.rootProject, 'socket.excludePaths')?.toString() - def patterns = [] - if (raw != null && !raw.trim().isEmpty()) { - raw.split(',').each { r -> - def p = r.trim() - if (!p.isEmpty()) { - // A pattern that doesn't compile is dropped, never thrown: the CLI emits a - // dialect-portable subset, so this only guards against a broken transport. - try { patterns << java.util.regex.Pattern.compile(p) } - catch (java.util.regex.PatternSyntaxException ignored) { } - } - } - } - gradle.ext.socketExcludeMatchersCache = patterns - patterns -} -gradle.ext.socketIsExcluded = { String rel -> - def c = (rel == null ? '' : rel).replace('\\', '/') - while (c.startsWith('./')) { c = c.substring(2) } - while (c.startsWith('/')) { c = c.substring(1) } - while (c.endsWith('/')) { c = c.substring(0, c.length() - 1) } - if (c.isEmpty()) { return false } - gradle.ext.socketExcludeMatchers.call().any { p -> p.matcher(c).matches() } -} -// `-Psocket.excludeBase` (the scan root; the root project's dir by default) anchors `--exclude-paths`: -// a project relocated outside the build root still matches, one outside the scan root never does. -gradle.ext.socketExcludeBaseCache = null -gradle.ext.socketIsExcludedDir = { java.io.File dir -> - if (gradle.ext.socketExcludeMatchers.call().isEmpty()) { return false } - if (gradle.ext.socketExcludeBaseCache == null) { - def base = gradle.socketProp.call(gradle.rootProject, 'socket.excludeBase')?.toString() - gradle.ext.socketExcludeBaseCache = (base ? new java.io.File(base) : gradle.rootProject.projectDir).canonicalFile.toPath() - } - def path = dir.canonicalFile.toPath() - // On another Windows drive than the scan root, so outside it. - if (path.root != gradle.ext.socketExcludeBaseCache.root) { return false } - def rel = gradle.ext.socketExcludeBaseCache.relativize(path).toString().replace(File.separator, '/') - !(rel == '..' || rel.startsWith('../')) && gradle.ext.socketIsExcluded.call(rel.isEmpty() ? '.' : rel) -} - -gradle.ext.socketWorkspacesInfo = Collections.synchronizedList([]) - -// Collect every non-excluded project's identity at configuration time - cheap, no dependency -// resolution, no sourceSets/jar introspection. -gradle.projectsEvaluated { g -> - def rootPath = g.rootProject.projectDir.toPath() - def rel = { java.io.File f -> - def r = rootPath.relativize(f.toPath()).toString().replace(File.separator, '/') - r.isEmpty() ? '.' : r - } - g.rootProject.allprojects.each { p -> - if (g.ext.socketIsExcludedDir.call(p.projectDir)) { - return - } - def buildFiles = [] - try { - def bf = p.buildFile - if (bf != null) buildFiles << rel(bf) - } catch (Exception ignore) {} - g.socketWorkspacesInfo.add([ - path : p.path, - group : (p.group ?: '').toString(), - name : p.name, - version: (p.version ?: '').toString(), - dir : rel(p.projectDir), - buildFiles: buildFiles, - ]) - } -} - -rootProject { rp -> - def recordsFileOverride = gradle.socketProp.call(rp, 'socket.recordsFile')?.toString() - def defaultRecordsFile = new File(rp.projectDir, '.socket.workspaces.records.tsv').absolutePath - def buildRootPath = rp.projectDir.absolutePath - - rp.tasks.create('socketWorkspaces') { - group = 'socket' - description = 'Emits Socket workspace records (project list only; no dependency resolution)' - outputs.upToDateWhen { false } - - doLast { - def esc = { v -> - (v == null ? '' : v.toString()) - .replace('\\', '\\\\').replace('\t', '\\t').replace('\n', '\\n').replace('\r', '\\r') - } - def lines = [] - def rec = { List fields -> lines << fields.collect { esc(it) }.join('\t') } - - rec(['meta', 'gradle', gradle.gradleVersion, System.getProperty('java.version')]) - rec(['buildRoot', buildRootPath]) - - def info - synchronized (gradle.socketWorkspacesInfo) { info = new ArrayList(gradle.socketWorkspacesInfo) } - info.each { pi -> - rec(['project', pi.path, pi.group, pi.name, pi.version, pi.dir]) - pi.buildFiles.each { f -> rec(['projectBuild', pi.path, f]) } - } - - def outFile = new File(recordsFileOverride ?: defaultRecordsFile) - outFile.parentFile?.mkdirs() - outFile.withWriter('UTF-8') { it.write(lines.join('\n') + '\n') } - println "Socket workspace records written to: ${outFile.absolutePath}" - } - } -} diff --git a/src/commands/manifest/scripts/socket-workspaces.plugin.scala b/src/commands/manifest/scripts/socket-workspaces.plugin.scala deleted file mode 100644 index 95ecc2efd9..0000000000 --- a/src/commands/manifest/scripts/socket-workspaces.plugin.scala +++ /dev/null @@ -1,145 +0,0 @@ -package socket - -import sbt._ -import sbt.Keys._ - -/** - * Emits only `meta`/`buildRoot`/`project`/`projectBuild` records, no dependency resolution, for - * the setup wizard; Coana generates the facts themselves. - * - * Must compile on Scala 2.10/sbt 0.13 and Scala 2.12/sbt 1.x. - */ -object SocketWorkspacesPlugin extends AutoPlugin { - override def trigger = allRequirements - - object autoImport { - val socketWorkspaces = - taskKey[Unit]("Emit Socket workspace records (project list only; no dependency resolution)") - } - import autoImport._ - - override def projectSettings: Seq[Setting[_]] = Seq( - aggregate in socketWorkspaces := false, - socketWorkspaces := { - val st = state.value - val buildRoot = (baseDirectory in ThisBuild).value - - val extracted = Project.extract(st) - val allRefs = extracted.structure.allProjectRefs - - // `-Dsocket.excludePaths` (scan-root-relative globs): a subproject whose dir is wholly excluded - // emits no project record, as in the gradle / maven producers. - val excludeMatchers = parseExcludeMatchers() - val rootCanonPath = buildRoot.getCanonicalFile.toPath - def relTo(base: java.nio.file.Path)(f: File): String = { - val r = base.relativize(f.getCanonicalFile.toPath).toString.replace(java.io.File.separator, "/") - if (r.isEmpty) "." else r - } - def relOf(f: File): String = relTo(rootCanonPath)(f) - // `-Dsocket.excludeBase`: the directory `--exclude-paths` is relative to (the scan root; the - // build root by default); a project outside it never matches. - val excludeBase = sys.props.get("socket.excludeBase").filter(_.nonEmpty) - .map(b => new File(b).getCanonicalFile.toPath).getOrElse(rootCanonPath) - def isExcludedRef(ref: ProjectRef): Boolean = excludeMatchers.nonEmpty && { - val dir = extracted.get(baseDirectory.in(ref)) - // Another Windows drive than the scan root is outside it. - dir.getCanonicalFile.toPath.getRoot == excludeBase.getRoot && { - val rel = relTo(excludeBase)(dir) - rel != ".." && !rel.startsWith("../") && isExcludedPath(rel, excludeMatchers) - } - } - - def rootIdOf(ref: ProjectRef): ModuleID = { - val sv = extracted.get(scalaVersion.in(ref)) - val sbv = extracted.get(scalaBinaryVersion.in(ref)) - CrossVersion.apply(sv, sbv)(extracted.get(projectID.in(ref))) - } - - val buildFilesByRef: Map[ProjectRef, Seq[String]] = - extracted.structure.settings - .flatMap { setting => - (setting.key.scope.project, setting.pos) match { - case (Select(ref: ProjectRef), pos: FilePosition) => - val f = new File(pos.path) - if (f.isAbsolute && f.isFile && f.getCanonicalFile.toPath.startsWith(rootCanonPath)) Some(ref -> relOf(f)) - else None - case _ => None - } - } - .groupBy(_._1) - .map { case (ref, pairs) => ref -> pairs.map(_._2) } - - val sb = new StringBuilder - def rec(fields: String*): Unit = { - sb.append(fields.map(esc).mkString("\t")); sb.append('\n') - } - - rec("meta", "sbt", extracted.getOpt(sbtVersion).getOrElse(""), sys.props.getOrElse("java.version", "")) - rec("buildRoot", rootCanonPath.toString) - - allRefs.foreach { ref => - if (!isExcludedRef(ref)) { - val mid = rootIdOf(ref) - val ver = if (mid.revision == null) "" else mid.revision - val baseDir = extracted.get(baseDirectory.in(ref)) - rec("project", ref.project, mid.organization, mid.name, ver, relOf(baseDir)) - (buildFilesByRef.getOrElse(ref, Nil) ++ baseBuildSbt(baseDir, rootCanonPath).map(relOf)).distinct.sorted - .foreach(f => rec("projectBuild", ref.project, f)) - } - } - - val recordsFile = sys.props.get("socket.recordsFile").filter(_.nonEmpty) match { - case Some(p) => new File(p) - case None => new File(buildRoot, ".socket.workspaces.records.tsv") - } - Option(recordsFile.getParentFile).foreach(_.mkdirs()) - IO.write(recordsFile, sb.toString) - println("Socket workspace records written to: " + recordsFile.getAbsolutePath) - } - ) - - // ---- path exclusion --------------------------------------------------------------------------- - - // `-Dsocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only - // to skip whole excluded subprojects. The CLI compiles the user-facing globs in - // exclude-paths-glob.mts (the single glob implementation, tested in CI); this plugin only - // Pattern.compile()s what it receives. - private def parseExcludeMatchers(): Seq[java.util.regex.Pattern] = { - sys.props.get("socket.excludePaths").map(_.trim).filter(_.nonEmpty) match { - case None => Nil - case Some(raw) => - raw.split(",").toSeq.flatMap { r => - val p = r.trim - // A pattern that doesn't compile is dropped, never thrown: the CLI emits a - // dialect-portable subset, so this only guards against a broken transport. - if (p.isEmpty) Nil - else - try Seq(java.util.regex.Pattern.compile(p)) - catch { case _: java.util.regex.PatternSyntaxException => Nil } - } - } - } - - private def isExcludedPath(rel: String, patterns: Seq[java.util.regex.Pattern]): Boolean = { - if (patterns.isEmpty) false - else { - var c = (if (rel == null) "" else rel).replace("\\", "/") - while (c.startsWith("./")) c = c.substring(2) - while (c.startsWith("/")) c = c.substring(1) - while (c.endsWith("/")) c = c.substring(0, c.length - 1) - if (c.isEmpty) false - else patterns.exists(_.matcher(c).matches()) - } - } - - // sbt loads the `.sbt` files in a project's base directory into that project - // (Load.configurationSources), so its build.sbt is the project's even when it sets nothing. - private def baseBuildSbt(base: File, rootCanonPath: java.nio.file.Path): Option[File] = - Some(new File(base, "build.sbt")).filter(f => f.isFile && f.getCanonicalFile.toPath.startsWith(rootCanonPath)) - - // Backslash-escape so a value can never break line/field framing (see records.ts unescape). - private def esc(v: String): String = { - if (v == null) "" - else v.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r") - } -} diff --git a/src/commands/manifest/scripts/test/README.md b/src/commands/manifest/scripts/test/README.md deleted file mode 100644 index abfca26ad0..0000000000 --- a/src/commands/manifest/scripts/test/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Workspace-enumeration compatibility tests - -These exercise the build-tool scripts `socket manifest setup --dynamic-sbom-inference` -still runs itself to list a build's projects without resolving dependencies: -`socket-workspaces.init.gradle`, `socket-workspaces.plugin.scala`, the Maven -extension's `CoanaWorkspacesLifecycleParticipant` and the dotnet tool's -`--workspaces`/`--members` modes. Coana generates the Socket facts themselves. - -Each ecosystem has two suites: `smoke-test-workspaces.sh` asserts the project -records, `smoke-test-exclude-base.sh` scan-root-relative `--exclude-paths`. - -## Run locally, on demand - -There is no CI for this matrix: SocketDev's org action allowlist forbids -`actions/setup-java` and `sbt/setup-sbt`. - -```sh -src/commands/manifest/scripts/test/run-compat.sh [dotnet|gradle|sbt|maven|all] -``` - -- Point `JDK8` / `JDK11` / `JDK17` / `JDK21` at JDK homes to use the right one - per row; otherwise the current `java` is used. The sbt rows need the `sbt` - launcher on `PATH`. -- Gradle and Maven distributions are expected unzipped under - `${SOCKET_COMPAT_CACHE:-${TMPDIR:-/tmp}/socket-manifest-compat}`; the runner - prints the archive URL for any that is missing. -- dotnet rows are SDK versions, each pinned with a `global.json`; install them - side by side under `$SOCKET_COMPAT_CACHE/dotnet` with `dotnet-install.sh`, and - build the tool first (`pnpm run build:dotnet-tool && pnpm build:dist:src`). diff --git a/src/commands/manifest/scripts/test/compat-cache.sh b/src/commands/manifest/scripts/test/compat-cache.sh deleted file mode 100755 index a4e5d6bf4c..0000000000 --- a/src/commands/manifest/scripts/test/compat-cache.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -# Shared cache root for the compat suites: the downloaded build-tool distributions. Point SOCKET_COMPAT_CACHE at a fresh -# `mktemp -d` for a cold run. -SOCKET_COMPAT_CACHE="${SOCKET_COMPAT_CACHE:-${TMPDIR:-/tmp}/socket-manifest-compat}" -mkdir -p "$SOCKET_COMPAT_CACHE" - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/.gitignore b/src/commands/manifest/scripts/test/dotnet-compat/.gitignore deleted file mode 100644 index cd42ee34e8..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -bin/ -obj/ diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/Basic.sln b/src/commands/manifest/scripts/test/dotnet-compat/basic/Basic.sln deleted file mode 100644 index a86f8a93bb..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/Basic.sln +++ /dev/null @@ -1,82 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "App", "src\App\App.csproj", "{5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lib", "src\Lib\Lib.csproj", "{C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{0C88DD14-F956-CE84-757C-A364CCF449FC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "App.Tests", "test\App.Tests\App.Tests.csproj", "{CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nuke", "tools\Nuke\Nuke.csproj", "{5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Debug|x64.ActiveCfg = Debug|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Debug|x64.Build.0 = Debug|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Debug|x86.ActiveCfg = Debug|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Debug|x86.Build.0 = Debug|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Release|Any CPU.Build.0 = Release|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Release|x64.ActiveCfg = Release|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Release|x64.Build.0 = Release|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Release|x86.ActiveCfg = Release|Any CPU - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5}.Release|x86.Build.0 = Release|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Debug|x64.ActiveCfg = Debug|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Debug|x64.Build.0 = Debug|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Debug|x86.ActiveCfg = Debug|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Debug|x86.Build.0 = Debug|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Release|Any CPU.Build.0 = Release|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Release|x64.ActiveCfg = Release|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Release|x64.Build.0 = Release|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Release|x86.ActiveCfg = Release|Any CPU - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82}.Release|x86.Build.0 = Release|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Debug|x64.ActiveCfg = Debug|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Debug|x64.Build.0 = Debug|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Debug|x86.ActiveCfg = Debug|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Debug|x86.Build.0 = Debug|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Release|Any CPU.Build.0 = Release|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Release|x64.ActiveCfg = Release|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Release|x64.Build.0 = Release|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Release|x86.ActiveCfg = Release|Any CPU - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73}.Release|x86.Build.0 = Release|Any CPU - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}.Debug|x64.ActiveCfg = Debug|Any CPU - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}.Debug|x86.ActiveCfg = Debug|Any CPU - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}.Release|x64.ActiveCfg = Release|Any CPU - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA}.Release|x86.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {5BDF8935-F5C4-4E87-BA55-78EE6C4F6BB5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {C8D2A239-CC93-4F79-9D8C-3760DD6FDD82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {CD9C21E4-FA0A-4666-8D23-D1DD08D21E73} = {0C88DD14-F956-CE84-757C-A364CCF449FC} - {5029FD7C-F7DF-4AF4-BC15-ABEA866ADBDA} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} - EndGlobalSection -EndGlobal diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/shared/Linked.cs b/src/commands/manifest/scripts/test/dotnet-compat/basic/shared/Linked.cs deleted file mode 100644 index 584bf18700..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/shared/Linked.cs +++ /dev/null @@ -1 +0,0 @@ -public static class Linked {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/App.csproj b/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/App.csproj deleted file mode 100644 index bfd5b96513..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/App.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - Exenet6.0 - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/Program.cs b/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/Program.cs deleted file mode 100644 index d66ad5d6d3..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/App/Program.cs +++ /dev/null @@ -1 +0,0 @@ -System.Console.WriteLine(new Lib.L()); diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/E.cs b/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/E.cs deleted file mode 100644 index 1eaeed48c1..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/E.cs +++ /dev/null @@ -1 +0,0 @@ -namespace Extra { public class E {} } diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/Extra.csproj b/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/Extra.csproj deleted file mode 100644 index d2609f95d5..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Extra/Extra.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - net6.0 - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/L.cs b/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/L.cs deleted file mode 100644 index d9e3b65f33..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/L.cs +++ /dev/null @@ -1 +0,0 @@ -namespace Lib { public class L {} } diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/Lib.csproj b/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/Lib.csproj deleted file mode 100644 index 2882a672c6..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/src/Lib/Lib.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - net6.0;netstandard2.0Acme.Lib2.3.4 - - - - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/App.Tests.csproj b/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/App.Tests.csproj deleted file mode 100644 index 7e3a303dc5..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/App.Tests.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - net6.0 - - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/T.cs b/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/T.cs deleted file mode 100644 index f3eafb8772..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/test/App.Tests/T.cs +++ /dev/null @@ -1 +0,0 @@ -public class T {} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/Nuke.csproj b/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/Nuke.csproj deleted file mode 100644 index 133e5daa22..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/basic/tools/Nuke/Nuke.csproj +++ /dev/null @@ -1,5 +0,0 @@ - - - net6.0 - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.csproj b/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.csproj deleted file mode 100644 index 3187d81c7c..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - net6.0 - - - - - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.sln b/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.sln deleted file mode 100644 index 35d08ae5de..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/App.sln +++ /dev/null @@ -1,67 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "App", "App.csproj", "{FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "core", "core", "{FBF56CC3-7AE6-AD2D-3F14-7F97FD322CD6}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "core\Core.csproj", "{F926C765-DA26-4E24-BEAE-0204C654BD79}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "..\shared\Shared.csproj", "{C16D86A2-769A-416B-9FF9-452D346804A4}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Debug|x64.ActiveCfg = Debug|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Debug|x64.Build.0 = Debug|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Debug|x86.ActiveCfg = Debug|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Debug|x86.Build.0 = Debug|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Release|Any CPU.Build.0 = Release|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Release|x64.ActiveCfg = Release|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Release|x64.Build.0 = Release|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Release|x86.ActiveCfg = Release|Any CPU - {FD6BBBA4-EC4D-4063-ACAE-BCB726AFA5C1}.Release|x86.Build.0 = Release|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Debug|x64.ActiveCfg = Debug|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Debug|x64.Build.0 = Debug|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Debug|x86.ActiveCfg = Debug|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Debug|x86.Build.0 = Debug|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Release|Any CPU.Build.0 = Release|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Release|x64.ActiveCfg = Release|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Release|x64.Build.0 = Release|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Release|x86.ActiveCfg = Release|Any CPU - {F926C765-DA26-4E24-BEAE-0204C654BD79}.Release|x86.Build.0 = Release|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Debug|x64.ActiveCfg = Debug|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Debug|x64.Build.0 = Debug|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Debug|x86.ActiveCfg = Debug|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Debug|x86.Build.0 = Debug|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Release|Any CPU.Build.0 = Release|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Release|x64.ActiveCfg = Release|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Release|x64.Build.0 = Release|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Release|x86.ActiveCfg = Release|Any CPU - {C16D86A2-769A-416B-9FF9-452D346804A4}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {F926C765-DA26-4E24-BEAE-0204C654BD79} = {FBF56CC3-7AE6-AD2D-3F14-7F97FD322CD6} - EndGlobalSection -EndGlobal diff --git a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/Core.csproj b/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/Core.csproj deleted file mode 100644 index cfcf38198a..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/app/core/Core.csproj +++ /dev/null @@ -1,3 +0,0 @@ - - net6.0 - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/Shared.csproj b/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/Shared.csproj deleted file mode 100644 index cfcf38198a..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/exclude-base/shared/Shared.csproj +++ /dev/null @@ -1,3 +0,0 @@ - - net6.0 - diff --git a/src/commands/manifest/scripts/test/dotnet-compat/lib.sh b/src/commands/manifest/scripts/test/dotnet-compat/lib.sh deleted file mode 100644 index 659bcca30c..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/lib.sh +++ /dev/null @@ -1,35 +0,0 @@ -# shellcheck shell=bash -# Sourced by the dotnet smoke tests after they set HERE and DOTNET. -REPO="$(cd "$HERE/../../../../../.." && pwd)" -TOOL="$REPO/dist/manifest-scripts/dotnet-tool/socket-facts-dotnet.dll" -export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 - -if [ ! -f "$TOOL" ]; then - echo "dotnet tool not built: run pnpm run build:dotnet-tool && pnpm build:dist:src" >&2 - exit 1 -fi - -# Copies the fixture paths $2... (relative to HERE) into $1, without restore -# and build output, so every run starts unrestored. -copy_fixture() { - ( cd "$HERE" && find "${@:2}" -type f \ - -not -path '*/obj/*' -not -path '*/bin/*' -not -path './stub-feed/*' \ - -not -name '*.socket.facts.json' -not -name 'packages.lock.json' \ - -exec sh -c 'mkdir -p "$1/$(dirname "$2")" && cp "$2" "$1/$2"' _ "$1" {} \; ) -} - -# Pins SDK version $2 (if any) with a global.json in $1, as a project would, -# and sets SDK_VERSION to the SDK dotnet then selects there. -pin_sdk() { - if [ -n "${2:-}" ]; then - printf '{"sdk": {"version": "%s", "rollForward": "disable"}}\n' "$2" > "$1/global.json" - fi - SDK_VERSION="$(cd "$1" && "$DOTNET" --version)" -} - -# Runs the tool from directory $1 with the remaining arguments. -run_tool() { - # A preview SDK's MSBuild needs a preview runtime (see run.mts). - ( cd "$1" && case "$SDK_VERSION" in *-*) export DOTNET_ROLL_FORWARD_TO_PRERELEASE=1 ;; esac - "$DOTNET" "$TOOL" --dotnet "$DOTNET" "${@:2}" >/dev/null ) -} diff --git a/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-exclude-base.sh b/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-exclude-base.sh deleted file mode 100755 index c6a403da44..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-exclude-base.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -# --exclude-paths relative to the scan root (--exclude-base), one level above -# the build root: a `../shared` project outside the build root is excluded by -# its scan-root path, and a nested project by the build root's path in the scan -# root, both from the projects --workspaces follows and from the solution -# members --members lists. A project outside the scan root is never excluded, -# even by a wildcard that would match its `../` path. -# -# Usage: smoke-test-exclude-base.sh [sdk-version] -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -DOTNET="${1:?usage: smoke-test-exclude-base.sh [sdk-version]}" -SDK="${2:-}" -# shellcheck source=SCRIPTDIR/lib.sh -. "$HERE/lib.sh" - -WORK="$(mktemp -d)" -trap 'rm -rf "$WORK"' EXIT -copy_fixture "$WORK" exclude-base -SCAN_ROOT="$(cd "$WORK/exclude-base" && pwd -P)" -pin_sdk "$SCAN_ROOT" "$SDK" -echo "+ dotnet SDK $SDK_VERSION (exclude base)" - -# The project names --workspaces keeps, or the member paths --members lists. -kept() { - local mode="$1" entry="$2" pattern="$3" base="${4:-$SCAN_ROOT}" - rm -f "$WORK/records.tsv" - run_tool "$SCAN_ROOT/app" --records "$WORK/records.tsv" --entry "$entry" \ - "--$mode" --exclude-paths "$pattern" --exclude-base "$base" - # A run that wrote no records keeps nothing, which check reports. - [ -f "$WORK/records.tsv" ] || return 0 - if [ "$mode" = workspaces ]; then - awk -F'\t' '$1 == "project" { print $4 }' "$WORK/records.tsv" - else - awk -F'\t' '$1 == "member" { print $2 }' "$WORK/records.tsv" - fi | LC_ALL=C sort | tr '\n' ' ' -} -check() { - local got - got="$(kept "$1" "$2" "$3" "${5:-}")" - if [ "$got" != "$4" ]; then - echo "FAIL: --$1 of $2 excluding $3 from ${5:-$SCAN_ROOT} kept [$got], want [$4]" >&2 - exit 1 - fi -} -check workspaces App.csproj '^(?:shared)(?:/.*)?$' 'App Core ' -check workspaces App.csproj '^(?:app/core)(?:/.*)?$' 'App Shared ' -# Build-root-relative, so it names nothing under the scan root. -check workspaces App.csproj '^(?:core)(?:/.*)?$' 'App Core Shared ' -check members App.sln '^(?:shared)(?:/.*)?$' 'App.csproj core/Core.csproj ' -check members App.sln '^(?:app/core)(?:/.*)?$' '../shared/Shared.csproj App.csproj ' -check members App.sln '^(?:core)(?:/.*)?$' '../shared/Shared.csproj App.csproj core/Core.csproj ' -# `**/shared`, scanned from app: ../shared is outside the scan root. -check workspaces App.csproj '^(?:(?:[^/]+/)*shared)(?:/.*)?$' 'App Core Shared ' "$SCAN_ROOT/app" -check members App.sln '^(?:(?:[^/]+/)*shared)(?:/.*)?$' '../shared/Shared.csproj App.csproj core/Core.csproj ' "$SCAN_ROOT/app" -echo "PASS: projects are excluded by their scan-root paths, never outside the scan root" diff --git a/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-workspaces.sh deleted file mode 100755 index c3c45a7812..0000000000 --- a/src/commands/manifest/scripts/test/dotnet-compat/smoke-test-workspaces.sh +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env bash -# Runs the dotnet tool's listing modes on the basic solution with one .NET SDK -# and asserts they evaluate projects without restoring anything: --workspaces -# lists the solution's built members and the projects they reference (an inner -# build's too), --members only the built members, minus --exclude-paths. -# -# Usage: smoke-test-workspaces.sh [sdk-version] -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -DOTNET="${1:?usage: smoke-test-workspaces.sh [sdk-version]}" -SDK="${2:-}" -# shellcheck source=SCRIPTDIR/lib.sh -. "$HERE/lib.sh" - -WORK="$(mktemp -d)" -trap 'rm -rf "$WORK"' EXIT -copy_fixture "$WORK" basic -pin_sdk "$WORK" "$SDK" -echo "+ dotnet SDK $SDK_VERSION (workspaces)" - -tool() { - run_tool "$WORK/basic" --records "$WORK/$1.tsv" --entry Basic.sln "${@:2}" -} -tool workspaces --workspaces -tool members --members -tool members-excluded --members --exclude-paths '^(?:test)(?:/.*)?$' - -python3 - "$WORK" <<'PY' -import os, sys -work = sys.argv[1] -errors = [] -def rows(name): - return [l.rstrip('\n').split('\t') for l in open(os.path.join(work, name + '.tsv')) if l.strip()] -def check(name, allowed, kind, expected): - got = [] - for r in rows(name): - if r[0] not in allowed: - errors.append(f"{name}: unexpected record kind {r[0]!r}; listing never restores") - elif r[0] == kind: - got.append(r[1] if kind == 'member' else (r[1], r[3])) - if sorted(got) != sorted(expected): - errors.append(f"{name}: {kind} records {sorted(got)} != {sorted(expected)}") - -# Nuke is in the solution but not built by its active configuration. -check('workspaces', {'meta', 'buildRoot', 'entry', 'project', 'projectBuild'}, 'project', [ - ('src/App/App.csproj', 'App'), - ('src/Lib/Lib.csproj', 'Acme.Lib'), - ('test/App.Tests/App.Tests.csproj', 'App.Tests'), - # Referenced only by Lib's net6.0 inner build. - ('src/Extra/Extra.csproj', 'Extra'), -]) -builds = {(r[1], r[2]) for r in rows('workspaces') if r[0] == 'projectBuild'} -for key in ('src/App/App.csproj', 'src/Lib/Lib.csproj', 'test/App.Tests/App.Tests.csproj', 'src/Extra/Extra.csproj'): - if (key, key) not in builds: - errors.append(f"workspaces: {key} has no projectBuild record of its own file") -check('members', {'meta', 'buildRoot', 'entry', 'member'}, 'member', - ['src/App/App.csproj', 'src/Lib/Lib.csproj', 'test/App.Tests/App.Tests.csproj']) -check('members-excluded', {'meta', 'buildRoot', 'entry', 'member'}, 'member', - ['src/App/App.csproj', 'src/Lib/Lib.csproj']) -if any('obj' in dirs for _, dirs, _ in os.walk(os.path.join(work, 'basic'))): - errors.append("an obj/ directory was written; listing must not restore") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print("PASS: listings evaluate the solution's built projects without restoring") -PY diff --git a/src/commands/manifest/scripts/test/gradle-compat/.gitignore b/src/commands/manifest/scripts/test/gradle-compat/.gitignore deleted file mode 100644 index 4369ca91c7..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Generated at test time. -project/workspaces-records.tsv -project/.gradle/ -project/build/ diff --git a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/build.gradle deleted file mode 100644 index c76d5a512e..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/build.gradle +++ /dev/null @@ -1 +0,0 @@ -// Aggregator only. diff --git a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/build.gradle deleted file mode 100644 index a26022f97e..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/core/build.gradle +++ /dev/null @@ -1 +0,0 @@ -// No dependencies. diff --git a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/settings.gradle b/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/settings.gradle deleted file mode 100644 index b787f45107..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/app/settings.gradle +++ /dev/null @@ -1,4 +0,0 @@ -rootProject.name = 'exclude-base' -include 'core', 'shared' -// A project outside the build root. -project(':shared').projectDir = file('../shared') diff --git a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/build.gradle deleted file mode 100644 index a26022f97e..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/exclude-base/shared/build.gradle +++ /dev/null @@ -1 +0,0 @@ -// No dependencies. diff --git a/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle b/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle deleted file mode 100644 index b14a29e089..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/project/build.gradle +++ /dev/null @@ -1,4 +0,0 @@ -// Smoke project for ../../socket-workspaces.init.gradle. -apply plugin: 'java' -group = 'demo' -version = '1.0.0' diff --git a/src/commands/manifest/scripts/test/gradle-compat/project/settings.gradle b/src/commands/manifest/scripts/test/gradle-compat/project/settings.gradle deleted file mode 100644 index d4408b64f3..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/project/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'gradle-compat-smoke' diff --git a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-exclude-base.sh b/src/commands/manifest/scripts/test/gradle-compat/smoke-test-exclude-base.sh deleted file mode 100755 index 1eb0d9b266..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-exclude-base.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# --exclude-paths relative to the scan root (-Psocket.excludeBase), one level above the build root: -# a project relocated outside the build root is excluded by its scan-root path, and a nested one -# by the build root's path in the scan root. A project outside the scan root is never excluded, -# even by a wildcard that would match its `../` path. -# -# Usage: smoke-test-exclude-base.sh /path/to/gradle -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -GRADLE="${1:?usage: smoke-test-exclude-base.sh }" -INIT="$HERE/../../socket-workspaces.init.gradle" -SCAN_ROOT="$(cd "$HERE/exclude-base" && pwd -P)" -OUT="$(mktemp -d)" -trap 'rm -rf "$OUT" "$SCAN_ROOT/app/.gradle"' EXIT - -echo "+ $("$GRADLE" --version 2>/dev/null | sed -n 's/^Gradle //p' | head -1) (exclude base)" -projects() { - rm -f "$OUT/records.tsv" - ( cd "$SCAN_ROOT/app" && "$GRADLE" --no-daemon --offline -g "$OUT/gradle-home" \ - --init-script "$INIT" -Psocket.recordsFile="$OUT/records.tsv" \ - "-Psocket.excludePaths=$1" "-Psocket.excludeBase=${2:-$SCAN_ROOT}" socketWorkspaces -q >&2 ) - # A build that wrote no records keeps nothing, which check reports. - [ -f "$OUT/records.tsv" ] || return 0 - awk -F'\t' '$1 == "project" { print $2 }' "$OUT/records.tsv" | sort | tr '\n' ' ' -} -check() { - local got - got="$(projects "$1" "${3:-}")" - if [ "$got" != "$2" ]; then - echo "FAIL: excluding $1 from ${3:-$SCAN_ROOT} kept [$got], want [$2]" >&2 - exit 1 - fi -} -check '^(?:shared)(?:/.*)?$' ': :core ' -check '^(?:app/core)(?:/.*)?$' ': :shared ' -# `**/shared`, scanned from app: ../shared is outside the scan root. -check '^(?:(?:[^/]+/)*shared)(?:/.*)?$' ': :core :shared ' "$SCAN_ROOT/app" -echo "PASS: projects are excluded by their scan-root paths, never outside the scan root" diff --git a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh deleted file mode 100755 index 870bdc4342..0000000000 --- a/src/commands/manifest/scripts/test/gradle-compat/smoke-test-workspaces.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env bash -# Run socket-workspaces.init.gradle against the smoke project and assert it emits exactly the -# expected project record - no dependency resolution, no node/root/file records at all. Guards, -# across the Gradle compat matrix, that the socketWorkspaces task registers and runs cleanly. -# -# Usage: smoke-test-workspaces.sh /path/to/gradle -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -GRADLE="${1:?usage: smoke-test-workspaces.sh }" -INIT="$HERE/../../socket-workspaces.init.gradle" -PROJECT="$HERE/project" -GUH="$HERE/.gradle-home" # isolated Gradle user home -> hermetic, no global init scripts -RECORDS="$PROJECT/workspaces-records.tsv" - -rm -rf "$GUH" "$RECORDS" "$PROJECT/.gradle" "$PROJECT/build" - -echo "+ $("$GRADLE" --version 2>/dev/null | sed -n 's/^Gradle //p' | head -1) (workspaces)" -( cd "$PROJECT" && "$GRADLE" --no-daemon --offline -g "$GUH" \ - --init-script "$INIT" -Psocket.recordsFile="$RECORDS" socketWorkspaces -q ) - -python3 - "$RECORDS" "$(cd "$PROJECT" && pwd -P)" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -errors = [] -tool = None -build_root = None -projects = [] -build_files = set() -for r in rows: - if r[0] == 'meta': - tool = r[1] - elif r[0] == 'buildRoot': - build_root = r[1] - elif r[0] == 'project': - projects.append(r) - elif r[0] == 'projectBuild': - build_files.add((r[1], r[2])) - else: - errors.append(f"unexpected record kind {r[0]!r} - workspaces must never resolve dependencies") - -if tool != 'gradle': - errors.append(f"meta tool {tool!r} != 'gradle'") -if build_root != sys.argv[2]: - errors.append(f"buildRoot {build_root!r} != {sys.argv[2]!r}") -if build_files != {(':', 'build.gradle')}: - errors.append(f"projectBuild records {sorted(build_files)} != [(':', 'build.gradle')]") -if len(projects) != 1: - errors.append(f"expected exactly 1 project record, got {len(projects)}: {projects}") -else: - _, path, group, name, _version, dir_ = projects[0] - if path != ':': errors.append(f"root project path {path!r} != ':'") - if group != 'demo': errors.append(f"root project group {group!r} != 'demo'") - if name != 'gradle-compat-smoke': errors.append(f"root project name {name!r} != 'gradle-compat-smoke'") - if dir_ != '.': errors.append(f"root project dir {dir_!r} != '.'") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print("PASS: tool=gradle; 1 project record with its build file, no dependency-resolution records") -PY diff --git a/src/commands/manifest/scripts/test/maven-compat/.gitignore b/src/commands/manifest/scripts/test/maven-compat/.gitignore deleted file mode 100644 index 8caaf77173..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Generated at test time. -project/workspaces-records.tsv -project/target/ -project/*/target/ diff --git a/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/pom.xml b/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/pom.xml deleted file mode 100644 index 197f06f8ab..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/core/pom.xml +++ /dev/null @@ -1,11 +0,0 @@ - - 4.0.0 - - demo - app - 1.0 - ../pom.xml - - core - pom - diff --git a/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/pom.xml b/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/pom.xml deleted file mode 100644 index 06e5a0a30c..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/exclude-base/app/pom.xml +++ /dev/null @@ -1,12 +0,0 @@ - - 4.0.0 - demo - app - 1.0 - pom - - core - - ../shared - - diff --git a/src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/pom.xml b/src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/pom.xml deleted file mode 100644 index 516382e76e..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/exclude-base/shared/pom.xml +++ /dev/null @@ -1,11 +0,0 @@ - - 4.0.0 - - demo - app - 1.0 - ../app/pom.xml - - shared - pom - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml deleted file mode 100644 index 0a0161cc74..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/app/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 4.0.0 - - demo - root - 1.0 - - app - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml deleted file mode 100644 index f16c76bf3b..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/lib/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 4.0.0 - - demo - root - 1.0 - - lib - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml deleted file mode 100644 index c835d62bf7..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/mid/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 4.0.0 - - demo - root - 1.0 - - mid - diff --git a/src/commands/manifest/scripts/test/maven-compat/project/pom.xml b/src/commands/manifest/scripts/test/maven-compat/project/pom.xml deleted file mode 100644 index e1cf2d9cc8..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/project/pom.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - 4.0.0 - demo - root - 1.0 - pom - - lib - mid - app - - diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-exclude-base.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-exclude-base.sh deleted file mode 100755 index 96f564a348..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-exclude-base.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash -# --exclude-paths relative to the scan root (-Dsocket.excludeBase), one level above the build root: -# a `../shared` outside the build root is excluded by its scan-root path, and a -# nested module by the build root's path in the scan root. A module outside the scan root is never -# excluded, even by a wildcard that would match its `../` path. -# -# Usage: smoke-test-exclude-base.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-exclude-base.sh }" -JAR="${2:?usage: smoke-test-exclude-base.sh }" -SCAN_ROOT="$(cd "$HERE/exclude-base" && pwd -P)" -OUT="$(mktemp -d)" -trap 'rm -rf "$OUT" "$SCAN_ROOT"/app/target "$SCAN_ROOT"/app/core/target "$SCAN_ROOT"/shared/target' EXIT - -echo "+ $("$MVN" -v 2>/dev/null | head -1) (exclude base)" -modules() { - rm -f "$OUT/records.tsv" - ( cd "$SCAN_ROOT/app" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-workspaces \ - "-Dsocket.recordsFile=$OUT/records.tsv" \ - "-Dsocket.excludePaths=$1" "-Dsocket.excludeBase=${2:-$SCAN_ROOT}" \ - validate >&2 ) - # A build that wrote no records keeps nothing, which check reports. - [ -f "$OUT/records.tsv" ] || return 0 - awk -F'\t' '$1 == "project" { print $4 }' "$OUT/records.tsv" | sort | tr '\n' ' ' -} -check() { - local got - got="$(modules "$1" "${3:-}")" - if [ "$got" != "$2" ]; then - echo "FAIL: excluding $1 from ${3:-$SCAN_ROOT} kept [$got], want [$2]" >&2 - exit 1 - fi -} -check '^(?:shared)(?:/.*)?$' 'app core ' -check '^(?:app/core)(?:/.*)?$' 'app shared ' -# `**/shared`, scanned from app: ../shared is outside the scan root. -check '^(?:(?:[^/]+/)*shared)(?:/.*)?$' 'app core shared ' "$SCAN_ROOT/app" -echo "PASS: modules are excluded by their scan-root paths, never outside the scan root" diff --git a/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh deleted file mode 100755 index e011e03326..0000000000 --- a/src/commands/manifest/scripts/test/maven-compat/smoke-test-workspaces.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bash -# Load the Coana Maven workspaces participant (CoanaWorkspacesLifecycleParticipant) on a given -# Maven binary and assert it emits exactly the expected reactor project records - no dependency -# graph at all. Guards, across the Maven compat matrix, that the participant registers and fires -# correctly. -# -# Usage: smoke-test-workspaces.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -MVN="${1:?usage: smoke-test-workspaces.sh }" -JAR="${2:?usage: smoke-test-workspaces.sh }" -PROJECT="$HERE/project" -RECORDS="$PROJECT/workspaces-records.tsv" - -rm -rf "$RECORDS" "$PROJECT"/*/target "$PROJECT"/target - -echo "+ $("$MVN" -v 2>/dev/null | head -1) (workspaces)" -( cd "$PROJECT" && "$MVN" --batch-mode -q \ - "-Dmaven.ext.class.path=$JAR" \ - -Dcoana.task=socket-workspaces \ - "-Dsocket.recordsFile=$RECORDS" \ - validate ) - -python3 - "$RECORDS" "$(cd "$PROJECT" && pwd -P)" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -errors = [] -tool = None -build_root = None -projects = {} -build_files = set() -for r in rows: - if r[0] == 'meta': - tool = r[1] - elif r[0] == 'buildRoot': - build_root = r[1] - elif r[0] == 'project': - projects[r[3]] = r # keyed by artifactId - elif r[0] == 'projectBuild': - build_files.add(r[2]) - else: - errors.append(f"unexpected record kind {r[0]!r} - workspaces must never resolve dependencies") - -if tool != 'maven': - errors.append(f"meta tool {tool!r} != 'maven'") -if build_root != sys.argv[2]: - errors.append(f"buildRoot {build_root!r} != {sys.argv[2]!r}") -expected_build_files = {'pom.xml', 'lib/pom.xml', 'mid/pom.xml', 'app/pom.xml'} -if build_files != expected_build_files: - errors.append(f"projectBuild files {sorted(build_files)} != {sorted(expected_build_files)}") -expected = {'root', 'lib', 'mid', 'app'} -if set(projects) != expected: - errors.append(f"expected reactor modules {sorted(expected)}, got {sorted(projects)}") -for artifact in expected & set(projects): - group = projects[artifact][2] - if group != 'demo': - errors.append(f"{artifact} group {group!r} != 'demo'") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print(f"PASS: tool=maven; reactor modules {sorted(projects)}, no dependency-resolution records") -PY diff --git a/src/commands/manifest/scripts/test/run-compat.sh b/src/commands/manifest/scripts/test/run-compat.sh deleted file mode 100755 index 72f53cb646..0000000000 --- a/src/commands/manifest/scripts/test/run-compat.sh +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env bash -# Run the workspace-enumeration compatibility matrix LOCALLY, on demand. -# -# GitHub Actions can't run this: SocketDev's org action allowlist forbids -# `actions/setup-java` and `sbt/setup-sbt`, so the build-tool matrix has no CI -# home. Run this whenever you change socket-workspaces.init.gradle, -# socket-workspaces.plugin.scala, the Maven extension or the dotnet tool's -# workspaces mode. -# -# JDKs: the matrix needs several Java versions (a row's required major is shown -# per run). Point JDK8 / JDK11 / JDK17 / JDK21 at JDK homes to use the right one -# per row; otherwise the current `java` is used (fine if it can run that tool). -# sbt rows additionally need the `sbt` launcher on PATH. -# -# dotnet rows need the SDKs installed side by side under $CACHE/dotnet (each row -# pins its SDK with a global.json), plus a built CLI with the dotnet tool -# (pnpm run build:dotnet-tool && pnpm build:dist:src). -# -# Usage: run-compat.sh [dotnet|gradle|sbt|maven|all] (default: all) -set -euo pipefail - -HERE="$(cd "$(dirname "$0")" && pwd)" -TOOL="${1:-all}" -# shellcheck source=SCRIPTDIR/compat-cache.sh -. "$HERE/compat-cache.sh" -CACHE="$SOCKET_COMPAT_CACHE" - -# Rows: " [scala]". -GRADLE_MATRIX=("1.12 8" "2.14.1 8" "3.3 8" "6.2.2 8" "8.10.2 17" "9.2.1 21") -# The Maven rows span the range the extension claims to support (see maven-extension/pom.xml). -MAVEN_MATRIX=("3.2.5 8" "3.6.3 11" "3.8.8 17" "3.9.9 17" "4.0.0-rc-6 21") -# One SDK per supported major. -DOTNET_MATRIX=("6.0.428" "7.0.410" "8.0.414" "9.0.315" "10.0.301" "11.0.100-rc.3.26522.148") -SBT_MATRIX=("0.13.18 8 2.10.7" "1.4.9 11 2.12.20" "1.6.2 17 2.12.20" "1.9.9 17 2.12.20") - -# Select a JDK for the given Java major: use $JDK if set, else current java. -use_jdk() { - local home_var="JDK$1" - local home="${!home_var:-}" - if [ -n "$home" ]; then - export JAVA_HOME="$home" - # The sbt launcher runs `java` from PATH and ignores JAVA_HOME. - export PATH="$home/bin:$PATH" - echo " JDK $1: $home" - else - echo " JDK $1 not provided (set $home_var= for fidelity); using current java" - unset JAVA_HOME || true - fi -} - -run_dotnet() { - local dotnet="$CACHE/dotnet/dotnet" - for sdk in "${DOTNET_MATRIX[@]}"; do - echo "== dotnet SDK $sdk ==" - if ! "$dotnet" --list-sdks 2>/dev/null | grep -q "^$sdk "; then - # SDK downloads stay out of this committed script (fleet CDN allowlist). - echo "dotnet SDK $sdk not found under $CACHE/dotnet." >&2 - echo "Fix: bash dotnet-install.sh --version $sdk --install-dir $CACHE/dotnet (https://dot.net/v1/dotnet-install.sh)" >&2 - exit 1 - fi - bash "$HERE/dotnet-compat/smoke-test-workspaces.sh" "$dotnet" "$sdk" - bash "$HERE/dotnet-compat/smoke-test-exclude-base.sh" "$dotnet" "$sdk" - done -} - -run_gradle() { - for row in "${GRADLE_MATRIX[@]}"; do - # shellcheck disable=SC2086 - set -- $row - local ver="$1" java="$2" - echo "== gradle $ver (wants JDK $java) ==" - use_jdk "$java" - local dir="$CACHE/gradle-$ver" - if [ ! -x "$dir/bin/gradle" ]; then - # Distribution downloads stay out of this committed script (fleet CDN - # allowlist); the operator fetches the archive once into the cache. - echo "gradle $ver not found at $dir/bin/gradle." >&2 - echo "Fix: download https://services.gradle.org/distributions/gradle-$ver-bin.zip and unzip it into $CACHE" >&2 - exit 1 - fi - bash "$HERE/gradle-compat/smoke-test-workspaces.sh" "$dir/bin/gradle" - bash "$HERE/gradle-compat/smoke-test-exclude-base.sh" "$dir/bin/gradle" - done -} - -run_maven() { - echo "== building the Maven extension jar ==" - bash "$HERE/../maven-extension/build-jar.sh" - local jar="$HERE/../maven-extension/coana-maven-extension.jar" - for row in "${MAVEN_MATRIX[@]}"; do - # shellcheck disable=SC2086 - set -- $row - local ver="$1" java="$2" - echo "== maven $ver (wants JDK $java) ==" - use_jdk "$java" - local dir="$CACHE/apache-maven-$ver" - if [ ! -x "$dir/bin/mvn" ]; then - # Distribution downloads stay out of this committed script (fleet CDN - # allowlist); the operator fetches the archive once into the cache. - local line="maven-${ver%%.*}" - echo "maven $ver not found at $dir/bin/mvn." >&2 - echo "Fix: download https://archive.apache.org/dist/maven/$line/$ver/binaries/apache-maven-$ver-bin.zip and unzip it into $CACHE" >&2 - exit 1 - fi - bash "$HERE/maven-compat/smoke-test-workspaces.sh" "$dir/bin/mvn" "$jar" - bash "$HERE/maven-compat/smoke-test-exclude-base.sh" "$dir/bin/mvn" "$jar" - done -} - -run_sbt() { - if ! command -v sbt >/dev/null 2>&1; then - echo "sbt launcher not found on PATH; install it (e.g. 'brew install sbt' or coursier) to run the sbt matrix" >&2 - return 1 - fi - for row in "${SBT_MATRIX[@]}"; do - # shellcheck disable=SC2086 - set -- $row - local ver="$1" java="$2" scala="$3" - echo "== sbt $ver / scala $scala (wants JDK $java) ==" - use_jdk "$java" - bash "$HERE/sbt-compat/smoke-test-workspaces.sh" "$ver" "$scala" - bash "$HERE/sbt-compat/smoke-test-exclude-base.sh" "$ver" "$scala" - done -} - -case "$TOOL" in - dotnet) run_dotnet ;; - gradle) run_gradle ;; - maven) run_maven ;; - sbt) run_sbt ;; - all) - run_dotnet - run_gradle - run_maven - run_sbt - ;; - *) - echo "usage: run-compat.sh [dotnet|gradle|sbt|maven|all]" >&2 - exit 1 - ;; -esac - -echo "compat matrix passed: $TOOL" diff --git a/src/commands/manifest/scripts/test/sbt-compat/.gitignore b/src/commands/manifest/scripts/test/sbt-compat/.gitignore deleted file mode 100644 index 90ea570bb9..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -# Generated at test time. -project/target/ -project/project/ -project/scala-version.sbt -project/workspaces-records.tsv diff --git a/src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/build.sbt b/src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/build.sbt deleted file mode 100644 index d90ea369ac..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/exclude-base/app/build.sbt +++ /dev/null @@ -1,2 +0,0 @@ -lazy val core = project -lazy val root = (project in file(".")).aggregate(core) diff --git a/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt b/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt deleted file mode 100644 index 7f63095479..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/project/build.sbt +++ /dev/null @@ -1,14 +0,0 @@ -// Smoke project for ../../socket-workspaces.plugin.scala. The `in ThisBuild` form parses on sbt 0.13 -// and 1.x; smoke-test-workspaces.sh sets scalaVersion per matrix entry. -organization in ThisBuild := "demo" -version in ThisBuild := "0.1.0" - -lazy val root = (project in file(".")) - .settings( - name := "sbt-compat-smoke", - // sbt 0.13's default chain otherwise hits slow or dead Ivy repos. - resolvers := Seq( - "Ivy Releases" at "https://scala.jfrog.io/artifactory/ivy-releases/", - "Maven Central" at "https://repo1.maven.org/maven2/" - ) ++ resolvers.value - ) diff --git a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-exclude-base.sh b/src/commands/manifest/scripts/test/sbt-compat/smoke-test-exclude-base.sh deleted file mode 100755 index 6c05f80527..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-exclude-base.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash -# --exclude-paths relative to the scan root (-Dsocket.excludeBase), one level above the build root: -# a subproject is excluded by its scan-root path, not its build-root one. sbt refuses projects -# outside the build root, so only the nested case exists. -# -# Usage: smoke-test-exclude-base.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -SBT_VERSION="${1:?usage: smoke-test-exclude-base.sh }" -SCALA_VERSION="${2:?usage: smoke-test-exclude-base.sh }" -PLUGIN="$HERE/../../socket-workspaces.plugin.scala" -SCAN_ROOT="$(cd "$HERE/exclude-base" && pwd -P)" -PROJECT="$SCAN_ROOT/app" -OUT="$(mktemp -d)" -trap 'rm -rf "$OUT" "$PROJECT/project" "$PROJECT/target" "$PROJECT/core" "$PROJECT/scala-version.sbt"' EXIT - -mkdir -p "$OUT/global-base/plugins" "$PROJECT/project" -cp "$PLUGIN" "$OUT/global-base/plugins/SocketWorkspacesPlugin.scala" -echo "sbt.version=$SBT_VERSION" > "$PROJECT/project/build.properties" -echo "scalaVersion in ThisBuild := \"$SCALA_VERSION\"" > "$PROJECT/scala-version.sbt" - -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (exclude base)" -projects() { - rm -f "$OUT/records.tsv" - ( cd "$PROJECT" && sbt -Dsbt.global.base="$OUT/global-base" -Dsbt.server.autostart=false \ - "-Dsocket.recordsFile=$OUT/records.tsv" \ - "-Dsocket.excludePaths=$1" "-Dsocket.excludeBase=$SCAN_ROOT" --batch socketWorkspaces >&2 ) - # A build that wrote no records keeps nothing, which check reports. - [ -f "$OUT/records.tsv" ] || return 0 - awk -F'\t' '$1 == "project" { print $2 }' "$OUT/records.tsv" | sort | tr '\n' ' ' -} -check() { - local got - got="$(projects "$1")" - if [ "$got" != "$2" ]; then - echo "FAIL: excluding $1 kept [$got], want [$2]" >&2 - exit 1 - fi -} -check '^(?:app/core)(?:/.*)?$' 'root ' -# Build-root-relative, so it names nothing under the scan root. -check '^(?:core)(?:/.*)?$' 'core root ' -echo "PASS: subprojects are excluded by their scan-root paths" diff --git a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh b/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh deleted file mode 100755 index a4f68cf5f8..0000000000 --- a/src/commands/manifest/scripts/test/sbt-compat/smoke-test-workspaces.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env bash -# Run socket-workspaces.plugin.scala against the smoke project on a given sbt version and assert it -# emits exactly the expected project record - no dependency resolution at all. Guards, across the -# sbt/scala compat matrix, that SocketWorkspacesPlugin registers and runs. -# -# The plugin is activated exactly as run.ts does it: dropped into a fresh sbt global base's plugins/. -# Usage: smoke-test-workspaces.sh -set -euo pipefail -HERE="$(cd "$(dirname "$0")" && pwd)" -SBT_VERSION="${1:?usage: smoke-test-workspaces.sh }" -SCALA_VERSION="${2:?usage: smoke-test-workspaces.sh }" -PLUGIN="$HERE/../../socket-workspaces.plugin.scala" -PROJECT="$HERE/project" -RECORDS="$PROJECT/workspaces-records.tsv" - -GB="$(mktemp -d)/global-base" -mkdir -p "$GB/plugins" -cp "$PLUGIN" "$GB/plugins/SocketWorkspacesPlugin.scala" - -# Pin the sbt + scala versions for this matrix entry (the launcher downloads the sbt version). -# `project/` (the meta-build dir) is an empty dir in git, so it's absent on a fresh checkout. -mkdir -p "$PROJECT/project" -echo "sbt.version=$SBT_VERSION" > "$PROJECT/project/build.properties" -echo "scalaVersion in ThisBuild := \"$SCALA_VERSION\"" > "$PROJECT/scala-version.sbt" -rm -rf "$RECORDS" "$PROJECT/target" "$PROJECT/project/target" - -echo "+ sbt $SBT_VERSION (scala $SCALA_VERSION) (workspaces)" -( cd "$PROJECT" && sbt -Dsbt.global.base="$GB" -Dsbt.server.autostart=false \ - -Dsocket.recordsFile="$RECORDS" --batch socketWorkspaces ) - -python3 - "$RECORDS" "$SCALA_VERSION" "$(cd "$PROJECT" && pwd -P)" <<'PY' -import sys -rows = [l.rstrip('\n').split('\t') for l in open(sys.argv[1]) if l.strip()] -# CrossVersion.apply appends _ (major.minor) to the artifact name. -binary_version = '.'.join(sys.argv[2].split('.')[:2]) -expected_name = f"sbt-compat-smoke_{binary_version}" -errors = [] -tool = None -build_root = None -projects = [] -build_files = set() -for r in rows: - if r[0] == 'meta': - tool = r[1] - elif r[0] == 'buildRoot': - build_root = r[1] - elif r[0] == 'project': - projects.append(r) - elif r[0] == 'projectBuild': - build_files.add(r[2]) - else: - errors.append(f"unexpected record kind {r[0]!r} - workspaces must never resolve dependencies") - -if tool != 'sbt': - errors.append(f"meta tool {tool!r} != 'sbt'") -if build_root != sys.argv[3]: - errors.append(f"buildRoot {build_root!r} != {sys.argv[3]!r}") -if build_files != {'build.sbt'}: - errors.append(f"projectBuild files {sorted(build_files)} != ['build.sbt']") -if len(projects) != 1: - errors.append(f"expected exactly 1 project record, got {len(projects)}: {projects}") -else: - _, _ref, org, name, _ver, dir_ = projects[0] - if org != 'demo': errors.append(f"root project org {org!r} != 'demo'") - if name != expected_name: errors.append(f"root project name {name!r} != {expected_name!r}") - if dir_ != '.': errors.append(f"root project dir {dir_!r} != '.'") - -if errors: - print("FAIL:") - for e in errors: print(" -", e) - sys.exit(1) -print("PASS: tool=sbt; 1 project record with its build file, no dependency-resolution records") -PY diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index d8dffe7c49..4056692ebb 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -12,8 +12,9 @@ vi.mock('./discover-manifest-roots.mts', async importOriginal => { findBuildToolCandidates: vi.fn(actual.findBuildToolCandidates), } }) -vi.mock('./enumerate-workspaces.mts', () => ({ - enumerateWorkspaces: vi.fn(), +vi.mock('./run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal()), + listBuildProjects: vi.fn(), })) vi.mock('@socketsecurity/registry/lib/prompts', () => ({ select: vi.fn(), @@ -29,7 +30,7 @@ import { logger } from '@socketsecurity/registry/lib/logger' import { select } from '@socketsecurity/registry/lib/prompts' import { findBuildToolCandidates } from './discover-manifest-roots.mts' -import { enumerateWorkspaces } from './enumerate-workspaces.mts' +import { listBuildProjects } from './run-manifest-facts.mts' import { setupMaven } from './setup-manifest-config.mts' import { discoverBuildRoots, @@ -38,7 +39,7 @@ import { } from './setup-recursive-manifest-config.mts' import type { BuildRoot } from './discover-manifest-roots.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' +import type { SocketFactsProject } from './run-manifest-facts.mts' import type { SocketJson } from '../../utils/socket-json.mts' function dirRoots(...dirs: string[]): BuildRoot[] { @@ -49,15 +50,14 @@ function mavenRoots(...dirs: string[]): BuildRoot[] { return dirs.map(dir => ({ dir, entryFile: 'pom.xml' })) } -function project(subprojectDir: string): SocketFactsSbomProject { - return { - type: 'maven', - name: subprojectDir, - id: subprojectDir, - subprojectDir, - manifestFiles: [{ file: `${subprojectDir}/pom.xml` }], - children: [], - } +// A Maven project of the build at `buildRoot`, loaded from `pomFile`. +function project( + buildRoot: string, + subprojectDir: string, + pomFile = 'pom.xml', +): SocketFactsProject { + const dir = path.resolve(buildRoot, subprojectDir) + return { buildFiles: [path.join(dir, pomFile)], dir } } describe('scanBuildRoots', () => { @@ -182,22 +182,16 @@ describe('setupRecursiveManifestConfig', () => { // listed as undefined can't be loaded. const loads = (modules: Record) => vi - .mocked(enumerateWorkspaces) + .mocked(listBuildProjects) .mockImplementation(async ({ cwd, entryFile }) => { const rel = path.relative(repo, path.join(cwd, entryFile ?? '')) if (rel in modules && !modules[rel]) { return undefined } - return { - buildRoot: cwd, - projects: [ - { - ...project('.'), - manifestFiles: [{ file: entryFile ?? 'pom.xml' }], - }, - ...(modules[rel] ?? []).map(project), - ], - } + return [ + project(cwd, '.', entryFile), + ...(modules[rel] ?? []).map(dir => project(cwd, dir)), + ] }) const answer = (answers: Answers) => vi.mocked(select).mockImplementation(async ({ choices, message }) => { @@ -228,7 +222,7 @@ describe('setupRecursiveManifestConfig', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(file(rel), '') } - vi.mocked(enumerateWorkspaces).mockReset() + vi.mocked(listBuildProjects).mockReset() vi.mocked(setupMaven).mockReset() vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) @@ -321,11 +315,11 @@ describe('setupRecursiveManifestConfig', () => { it('loads a build again after configuring it, and skips it once it loads', async () => { let attempts = 0 - vi.mocked(enumerateWorkspaces).mockImplementation(async ({ cwd }) => { + vi.mocked(listBuildProjects).mockImplementation(async ({ cwd }) => { if (cwd === file('legacy') && (attempts += 1) === 1) { return undefined } - return { buildRoot: cwd, projects: [project('.')] } + return [project(cwd, '.')] }) vi.mocked(setupMaven).mockImplementation(async config => { config.javaHome = '/opt/jdk-8' diff --git a/src/sea/README.md b/src/sea/README.md index a8e31d03f5..2971a619a4 100644 --- a/src/sea/README.md +++ b/src/sea/README.md @@ -33,13 +33,13 @@ Build on the target OS and architecture. The builder supports `darwin`, `linux`, The builder creates a private temporary copy of the distribution. It does not replace the checkout's `dist` or `external` directories. It writes the executable and manifest to `build/sea`. Use `--output-dir` or `SOCKET_CLI_SEA_OUTPUT_DIR` to select another directory; the command-line option takes precedence. -The builder stages independent payloads in parallel. It waits for all staging jobs before cleanup. It builds the .NET facts helper before Rollup copies the distribution. +The builder stages independent payloads in parallel. It waits for all staging jobs before cleanup. Verified source downloads are cached under `~/.cache/socket-sea/downloads`; each cache hit is checked against its pinned digest, and Node's `SHASUMS256.txt` is fetched fresh for each build. The runtime executable does not access this cache or download helper tools. ## Embedded tools -The build embeds the .NET facts helper, `socket-patch`, and `uv` when a verified payload exists for the target. The .NET helper still needs a compatible .NET SDK from the project or `PATH`. The scan command uses `SOCKET_CLI_UV_PATH` when set. Otherwise, it extracts embedded `uv` to a temporary directory when needed. +The build embeds `socket-patch` and `uv` when a verified payload exists for the target. The scan command uses `SOCKET_CLI_UV_PATH` when set. Otherwise, it extracts embedded `uv` to a temporary directory when needed. The build stages and embeds the `cdxgen` and `synp` APIs for darwin-arm64, but the manifest marks both features unavailable. Their source provenance and third-party notice obligations are not resolved, so the CLI refuses to run them. Their notice files stay with this build because the payloads are already embedded in the executable. diff --git a/src/sea/build-sea.mts b/src/sea/build-sea.mts index d63ed6e865..bd553107b9 100644 --- a/src/sea/build-sea.mts +++ b/src/sea/build-sea.mts @@ -924,10 +924,6 @@ async function main(): Promise { } const synpVersion = packageJson.devDependencies?.['synp'] const prepTasks = [ - // The 1.14.x distribution includes this first-party helper. Build it - // before Rollup copies manifest-scripts into the private distribution. - // Its runtime still uses the user's .NET SDK; NuGet is build-time only. - run('pnpm', ['run', 'build:dotnet-tool']), stageSocketPatch(target, stage, socketPatchVersion, socketPatchLicense), (async () => { const cdxgenApi = await stageCdxgenApi(target, stage, cdxgenVersion) @@ -946,15 +942,11 @@ async function main(): Promise { return { cdxgenApi, synpPayload } })(), stageUv(stage, target[0], target[1]), - // Rollup copies this helper into manifest-scripts for standalone builds. - run('pnpm', ['run', 'build:maven-extension']), ] as const const prepLabels = [ - '.NET facts helper', 'socket-patch payload', 'cdxgen and synp payloads', 'uv payload', - 'Maven manifest extension', ] as const const prepResults = await Promise.allSettled(prepTasks) const prepErrors = prepResults.flatMap((result, index) => @@ -973,18 +965,18 @@ async function main(): Promise { ) } const socketPatch = ( - prepResults[1] as PromiseFulfilledResult< + prepResults[0] as PromiseFulfilledResult< Awaited> > ).value const { cdxgenApi, synpPayload } = ( - prepResults[2] as PromiseFulfilledResult<{ + prepResults[1] as PromiseFulfilledResult<{ cdxgenApi: Awaited> synpPayload: Awaited> | undefined }> ).value const uvPayload = ( - prepResults[3] as PromiseFulfilledResult< + prepResults[2] as PromiseFulfilledResult< Awaited> > ).value @@ -995,9 +987,6 @@ async function main(): Promise { await fs.writeFile(socketPatchHashFile, `${socketPatch.digest}\n`) } - // Rollup depends on the completed helper and copies it into stageDist. - // Keep it ordered after preparation, while the independent downloads and - // helper build above are allowed to overlap. await run( 'pnpm', [ @@ -1091,20 +1080,6 @@ async function main(): Promise { ) } } - const dotnetToolDirectory = path.join( - stageDist, - 'manifest-scripts/dotnet-tool', - ) - const dotnetToolEntry = path.join( - dotnetToolDirectory, - 'socket-facts-dotnet.dll', - ) - const dotnetToolStat = await fs.stat(dotnetToolEntry).catch(() => undefined) - if (!dotnetToolStat?.isFile() || dotnetToolStat.size === 0) { - throw new Error( - 'The .NET facts helper was not copied into the SEA distribution', - ) - } const capabilities = createSeaCapabilities({ triple, hasCdxgen: Boolean(cdxgenApi), @@ -1215,14 +1190,6 @@ async function main(): Promise { file: 'dist/', sha256: await digestTree(path.join(stage, 'dist')), }, - { - id: 'socket-dotnet-facts-helper', - version: appVersion, - file: 'dist/manifest-scripts/dotnet-tool/', - sha256: await digestTree( - path.join(stage, 'dist/manifest-scripts/dotnet-tool'), - ), - }, { id: 'external-dependencies', version: appVersion, @@ -1365,15 +1332,7 @@ async function main(): Promise { 'external', ), }, - runtimeRequirements: [ - { - capability: 'manifest-dotnet-facts', - executable: 'dotnet', - resolution: 'socket manifest dotnet --bin or PATH', - requirement: - 'A .NET SDK compatible with the selected project; the Socket facts helper DLL is embedded, but the SDK/runtime is user-provided.', - }, - ], + runtimeRequirements: [], capabilities, } const manifestStage = path.join(stage, 'artifact.manifest.json') diff --git a/src/sea/capabilities.mts b/src/sea/capabilities.mts index 8c3d276461..01ff9136e1 100644 --- a/src/sea/capabilities.mts +++ b/src/sea/capabilities.mts @@ -23,7 +23,6 @@ export function createSeaCapabilities({ return { available: [ 'socket-core', - 'manifest-dotnet-facts', ...(hasSocketPatch ? ['socket-patch'] : []), ...(hasUv ? ['uv'] : []), ], diff --git a/test/release-workflow.test.mts b/test/release-workflow.test.mts index 4ef9672b58..3a76c0e9f7 100644 --- a/test/release-workflow.test.mts +++ b/test/release-workflow.test.mts @@ -1,10 +1,5 @@ import { execFileSync } from 'node:child_process' -import { - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' @@ -153,9 +148,7 @@ describe('v1 release workflow contract', () => { const stage = workflow.jobs.publish.steps.find( step => step.name === 'Stage release packages', ) - const parser = stage?.run - ?.split("<<'NODE'\n")[1] - ?.split('\nNODE')[0] + const parser = stage?.run?.split("<<'NODE'\n")[1]?.split('\nNODE')[0] expect(parser).toBeDefined() const directory = mkdtempSync(path.join(tmpdir(), 'npm-stage-output-')) @@ -221,7 +214,9 @@ describe('v1 release workflow contract', () => { expect(checkIndex).toBeGreaterThanOrEqual(0) expect(finalizeIndex).toBeGreaterThan(checkIndex) expect(finalize?.run).toContain('make_latest=false') - expect(finalize?.run).toContain('gh release view "${TAG}" --json databaseId') + expect(finalize?.run).toContain( + 'gh release view "${TAG}" --json databaseId', + ) expect(finalize?.run).not.toContain('releases/tags/${TAG}') }) @@ -234,7 +229,7 @@ describe('v1 release workflow contract', () => { step => step.name === 'Validate release policy and choose npm dist-tag', ) const buildIndex = verifySteps.findIndex( - step => step.name === 'Build Maven manifest extension jar', + step => step.name === 'Build and pack socket', ) expect(versionGuard).toBeDefined() expect(versionGuard?.if).toBe('${{ inputs.dry-run == false }}') diff --git a/test/unit/sea/build-sea.test.mts b/test/unit/sea/build-sea.test.mts index d0039d979a..293b6bc1ed 100644 --- a/test/unit/sea/build-sea.test.mts +++ b/test/unit/sea/build-sea.test.mts @@ -96,7 +96,7 @@ describe('SEA capability policy', () => { hasSocketPatch: false, hasUv: false, }).available, - ).toEqual(['socket-core', 'manifest-dotnet-facts']) + ).toEqual(['socket-core']) }) }) From 57729f04becffe159ed503701803b37a48bcc08b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Sat, 14 Nov 2026 00:16:28 +0100 Subject: [PATCH 04/23] Harden how socket-cli runs Coana's facts generation - An unreadable result file now fails the build root with a message, as a missing one does, instead of throwing out of the walk or the wizard. - spawnCoana looks the default org up once per process, failure included, so a scan no longer repeats the lookup for every build root and solution listing. The lookup is silent: downloading Coana still reports a failed one when it needs the org. - Coana runs in socket-cli's own working directory, so the paths in its log lines read from there rather than as bare file names. Coana takes every path in the request as absolute and runs build tools in the build root. - When a pinned --reach-version or --fix-version Coana writes no result, socket-cli says it may predate facts generation and names the bundled version as the minimum. - Generation, the wizard's project listing and the dotnet members listing take one options type and build their request with one toSocketFactsRequest. An unresolvable build tool comes back as a failed CResult that each caller handles its own way, and the members listing now sends javaHome as the others do. --- .../manifest/discover-manifest-roots.mts | 14 +- .../manifest/generate-recursive-manifests.mts | 3 +- src/commands/manifest/run-manifest-facts.mts | 320 ++++++++---------- .../manifest/run-manifest-facts.test.mts | 114 ++++++- src/utils/coana-release.mts | 6 +- src/utils/coana-release.test.mts | 25 +- 6 files changed, 272 insertions(+), 210 deletions(-) diff --git a/src/commands/manifest/discover-manifest-roots.mts b/src/commands/manifest/discover-manifest-roots.mts index f056086290..a57638e4ca 100644 --- a/src/commands/manifest/discover-manifest-roots.mts +++ b/src/commands/manifest/discover-manifest-roots.mts @@ -21,6 +21,7 @@ import { excludePathToScanIgnores } from '../scan/exclude-paths.mts' import type { SocketFactsContext, SocketFactsProject, + SocketFactsRequestOptions, } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' @@ -191,13 +192,10 @@ export function isBuildRootCovered( ) } -export type RootBuildOptions = { - bin?: string | undefined - buildOpts: string[] - context?: SocketFactsContext | undefined - excludeBase?: string | undefined - excludePaths?: string[] | undefined -} +export type RootBuildOptions = Pick< + SocketFactsRequestOptions, + 'bin' | 'buildOpts' | 'excludeBase' | 'excludePaths' | 'javaHome' +> & { context?: SocketFactsContext | undefined } // A dotnet solution is covered once every project it builds is, or, when the // SDK cannot read it, by a same-named solution in the other format beside it @@ -220,7 +218,7 @@ async function isSolutionCovered( return false } const list = (file: string) => - listMembers({ ...opts, dir: root.dir, entryFile: file }) + listMembers({ ...opts, cwd: root.dir, entryFile: file }) const listed = await list(entryFile) if (!listed) { // Unless the twin is readable, this one is built and its failure shows. diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 9e4f830d4f..e9a6cc08fa 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -207,7 +207,7 @@ function statusOf(loader: Loader | undefined): RecursiveManifestOutcomeStatus { // The options a build's listings take besides the build itself. export function buildToolScriptOptions( - config: Pick, + config: Pick, excludeBase: string | undefined, excludePaths: string[] | undefined, context?: SocketFactsContext | undefined, @@ -218,6 +218,7 @@ export function buildToolScriptOptions( context, excludeBase, excludePaths, + javaHome: config.javaHome, } } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 5147a4e115..a24d3c9e49 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -7,15 +7,15 @@ import { looksLikeSbtBuild, resolveBuildToolBin, } from './scripts/build-tool.mts' -import constants from '../../constants.mts' +import { COANA_CLI_VERSION, SOCKET_JSON } from '../../constants.mts' import { isStandaloneSea } from '../../sea/runtime.mts' import { spawnCoana } from '../../utils/coana-release.mts' import { getErrorMessageOr } from '../../utils/errors.mts' import { withTmpDir } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' -import { getDefaultOrgSlug } from '../ci/fetch-default-org-slug.mts' import type { BuildTool } from './scripts/build-tool.mts' +import type { CResult } from '../../types.mts' export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' @@ -46,7 +46,7 @@ export const FLAG_HINTS: BuildOptionHints = { 'verbose', ]), setupCommand: 'socket manifest setup', - socketJson: constants.SOCKET_JSON, + socketJson: SOCKET_JSON, } // What a later Coana run needs of one generated build root; passed back to it @@ -145,17 +145,30 @@ type ProjectList = | { projects: SocketFactsProject[]; status: 'listed' } | { status: 'failed' } -let defaultOrgSlug: Promise | undefined +// Coana rejects a command or flag it predates, so it writes no result. +function warnIfPinnedCoanaPredatesFacts(context: SocketFactsContext): void { + const pinned = context.coanaVersion + if (pinned && pinned !== COANA_CLI_VERSION) { + logger.info( + `The pinned Coana ${pinned} may predate Socket facts generation; pin ${COANA_CLI_VERSION}, the version this Socket CLI bundles, or newer.`, + ) + } +} -// Resolved once: each build root is its own Coana run. -function orgSlugFor(context: SocketFactsContext): Promise { - if (context.orgSlug) { - return Promise.resolve(context.orgSlug) +async function readResult( + resultFile: string, +): Promise<{ error?: string | undefined; result: T | undefined }> { + if (!existsSync(resultFile)) { + return { result: undefined } + } + try { + return { result: JSON.parse(await fs.readFile(resultFile, 'utf8')) as T } + } catch (e) { + return { + error: `Coana's result is unreadable (${getErrorMessageOr(e, String(e))})`, + result: undefined, + } } - defaultOrgSlug ??= getDefaultOrgSlug(true).then(r => - r.ok ? r.data : undefined, - ) - return defaultOrgSlug } function toRequestHints(hints: BuildOptionHints): SocketFactsRequest['hints'] { @@ -187,148 +200,146 @@ async function runGenerateSocketFacts( resultFile, ...flags, ], - await orgSlugFor(context), + context.orgSlug, { coanaVersion: context.coanaVersion, - cwd: request.buildRoot, // Coana logs to stdout; keep the command's own stdout machine-readable. stdio: ['inherit', 2, 'inherit'], }, ) - const result = existsSync(resultFile) - ? (JSON.parse(await fs.readFile(resultFile, 'utf8')) as T) - : undefined + const { error, result } = await readResult(resultFile) + const failure = spawned.ok + ? undefined + : [spawned.message, spawned.cause].filter(Boolean).join(': ') return { - message: spawned.ok - ? undefined - : [spawned.message, spawned.cause].filter(Boolean).join(': '), + message: [failure, error].filter(Boolean).join('; ') || undefined, result, } }) } -// Resolves `bin` as the build tool's own runner would: the SOCKET_CLI_*_PATH -// override first, then the given bin, the project wrapper, PATH. -function requestBin(tool: BuildTool, dir: string, bin: string | undefined) { - return resolveBuildToolBin( - tool, - dir, - bin || undefined, - tool !== 'dotnet' && isStandaloneSea(), - ) -} - -const membersByRequest = new Map>() - -// The projects a dotnet solution builds; undefined when the SDK cannot read -// it, empty when the listing fails, which the build itself then reports. -export function listDotnetSolutionMembers({ - bin, - buildOpts, - context = {}, - dir, - entryFile, - excludeBase, - excludePaths, -}: { +export type SocketFactsRequestOptions = { bin?: string | undefined buildOpts: string[] - context?: SocketFactsContext | undefined - dir: string - entryFile: string + cwd: string + ecosystem: BuildTool + // The file in `cwd` to build: Maven's POM (unset leaves Maven's default), + // dotnet's solution or project (required). + entryFile?: string | undefined + // What `excludePaths` are relative to, as a build can reach modules outside + // its own directory; `cwd` when unset. excludeBase?: string | undefined + excludeConfigs?: string | undefined excludePaths?: string[] | undefined -}): Promise { - const key = JSON.stringify([ - bin, - buildOpts, - dir, - entryFile, - excludeBase, - excludePaths, - ]) - return getOrInsert(membersByRequest, key, async () => { - let request: SocketFactsRequest - try { - request = { - buildRoot: path.resolve(dir), - config: { - bin: requestBin('dotnet', dir, bin), - buildOpts, - ignoreUnresolved: false, - verbose: false, - }, - entryFile, - excludeBase: path.resolve(excludeBase ?? dir), - ...(excludePaths?.length ? { excludePaths } : {}), - hints: toRequestHints(FLAG_HINTS), - tool: 'dotnet', - } - } catch { - return [] - } - const { result } = await runGenerateSocketFacts( - request, - ['--list-members'], - context, - ) - if (!result) { - return [] - } - return result.members ?? undefined - }) + hints?: BuildOptionHints | undefined + ignoreUnresolved?: boolean | undefined + includeConfigs?: string | undefined + // As written: Coana expands `$VAR` references itself. + javaHome?: string | undefined + verbose?: boolean | undefined } -// The projects a build loads, as the build reports them, without resolving its -// dependencies; undefined when the build cannot list them, which Coana -// reports. -export async function listBuildProjects({ +// `bin` is resolved as the build tool's own runner would: the +// SOCKET_CLI_*_PATH override first, then the given bin, the project wrapper, +// PATH. +function toSocketFactsRequest({ bin, buildOpts, cwd, ecosystem, entryFile, excludeBase, + excludeConfigs, excludePaths, + hints = FLAG_HINTS, + ignoreUnresolved = false, + includeConfigs, javaHome, - verbose, -}: { - bin: string - buildOpts: string[] - cwd: string - ecosystem: BuildTool - entryFile?: string | undefined - excludeBase?: string | undefined - excludePaths?: string[] | undefined - javaHome?: string | undefined - verbose: boolean -}): Promise { + verbose = false, +}: SocketFactsRequestOptions): CResult { let resolvedBin: string try { - resolvedBin = requestBin(ecosystem, cwd, bin) - } catch (e) { - logger.fail( - `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, + resolvedBin = resolveBuildToolBin( + ecosystem, + cwd, + bin || undefined, + ecosystem !== 'dotnet' && isStandaloneSea(), ) - return undefined + } catch (e) { + return { + ok: false, + message: `Could not run the ${ecosystem} build tool`, + cause: getErrorMessageOr(e, String(e)), + } + } + return { + ok: true, + data: { + buildRoot: path.resolve(cwd), + config: { + bin: resolvedBin, + buildOpts, + ...(excludeConfigs ? { excludeConfigs } : {}), + ignoreUnresolved, + ...(includeConfigs ? { includeConfigs } : {}), + ...(javaHome ? { javaHome } : {}), + verbose, + }, + ...(entryFile ? { entryFile } : {}), + excludeBase: path.resolve(excludeBase ?? cwd), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: toRequestHints(hints), + tool: ecosystem, + }, + } +} + +const membersByRequest = new Map>() + +// The projects a dotnet solution builds; undefined when the SDK cannot read +// it, empty when the listing fails, which the build itself then reports. +export async function listDotnetSolutionMembers({ + context = {}, + ...options +}: Omit & { + context?: SocketFactsContext | undefined +}): Promise { + const request = toSocketFactsRequest({ ...options, ecosystem: 'dotnet' }) + if (!request.ok) { + // Left for the build itself to report. + return [] } - const request: SocketFactsRequest = { - buildRoot: path.resolve(cwd), - config: { - bin: resolvedBin, - buildOpts, - ignoreUnresolved: false, - ...(javaHome ? { javaHome } : {}), - verbose, + return await getOrInsert( + membersByRequest, + JSON.stringify(request.data), + async () => { + const { result } = await runGenerateSocketFacts( + request.data, + ['--list-members'], + context, + ) + if (!result) { + return [] + } + return result.members ?? undefined }, - ...(entryFile ? { entryFile } : {}), - excludeBase: path.resolve(excludeBase ?? cwd), - ...(excludePaths?.length ? { excludePaths } : {}), - hints: toRequestHints(FLAG_HINTS), - tool: ecosystem, + ) +} + +// The projects a build loads, as the build reports them, without resolving its +// dependencies; undefined when the build cannot list them, after reporting +// why. +export async function listBuildProjects( + options: SocketFactsRequestOptions, +): Promise { + const { cwd, ecosystem } = options + const request = toSocketFactsRequest(options) + if (!request.ok) { + logger.fail(`${request.message}: ${request.cause}`) + return undefined } const { message, result } = await runGenerateSocketFacts( - request, + request.data, ['--list-projects'], {}, ) @@ -343,43 +354,14 @@ export async function listBuildProjects({ // Generates one build root's `.socket.facts.json` with Coana. With a // work dir in `context`, also collects what a later Coana run reads of it. A -// failure sets a non-zero exit code; Coana reports why. +// failure sets a non-zero exit code; only a failed build is Coana's to report. export async function runManifestFacts({ - bin, - buildOpts, context = {}, - cwd, - ecosystem, - entryFile, - excludeBase, - excludeConfigs, - excludePaths, - hints = FLAG_HINTS, - ignoreUnresolved, - includeConfigs, - javaHome, - verbose, -}: { - bin: string - buildOpts: string[] + ...options +}: SocketFactsRequestOptions & { context?: SocketFactsContext | undefined - cwd: string - ecosystem: BuildTool - // The file in `cwd` to build: Maven's POM (unset leaves Maven's default), - // dotnet's solution or project (required). - entryFile?: string | undefined - // What `excludePaths` are relative to, as a build can reach modules outside - // its own directory; `cwd` when unset. - excludeBase?: string | undefined - excludeConfigs: string - excludePaths?: string[] | undefined - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - // As written: Coana expands `$VAR` references itself. - javaHome?: string | undefined - verbose: boolean }): Promise { + const { cwd, ecosystem } = options if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { process.exitCode = 1 logger.fail( @@ -388,37 +370,16 @@ export async function runManifestFacts({ return null } - let resolvedBin: string - try { - resolvedBin = requestBin(ecosystem, cwd, bin) - } catch (e) { + const request = toSocketFactsRequest(options) + if (!request.ok) { process.exitCode = 1 - logger.fail( - `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, - ) + logger.fail(`${request.message}: ${request.cause}`) return null } - const request: SocketFactsRequest = { - buildRoot: path.resolve(cwd), - config: { - bin: resolvedBin, - buildOpts, - ...(excludeConfigs ? { excludeConfigs } : {}), - ignoreUnresolved, - ...(includeConfigs ? { includeConfigs } : {}), - ...(javaHome ? { javaHome } : {}), - verbose, - }, - ...(entryFile ? { entryFile } : {}), - excludeBase: path.resolve(excludeBase ?? cwd), - ...(excludePaths?.length ? { excludePaths } : {}), - hints: toRequestHints(hints), - tool: ecosystem, - } const { workDir } = context const { message, result } = await runGenerateSocketFacts( - request, + request.data, workDir ? [ ...(workDir.withFiles ? ['--with-files'] : []), @@ -435,6 +396,7 @@ export async function runManifestFacts({ logger.fail( `Could not generate Socket facts for the ${ecosystem} project at \`${cwd}\`${message ? `: ${message}` : '.'}`, ) + warnIfPinnedCoanaPredatesFacts(context) } return null } diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 3555eedd6b..43c40109c7 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -4,18 +4,18 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { logger } from '@socketsecurity/registry/lib/logger' + vi.mock('../../utils/coana-release.mts', () => ({ spawnCoana: vi.fn(), })) -vi.mock('../ci/fetch-default-org-slug.mts', () => ({ - getDefaultOrgSlug: vi.fn(async () => ({ ok: true, data: 'default-org' })), -})) import { listBuildProjects, listDotnetSolutionMembers, runManifestFacts, } from './run-manifest-facts.mts' +import { COANA_CLI_VERSION } from '../../constants.mts' import { spawnCoana } from '../../utils/coana-release.mts' import type { SocketFactsWorkDir } from './run-manifest-facts.mts' @@ -35,20 +35,17 @@ const baseArgs = { let cwd = '' let calls: Call[] = [] -// Answers each Coana run with `result`, as `coana generate-socket-facts` writes -// it, or writes nothing when `result` is undefined. -function coanaAnswers(result: unknown, ok = true): void { +// Answers each Coana run by writing `text` as its result file, or nothing when +// `text` is undefined. +function coanaWrites(text: string | undefined, ok = true): void { vi.mocked(spawnCoana).mockImplementation(async args => { const list = [...args] const request = JSON.parse( await fs.readFile(list[list.indexOf('--request') + 1]!, 'utf8'), ) calls.push({ args: list, request }) - if (result !== undefined) { - await fs.writeFile( - list[list.indexOf('--output-file') + 1]!, - JSON.stringify(result), - ) + if (text !== undefined) { + await fs.writeFile(list[list.indexOf('--output-file') + 1]!, text) } return ok ? { ok: true, data: '' } @@ -56,6 +53,12 @@ function coanaAnswers(result: unknown, ok = true): void { }) } +// Answers each Coana run with `result`, as `coana generate-socket-facts` writes +// it, or writes nothing when `result` is undefined. +function coanaAnswers(result: unknown, ok = true): void { + coanaWrites(result === undefined ? undefined : JSON.stringify(result), ok) +} + beforeEach(async () => { cwd = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'run-manifest-facts-')), @@ -65,6 +68,7 @@ beforeEach(async () => { process.exitCode = undefined }) afterEach(async () => { + vi.restoreAllMocks() await fs.rm(cwd, { recursive: true, force: true }) delete process.env['SOCKET_CLI_MAVEN_PATH'] process.exitCode = undefined @@ -116,10 +120,15 @@ describe('runManifestFacts', () => { expect(vi.mocked(spawnCoana).mock.calls[0]![1]).toBe('acme') expect(vi.mocked(spawnCoana).mock.calls[0]![2]).toMatchObject({ coanaVersion: '1.2.3', - cwd, }) }) + it("runs Coana in socket-cli's own cwd, so its logs show paths from there", async () => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ ...baseArgs, cwd }) + expect(vi.mocked(spawnCoana).mock.calls[0]![2]?.cwd).toBeUndefined() + }) + it('sends the SOCKET_CLI_*_PATH override as the bin', async () => { const mvn = path.join(cwd, 'mvn') await fs.writeFile(mvn, '', { mode: 0o755 }) @@ -129,6 +138,17 @@ describe('runManifestFacts', () => { expect(calls[0]!.request.config.bin).toBe(mvn) }) + it('fails the root without running Coana when the bin cannot be resolved', async () => { + const fail = vi.spyOn(logger, 'fail') + process.env['SOCKET_CLI_MAVEN_PATH'] = path.join(cwd, 'missing-mvn') + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeNull() + expect(process.exitCode).toBe(1) + expect(spawnCoana).not.toHaveBeenCalled() + expect(fail).toHaveBeenCalledWith( + expect.stringContaining('Could not run the maven build tool: '), + ) + }) + it('installs files into the work dir and collects the root for reachability', async () => { const entry = { factsFile: '/r/pom.xml.socket.facts.json', @@ -185,6 +205,40 @@ describe('runManifestFacts', () => { expect(process.exitCode).toBe(1) }) + it('fails the root when Coana writes an unreadable result', async () => { + const fail = vi.spyOn(logger, 'fail') + coanaWrites('{"status":"gener') + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeNull() + expect(process.exitCode).toBe(1) + expect(fail).toHaveBeenCalledWith( + expect.stringContaining("Coana's result is unreadable"), + ) + }) + + it('names the bundled Coana when a pinned one writes no result', async () => { + const info = vi.spyOn(logger, 'info') + coanaAnswers(undefined, false) + await runManifestFacts({ + ...baseArgs, + context: { coanaVersion: '1.0.0', orgSlug: 'acme' }, + cwd, + }) + expect(info).toHaveBeenCalledWith( + `The pinned Coana 1.0.0 may predate Socket facts generation; pin ${COANA_CLI_VERSION}, the version this Socket CLI bundles, or newer.`, + ) + }) + + it('does not blame the pinned Coana for a build it reports as failed', async () => { + const info = vi.spyOn(logger, 'info') + coanaAnswers({ status: 'failed' }, false) + await runManifestFacts({ + ...baseArgs, + context: { coanaVersion: '1.0.0', orgSlug: 'acme' }, + cwd, + }) + expect(info).not.toHaveBeenCalled() + }) + it('does not run Coana outside an sbt build', async () => { coanaAnswers({ status: 'empty' }) expect( @@ -202,15 +256,32 @@ describe('runManifestFacts', () => { describe('listDotnetSolutionMembers', () => { it('lists the members once for the same request', async () => { coanaAnswers({ members: ['/r/A/A.csproj'] }) - const request = { buildOpts: [], dir: cwd, entryFile: 'All.sln' } + const request = { + buildOpts: [], + cwd, + entryFile: 'All.sln', + javaHome: '$JAVA11_HOME', + } expect(await listDotnetSolutionMembers(request)).toEqual(['/r/A/A.csproj']) expect(await listDotnetSolutionMembers(request)).toEqual(['/r/A/A.csproj']) expect(spawnCoana).toHaveBeenCalledOnce() expect(calls[0]!.args).toContain('--list-members') - expect(calls[0]!.request).toMatchObject({ + expect(calls[0]!.request).toEqual({ buildRoot: cwd, + config: { + bin: 'dotnet', + buildOpts: [], + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, entryFile: 'All.sln', excludeBase: cwd, + hints: { + flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], + setupCommand: 'socket manifest setup', + socketJson: 'socket.json', + }, tool: 'dotnet', }) }) @@ -220,7 +291,7 @@ describe('listDotnetSolutionMembers', () => { expect( await listDotnetSolutionMembers({ buildOpts: [], - dir: cwd, + cwd, entryFile: 'All.slnx', }), ).toBeUndefined() @@ -231,7 +302,7 @@ describe('listDotnetSolutionMembers', () => { expect( await listDotnetSolutionMembers({ buildOpts: [], - dir: cwd, + cwd, entryFile: 'Broken.sln', }), ).toEqual([]) @@ -277,6 +348,12 @@ describe('listBuildProjects', () => { }) }) + it('lists nothing without running Coana when the bin cannot be resolved', async () => { + process.env['SOCKET_CLI_MAVEN_PATH'] = path.join(cwd, 'missing-mvn') + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + expect(spawnCoana).not.toHaveBeenCalled() + }) + it('lists nothing when the build cannot list its projects', async () => { coanaAnswers({ status: 'failed' }, false) expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() @@ -286,4 +363,9 @@ describe('listBuildProjects', () => { coanaAnswers(undefined, false) expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() }) + + it('lists nothing when Coana writes an unreadable result', async () => { + coanaWrites('') + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + }) }) diff --git a/src/utils/coana-release.mts b/src/utils/coana-release.mts index 773f16d94d..71a8da04f2 100644 --- a/src/utils/coana-release.mts +++ b/src/utils/coana-release.mts @@ -386,6 +386,10 @@ function withoutNpmPackageEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { return out } +// Kept for the process, failure included, as a scan runs Coana once per build +// root. Silent: the download reports a failed lookup when it needs the org. +let defaultOrg: Promise> | undefined + /** * Run the Coana CLI, downloading it into the cache that Coana and the Socket * CLIs share when the cache lacks the version. Returns a CResult with Coana's @@ -456,7 +460,7 @@ export async function spawnCoana( const org: CResult = orgSlug ? { ok: true, data: orgSlug } - : await getDefaultOrgSlug() + : await (defaultOrg ??= getDefaultOrgSlug(true)) if (org.ok) { mixinsEnv['SOCKET_ORG_SLUG'] = org.data } diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index f7454f0392..2056339a2b 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -3,12 +3,13 @@ * * Test Coverage: * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, - * cwd and environment, and surfaces a failing run's output. + * cwd and environment, surfaces a failing run's output, and looks the + * default org up once. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real - * coana-cache.mjs, so nothing is mocked. This needs dist/coana-cache.mjs, which - * the build copies there. + * coana-cache.mjs, so only the default-org lookup is mocked. This needs + * dist/coana-cache.mjs, which the build copies there. * * Related Files: * - utils/coana-release.mts (implementation) @@ -19,10 +20,15 @@ import { promises as fs } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { spawn } from '@socketsecurity/registry/lib/spawn' +vi.mock('../commands/ci/fetch-default-org-slug.mts', () => ({ + getDefaultOrgSlug: vi.fn(async () => ({ ok: true, data: 'default-org' })), +})) + +import { getDefaultOrgSlug } from '../commands/ci/fetch-default-org-slug.mts' import constants from '../constants.mts' import { spawnCoana } from './coana-release.mts' import { getCliUserAgent } from './sdk.mts' @@ -47,8 +53,9 @@ type FakeRun = { async function runFake( options?: Parameters[2], + { orgSlug }: { orgSlug?: string | undefined } = { orgSlug: 'acme' }, ): Promise { - const result = await spawnCoana(['run', '.'], 'acme', { + const result = await spawnCoana(['run', '.'], orgSlug, { coanaVersion: VERSION, stdio: 'pipe', ...options, @@ -134,6 +141,14 @@ describe('spawnCoana', () => { ) }) + it('looks the default org up once for every run given no org', async () => { + const first = await runFake(undefined, {}) + const second = await runFake(undefined, {}) + expect(first.env['SOCKET_ORG_SLUG']).toBe('default-org') + expect(second.env['SOCKET_ORG_SLUG']).toBe('default-org') + expect(getDefaultOrgSlug).toHaveBeenCalledOnce() + }) + it('surfaces captured stdout when stderr is empty (Coana logs some failures to stdout)', async () => { const result = await spawnCoana(['fail'], 'acme', { coanaVersion: VERSION, From b4b05427cb6352d9118fef90c82cfebcf031f160 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Sun, 15 Nov 2026 08:51:45 +0100 Subject: [PATCH 05/23] Call runManifestFacts directly from the JVM manifest commands convert-gradle-to-facts, convert-maven-to-facts and convert-sbt-to-facts only renamed their tool's options to buildOpts and set the ecosystem. The gradle, kotlin, scala and maven commands and auto-manifest now pass both to runManifestFacts themselves, and the three files go. --- src/commands/manifest/cmd-manifest-gradle.mts | 7 +-- src/commands/manifest/cmd-manifest-kotlin.mts | 7 +-- src/commands/manifest/cmd-manifest-maven.mts | 7 +-- src/commands/manifest/cmd-manifest-scala.mts | 7 +-- .../manifest/convert-gradle-to-facts.mts | 49 ------------------ .../manifest/convert-maven-to-facts.mts | 50 ------------------ .../manifest/convert-sbt-to-facts.mts | 51 ------------------- .../manifest/generate_auto_manifest.mts | 31 ++++++----- .../manifest/generate_auto_manifest.test.mts | 18 +++---- 9 files changed, 43 insertions(+), 184 deletions(-) delete mode 100644 src/commands/manifest/convert-gradle-to-facts.mts delete mode 100644 src/commands/manifest/convert-maven-to-facts.mts delete mode 100644 src/commands/manifest/convert-sbt-to-facts.mts diff --git a/src/commands/manifest/cmd-manifest-gradle.mts b/src/commands/manifest/cmd-manifest-gradle.mts index c30bd27243..48b704192d 100644 --- a/src/commands/manifest/cmd-manifest-gradle.mts +++ b/src/commands/manifest/cmd-manifest-gradle.mts @@ -3,10 +3,10 @@ import path from 'node:path' import { debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' @@ -297,12 +297,13 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await convertGradleToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedGradleOpts, cwd, + ecosystem: 'gradle', excludeConfigs: String(excludeConfigs || ''), excludePaths, - gradleOpts: parsedGradleOpts, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, diff --git a/src/commands/manifest/cmd-manifest-kotlin.mts b/src/commands/manifest/cmd-manifest-kotlin.mts index 030ca6a893..00b2d137bb 100644 --- a/src/commands/manifest/cmd-manifest-kotlin.mts +++ b/src/commands/manifest/cmd-manifest-kotlin.mts @@ -3,10 +3,10 @@ import path from 'node:path' import { debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' @@ -300,12 +300,13 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await convertGradleToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedGradleOpts, cwd, + ecosystem: 'gradle', excludeConfigs: String(excludeConfigs || ''), excludePaths, - gradleOpts: parsedGradleOpts, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, diff --git a/src/commands/manifest/cmd-manifest-maven.mts b/src/commands/manifest/cmd-manifest-maven.mts index e9e64447fe..69b16494de 100644 --- a/src/commands/manifest/cmd-manifest-maven.mts +++ b/src/commands/manifest/cmd-manifest-maven.mts @@ -3,9 +3,9 @@ import path from 'node:path' import { debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' -import { convertMavenToFacts } from './convert-maven-to-facts.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import constants, { SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' @@ -234,15 +234,16 @@ async function run( const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths']) assertValidExcludePaths(excludePaths) - await convertMavenToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedMavenOpts, cwd, + ecosystem: 'maven', excludeConfigs: String(excludeConfigs || ''), excludePaths, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, - mavenOpts: parsedMavenOpts, verbose: Boolean(verbose), }) } diff --git a/src/commands/manifest/cmd-manifest-scala.mts b/src/commands/manifest/cmd-manifest-scala.mts index 19f887dfb4..e805db3ff2 100644 --- a/src/commands/manifest/cmd-manifest-scala.mts +++ b/src/commands/manifest/cmd-manifest-scala.mts @@ -3,10 +3,10 @@ import path from 'node:path' import { debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' -import { convertSbtToFacts } from './convert-sbt-to-facts.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' import { checkCommandInput } from '../../utils/check-input.mts' @@ -351,15 +351,16 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await convertSbtToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedSbtOpts, cwd, + ecosystem: 'sbt', excludeConfigs: String(excludeConfigs || ''), excludePaths, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, - sbtOpts: parsedSbtOpts, verbose: Boolean(verbose), }) return diff --git a/src/commands/manifest/convert-gradle-to-facts.mts b/src/commands/manifest/convert-gradle-to-facts.mts deleted file mode 100644 index b00782a60a..0000000000 --- a/src/commands/manifest/convert-gradle-to-facts.mts +++ /dev/null @@ -1,49 +0,0 @@ -import { runManifestFacts } from './run-manifest-facts.mts' - -import type { - BuildOptionHints, - RunManifestFactsOutcome, - SocketFactsContext, -} from './run-manifest-facts.mts' - -// Generates `gradle.socket.facts.json` for a Gradle project with Coana. -export async function convertGradleToFacts({ - bin, - context, - cwd, - excludeConfigs, - excludePaths, - gradleOpts, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - verbose, -}: { - bin: string - context?: SocketFactsContext | undefined - cwd: string - excludeConfigs: string - excludePaths?: string[] | undefined - gradleOpts: string[] - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - verbose: boolean -}): Promise { - return await runManifestFacts({ - bin, - buildOpts: gradleOpts, - context, - cwd, - ecosystem: 'gradle', - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - verbose, - }) -} diff --git a/src/commands/manifest/convert-maven-to-facts.mts b/src/commands/manifest/convert-maven-to-facts.mts deleted file mode 100644 index e51aefeafe..0000000000 --- a/src/commands/manifest/convert-maven-to-facts.mts +++ /dev/null @@ -1,50 +0,0 @@ -import { runManifestFacts } from './run-manifest-facts.mts' - -import type { - BuildOptionHints, - RunManifestFactsOutcome, - SocketFactsContext, -} from './run-manifest-facts.mts' - -// Generates `pom.xml.socket.facts.json` (named after the POM Maven runs on) -// for a Maven project with Coana. -export async function convertMavenToFacts({ - bin, - context, - cwd, - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - mavenOpts, - verbose, -}: { - bin: string - context?: SocketFactsContext | undefined - cwd: string - excludeConfigs: string - excludePaths?: string[] | undefined - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - mavenOpts: string[] - verbose: boolean -}): Promise { - return await runManifestFacts({ - bin, - buildOpts: mavenOpts, - context, - cwd, - ecosystem: 'maven', - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - verbose, - }) -} diff --git a/src/commands/manifest/convert-sbt-to-facts.mts b/src/commands/manifest/convert-sbt-to-facts.mts deleted file mode 100644 index 5d209c8895..0000000000 --- a/src/commands/manifest/convert-sbt-to-facts.mts +++ /dev/null @@ -1,51 +0,0 @@ -import { runManifestFacts } from './run-manifest-facts.mts' - -import type { - BuildOptionHints, - RunManifestFactsOutcome, - SocketFactsContext, -} from './run-manifest-facts.mts' - -// Generates `sbt.socket.facts.json` for an sbt project with Coana. -// sbt 0.13/early 1.x can't run on modern JDKs — pass a compatible JDK via -// `--sbt-opts "--java-home "` or `JAVA_HOME`. -export async function convertSbtToFacts({ - bin, - context, - cwd, - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - sbtOpts, - verbose, -}: { - bin: string - context?: SocketFactsContext | undefined - cwd: string - excludeConfigs: string - excludePaths?: string[] | undefined - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - sbtOpts: string[] - verbose: boolean -}): Promise { - return await runManifestFacts({ - bin, - buildOpts: sbtOpts, - context, - cwd, - ecosystem: 'sbt', - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - verbose, - }) -} diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 043cec08d1..7508e42882 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -4,15 +4,15 @@ import { logger } from '@socketsecurity/registry/lib/logger' import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' -import { convertMavenToFacts } from './convert-maven-to-facts.mts' -import { convertSbtToFacts } from './convert-sbt-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { resolveEcosystemConfig } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' -import { REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG } from './run-manifest-facts.mts' +import { + REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, + runManifestFacts, +} from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import { ENVIRONMENT_YML, @@ -112,8 +112,11 @@ export async function generateAutoManifest({ // `defaults.manifest.sbt.facts: false` in socket.json. if (sockJson.defaults?.manifest?.sbt?.facts !== false) { logger.log('Detected a Scala sbt build, generating Socket facts...') - const outcome = await convertSbtToFacts({ - ...sbtArgs, + const { sbtOpts, ...sbtCommon } = sbtArgs + const outcome = await runManifestFacts({ + ...sbtCommon, + buildOpts: sbtOpts, + ecosystem: 'sbt', excludeConfigs: sockJson.defaults?.manifest?.sbt?.excludeConfigs ?? '', excludePaths, ignoreUnresolved: Boolean( @@ -154,8 +157,11 @@ export async function generateAutoManifest({ logger.log( 'Detected a gradle build (Gradle, Kotlin, Scala), generating Socket facts...', ) - const outcome = await convertGradleToFacts({ - ...gradleArgs, + const { gradleOpts, ...gradleCommon } = gradleArgs + const outcome = await runManifestFacts({ + ...gradleCommon, + buildOpts: gradleOpts, + ecosystem: 'gradle', excludeConfigs: sockJson.defaults?.manifest?.gradle?.excludeConfigs ?? '', excludePaths, @@ -181,12 +187,16 @@ export async function generateAutoManifest({ if (!sockJson?.defaults?.manifest?.maven?.disabled && detected.maven) { logger.log('Detected a Maven pom.xml build, generating Socket facts...') - const outcome = await convertMavenToFacts({ + const outcome = await runManifestFacts({ // Configured bin wins; else prefer ./mvnw, else mvn on PATH. bin: sockJson.defaults?.manifest?.maven?.bin ?? resolveBuildToolBin('maven', cwd), + buildOpts: parseBuildToolOpts( + sockJson.defaults?.manifest?.maven?.mavenOpts ?? undefined, + ), cwd, + ecosystem: 'maven', excludeConfigs: sockJson.defaults?.manifest?.maven?.excludeConfigs ?? '', excludePaths, ignoreUnresolved: Boolean( @@ -194,9 +204,6 @@ export async function generateAutoManifest({ ), includeConfigs: sockJson.defaults?.manifest?.maven?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.maven?.javaHome ?? undefined, - mavenOpts: parseBuildToolOpts( - sockJson.defaults?.manifest?.maven?.mavenOpts ?? undefined, - ), context, hints, verbose: Boolean(sockJson.defaults?.manifest?.maven?.verbose), diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index e505e6cba0..5af24dd73a 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -19,11 +19,9 @@ vi.mock('./convert_sbt_to_maven.mts', () => ({ vi.mock('./convert-dotnet-to-facts.mts', () => ({ convertDotnetToFacts: vi.fn(async () => undefined), })) -vi.mock('./convert-gradle-to-facts.mts', () => ({ - convertGradleToFacts: vi.fn(async () => undefined), -})) -vi.mock('./convert-sbt-to-facts.mts', () => ({ - convertSbtToFacts: vi.fn(async () => undefined), +vi.mock('./run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal()), + runManifestFacts: vi.fn(async () => undefined), })) vi.mock('./handle-manifest-conda.mts', () => ({ handleManifestConda: vi.fn(async () => undefined), @@ -36,10 +34,10 @@ import { logger } from '@socketsecurity/registry/lib/logger' import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { generateAutoManifest } from './generate_auto_manifest.mts' import { handleManifestConda } from './handle-manifest-conda.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' import type { SocketJson } from '../../utils/socket-json.mts' @@ -59,7 +57,7 @@ const baseDetected = { describe('generateAutoManifest — bazel branch', () => { beforeEach(() => { vi.mocked(extractBazelToMaven).mockClear() - vi.mocked(convertGradleToFacts).mockClear() + vi.mocked(runManifestFacts).mockClear() vi.mocked(convertGradleToMaven).mockClear() vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) vi.mocked(extractBazelToMaven).mockResolvedValue({ @@ -272,7 +270,7 @@ describe('generateAutoManifest — bazel branch', () => { }) expect(extractBazelToMaven).toHaveBeenCalledTimes(1) // Socket facts is the default for the gradle branch. - expect(convertGradleToFacts).toHaveBeenCalledTimes(1) + expect(runManifestFacts).toHaveBeenCalledTimes(1) expect(convertGradleToMaven).not.toHaveBeenCalled() }) @@ -287,7 +285,7 @@ describe('generateAutoManifest — bazel branch', () => { verbose: false, }) expect(convertGradleToMaven).toHaveBeenCalledTimes(1) - expect(convertGradleToFacts).not.toHaveBeenCalled() + expect(runManifestFacts).not.toHaveBeenCalled() }) it('honors socket.json out override (user-supplied .socket-auto-manifest dir)', async () => { @@ -394,7 +392,7 @@ describe('generateAutoManifest — conda branch', () => { it('aborts on a failed facts generator even when the exit code was already set', async () => { process.exitCode = 1 - vi.mocked(convertGradleToFacts).mockResolvedValueOnce(null) + vi.mocked(runManifestFacts).mockResolvedValueOnce(null) await expect( generateAutoManifest({ cwd: '/tmp/repo', From e2ad97d91212e1281430836905acb2a513807259 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Mon, 16 Nov 2026 00:05:07 +0100 Subject: [PATCH 06/23] Send a per-tool reachability javaHome to Coana `defaults.manifest.{gradle,maven,sbt}.reachability.javaHome` in socket.json names the JDK the reachability run analyses against, which can differ from the one the build runs on. It cascades through nested socket.json files like `javaHome`, field by field within `reachability`, and null clears an inherited value. Each JVM build root's request to `coana generate-socket-facts` carries it, as written, as `config.reachability.javaHome`; Coana keeps it with the root's state for the later reachability run. Facts generation ignores it. The setup wizard now compares a nested section field by field when deciding what to write, so configuring a project no longer pins an inherited `reachability` value into its own socket.json. --- src/commands/manifest/build-root-config.mts | 11 +++ .../manifest/build-root-config.test.mts | 14 +++ .../manifest/generate-recursive-manifests.mts | 7 ++ .../generate-recursive-manifests.test.mts | 56 ++++++++++- .../manifest/generate_auto_manifest.mts | 15 +++ .../manifest/generate_auto_manifest.test.mts | 29 ++++++ src/commands/manifest/run-manifest-facts.mts | 7 ++ .../manifest/run-manifest-facts.test.mts | 24 +++++ .../setup-recursive-manifest-config.mts | 30 +++++- .../setup-recursive-manifest-config.test.mts | 33 +++++++ src/utils/socket-json.mts | 45 +++++++-- src/utils/socket-json.test.mts | 96 +++++++++++++++++++ 12 files changed, 354 insertions(+), 13 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index d8d3ec3011..cec051cfbd 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -179,7 +179,18 @@ export function createBuildRootSettingsResolver( let entryDisabledBy: DisabledBy | undefined if (entryKey) { const entry = builds![entryKey] as SocketJsonBuildEntry + const sectionReachability = section['reachability'] Object.assign(section, entry) + // Merged field by field, as the cascade merges it. + if ( + isObjectObject(sectionReachability) && + isObjectObject(entry['reachability']) + ) { + section['reachability'] = { + ...sectionReachability, + ...entry['reachability'], + } + } if (entry.disabled !== undefined) { entryDisabledBy = { dir: root.dir, key: entryKey } } diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index 2126a8075f..a633f9be6e 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -82,6 +82,20 @@ describe('createBuildRootSettingsResolver', () => { }) }) + it("merges an entry's reachability into the section's field by field", async () => { + await write('.', { maven: { reachability: { javaHome: '/jdk-17' } } }) + await write( + 'svc', + { builds: { 'pom.xml': { reachability: { other: 'x' } } } }, + ['pom.xml'], + ) + + expect( + createBuildRootSettingsResolver()('maven', maven('svc')).sockJson.defaults + ?.manifest?.maven, + ).toEqual({ reachability: { javaHome: '/jdk-17', other: 'x' } }) + }) + it('names a Gradle or sbt build by any build file of its directory', async () => { await write( 'lib', diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index e9a6cc08fa..7adb4bae3f 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -87,6 +87,7 @@ export type EcosystemBuildConfig = { ignoreUnresolved: boolean includeConfigs: string javaHome: string | undefined + reachability: { javaHome: string | undefined } // Set when this build root should be skipped entirely (never invoked). skipReason: string | undefined verbose: boolean @@ -705,6 +706,7 @@ async function runCandidate( ignoreUnresolved: ctx.ignoreUnresolved ?? dirConfig.ignoreUnresolved, includeConfigs: dirConfig.includeConfigs, javaHome: dirConfig.javaHome, + reachability: dirConfig.reachability, verbose: ctx.verbose || dirConfig.verbose, }) if (result === null) { @@ -822,6 +824,7 @@ export async function buildUncoveredRoot({ ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, + reachability: config.reachability, verbose: config.verbose, }) if (result) { @@ -932,6 +935,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: undefined, + reachability: { javaHome: undefined }, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } @@ -946,6 +950,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, + reachability: { javaHome: config?.reachability?.javaHome ?? undefined }, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } @@ -960,6 +965,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, + reachability: { javaHome: config?.reachability?.javaHome ?? undefined }, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } @@ -976,6 +982,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, + reachability: { javaHome: config?.reachability?.javaHome ?? undefined }, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 6b1d3beaaf..39c2fbcf1a 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -822,12 +822,65 @@ describe('generateRecursiveManifests', () => { expect(javaHomeByCall.get('maven:reactor')).toBeUndefined() }) + it("passes each gradle, maven and sbt root's reachability javaHome on its request", async () => { + const outer = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'dsi-reachability-')), + ) + try { + for (const file of [ + 'gradle/build.gradle', + 'maven/pom.xml', + 'sbt/build.sbt', + ]) { + // eslint-disable-next-line no-await-in-loop + await fs.mkdir(path.join(outer, path.dirname(file))) + // eslint-disable-next-line no-await-in-loop + await fs.writeFile(path.join(outer, file), '') + } + mockCascade(() => ({ + defaults: { + manifest: { + gradle: { reachability: { javaHome: '$GRADLE_JDK' } }, + maven: { reachability: { javaHome: '$MAVEN_JDK' } }, + sbt: { reachability: { javaHome: '$SBT_JDK' } }, + }, + }, + })) + mockFacts(async ({ cwd }) => ({ + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [], + })) + + await generateRecursiveManifests({ cwd: outer, verbose: false }) + + expect( + Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ), + ).toEqual({ + gradle: { javaHome: '$GRADLE_JDK' }, + maven: { javaHome: '$MAVEN_JDK' }, + sbt: { javaHome: '$SBT_JDK' }, + }) + } finally { + await fs.rm(outer, { recursive: true, force: true }) + } + }) + it('resolves an explicit null override back to the no-restriction default, not a literal null', async () => { mockCascade(dir => dir === dualMarkerDir ? { defaults: { - manifest: { maven: { excludeConfigs: null, javaHome: null } }, + manifest: { + maven: { + excludeConfigs: null, + javaHome: null, + reachability: { javaHome: null }, + }, + }, }, } : {}, @@ -849,6 +902,7 @@ describe('generateRecursiveManifests', () => { ) expect(call?.[0].excludeConfigs).toBe('') expect(call?.[0].javaHome).toBeUndefined() + expect(call?.[0].reachability?.javaHome).toBeUndefined() }) it("honors a build root's own socket.json verbose and points hints at it", async () => { diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 7508e42882..fc56e43f99 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -124,6 +124,11 @@ export async function generateAutoManifest({ ), includeConfigs: sockJson.defaults?.manifest?.sbt?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.sbt?.javaHome ?? undefined, + reachability: { + javaHome: + sockJson.defaults?.manifest?.sbt?.reachability?.javaHome ?? + undefined, + }, context, hints, }) @@ -171,6 +176,11 @@ export async function generateAutoManifest({ includeConfigs: sockJson.defaults?.manifest?.gradle?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.gradle?.javaHome ?? undefined, + reachability: { + javaHome: + sockJson.defaults?.manifest?.gradle?.reachability?.javaHome ?? + undefined, + }, context, hints, }) @@ -204,6 +214,11 @@ export async function generateAutoManifest({ ), includeConfigs: sockJson.defaults?.manifest?.maven?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.maven?.javaHome ?? undefined, + reachability: { + javaHome: + sockJson.defaults?.manifest?.maven?.reachability?.javaHome ?? + undefined, + }, context, hints, verbose: Boolean(sockJson.defaults?.manifest?.maven?.verbose), diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index 5af24dd73a..53970da052 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -274,6 +274,35 @@ describe('generateAutoManifest — bazel branch', () => { expect(convertGradleToMaven).not.toHaveBeenCalled() }) + it('passes each JVM build tool its socket.json reachability javaHome', async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { + gradle: { reachability: { javaHome: '$GRADLE_JDK' } }, + maven: { bin: 'mvn', reachability: { javaHome: '$MAVEN_JDK' } }, + sbt: { reachability: { javaHome: '$SBT_JDK' } }, + }, + }, + } as SocketJson) + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, maven: true, sbt: true }, + outputKind: 'text', + verbose: false, + }) + expect( + Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ), + ).toEqual({ + gradle: { javaHome: '$GRADLE_JDK' }, + maven: { javaHome: '$MAVEN_JDK' }, + sbt: { javaHome: '$SBT_JDK' }, + }) + }) + it('uses the gradle pom generator when defaults.manifest.gradle.facts is false', async () => { vi.mocked(readOrDefaultSocketJson).mockReturnValue({ defaults: { manifest: { gradle: { facts: false } } }, diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index a24d3c9e49..a24798ce23 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -115,6 +115,7 @@ type SocketFactsRequest = { ignoreUnresolved: boolean includeConfigs?: string | undefined javaHome?: string | undefined + reachability?: { javaHome: string } | undefined verbose: boolean } entryFile?: string | undefined @@ -236,6 +237,8 @@ export type SocketFactsRequestOptions = { includeConfigs?: string | undefined // As written: Coana expands `$VAR` references itself. javaHome?: string | undefined + // Unused by facts generation: Coana keeps it for the reachability run. + reachability?: { javaHome?: string | undefined } | undefined verbose?: boolean | undefined } @@ -255,6 +258,7 @@ function toSocketFactsRequest({ ignoreUnresolved = false, includeConfigs, javaHome, + reachability, verbose = false, }: SocketFactsRequestOptions): CResult { let resolvedBin: string @@ -283,6 +287,9 @@ function toSocketFactsRequest({ ignoreUnresolved, ...(includeConfigs ? { includeConfigs } : {}), ...(javaHome ? { javaHome } : {}), + ...(reachability?.javaHome + ? { reachability: { javaHome: reachability.javaHome } } + : {}), verbose, }, ...(entryFile ? { entryFile } : {}), diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 43c40109c7..67278c6c97 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -123,6 +123,30 @@ describe('runManifestFacts', () => { }) }) + it("sends the reachability run's javaHome as written, next to the build's", async () => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ + ...baseArgs, + cwd, + javaHome: '$JAVA11_HOME', + reachability: { javaHome: '${JAVA17_HOME}' }, + }) + expect(calls[0]!.request.config).toMatchObject({ + javaHome: '$JAVA11_HOME', + reachability: { javaHome: '${JAVA17_HOME}' }, + }) + }) + + it('sends no reachability settings when none are set', async () => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ + ...baseArgs, + cwd, + reachability: { javaHome: undefined }, + }) + expect(calls[0]!.request.config).not.toHaveProperty('reachability') + }) + it("runs Coana in socket-cli's own cwd, so its logs show paths from there", async () => { coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd }) diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index fc632c4eee..640fa485a4 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -5,6 +5,7 @@ import micromatch from 'micromatch' import { joinAnd } from '@socketsecurity/registry/lib/arrays' import { logger } from '@socketsecurity/registry/lib/logger' +import { isObjectObject } from '@socketsecurity/registry/lib/objects' import { select } from '@socketsecurity/registry/lib/prompts' import { pluralize } from '@socketsecurity/registry/lib/words' @@ -83,6 +84,28 @@ function notCanceled(): CResult<{ canceled: boolean }> { return { ok: true, data: { canceled: false } } } +// A nested section (`reachability`) compares field by field, as the cascade +// merges it. +function changedFields( + seed: Record, + inherited: Record, +): Record { + const changed: Record = {} + for (const key of Object.keys(seed)) { + const value = seed[key] + const base = inherited[key] + if (isObjectObject(value) && isObjectObject(base)) { + const nested = changedFields(value, base) + if (Object.keys(nested).length) { + changed[key] = nested + } + } else if (value !== base) { + changed[key] = value + } + } + return changed +} + function getEcosystemSection( sockJson: SocketJson, ecosystem: BuildTool, @@ -457,12 +480,13 @@ async function configureBuild( } const before = JSON.stringify(target) + const changed = changedFields(seed, inherited) // An answer the wizard removed leaves the field to inheritance. for (const field of new Set([...seeded, ...Object.keys(seed)])) { - if (!Object.hasOwn(seed, field) || seed[field] === inherited[field]) { - delete target[field] + if (Object.hasOwn(changed, field)) { + target[field] = changed[field] } else { - target[field] = seed[field] + delete target[field] } } const label = buildLabel(cwd, build) diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 4056692ebb..82e4d68c1b 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -538,6 +538,39 @@ describe('setupRecursiveManifestConfig', () => { expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({}) }) + it('writes an inherited reachability setting only where it differs, field by field', async () => { + await writeSettings('.', { + maven: { reachability: { javaHome: '/opt/jdk-17' } }, + }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + vi.mocked(setupMaven).mockResolvedValue({ + ok: true, + data: { canceled: false }, + }) + const answers: Answers = [ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ] + answer(answers) + + await setupRecursiveManifestConfig(repo, false) + expect(existsSync(file('legacy/socket.json'))).toBe(false) + + vi.mocked(setupMaven).mockImplementation(async config => { + config.reachability = { javaHome: null } + return { ok: true, data: { canceled: false } } + }) + answer(answers) + + await setupRecursiveManifestConfig(repo, false) + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { javaHome: null }, + }) + }) + it('loads a build left skipped under its own name, so its modules are not asked about', async () => { await writeSettings('legacy', { builds: { 'pom.xml': { disabled: true } }, diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 7610630703..659dcd377c 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -30,6 +30,13 @@ import { SOCKET_JSON, SOCKET_WEBSITE_URL } from '../constants.mts' import type { CResult } from '../types.mts' +// Settings only the reachability run reads; they cascade field by field like +// the rest of an ecosystem's section. +export type ReachabilityDefaults = { + // JDK for reachability analysis; passed to Coana as written. + javaHome?: string | undefined | null +} + export interface SocketJson { ' _____ _ _ ': string '| __|___ ___| |_ ___| |_ ': string @@ -94,6 +101,7 @@ export interface SocketJson { // JDK path; sets JAVA_HOME for this ecosystem's build tool. Supports // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null + reachability?: ReachabilityDefaults | undefined verbose?: boolean | undefined } maven?: { @@ -109,6 +117,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null mavenOpts?: string | undefined | null + reachability?: ReachabilityDefaults | undefined verbose?: boolean | undefined } sbt?: { @@ -127,6 +136,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null outfile?: string | undefined | null + reachability?: ReachabilityDefaults | undefined sbtOpts?: string | undefined | null stdout?: boolean | undefined verbose?: boolean | undefined @@ -187,9 +197,20 @@ export async function readOrDefaultSocketJsonUp( return getDefaultSocketJson() } -// Shallow-merges `defaults.manifest.` per ecosystem: fields set in -// `override` win, others fall through to `base`. Only this section cascades; -// everything else in `defaults` comes from `base` only. +function mergeJvmDefaults< + T extends { reachability?: ReachabilityDefaults | undefined }, +>(base: T | undefined, override: T): T { + const merged = { ...base, ...override } + if (base?.reachability && override.reachability) { + merged.reachability = { ...base.reachability, ...override.reachability } + } + return merged +} + +// Merges `defaults.manifest.` per ecosystem, and a JVM section's +// `reachability` within it: fields set in `override` win, others fall through +// to `base`. Only this section cascades; everything else in `defaults` comes +// from `base` only. function mergeManifestDefaults( base: SocketJson, override: SocketJson, @@ -215,16 +236,22 @@ function mergeManifestDefaults( } } if (overrideManifest.gradle) { - mergedManifest.gradle = { - ...baseManifest?.gradle, - ...overrideManifest.gradle, - } + mergedManifest.gradle = mergeJvmDefaults( + baseManifest?.gradle, + overrideManifest.gradle, + ) } if (overrideManifest.maven) { - mergedManifest.maven = { ...baseManifest?.maven, ...overrideManifest.maven } + mergedManifest.maven = mergeJvmDefaults( + baseManifest?.maven, + overrideManifest.maven, + ) } if (overrideManifest.sbt) { - mergedManifest.sbt = { ...baseManifest?.sbt, ...overrideManifest.sbt } + mergedManifest.sbt = mergeJvmDefaults( + baseManifest?.sbt, + overrideManifest.sbt, + ) } return { ...base, diff --git a/src/utils/socket-json.test.mts b/src/utils/socket-json.test.mts index d0ed1c46ba..8e082322b6 100644 --- a/src/utils/socket-json.test.mts +++ b/src/utils/socket-json.test.mts @@ -134,4 +134,100 @@ describe('readSocketJsonChain and mergeSocketJsonChain', () => { excludeConfigs: null, }) }) + + describe('reachability', () => { + let buildRoot = '' + + beforeEach(async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + maven: { reachability: { javaHome: '$JAVA17_HOME' } }, + }, + }, + }) + buildRoot = path.join(root, 'project') + await fs.mkdir(buildRoot, { recursive: true }) + }) + + it('inherits the reachability javaHome when the override only sets other fields', async () => { + await writeSocketJson(buildRoot, { + version: 1, + defaults: { manifest: { maven: { javaHome: '/opt/jdk-11' } } }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(mavenConfig(result)).toEqual({ + javaHome: '/opt/jdk-11', + reachability: { javaHome: '$JAVA17_HOME' }, + }) + }) + + it('lets the nearest socket.json override the reachability javaHome', async () => { + await writeSocketJson(buildRoot, { + version: 1, + defaults: { + manifest: { maven: { reachability: { javaHome: '/opt/jdk-21' } } }, + }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(mavenConfig(result)?.reachability).toEqual({ + javaHome: '/opt/jdk-21', + }) + }) + + it('treats an explicit null reachability javaHome as clearing the inherited one', async () => { + await writeSocketJson(buildRoot, { + version: 1, + defaults: { manifest: { maven: { reachability: { javaHome: null } } } }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(mavenConfig(result)?.reachability).toEqual({ javaHome: null }) + }) + + it('merges reachability field by field rather than replacing it whole', async () => { + await writeSocketJson(buildRoot, { + version: 1, + defaults: { manifest: { maven: { reachability: { other: 'x' } } } }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(mavenConfig(result)?.reachability).toEqual({ + javaHome: '$JAVA17_HOME', + other: 'x', + }) + }) + + it('cascades gradle and sbt reachability the same way', async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + gradle: { reachability: { javaHome: '/opt/gradle-jdk' } }, + sbt: { reachability: { javaHome: '/opt/sbt-jdk' } }, + }, + }, + }) + await writeSocketJson(buildRoot, { + version: 1, + defaults: { + manifest: { + gradle: { reachability: { javaHome: null } }, + sbt: { bin: 'sbt' }, + }, + }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(result.defaults?.manifest?.gradle?.reachability).toEqual({ + javaHome: null, + }) + expect(result.defaults?.manifest?.sbt?.reachability).toEqual({ + javaHome: '/opt/sbt-jdk', + }) + }) + }) }) From 67c18e2b4281a8776cb412028754f9e217251f87 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Mon, 16 Nov 2026 00:12:57 +0100 Subject: [PATCH 07/23] Ask for the reachability JDK in the JVM setup wizards The Gradle, Maven and sbt sub-wizards end with a reachability step: "Use a different Java for reachability analysis?". Only a yes asks for the JDK, written to `reachability.javaHome`; a no leaves the setting as it is, so an inherited value is neither pinned nor cleared. Pom mode skips the step, as it produces no facts for a reachability run. When configuring a nested project, the wizard seeds `reachability` from the inherited and the project's own fields together, as the cascade merges them. --- .../manifest/setup-manifest-config.mts | 76 ++++++++++++- .../manifest/setup-manifest-config.test.mts | 107 +++++++++++++++++- .../setup-recursive-manifest-config.test.mts | 28 +++++ 3 files changed, 204 insertions(+), 7 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 8cbd34f4f8..82c3c96457 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -13,7 +13,10 @@ import { } from '../../utils/socket-json.mts' import type { CResult } from '../../types.mts' -import type { ManifestDefaults } from '../../utils/socket-json.mts' +import type { + ManifestDefaults, + ReachabilityDefaults, +} from '../../utils/socket-json.mts' // Whether the prompt was canceled. A blank answer clears a value set before // with null rather than deleting the key, so it doesn't silently start @@ -385,10 +388,11 @@ export async function setupGradle( return canceledByUser() } } + const generatesFacts = factsOnly || config.facts !== false // The config filters and --ignore-unresolved only apply to facts generation // (the default); skip them when pom generation (--pom) is selected. - if (factsOnly || config.facts !== false) { + if (generatesFacts) { const factsOptions = await setupFactsOptions(config) if (!factsOptions.ok || factsOptions.data.canceled) { return factsOptions @@ -399,6 +403,10 @@ export async function setupGradle( return canceledByUser() } + if (generatesFacts) { + return await setupReachability(config) + } + return notCanceled() } @@ -440,7 +448,7 @@ export async function setupMaven( return canceledByUser() } - return notCanceled() + return await setupReachability(config) } export async function setupSbt( @@ -478,11 +486,12 @@ export async function setupSbt( return canceledByUser() } } + const generatesFacts = factsOnly || config.facts !== false // Socket facts is the default. The pom output questions (stdout/outfile) // only apply when pom generation (--pom) is explicitly selected; otherwise // ask the facts-only options. - if (!factsOnly && config.facts === false) { + if (!generatesFacts) { const stdout = await askForStdout(config.stdout) if (stdout === undefined) { return canceledByUser() @@ -520,6 +529,10 @@ export async function setupSbt( return canceledByUser() } + if (generatesFacts) { + return await setupReachability(config) + } + return notCanceled() } @@ -625,10 +638,13 @@ async function askForBin( }) } -async function askForJavaHome(defaultName = ''): Promise { +async function askForJavaHome( + defaultName = '', + question = 'What JDK should this build tool use? Leave blank to use the JDK already on PATH/JAVA_HOME.', +): Promise { return await input({ message: - 'What JDK should this build tool use? Leave blank to use the JDK already on PATH/JAVA_HOME. Supports $VAR/${VAR}.' + + `${question} Supports $VAR/\${VAR}.` + (defaultName ? ' (Backspace to leave default)' : ''), default: defaultName, required: false, @@ -716,6 +732,54 @@ async function askForIgnoreUnresolvedFlag( }) } +// Settings only the reachability run reads. A "no" leaves a setting as it is, +// so an inherited value is neither pinned nor cleared. +async function setupReachability(config: { + reachability?: ReachabilityDefaults | undefined +}): Promise> { + const reachability = { ...config.reachability } + + const wantsJavaHome = await select({ + message: 'Use a different Java for reachability analysis?', + choices: [ + { + name: 'no', + value: false, + description: 'Leave the JDK for reachability analysis unset', + }, + { + name: 'yes', + value: true, + description: 'Set the JDK reachability analysis uses', + }, + ], + default: !!reachability.javaHome, + }) + if (wantsJavaHome === undefined || wantsJavaHome === null) { + return canceledByUser() + } + if ( + wantsJavaHome && + applyAnswer( + reachability, + 'javaHome', + await askForJavaHome( + reachability.javaHome || '', + 'What JDK should reachability analysis use?', + ), + ) + ) { + return canceledByUser() + } + + if (Object.keys(reachability).length) { + config.reachability = reachability + } else { + delete config.reachability + } + return notCanceled() +} + // Prompts for the facts-only options every facts generator shares: the config // include/exclude filters and --ignore-unresolved. Mutates `config` in place. async function setupFactsOptions( diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 7138ddee3e..9d363286b0 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' // Simulates a real prompt: pressing Enter with nothing typed returns // whatever `default` was shown - the same contract inquirer honors. This is @@ -90,6 +90,111 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) }) +describe('reachability step', () => { + const REACHABILITY_QUESTION = + 'Use a different Java for reachability analysis?' + + // Answers the reachability question with `wantsJavaHome` and its JDK prompt + // with `javaHome`; every other prompt keeps its default. + function answerReachability(wantsJavaHome: boolean, javaHome = ''): void { + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === REACHABILITY_QUESTION ? wantsJavaHome : (def ?? ''), + ) + vi.mocked(input).mockImplementation(async ({ default: def, message }) => + message.startsWith('What JDK should reachability analysis use?') + ? javaHome + : (def ?? ''), + ) + } + + afterEach(() => { + vi.mocked(input).mockReset() + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + }) + + it.for([ + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s writes the JDK named after a yes to reachability.javaHome', + async ({ 1: setup }) => { + answerReachability(true, '$JAVA17_HOME') + const config: Record = { javaHome: '/opt/jdk-11' } + + const result = await setup(config) + + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(config).toEqual({ + javaHome: '/opt/jdk-11', + reachability: { javaHome: '$JAVA17_HOME' }, + }) + }, + ) + + it('writes nothing on a no and never asks for the JDK', async () => { + answerReachability(false, '/never-asked') + const config: Record = {} + + await setupMaven(config) + + expect(config).toEqual({}) + expect( + vi + .mocked(input) + .mock.calls.some(([{ message }]) => message.includes('reachability')), + ).toBe(false) + }) + + it('leaves a value it shows as is on a no, neither clearing nor restating it', async () => { + answerReachability(false) + const config: Record = { + reachability: { javaHome: '/opt/jdk-17' }, + } + + await setupMaven(config) + + expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) + }) + + it('offers the shown value as the default and clears it on a blank answer', async () => { + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === REACHABILITY_QUESTION ? true : (def ?? ''), + ) + const shown: unknown[] = [] + vi.mocked(input).mockImplementation(async ({ default: def, message }) => { + if (message.startsWith('What JDK should reachability analysis use?')) { + shown.push(def) + return '' + } + return def ?? '' + }) + const config: Record = { + reachability: { javaHome: '/opt/jdk-17' }, + } + + await setupGradle(config, { factsOnly: true }) + + expect(shown).toEqual(['/opt/jdk-17']) + expect(config['reachability']).toEqual({ javaHome: null }) + }) + + it('does not ask in pom mode, where no facts reach a reachability run', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return def ?? '' + }) + + await setupGradle({ facts: false }) + await setupSbt({ facts: false }) + + expect(messages).not.toContain(REACHABILITY_QUESTION) + }) +}) + describe('setupDotnet', () => { it('preserves explicit nulls on a blank re-prompt', async () => { const config: Record = { bin: null, dotnetOpts: null } diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 82e4d68c1b..bbf326dff0 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -571,6 +571,34 @@ describe('setupRecursiveManifestConfig', () => { }) }) + it('seeds reachability with both the inherited and the own fields', async () => { + await writeSettings('.', { + maven: { reachability: { javaHome: '/opt/jdk-17' } }, + }) + await writeSettings('legacy', { maven: { reachability: { other: 'x' } } }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + let seeded: unknown + vi.mocked(setupMaven).mockImplementation(async config => { + seeded = structuredClone(config) + return { ok: true, data: { canceled: false } } + }) + answer([ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ]) + + await setupRecursiveManifestConfig(repo, false) + + expect(seeded).toEqual({ + reachability: { javaHome: '/opt/jdk-17', other: 'x' }, + }) + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { other: 'x' }, + }) + }) + it('loads a build left skipped under its own name, so its modules are not asked about', async () => { await writeSettings('legacy', { builds: { 'pom.xml': { disabled: true } }, From f09d14a34b10df498b2b991da2395623985628fe Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Mon, 16 Nov 2026 15:11:59 +0100 Subject: [PATCH 08/23] Add a per-tool reachability build setting to socket.json `defaults.manifest.{dotnet,gradle,maven,sbt}.reachability.build` says whether reachability analysis builds the project first: "compile" or "none", with unset meaning "none". It cascades through nested socket.json files field by field within `reachability`, as `javaHome` does, so a nested "none" overrides an inherited "compile". dotnet gains a `reachability` section for it; `javaHome` stays JVM-only. Reading a socket.json now rejects any other value, naming the key and the allowed values. The reads that fall back to the default socket.json on an unreadable file fail the command instead, so a mistyped value is never dropped silently. --- .../manifest/setup-manifest-config.mts | 4 +- src/utils/socket-json.mts | 94 ++++++++---- src/utils/socket-json.test.mts | 136 +++++++++++++++++- 3 files changed, 201 insertions(+), 33 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 82c3c96457..2f408cc3ca 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -14,8 +14,8 @@ import { import type { CResult } from '../../types.mts' import type { + JvmReachabilityDefaults, ManifestDefaults, - ReachabilityDefaults, } from '../../utils/socket-json.mts' // Whether the prompt was canceled. A blank answer clears a value set before @@ -735,7 +735,7 @@ async function askForIgnoreUnresolvedFlag( // Settings only the reachability run reads. A "no" leaves a setting as it is, // so an inherited value is neither pinned nor cleared. async function setupReachability(config: { - reachability?: ReachabilityDefaults | undefined + reachability?: JvmReachabilityDefaults | undefined }): Promise> { const reachability = { ...config.reachability } diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 659dcd377c..1158d9bda7 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -24,15 +24,24 @@ import path from 'node:path' import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' -import { formatErrorWithDetail } from './errors.mts' +import { InputError, formatErrorWithDetail } from './errors.mts' import { findUp } from './fs.mts' import { SOCKET_JSON, SOCKET_WEBSITE_URL } from '../constants.mts' import type { CResult } from '../types.mts' +export const REACHABILITY_BUILD_MODES = ['compile', 'none'] as const + +// Whether reachability analysis builds the project first; unset means none. +export type ReachabilityBuild = (typeof REACHABILITY_BUILD_MODES)[number] + // Settings only the reachability run reads; they cascade field by field like // the rest of an ecosystem's section. export type ReachabilityDefaults = { + build?: ReachabilityBuild | undefined +} + +export type JvmReachabilityDefaults = ReachabilityDefaults & { // JDK for reachability analysis; passed to Coana as written. javaHome?: string | undefined | null } @@ -83,6 +92,7 @@ export interface SocketJson { excludeConfigs?: string | undefined | null includeConfigs?: string | undefined | null ignoreUnresolved?: boolean | undefined + reachability?: ReachabilityDefaults | undefined verbose?: boolean | undefined } gradle?: { @@ -101,7 +111,7 @@ export interface SocketJson { // JDK path; sets JAVA_HOME for this ecosystem's build tool. Supports // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null - reachability?: ReachabilityDefaults | undefined + reachability?: JvmReachabilityDefaults | undefined verbose?: boolean | undefined } maven?: { @@ -117,7 +127,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null mavenOpts?: string | undefined | null - reachability?: ReachabilityDefaults | undefined + reachability?: JvmReachabilityDefaults | undefined verbose?: boolean | undefined } sbt?: { @@ -136,7 +146,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null outfile?: string | undefined | null - reachability?: ReachabilityDefaults | undefined + reachability?: JvmReachabilityDefaults | undefined sbtOpts?: string | undefined | null stdout?: boolean | undefined verbose?: boolean | undefined @@ -171,12 +181,41 @@ export type SocketJsonBuildEntry = { export type SocketJsonInDir = { dir: string; sockJson: SocketJson } +const REACHABILITY_BUILD_TOOLS = ['dotnet', 'gradle', 'maven', 'sbt'] as const + +// With `defaultOnError`, only an invalid value fails a read. +function socketJsonOrThrow(jsonCResult: CResult): SocketJson { + if (!jsonCResult.ok) { + throw new InputError( + `${jsonCResult.message}: ${jsonCResult.cause ?? 'unknown cause'}`, + ) + } + return jsonCResult.data +} + +function validateSocketJson( + sockJson: SocketJson, + sockJsonPath: string, +): CResult { + for (const tool of REACHABILITY_BUILD_TOOLS) { + const build: unknown = + sockJson.defaults?.manifest?.[tool]?.reachability?.build + if ( + build !== undefined && + !(REACHABILITY_BUILD_MODES as readonly unknown[]).includes(build) + ) { + return { + ok: false, + message: `Invalid ${SOCKET_JSON} at ${sockJsonPath}`, + cause: `\`defaults.manifest.${tool}.reachability.build\` is ${JSON.stringify(build)}; set it to ${REACHABILITY_BUILD_MODES.map(m => `"${m}"`).join(' or ')}, or remove it`, + } + } + } + return { ok: true, data: sockJson } +} + export function readOrDefaultSocketJson(cwd: string): SocketJson { - const jsonCResult = readSocketJsonSync(cwd, true) - return jsonCResult.ok - ? jsonCResult.data - : // This should be unreachable but it makes TS happy. - getDefaultSocketJson() + return socketJsonOrThrow(readSocketJsonSync(cwd, true)) } export async function findSocketJsonUp( @@ -191,13 +230,12 @@ export async function readOrDefaultSocketJsonUp( const socketJsonPath = await findSocketJsonUp(cwd) if (socketJsonPath) { const socketJsonDir = path.dirname(socketJsonPath) - const jsonCResult = readSocketJsonSync(socketJsonDir, true) - return jsonCResult.ok ? jsonCResult.data : getDefaultSocketJson() + return socketJsonOrThrow(readSocketJsonSync(socketJsonDir, true)) } return getDefaultSocketJson() } -function mergeJvmDefaults< +function mergeBuildToolDefaults< T extends { reachability?: ReachabilityDefaults | undefined }, >(base: T | undefined, override: T): T { const merged = { ...base, ...override } @@ -207,7 +245,7 @@ function mergeJvmDefaults< return merged } -// Merges `defaults.manifest.` per ecosystem, and a JVM section's +// Merges `defaults.manifest.` per ecosystem, and a build tool's // `reachability` within it: fields set in `override` win, others fall through // to `base`. Only this section cascades; everything else in `defaults` comes // from `base` only. @@ -230,25 +268,25 @@ function mergeManifestDefaults( mergedManifest.conda = { ...baseManifest?.conda, ...overrideManifest.conda } } if (overrideManifest.dotnet) { - mergedManifest.dotnet = { - ...baseManifest?.dotnet, - ...overrideManifest.dotnet, - } + mergedManifest.dotnet = mergeBuildToolDefaults( + baseManifest?.dotnet, + overrideManifest.dotnet, + ) } if (overrideManifest.gradle) { - mergedManifest.gradle = mergeJvmDefaults( + mergedManifest.gradle = mergeBuildToolDefaults( baseManifest?.gradle, overrideManifest.gradle, ) } if (overrideManifest.maven) { - mergedManifest.maven = mergeJvmDefaults( + mergedManifest.maven = mergeBuildToolDefaults( baseManifest?.maven, overrideManifest.maven, ) } if (overrideManifest.sbt) { - mergedManifest.sbt = mergeJvmDefaults( + mergedManifest.sbt = mergeBuildToolDefaults( baseManifest?.sbt, overrideManifest.sbt, ) @@ -275,10 +313,10 @@ export function readSocketJsonChain(dir: string): SocketJsonInDir[] { let current = path.resolve(dir) for (;;) { if (existsSync(path.join(current, SOCKET_JSON))) { - const jsonCResult = readSocketJsonSync(current, true) - if (jsonCResult.ok) { - chain.unshift({ dir: current, sockJson: jsonCResult.data }) - } + chain.unshift({ + dir: current, + sockJson: socketJsonOrThrow(readSocketJsonSync(current, true)), + }) } const parent = path.dirname(current) if (parent === current) { @@ -356,9 +394,7 @@ export async function readSocketJson( return { ok: true, data: getDefaultSocketJson() } } - // Do we really care to validate? All properties are optional so code will have - // to check every step of the way regardless. Who cares about validation here...? - return { ok: true, data: obj } + return validateSocketJson(obj, sockJsonPath) } export function readSocketJsonSync( @@ -416,9 +452,7 @@ export function readSocketJsonSync( return { ok: true, data: getDefaultSocketJson() } } - // TODO: Do we need to validate? All properties are optional so code will have - // to check every step of the way regardless. - return { ok: true, data: jsonObj } + return validateSocketJson(jsonObj, sockJsonPath) } export async function writeSocketJson( diff --git a/src/utils/socket-json.test.mts b/src/utils/socket-json.test.mts index 8e082322b6..5c203c1c1c 100644 --- a/src/utils/socket-json.test.mts +++ b/src/utils/socket-json.test.mts @@ -4,7 +4,13 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mergeSocketJsonChain, readSocketJsonChain } from './socket-json.mts' +import { InputError } from './errors.mts' +import { + mergeSocketJsonChain, + readOrDefaultSocketJson, + readSocketJsonChain, + readSocketJsonSync, +} from './socket-json.mts' import type { SocketJson } from './socket-json.mts' @@ -229,5 +235,133 @@ describe('readSocketJsonChain and mergeSocketJsonChain', () => { javaHome: '/opt/sbt-jdk', }) }) + + it('cascades the reachability build field by field, for dotnet too', async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { build: 'compile' } }, + maven: { reachability: { javaHome: '$JAVA17_HOME' } }, + }, + }, + }) + await writeSocketJson(buildRoot, { + version: 1, + defaults: { + manifest: { + dotnet: { bin: 'dotnet' }, + maven: { reachability: { build: 'compile' } }, + }, + }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(result.defaults?.manifest?.dotnet).toEqual({ + bin: 'dotnet', + reachability: { build: 'compile' }, + }) + expect(mavenConfig(result)?.reachability).toEqual({ + build: 'compile', + javaHome: '$JAVA17_HOME', + }) + }) + + it("lets a nested socket.json's none override an inherited compile", async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { gradle: { reachability: { build: 'compile' } } }, + }, + }) + await writeSocketJson(buildRoot, { + version: 1, + defaults: { manifest: { gradle: { reachability: { build: 'none' } } } }, + }) + + const result = readSocketJsonCascade(buildRoot) + expect(result.defaults?.manifest?.gradle?.reachability).toEqual({ + build: 'none', + }) + }) + }) +}) + +describe('reachability.build validation', () => { + let dir = '' + + beforeEach(async () => { + dir = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'socket-json-build-')), + ) + }) + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }) + }) + + it.for(['compile', 'none', undefined])( + 'accepts a build of %s', + async build => { + const sockJson = { + version: 1, + defaults: { manifest: { maven: { reachability: { build } } } }, + } + await writeSocketJson(dir, sockJson) + + expect(readSocketJsonSync(dir)).toEqual({ + ok: true, + data: JSON.parse(JSON.stringify(sockJson)), + }) + }, + ) + + it.for(['dotnet', 'gradle', 'maven', 'sbt'])( + 'rejects any other %s build, naming the key and the allowed values, even with defaultOnError', + async tool => { + await writeSocketJson(dir, { + version: 1, + defaults: { + manifest: { [tool]: { reachability: { build: 'package' } } }, + }, + }) + + expect(readSocketJsonSync(dir, true)).toEqual({ + ok: false, + message: `Invalid socket.json at ${path.join(dir, 'socket.json')}`, + cause: `\`defaults.manifest.${tool}.reachability.build\` is "package"; set it to "compile" or "none", or remove it`, + }) + }, + ) + + it('rejects a null build, as only an absent one means none', async () => { + await writeSocketJson(dir, { + version: 1, + defaults: { manifest: { sbt: { reachability: { build: null } } } }, + }) + + expect(readSocketJsonSync(dir).ok).toBe(false) + }) + + it('fails the command rather than falling back to the default socket.json', async () => { + await writeSocketJson(dir, { + version: 1, + defaults: { manifest: { gradle: { reachability: { build: true } } } }, + }) + + expect(() => readOrDefaultSocketJson(dir)).toThrow(InputError) + expect(() => readOrDefaultSocketJson(dir)).toThrow( + /defaults\.manifest\.gradle\.reachability\.build` is true; set it to "compile" or "none"/, + ) + }) + + it("fails the cascade on a nested socket.json's invalid build", async () => { + const buildRoot = path.join(dir, 'project') + await fs.mkdir(buildRoot) + await writeSocketJson(buildRoot, { + version: 1, + defaults: { manifest: { maven: { reachability: { build: 'Compile' } } } }, + }) + + expect(() => readSocketJsonCascade(buildRoot)).toThrow(InputError) }) }) From 35803722a0269e6c599ea8b232b6a7e6b2244ecd Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Mon, 16 Nov 2026 15:14:44 +0100 Subject: [PATCH 09/23] Send a per-tool reachability build setting to Coana Each build root's request to `coana generate-socket-facts` carries the tool's `reachability.build` from socket.json, as configured ("none" or "compile"), as `config.reachability.build` next to `config.reachability.javaHome`; it is absent when unset. This covers dotnet roots too. Facts generation ignores it; Coana keeps it with the root's state for the later reachability run. --- .../manifest/generate-recursive-manifests.mts | 27 +++++++--- .../generate-recursive-manifests.test.mts | 51 +++++++++++++++++++ .../manifest/generate_auto_manifest.mts | 3 ++ .../manifest/generate_auto_manifest.test.mts | 31 +++++++++++ src/commands/manifest/run-manifest-facts.mts | 20 ++++++-- .../manifest/run-manifest-facts.test.mts | 30 ++++++++++- 6 files changed, 151 insertions(+), 11 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 7adb4bae3f..174e12d287 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -61,7 +61,7 @@ import type { } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' -import type { SocketJson } from '../../utils/socket-json.mts' +import type { ReachabilityBuild, SocketJson } from '../../utils/socket-json.mts' export type RecursiveManifestOutcomeStatus = | 'aborted' @@ -87,7 +87,10 @@ export type EcosystemBuildConfig = { ignoreUnresolved: boolean includeConfigs: string javaHome: string | undefined - reachability: { javaHome: string | undefined } + reachability: { + build: ReachabilityBuild | undefined + javaHome: string | undefined + } // Set when this build root should be skipped entirely (never invoked). skipReason: string | undefined verbose: boolean @@ -935,7 +938,10 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: undefined, - reachability: { javaHome: undefined }, + reachability: { + build: config?.reachability?.build, + javaHome: undefined, + }, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } @@ -950,7 +956,10 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - reachability: { javaHome: config?.reachability?.javaHome ?? undefined }, + reachability: { + build: config?.reachability?.build, + javaHome: config?.reachability?.javaHome ?? undefined, + }, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } @@ -965,7 +974,10 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - reachability: { javaHome: config?.reachability?.javaHome ?? undefined }, + reachability: { + build: config?.reachability?.build, + javaHome: config?.reachability?.javaHome ?? undefined, + }, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } @@ -982,7 +994,10 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - reachability: { javaHome: config?.reachability?.javaHome ?? undefined }, + reachability: { + build: config?.reachability?.build, + javaHome: config?.reachability?.javaHome ?? undefined, + }, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 39c2fbcf1a..7f942dd7ec 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -869,6 +869,57 @@ describe('generateRecursiveManifests', () => { } }) + it("passes each root's reachability build on its request, dotnet's too", async () => { + const outer = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'dsi-reachability-build-')), + ) + try { + for (const file of [ + 'dotnet/App.sln', + 'gradle/build.gradle', + 'maven/pom.xml', + 'sbt/build.sbt', + ]) { + // eslint-disable-next-line no-await-in-loop + await fs.mkdir(path.join(outer, path.dirname(file))) + // eslint-disable-next-line no-await-in-loop + await fs.writeFile(path.join(outer, file), '') + } + mockCascade(() => ({ + defaults: { + manifest: { + dotnet: { reachability: { build: 'compile' } }, + gradle: { + reachability: { build: 'compile', javaHome: '$GRADLE_JDK' }, + }, + maven: { reachability: { build: 'none' } }, + }, + }, + })) + mockFacts(async ({ cwd }) => ({ + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [], + })) + + await generateRecursiveManifests({ cwd: outer, verbose: false }) + + expect( + Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ), + ).toStrictEqual({ + dotnet: { build: 'compile', javaHome: undefined }, + gradle: { build: 'compile', javaHome: '$GRADLE_JDK' }, + maven: { build: 'none', javaHome: undefined }, + sbt: { build: undefined, javaHome: undefined }, + }) + } finally { + await fs.rm(outer, { recursive: true, force: true }) + } + }) + it('resolves an explicit null override back to the no-restriction default, not a literal null', async () => { mockCascade(dir => dir === dualMarkerDir diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index fc56e43f99..541f77044b 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -125,6 +125,7 @@ export async function generateAutoManifest({ includeConfigs: sockJson.defaults?.manifest?.sbt?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.sbt?.javaHome ?? undefined, reachability: { + build: sockJson.defaults?.manifest?.sbt?.reachability?.build, javaHome: sockJson.defaults?.manifest?.sbt?.reachability?.javaHome ?? undefined, @@ -177,6 +178,7 @@ export async function generateAutoManifest({ sockJson.defaults?.manifest?.gradle?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.gradle?.javaHome ?? undefined, reachability: { + build: sockJson.defaults?.manifest?.gradle?.reachability?.build, javaHome: sockJson.defaults?.manifest?.gradle?.reachability?.javaHome ?? undefined, @@ -215,6 +217,7 @@ export async function generateAutoManifest({ includeConfigs: sockJson.defaults?.manifest?.maven?.includeConfigs ?? '', javaHome: sockJson.defaults?.manifest?.maven?.javaHome ?? undefined, reachability: { + build: sockJson.defaults?.manifest?.maven?.reachability?.build, javaHome: sockJson.defaults?.manifest?.maven?.reachability?.javaHome ?? undefined, diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index 53970da052..dd8614d4dd 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -303,6 +303,35 @@ describe('generateAutoManifest — bazel branch', () => { }) }) + it('passes each JVM build tool its socket.json reachability build as configured', async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { + gradle: { reachability: { build: 'compile' } }, + maven: { bin: 'mvn', reachability: { build: 'none' } }, + sbt: { reachability: { javaHome: '$SBT_JDK' } }, + }, + }, + } as SocketJson) + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, maven: true, sbt: true }, + outputKind: 'text', + verbose: false, + }) + expect( + Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ), + ).toStrictEqual({ + gradle: { build: 'compile', javaHome: undefined }, + maven: { build: 'none', javaHome: undefined }, + sbt: { build: undefined, javaHome: '$SBT_JDK' }, + }) + }) + it('uses the gradle pom generator when defaults.manifest.gradle.facts is false', async () => { vi.mocked(readOrDefaultSocketJson).mockReturnValue({ defaults: { manifest: { gradle: { facts: false } } }, @@ -458,6 +487,7 @@ describe('generateAutoManifest — dotnet branch', () => { dotnetOpts: '-p:Configuration=Release', includeConfigs: 'net8.0', ignoreUnresolved: true, + reachability: { build: 'compile' }, }, }, }, @@ -470,6 +500,7 @@ describe('generateAutoManifest — dotnet branch', () => { buildOpts: ['-p:Configuration=Release'], ignoreUnresolved: true, includeConfigs: 'net8.0', + reachability: { build: 'compile', javaHome: undefined }, }), cwd: '/tmp/repo', }), diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index a24798ce23..a8292fcbf2 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -16,6 +16,7 @@ import { getOrInsert } from '../../utils/get-or-insert.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' +import type { ReachabilityBuild } from '../../utils/socket-json.mts' export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' @@ -115,7 +116,9 @@ type SocketFactsRequest = { ignoreUnresolved: boolean includeConfigs?: string | undefined javaHome?: string | undefined - reachability?: { javaHome: string } | undefined + reachability?: + | { build?: ReachabilityBuild | undefined; javaHome?: string | undefined } + | undefined verbose: boolean } entryFile?: string | undefined @@ -238,7 +241,9 @@ export type SocketFactsRequestOptions = { // As written: Coana expands `$VAR` references itself. javaHome?: string | undefined // Unused by facts generation: Coana keeps it for the reachability run. - reachability?: { javaHome?: string | undefined } | undefined + reachability?: + | { build?: ReachabilityBuild | undefined; javaHome?: string | undefined } + | undefined verbose?: boolean | undefined } @@ -287,8 +292,15 @@ function toSocketFactsRequest({ ignoreUnresolved, ...(includeConfigs ? { includeConfigs } : {}), ...(javaHome ? { javaHome } : {}), - ...(reachability?.javaHome - ? { reachability: { javaHome: reachability.javaHome } } + ...(reachability?.build || reachability?.javaHome + ? { + reachability: { + ...(reachability.build ? { build: reachability.build } : {}), + ...(reachability.javaHome + ? { javaHome: reachability.javaHome } + : {}), + }, + } : {}), verbose, }, diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 67278c6c97..7c9daed688 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -137,12 +137,40 @@ describe('runManifestFacts', () => { }) }) + it.for(['compile', 'none'] as const)( + 'sends a reachability build of %s as configured, next to javaHome', + async build => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ + ...baseArgs, + cwd, + reachability: { build, javaHome: '$JAVA17_HOME' }, + }) + expect(calls[0]!.request.config.reachability).toEqual({ + build, + javaHome: '$JAVA17_HOME', + }) + }, + ) + + it('sends a reachability build without a javaHome', async () => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ + ...baseArgs, + cwd, + reachability: { build: 'compile' }, + }) + expect(calls[0]!.request.config.reachability).toEqual({ + build: 'compile', + }) + }) + it('sends no reachability settings when none are set', async () => { coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd, - reachability: { javaHome: undefined }, + reachability: { build: undefined, javaHome: undefined }, }) expect(calls[0]!.request.config).not.toHaveProperty('reachability') }) From 093e3194e78f091d8a21aa50f18d7076743beeaa Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Mon, 16 Nov 2026 15:16:36 +0100 Subject: [PATCH 10/23] Ask whether to build before reachability analysis in the setup wizards The dotnet, Gradle, Maven and sbt sub-wizards' reachability step now asks "Build project before reachability analysis? Note: A failed build fails the scan." A yes writes "compile" to `reachability.build`. A no leaves it unset, except where the project would otherwise inherit "compile" from an ancestor socket.json; there it writes "none" so the answer takes effect. The JDK question that follows stays JVM-only. Pom mode still skips the step, as it produces no facts for a reachability run. --- .../manifest/setup-manifest-config.mts | 96 +++++++++--- .../manifest/setup-manifest-config.test.mts | 138 ++++++++++++++++++ .../setup-recursive-manifest-config.mts | 34 ++++- .../setup-recursive-manifest-config.test.mts | 64 +++++++- 4 files changed, 309 insertions(+), 23 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 2f408cc3ca..620c36ec21 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -16,8 +16,14 @@ import type { CResult } from '../../types.mts' import type { JvmReachabilityDefaults, ManifestDefaults, + ReachabilityBuild, } from '../../utils/socket-json.mts' +export type ReachabilityStepOptions = { + // What the project inherits from ancestor socket.json files. + inheritedReachabilityBuild?: ReachabilityBuild | undefined +} + // Whether the prompt was canceled. A blank answer clears a value set before // with null rather than deleting the key, so it doesn't silently start // inheriting an ancestor's value again. @@ -318,6 +324,7 @@ async function setupConda( export async function setupDotnet( config: ManifestDefaults<'dotnet'>, + { inheritedReachabilityBuild }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'dotnet'))) { return canceledByUser() @@ -347,14 +354,20 @@ export async function setupDotnet( return canceledByUser() } - return notCanceled() + return await setupReachability(config, { + askJavaHome: false, + inheritedReachabilityBuild, + }) } export async function setupGradle( config: ManifestDefaults<'gradle'>, // Set by the recursive dynamic-sbom-inference wizard, which has no // pom-mode equivalent - skips the facts/pom question entirely. - { factsOnly = false }: { factsOnly?: boolean } = {}, + { + factsOnly = false, + inheritedReachabilityBuild, + }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if ( applyAnswer(config, 'bin', await askForBin(config.bin || '', './gradlew')) @@ -404,7 +417,7 @@ export async function setupGradle( } if (generatesFacts) { - return await setupReachability(config) + return await setupReachability(config, { inheritedReachabilityBuild }) } return notCanceled() @@ -412,6 +425,7 @@ export async function setupGradle( export async function setupMaven( config: ManifestDefaults<'maven'>, + { inheritedReachabilityBuild }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'mvn'))) { return canceledByUser() @@ -448,13 +462,16 @@ export async function setupMaven( return canceledByUser() } - return await setupReachability(config) + return await setupReachability(config, { inheritedReachabilityBuild }) } export async function setupSbt( config: ManifestDefaults<'sbt'>, // See setupGradle's matching parameter for why. - { factsOnly = false }: { factsOnly?: boolean } = {}, + { + factsOnly = false, + inheritedReachabilityBuild, + }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'sbt'))) { return canceledByUser() @@ -530,7 +547,7 @@ export async function setupSbt( } if (generatesFacts) { - return await setupReachability(config) + return await setupReachability(config, { inheritedReachabilityBuild }) } return notCanceled() @@ -732,13 +749,64 @@ async function askForIgnoreUnresolvedFlag( }) } -// Settings only the reachability run reads. A "no" leaves a setting as it is, -// so an inherited value is neither pinned nor cleared. -async function setupReachability(config: { - reachability?: JvmReachabilityDefaults | undefined -}): Promise> { +// Settings only the reachability run reads. A "no" to the JDK leaves it as it +// is, so an inherited value is neither pinned nor cleared; a "no" to building +// unsets the build, and writes "none" only to override an inherited "compile". +async function setupReachability( + config: { reachability?: JvmReachabilityDefaults | undefined }, + { + askJavaHome = true, + inheritedReachabilityBuild, + }: ReachabilityStepOptions & { askJavaHome?: boolean | undefined } = {}, +): Promise> { const reachability = { ...config.reachability } + const wantsBuild = await select({ + message: + 'Build project before reachability analysis? Note: A failed build fails the scan.', + choices: [ + { + name: 'no', + value: false, + description: 'Analyze the project without building it', + }, + { + name: 'yes', + value: true, + description: 'Compile the project before reachability analysis', + }, + ], + default: reachability.build === 'compile', + }) + if (wantsBuild === undefined || wantsBuild === null) { + return canceledByUser() + } + if (wantsBuild) { + reachability.build = 'compile' + } else if (inheritedReachabilityBuild === 'compile') { + reachability.build = 'none' + } else { + delete reachability.build + } + + if (askJavaHome) { + const javaHome = await setupReachabilityJavaHome(reachability) + if (!javaHome.ok || javaHome.data.canceled) { + return javaHome + } + } + + if (Object.keys(reachability).length) { + config.reachability = reachability + } else { + delete config.reachability + } + return notCanceled() +} + +async function setupReachabilityJavaHome( + reachability: JvmReachabilityDefaults, +): Promise> { const wantsJavaHome = await select({ message: 'Use a different Java for reachability analysis?', choices: [ @@ -771,12 +839,6 @@ async function setupReachability(config: { ) { return canceledByUser() } - - if (Object.keys(reachability).length) { - config.reachability = reachability - } else { - delete config.reachability - } return notCanceled() } diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 9d363286b0..1be279a635 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -195,6 +195,144 @@ describe('reachability step', () => { }) }) +describe('reachability build step', () => { + const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' + + // Answers the build question with `wantsBuild`; every other prompt keeps + // its default. Returns the build question's shown default per call. + function answerBuild(wantsBuild: boolean): unknown[] { + const shown: unknown[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message === BUILD_QUESTION) { + shown.push(def) + return wantsBuild + } + return def ?? '' + }) + return shown + } + + afterEach(() => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + }) + + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s writes compile to reachability.build after a yes', + async ({ 1: setup }) => { + answerBuild(true) + const config: Record = {} + + const result = await setup(config) + + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(config).toEqual({ reachability: { build: 'compile' } }) + }, + ) + + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s leaves reachability.build unset after a no at the top level, never writing none', + async ({ 1: setup }) => { + answerBuild(false) + const config: Record = {} + + await setup(config) + + expect(config).toEqual({}) + }, + ) + + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s writes none after a no when the project inherits compile', + async ({ 1: setup }) => { + const shown = answerBuild(false) + const config: Record = { + reachability: { build: 'compile' }, + } + + await setup(config, { inheritedReachabilityBuild: 'compile' }) + + expect(shown).toEqual([true]) + expect(config).toEqual({ reachability: { build: 'none' } }) + }, + ) + + it('leaves the build unset after a no when the project inherits none', async () => { + answerBuild(false) + const config: Record = { reachability: { build: 'none' } } + + await setupGradle(config, { inheritedReachabilityBuild: 'none' }) + + expect(config).toEqual({}) + }) + + it('unsets a build it shows as the default after a no, keeping the JDK', async () => { + const shown = answerBuild(false) + const config: Record = { + reachability: { build: 'compile', javaHome: '/opt/jdk-17' }, + } + + await setupMaven(config) + + expect(shown).toEqual([true]) + expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) + }) + + it('removes a written none after a no', async () => { + const shown = answerBuild(false) + const config: Record = { reachability: { build: 'none' } } + + await setupDotnet(config) + + expect(shown).toEqual([false]) + expect(config).toEqual({}) + }) + + it('never asks dotnet for a reachability JDK', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return message === BUILD_QUESTION ? true : (def ?? '') + }) + const config: Record = {} + + await setupDotnet(config) + + expect(messages).toContain(BUILD_QUESTION) + expect(messages.some(m => m.includes('Java'))).toBe(false) + expect(config).toEqual({ reachability: { build: 'compile' } }) + }) + + it('does not ask in pom mode, where no facts reach a reachability run', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return def ?? '' + }) + + await setupGradle({ facts: false }) + await setupSbt({ facts: false }) + + expect(messages).not.toContain(BUILD_QUESTION) + }) +}) + describe('setupDotnet', () => { it('preserves explicit nulls on a blank re-prompt', async () => { const config: Record = { bin: null, dotnetOpts: null } diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index 640fa485a4..b602a16434 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -57,9 +57,11 @@ import type { import type { BuildRoot, Membership } from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { BuildTool } from './scripts/build-tool.mts' +import type { ReachabilityStepOptions } from './setup-manifest-config.mts' import type { CResult } from '../../types.mts' import type { ManifestDefaults, + ReachabilityBuild, SocketJson, SocketJsonInDir, } from '../../utils/socket-json.mts' @@ -106,6 +108,15 @@ function changedFields( return changed } +function inheritedReachabilityBuildOf( + inherited: Record, +): ReachabilityBuild | undefined { + const reachability = inherited['reachability'] + return isObjectObject(reachability) + ? (reachability['build'] as ReachabilityBuild | undefined) + : undefined +} + function getEcosystemSection( sockJson: SocketJson, ecosystem: BuildTool, @@ -474,7 +485,9 @@ async function configureBuild( } const seeded = Object.keys(seed) - const result = await runEcosystemWizard(ecosystem, seed) + const result = await runEcosystemWizard(ecosystem, seed, { + inheritedReachabilityBuild: inheritedReachabilityBuildOf(inherited), + }) if (!result.ok || result.data.canceled) { return result } @@ -830,19 +843,24 @@ async function reviewBuild( async function runEcosystemWizard( ecosystem: BuildTool, config: Record, + options: ReachabilityStepOptions = {}, ): Promise> { if (ecosystem === 'dotnet') { - return await setupDotnet(config as ManifestDefaults<'dotnet'>) + return await setupDotnet(config as ManifestDefaults<'dotnet'>, options) } if (ecosystem === 'gradle') { return await setupGradle(config as ManifestDefaults<'gradle'>, { + ...options, factsOnly: true, }) } if (ecosystem === 'maven') { - return await setupMaven(config as ManifestDefaults<'maven'>) + return await setupMaven(config as ManifestDefaults<'maven'>, options) } - return await setupSbt(config as ManifestDefaults<'sbt'>, { factsOnly: true }) + return await setupSbt(config as ManifestDefaults<'sbt'>, { + ...options, + factsOnly: true, + }) } // Accepting every prompt's default leaves an ecosystem's section empty (see @@ -925,8 +943,14 @@ async function setupRootDefaults( const manifest = manifestOf(own) const section = { ...getEcosystemSection(own, ecosystem) } manifest[ecosystem] = section + const inherited = getEcosystemSection( + draftCascade(draft, path.dirname(cwd)), + ecosystem, + ) // eslint-disable-next-line no-await-in-loop - const result = await runEcosystemWizard(ecosystem, section) + const result = await runEcosystemWizard(ecosystem, section, { + inheritedReachabilityBuild: inheritedReachabilityBuildOf(inherited), + }) if (!result.ok || result.data.canceled) { return result } diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index bbf326dff0..9e37da3b5a 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -17,6 +17,7 @@ vi.mock('./run-manifest-facts.mts', async importOriginal => ({ listBuildProjects: vi.fn(), })) vi.mock('@socketsecurity/registry/lib/prompts', () => ({ + input: vi.fn(), select: vi.fn(), })) vi.mock('./setup-manifest-config.mts', () => ({ @@ -27,7 +28,7 @@ vi.mock('./setup-manifest-config.mts', () => ({ })) import { logger } from '@socketsecurity/registry/lib/logger' -import { select } from '@socketsecurity/registry/lib/prompts' +import { input, select } from '@socketsecurity/registry/lib/prompts' import { findBuildToolCandidates } from './discover-manifest-roots.mts' import { listBuildProjects } from './run-manifest-facts.mts' @@ -599,6 +600,67 @@ describe('setupRecursiveManifestConfig', () => { }) }) + describe('after a no to building before reachability analysis', () => { + const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' + + // Runs the real Maven wizard for legacy, answering the build question no + // and its other prompts with their defaults, under a parent with + // `parentBuild`. + async function configureUnder( + parentBuild: 'compile' | 'none' | undefined, + ): Promise { + const actual = await vi.importActual< + typeof import('./setup-manifest-config.mts') + >('./setup-manifest-config.mts') + vi.mocked(setupMaven).mockImplementation(actual.setupMaven) + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + await writeSettings( + '.', + parentBuild ? { maven: { reachability: { build: parentBuild } } } : {}, + ) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + const rules: Answers = [ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ] + vi.mocked(select).mockImplementation( + async ({ default: def, message }) => { + asked.push(message) + if (message === BUILD_QUESTION) { + return false as never + } + const rule = rules.find(({ 0: start }) => message.startsWith(start)) + return (rule ? rule[1] : (def ?? '')) as never + }, + ) + + const result = await setupRecursiveManifestConfig(repo, false) + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(asked).toContain(BUILD_QUESTION) + } + + it('writes none under a parent that sets compile', async () => { + await configureUnder('compile') + + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { build: 'none' }, + }) + }) + + it.for(['none', undefined] as const)( + 'leaves the build unset under a parent whose build is %s', + async parentBuild => { + await configureUnder(parentBuild) + + expect(existsSync(file('legacy/socket.json'))).toBe(false) + }, + ) + }) + it('loads a build left skipped under its own name, so its modules are not asked about', async () => { await writeSettings('legacy', { builds: { 'pom.xml': { disabled: true } }, From ff72baa7cf7a457895e659f3eaeca071e589e983 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 06:12:18 +0100 Subject: [PATCH 11/23] Name --exclude-paths in the remedies Coana reports Every command that generates Socket facts takes --exclude-paths, so each request's hints now carry it as excludePathsFlag. Coana offers it where a project resolved no dependencies and can only be left out of the scan. --- src/commands/manifest/generate-recursive-manifests.mts | 2 ++ .../manifest/generate-recursive-manifests.test.mts | 1 + src/commands/manifest/generate_auto_manifest.mts | 2 ++ src/commands/manifest/run-manifest-facts.mts | 9 +++++++++ src/commands/manifest/run-manifest-facts.test.mts | 2 ++ 5 files changed, 16 insertions(+) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 174e12d287..df3cd8cfb7 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -30,6 +30,7 @@ import { loadBuild, withModules } from './load-build.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' import { DSI_SETUP_COMMAND, + EXCLUDE_PATHS_FLAG, REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, runManifestFacts, setSidecarEntry, @@ -702,6 +703,7 @@ async function runCandidate( continueOnInstallErrorsFlag: ctx.context.workDir?.withFiles ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG : undefined, + excludePathsFlag: EXCLUDE_PATHS_FLAG, flags: ctx.optionFlags, setupCommand: DSI_SETUP_COMMAND, socketJson: socketJsonPath(root.dir), diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 7f942dd7ec..5afa9a7d8f 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -980,6 +980,7 @@ describe('generateRecursiveManifests', () => { `${opts.ecosystem}:${relOf(opts.cwd)}` === 'maven:dual-marker-dir', )?.hints expect(hints?.flags.size).toBe(0) + expect(hints?.excludePathsFlag).toBe('--exclude-paths') expect(path.resolve(hints?.socketJson ?? '')).toBe( path.join(dualMarkerDir, 'socket.json'), ) diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 541f77044b..18e0641a57 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -10,6 +10,7 @@ import { resolveEcosystemConfig } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' import { + EXCLUDE_PATHS_FLAG, REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, runManifestFacts, } from './run-manifest-facts.mts' @@ -32,6 +33,7 @@ import type { OutputKind } from '../../types.mts' // Auto-manifest reads every build option from the root socket.json. const AUTO_MANIFEST_HINTS: BuildOptionHints = { + excludePathsFlag: EXCLUDE_PATHS_FLAG, flags: new Set(), setupCommand: 'socket manifest setup', socketJson: SOCKET_JSON, diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index a8292fcbf2..5019e8fd22 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -26,6 +26,8 @@ export type BuildOptionHints = { // Reachability scans only: reachability cannot install a dependency that // `ignoreUnresolved` lets through, so it must be told to continue too. continueOnInstallErrorsFlag?: string | undefined + // The invoking command's option that leaves paths out of the scan. + excludePathsFlag?: string | undefined // Taken as flags; every other option is set in `socketJson`. flags: ReadonlySet // Wizard that writes `socketJson`. @@ -36,11 +38,14 @@ export type BuildOptionHints = { export const DSI_SETUP_COMMAND = 'socket manifest setup --dynamic-sbom-inference' +export const EXCLUDE_PATHS_FLAG = '--exclude-paths' + export const REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG = '--reach-continue-on-install-errors' // The single-build manifest commands take every option as a flag. export const FLAG_HINTS: BuildOptionHints = { + excludePathsFlag: EXCLUDE_PATHS_FLAG, flags: new Set([ 'excludeConfigs', 'ignoreUnresolved', @@ -126,6 +131,7 @@ type SocketFactsRequest = { excludePaths?: string[] | undefined hints: { continueOnInstallErrorsFlag?: string | undefined + excludePathsFlag?: string | undefined flags: BuildOption[] setupCommand: string socketJson: string @@ -180,6 +186,9 @@ function toRequestHints(hints: BuildOptionHints): SocketFactsRequest['hints'] { ...(hints.continueOnInstallErrorsFlag ? { continueOnInstallErrorsFlag: hints.continueOnInstallErrorsFlag } : {}), + ...(hints.excludePathsFlag + ? { excludePathsFlag: hints.excludePathsFlag } + : {}), flags: [...hints.flags].sort(), setupCommand: hints.setupCommand, socketJson: hints.socketJson, diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 7c9daed688..f6c4bbc352 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -111,6 +111,7 @@ describe('runManifestFacts', () => { excludeBase: cwd, excludePaths: ['docs/**'], hints: { + excludePathsFlag: '--exclude-paths', flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], setupCommand: 'socket manifest setup', socketJson: 'socket.json', @@ -330,6 +331,7 @@ describe('listDotnetSolutionMembers', () => { entryFile: 'All.sln', excludeBase: cwd, hints: { + excludePathsFlag: '--exclude-paths', flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], setupCommand: 'socket manifest setup', socketJson: 'socket.json', From 8569967eb996822dcd8666f5fd2f3afb9b38b7b0 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:21:08 +0100 Subject: [PATCH 12/23] List a skipped build with the options its run would use Loading a build that its own socket.json entry skips listed it with no Coana context and the plain-command hints, so it ignored the scan's pinned Coana version, its org and the dynamic SBOM inference hints. The walk now builds one set of options per build root and both the listing and facts generation use it. --- .../manifest/generate-recursive-manifests.mts | 64 +++++++++++-------- .../generate-recursive-manifests.test.mts | 30 +++++++++ src/commands/manifest/load-build.mts | 34 ++-------- src/commands/manifest/run-manifest-facts.mts | 17 +++-- .../manifest/run-manifest-facts.test.mts | 14 ++++ .../setup-recursive-manifest-config.mts | 11 +++- 6 files changed, 106 insertions(+), 64 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index df3cd8cfb7..4abacc0dd0 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -58,6 +58,7 @@ import type { RunManifestFactsOutcome, RunManifestFactsResult, SocketFactsContext, + SocketFactsRunOptions, SocketFactsSidecarEntry, } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' @@ -491,12 +492,8 @@ async function walkTool( if (skipOf(next) === 'load') { // eslint-disable-next-line no-await-in-loop const loaded = await loadBuild({ - config: configFor(next), - ecosystem, - excludePaths: ctx.excludePaths, - root: next.root, + ...runOptions(ctx, ecosystem, next, configFor(next)), scanRoot: ctx.realCwd, - verbose: ctx.verbose, }) const why = describeDisabledBy(ecosystem, resolvedFor(next).disabledBy!) if (loaded) { @@ -664,30 +661,15 @@ async function warnUnappliedEntry( ) } -async function runCandidate( +// How the walk runs Coana on a build root, whether to generate its facts or +// only to list what it loads. +function runOptions( ctx: WalkContext, ecosystem: BuildTool, - candidate: Candidate, + { root }: Candidate, dirConfig: EcosystemBuildConfig, -): Promise { - const { root } = candidate - const expectedFactsPath = path.join( - root.dir, - socketFactsFileName(ecosystem, root.entryFile) ?? '', - ) - const expectedKey = await realpathOrResolved(expectedFactsPath) - if (!ctx.originals.has(expectedKey)) { - ctx.originals.set( - expectedKey, - await saveFacts( - ctx, - expectedFactsPath, - expectedKey, - `${ecosystem}-${candidate.index}`, - ), - ) - } - const result = await runManifestFacts({ +): SocketFactsRunOptions { + return { bin: dirConfig.bin, buildOpts: dirConfig.buildOpts, context: ctx.context, @@ -713,7 +695,35 @@ async function runCandidate( javaHome: dirConfig.javaHome, reachability: dirConfig.reachability, verbose: ctx.verbose || dirConfig.verbose, - }) + } +} + +async function runCandidate( + ctx: WalkContext, + ecosystem: BuildTool, + candidate: Candidate, + dirConfig: EcosystemBuildConfig, +): Promise { + const { root } = candidate + const expectedFactsPath = path.join( + root.dir, + socketFactsFileName(ecosystem, root.entryFile) ?? '', + ) + const expectedKey = await realpathOrResolved(expectedFactsPath) + if (!ctx.originals.has(expectedKey)) { + ctx.originals.set( + expectedKey, + await saveFacts( + ctx, + expectedFactsPath, + expectedKey, + `${ecosystem}-${candidate.index}`, + ), + ) + } + const result = await runManifestFacts( + runOptions(ctx, ecosystem, candidate, dirConfig), + ) if (result === null) { return undefined } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 5afa9a7d8f..d616bc1894 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -1726,6 +1726,36 @@ describe('generateRecursiveManifests', () => { } }) + it('loads it with the Coana, org and hints its build would run with', async () => { + vi.mocked(listBuildProjects).mockResolvedValue( + listed(path.join(outer, 'legacy'), [mavenProject('.')]), + ) + const context = { coanaVersion: '1.2.3', orgSlug: 'acme' } + vi.spyOn(logger, 'warn').mockImplementation(() => logger) + + await generateRecursiveManifests({ + context, + cwd: outer, + optionFlags: new Set(['verbose']), + verbose: false, + }) + + expect(listBuildProjects).toHaveBeenCalledWith( + expect.objectContaining({ + context, + cwd: path.join(outer, 'legacy'), + entryFile: 'pom.xml', + hints: { + continueOnInstallErrorsFlag: undefined, + excludePathsFlag: '--exclude-paths', + flags: new Set(['verbose']), + setupCommand: 'socket manifest setup --dynamic-sbom-inference', + socketJson: expect.stringMatching(/legacy\/socket\.json$/), + }, + }), + ) + }) + it('reports a skipped build that another build includes as part of that build, warning that the skip does not apply', async () => { await fs.mkdir(path.join(outer, 'zzz-reactor'), { recursive: true }) await fs.writeFile(pom('zzz-reactor'), '') diff --git a/src/commands/manifest/load-build.mts b/src/commands/manifest/load-build.mts index 1ff150d75e..0fae5f66d6 100644 --- a/src/commands/manifest/load-build.mts +++ b/src/commands/manifest/load-build.mts @@ -3,9 +3,8 @@ import { pluralize } from '@socketsecurity/registry/lib/words' import { membershipOf } from './discover-manifest-roots.mts' import { listBuildProjects } from './run-manifest-facts.mts' -import type { BuildRoot, Membership } from './discover-manifest-roots.mts' -import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' -import type { BuildTool } from './scripts/build-tool.mts' +import type { Membership } from './discover-manifest-roots.mts' +import type { SocketFactsRunOptions } from './run-manifest-facts.mts' export type LoadedBuild = { membership: Membership @@ -15,31 +14,12 @@ export type LoadedBuild = { // Lets the build tool load a build, resolving nothing, for what it includes. export async function loadBuild({ - config, - ecosystem, - excludePaths, - root, scanRoot, - verbose, -}: { - config: EcosystemBuildConfig - ecosystem: BuildTool - excludePaths: string[] | undefined - root: BuildRoot - scanRoot: string - verbose: boolean -}): Promise { - const projects = await listBuildProjects({ - bin: config.bin, - buildOpts: config.buildOpts, - cwd: root.dir, - ecosystem, - entryFile: root.entryFile, - excludeBase: scanRoot, - excludePaths, - javaHome: config.javaHome, - verbose: verbose || config.verbose, - }) + ...options +}: SocketFactsRunOptions & { scanRoot: string }): Promise< + LoadedBuild | undefined +> { + const projects = await listBuildProjects(options) if (!projects) { return undefined } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 5019e8fd22..b87138a47b 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -256,6 +256,10 @@ export type SocketFactsRequestOptions = { verbose?: boolean | undefined } +export type SocketFactsRunOptions = SocketFactsRequestOptions & { + context?: SocketFactsContext | undefined +} + // `bin` is resolved as the build tool's own runner would: the // SOCKET_CLI_*_PATH override first, then the given bin, the project wrapper, // PATH. @@ -357,9 +361,10 @@ export async function listDotnetSolutionMembers({ // The projects a build loads, as the build reports them, without resolving its // dependencies; undefined when the build cannot list them, after reporting // why. -export async function listBuildProjects( - options: SocketFactsRequestOptions, -): Promise { +export async function listBuildProjects({ + context = {}, + ...options +}: SocketFactsRunOptions): Promise { const { cwd, ecosystem } = options const request = toSocketFactsRequest(options) if (!request.ok) { @@ -369,7 +374,7 @@ export async function listBuildProjects( const { message, result } = await runGenerateSocketFacts( request.data, ['--list-projects'], - {}, + context, ) if (!result) { logger.fail( @@ -386,9 +391,7 @@ export async function listBuildProjects( export async function runManifestFacts({ context = {}, ...options -}: SocketFactsRequestOptions & { - context?: SocketFactsContext | undefined -}): Promise { +}: SocketFactsRunOptions): Promise { const { cwd, ecosystem } = options if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { process.exitCode = 1 diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index f6c4bbc352..62198fcbae 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -402,6 +402,20 @@ describe('listBuildProjects', () => { }) }) + it('lists with the Coana version and org of its context', async () => { + coanaAnswers({ projects: [], status: 'listed' }) + await listBuildProjects({ + ...listArgs, + context: { coanaVersion: '1.2.3', orgSlug: 'acme' }, + cwd, + }) + expect(spawnCoana).toHaveBeenCalledWith( + expect.arrayContaining(['--list-projects']), + 'acme', + expect.objectContaining({ coanaVersion: '1.2.3' }), + ) + }) + it('lists nothing without running Coana when the bin cannot be resolved', async () => { process.env['SOCKET_CLI_MAVEN_PATH'] = path.join(cwd, 'missing-mvn') expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index b602a16434..d6f84e4654 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -664,14 +664,19 @@ async function loadOrAsk( allowDirectory = true, ): Promise> { for (;;) { + const config = buildConfig(walk, build) // eslint-disable-next-line no-await-in-loop const loaded = await loadBuild({ - config: buildConfig(walk, build), + bin: config.bin, + buildOpts: config.buildOpts, + cwd: build.root.dir, ecosystem: build.ecosystem, + entryFile: build.root.entryFile, + excludeBase: walk.cwd, excludePaths: walk.excludePaths, - root: build.root, + javaHome: config.javaHome, scanRoot: walk.cwd, - verbose: false, + verbose: config.verbose, }) if (loaded) { return { ok: true, data: { canceled: false, loaded } } From f198e8f3e7ac239e323a43921b6e0a8a0d12ef5f Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:26:17 +0100 Subject: [PATCH 13/23] Key sidecar entries by the facts file's real path Coana's facts path and the walk's path to the same file can differ when a directory is reached through a symlink, such as /var and /private/var on macOS, and then a kept run's sidecar entry was not found. The work dir now holds its entries in a map keyed by the real path, resolved in setSidecarEntry and sidecarEntryOf alone. --- src/commands/fix/generated-socket-facts.mts | 4 +- .../fix/generated-socket-facts.test.mts | 4 +- .../manifest/generate-recursive-manifests.mts | 7 +++- .../generate-recursive-manifests.test.mts | 10 ++--- src/commands/manifest/run-manifest-facts.mts | 24 ++++++------ .../manifest/run-manifest-facts.test.mts | 37 +++++++++++++++++-- src/commands/scan/handle-create-new-scan.mts | 6 ++- .../scan/handle-create-new-scan.test.mts | 2 +- src/commands/scan/handle-scan-reach.mts | 4 +- src/commands/scan/handle-scan-reach.test.mts | 4 +- .../scan/run-dynamic-sbom-inference.test.mts | 2 +- 11 files changed, 71 insertions(+), 33 deletions(-) diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index a1a49f5f3f..cd019ec5ac 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -73,7 +73,7 @@ export async function generateSocketFactsForFix({ const sidecarFile = path.join(tmpDir, 'sidecar.json') const workDir: SocketFactsWorkDir = { dir: path.join(tmpDir, 'work'), - entries: [], + entries: new Map(), withFiles: false, } try { @@ -90,7 +90,7 @@ export async function generateSocketFactsForFix({ paths = factsPaths.map(p => path.resolve(cwd, p)) // Written even when empty, as for reach; applying fixes looks each facts // file up in it, so an empty one is the same as none. - await writeFile(sidecarFile, JSON.stringify(workDir.entries)) + await writeFile(sidecarFile, JSON.stringify([...workDir.entries.values()])) } catch (e) { // A failed build root aborts inference after others wrote their facts. await reset(await findFactsPaths()) diff --git a/src/commands/fix/generated-socket-facts.test.mts b/src/commands/fix/generated-socket-facts.test.mts index 4f501dbe4e..650611477e 100644 --- a/src/commands/fix/generated-socket-facts.test.mts +++ b/src/commands/fix/generated-socket-facts.test.mts @@ -89,7 +89,7 @@ describe('generateSocketFactsForFix', () => { const entry = { factsFile: fresh, stateDir: path.join(tmpDir, 'work', 'x') } mockRunDynamicSbomInference.mockImplementation(async ({ context }) => { await fs.writeFile(fresh, 'generated') - context.workDir.entries.push(entry) + context.workDir.entries.set(entry.factsFile, entry) return { discardedFactsPaths: [], factsOnlyTypes: ['maven', 'nuget'], @@ -107,7 +107,7 @@ describe('generateSocketFactsForFix', () => { orgSlug: undefined, workDir: { dir: path.join(tmpDir, 'work'), - entries: [entry], + entries: new Map([[entry.factsFile, entry]]), withFiles: false, }, }, diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 4abacc0dd0..5a6c1200c0 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -763,7 +763,7 @@ async function putFacts( ): Promise { const { workDir } = ctx.context if (workDir) { - setSidecarEntry(workDir, key, state?.sidecar) + await setSidecarEntry(workDir, key, state?.sidecar) } if (!state) { return @@ -787,7 +787,10 @@ async function saveFacts( await fs.copyFile(file, facts) } const { workDir } = ctx.context - return { facts, sidecar: workDir && sidecarEntryOf(workDir, key) } + return { + facts, + sidecar: workDir && (await sidecarEntryOf(workDir, key)), + } } // Builds `root` unless earlier builds cover it, then adds what it loaded to diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index d616bc1894..e8afca09db 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -63,7 +63,7 @@ function reported({ factsPath, projects }: TestFacts) { } function newWorkDir(): SocketFactsWorkDir { - return { dir: '/work', entries: [], withFiles: true } + return { dir: '/work', entries: new Map(), withFiles: true } } function mockFacts( @@ -211,7 +211,7 @@ describe('generateRecursiveManifests', () => { mockFacts(async ({ cwd }) => { const factsPath = path.join(cwd, 'pom.xml.socket.facts.json') await fs.writeFile(factsPath, 'generated') - setSidecarEntry(workDir, factsPath, { + await setSidecarEntry(workDir, factsPath, { factsFile: factsPath, stateDir: cwd, }) @@ -248,7 +248,7 @@ describe('generateRecursiveManifests', () => { .mock.calls.some(([opts]) => opts.cwd === sharedLib), ).toBe(builtAlone) expect(await fs.readFile(sharedFacts, 'utf8')).toBe('committed') - expect(workDir.entries.map(entry => entry.factsFile)).toEqual([ + expect([...workDir.entries.values()].map(e => e.factsFile)).toEqual([ path.join(reactorA, 'pom.xml.socket.facts.json'), ]) // The restored file is not this scan's, so it is not to be collected. @@ -286,7 +286,7 @@ describe('generateRecursiveManifests', () => { mockFacts(async ({ cwd }) => { const factsPath = path.join(main, 'gradle.socket.facts.json') await fs.writeFile(factsPath, cwd) - setSidecarEntry(workDir, factsPath, { + await setSidecarEntry(workDir, factsPath, { factsFile: factsPath, stateDir: cwd, }) @@ -316,7 +316,7 @@ describe('generateRecursiveManifests', () => { expect(generated[0]!.discardedFactsPath).toBeUndefined() // The kept build's own facts and sidecar entry, whichever ran last. expect(await fs.readFile(factsPath!, 'utf8')).toBe(generated[0]!.dir) - expect(workDir.entries).toEqual([ + expect([...workDir.entries.values()]).toEqual([ { factsFile: factsPath, stateDir: generated[0]!.dir }, ]) } finally { diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index b87138a47b..044f5d2382 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -11,7 +11,7 @@ import { COANA_CLI_VERSION, SOCKET_JSON } from '../../constants.mts' import { isStandaloneSea } from '../../sea/runtime.mts' import { spawnCoana } from '../../utils/coana-release.mts' import { getErrorMessageOr } from '../../utils/errors.mts' -import { withTmpDir } from '../../utils/fs.mts' +import { realpathOrResolved, withTmpDir } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import type { BuildTool } from './scripts/build-tool.mts' @@ -66,28 +66,30 @@ export type SocketFactsSidecarEntry = { // the entries of the build roots generated into it. export type SocketFactsWorkDir = { dir: string - entries: SocketFactsSidecarEntry[] + // By the facts file's real path, as Coana's and the walk's paths to one + // file may differ in a symlinked directory. + entries: Map // Reachability only: also install the dependencies the analysis reads. withFiles: boolean } -export function sidecarEntryOf( +export async function sidecarEntryOf( workDir: SocketFactsWorkDir, factsFile: string, -): SocketFactsSidecarEntry | undefined { - return workDir.entries.find(entry => entry.factsFile === factsFile) +): Promise { + return workDir.entries.get(await realpathOrResolved(factsFile)) } // A facts file has one entry: the run that wrote it last. -export function setSidecarEntry( +export async function setSidecarEntry( workDir: SocketFactsWorkDir, factsFile: string, entry: SocketFactsSidecarEntry | undefined, -): void { - const kept = workDir.entries.filter(other => other.factsFile !== factsFile) - workDir.entries.splice(0, workDir.entries.length, ...kept) +): Promise { + const key = await realpathOrResolved(factsFile) + workDir.entries.delete(key) if (entry) { - workDir.entries.push(entry) + workDir.entries.set(key, entry) } } @@ -442,7 +444,7 @@ export async function runManifestFacts({ ) return null } - setSidecarEntry(workDir, result.factsPath, result.sidecarEntry) + await setSidecarEntry(workDir, result.factsPath, result.sidecarEntry) } return { factsPath: result.factsPath, diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 62198fcbae..48e03e403f 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -14,6 +14,7 @@ import { listBuildProjects, listDotnetSolutionMembers, runManifestFacts, + sidecarEntryOf, } from './run-manifest-facts.mts' import { COANA_CLI_VERSION } from '../../constants.mts' import { spawnCoana } from '../../utils/coana-release.mts' @@ -215,7 +216,7 @@ describe('runManifestFacts', () => { }) const workDir: SocketFactsWorkDir = { dir: '/w', - entries: [], + entries: new Map(), withFiles: true, } await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) @@ -224,7 +225,37 @@ describe('runManifestFacts', () => { '--work-dir', '/w', ]) - expect(workDir.entries).toEqual([entry]) + expect([...workDir.entries.values()]).toEqual([entry]) + }) + + it('finds the entry by the real path of a facts file Coana names through a symlink', async () => { + const real = path.join(cwd, 'real') + const link = path.join(cwd, 'link') + await fs.mkdir(real) + await fs.symlink(real, link) + await fs.writeFile(path.join(real, 'pom.xml.socket.facts.json'), '{}') + const entry = { + factsFile: path.join(link, 'pom.xml.socket.facts.json'), + stateDir: '/w/x', + } + coanaAnswers({ + factsPath: entry.factsFile, + projects: [], + sidecarEntry: entry, + status: 'generated', + }) + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + withFiles: true, + } + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd: link }) + expect( + await sidecarEntryOf( + workDir, + path.join(real, 'pom.xml.socket.facts.json'), + ), + ).toEqual(entry) }) it('keeps state without installing files for socket fix', async () => { @@ -234,7 +265,7 @@ describe('runManifestFacts', () => { sidecarEntry: { factsFile: '/r/f', stateDir: '/w/y' }, status: 'generated', }) - const workDir = { dir: '/w', entries: [], withFiles: false } + const workDir = { dir: '/w', entries: new Map(), withFiles: false } await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) expect(calls[0]!.args.slice(-2)).toEqual(['--work-dir', '/w']) expect(calls[0]!.args).not.toContain('--with-files') diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index b958148fb2..51dc1d41d1 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -172,7 +172,7 @@ async function createNewScan( workDir: reach.runReachabilityAnalysis ? { dir: path.join(manifestTmpDir, 'socket-facts-work'), - entries: [], + entries: new Map(), withFiles: true, } : undefined, @@ -335,7 +335,9 @@ async function createNewScan( packagePaths, reachabilityOptions: mergedReachabilityOptions, repoName, - socketFactsSidecar: factsContext.workDir?.entries, + socketFactsSidecar: factsContext.workDir && [ + ...factsContext.workDir.entries.values(), + ], spinner, target: targets[0]!, }) diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index acb6ecf6b1..1206484754 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -496,7 +496,7 @@ describe('handleCreateNewScan excludePaths', () => { } mockGenerateRecursiveManifests.mockImplementationOnce( async ({ context }) => { - context.workDir.entries.push(entry) + context.workDir.entries.set(entry.factsFile, entry) return [ { dir: '/repo/service-a', diff --git a/src/commands/scan/handle-scan-reach.mts b/src/commands/scan/handle-scan-reach.mts index 7e72993954..b600c67e0c 100644 --- a/src/commands/scan/handle-scan-reach.mts +++ b/src/commands/scan/handle-scan-reach.mts @@ -139,7 +139,7 @@ async function runScanReach( outputPath, packagePaths, reachabilityOptions: mergedReachabilityOptions, - socketFactsSidecar: workDir?.entries, + socketFactsSidecar: workDir && [...workDir.entries.values()], spinner, target: targets[0]!, }) @@ -171,7 +171,7 @@ export async function handleScanReach( // Coana's run reads what facts generation keeps in the work dir. return config.reachabilityOptions.dynamicSbomInference ? await withTmpDir('socket-dynamic-sbom-inference-', dir => - runScanReach(config, { dir, entries: [], withFiles: true }), + runScanReach(config, { dir, entries: new Map(), withFiles: true }), ) : await runScanReach(config, undefined) } diff --git a/src/commands/scan/handle-scan-reach.test.mts b/src/commands/scan/handle-scan-reach.test.mts index 9d7dac0743..ea20d55430 100644 --- a/src/commands/scan/handle-scan-reach.test.mts +++ b/src/commands/scan/handle-scan-reach.test.mts @@ -357,7 +357,7 @@ describe('handleScanReach', () => { } mockRunDynamicSbomInference.mockImplementationOnce( async ({ context }) => { - context.workDir.entries.push(entry) + context.workDir.entries.set(entry.factsFile, entry) return { factsOnlyTypes: ['maven'], factsPaths: [ @@ -386,7 +386,7 @@ describe('handleScanReach', () => { // A caller-owned dir that outlives the analysis reading it. workDir: { dir: expect.any(String), - entries: [entry], + entries: new Map([[entry.factsFile, entry]]), withFiles: true, }, }, diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index 5f08f517c0..f741044a5b 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -34,7 +34,7 @@ const generated = { const context = { coanaVersion: '1.2.3', - workDir: { dir: '/work', entries: [], withFiles: true }, + workDir: { dir: '/work', entries: new Map(), withFiles: true }, } function run( From 1a29f7b26325a17ae99e6c24deb4f16864062083 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:28:32 +0100 Subject: [PATCH 14/23] Validate reachability settings wherever socket.json can set them Only defaults.manifest..reachability.build was checked, so a reachability that is not an object, a non-string javaHome, or any bad value in a defaults.manifest.builds entry reached the Coana request unchecked. Each tool section and each builds entry now rejects them, naming the key and the values it takes. --- src/commands/manifest/build-root-config.mts | 8 ++++ .../manifest/build-root-config.test.mts | 12 ++++++ src/utils/socket-json.mts | 42 +++++++++++++++---- src/utils/socket-json.test.mts | 36 +++++++++++++++- 4 files changed, 90 insertions(+), 8 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index cec051cfbd..57e4d4e3b6 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -11,6 +11,7 @@ import { InputError } from '../../utils/errors.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { mergeSocketJsonChain, + reachabilityProblem, readSocketJsonChain, } from '../../utils/socket-json.mts' @@ -93,6 +94,13 @@ function validateBuilds({ dir, sockJson }: SocketJsonInDir): void { `${buildsSetting(key)}.disabled in ${file} must be true or false.`, ) } + const problem = reachabilityProblem( + entry['reachability'], + `${buildsSetting(key)}.reachability`, + ) + if (problem) { + throw new InputError(`Invalid ${file}: ${problem}.`) + } } for (const tool of BUILD_TOOLS) { const keys = ownEntryKeys(tool, dir, builds) diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index a633f9be6e..8abc4b8321 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -217,6 +217,18 @@ describe('createBuildRootSettingsResolver', () => { it.for([ [{ 'pom.xml': true }, 'must be an object'], [{ 'pom.xml': { disabled: 'yes' } }, 'must be true or false'], + [ + { 'pom.xml': { reachability: 'compile' } }, + '`defaults.manifest.builds["pom.xml"].reachability` is "compile"; set it to an object', + ], + [ + { 'pom.xml': { reachability: { build: 'package' } } }, + '`defaults.manifest.builds["pom.xml"].reachability.build` is "package"; set it to "compile" or "none"', + ], + [ + { 'pom.xml': { reachability: { javaHome: false } } }, + '`defaults.manifest.builds["pom.xml"].reachability.javaHome` is false; set it to a JDK path', + ], ] as const)('rejects the entries %j', async ({ 0: builds, 1: reason }) => { await write('.', { builds }, ['pom.xml']) diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 1158d9bda7..2d57b6b3eb 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -23,6 +23,7 @@ import path from 'node:path' import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' +import { isObjectObject } from '@socketsecurity/registry/lib/objects' import { InputError, formatErrorWithDetail } from './errors.mts' import { findUp } from './fs.mts' @@ -198,22 +199,49 @@ function validateSocketJson( sockJsonPath: string, ): CResult { for (const tool of REACHABILITY_BUILD_TOOLS) { - const build: unknown = - sockJson.defaults?.manifest?.[tool]?.reachability?.build - if ( - build !== undefined && - !(REACHABILITY_BUILD_MODES as readonly unknown[]).includes(build) - ) { + const problem = reachabilityProblem( + sockJson.defaults?.manifest?.[tool]?.reachability, + `defaults.manifest.${tool}.reachability`, + ) + if (problem) { return { ok: false, message: `Invalid ${SOCKET_JSON} at ${sockJsonPath}`, - cause: `\`defaults.manifest.${tool}.reachability.build\` is ${JSON.stringify(build)}; set it to ${REACHABILITY_BUILD_MODES.map(m => `"${m}"`).join(' or ')}, or remove it`, + cause: problem, } } } return { ok: true, data: sockJson } } +// What is wrong with a `reachability` setting at `key`, if anything. +export function reachabilityProblem( + reachability: unknown, + key: string, +): string | undefined { + if (reachability === undefined) { + return undefined + } + if (!isObjectObject(reachability)) { + return `\`${key}\` is ${JSON.stringify(reachability)}; set it to an object, or remove it` + } + const { build, javaHome } = reachability as Record + if ( + build !== undefined && + !(REACHABILITY_BUILD_MODES as readonly unknown[]).includes(build) + ) { + return `\`${key}.build\` is ${JSON.stringify(build)}; set it to ${REACHABILITY_BUILD_MODES.map(m => `"${m}"`).join(' or ')}, or remove it` + } + if ( + javaHome !== undefined && + javaHome !== null && + typeof javaHome !== 'string' + ) { + return `\`${key}.javaHome\` is ${JSON.stringify(javaHome)}; set it to a JDK path, or to null to clear an inherited one, or remove it` + } + return undefined +} + export function readOrDefaultSocketJson(cwd: string): SocketJson { return socketJsonOrThrow(readSocketJsonSync(cwd, true)) } diff --git a/src/utils/socket-json.test.mts b/src/utils/socket-json.test.mts index 5c203c1c1c..27cef9b0d2 100644 --- a/src/utils/socket-json.test.mts +++ b/src/utils/socket-json.test.mts @@ -287,7 +287,7 @@ describe('readSocketJsonChain and mergeSocketJsonChain', () => { }) }) -describe('reachability.build validation', () => { +describe('reachability validation', () => { let dir = '' beforeEach(async () => { @@ -342,6 +342,40 @@ describe('reachability.build validation', () => { expect(readSocketJsonSync(dir).ok).toBe(false) }) + it.for([ + [ + 'compile', + '`defaults.manifest.maven.reachability` is "compile"; set it to an object, or remove it', + ], + [ + { javaHome: 17 }, + '`defaults.manifest.maven.reachability.javaHome` is 17; set it to a JDK path, or to null to clear an inherited one, or remove it', + ], + ] as const)( + 'rejects the reachability %j, naming the key', + async ({ 0: reachability, 1: cause }) => { + await writeSocketJson(dir, { + version: 1, + defaults: { manifest: { maven: { reachability } } }, + } as never) + + expect(readSocketJsonSync(dir)).toEqual({ + ok: false, + message: `Invalid socket.json at ${path.join(dir, 'socket.json')}`, + cause, + }) + }, + ) + + it('accepts a null reachability javaHome, which clears an inherited one', async () => { + await writeSocketJson(dir, { + version: 1, + defaults: { manifest: { gradle: { reachability: { javaHome: null } } } }, + }) + + expect(readSocketJsonSync(dir).ok).toBe(true) + }) + it('fails the command rather than falling back to the default socket.json', async () => { await writeSocketJson(dir, { version: 1, From b127cb9cf0a2195518b493d85899976bfdcf0320 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:28:58 +0100 Subject: [PATCH 15/23] Document the reachability settings in the dynamic SBOM inference guide The fields table now lists reachability.build and reachability.javaHome, which only reachability runs read, and says how they cascade. --- docs/dynamic-sbom-inference-settings.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/dynamic-sbom-inference-settings.md b/docs/dynamic-sbom-inference-settings.md index 4d28e1441f..ce15fd6663 100644 --- a/docs/dynamic-sbom-inference-settings.md +++ b/docs/dynamic-sbom-inference-settings.md @@ -77,6 +77,11 @@ Under `defaults.manifest.maven`, `.gradle`, `.sbt` or `.dotnet`, or inside a | `disabled` | `true` skips builds; see below. | | `facts` | Gradle and sbt: `false` skips the build. | | `verbose` | `true` streams the build tool's output. | +| `reachability.build` | Reachability scans only. `"compile"` builds the project before the analysis; a failed build fails the scan. `"none"` or unset analyses it unbuilt. | +| `reachability.javaHome` | Reachability scans only; Maven, Gradle and sbt. JDK for the analysis, passed to Coana as written. | + +The fields under `reachability` cascade one by one: a nearer `socket.json` or +a `builds` entry that sets only `build` keeps an inherited `javaHome`. ## Skipping builds From fed7da35a8f96a7ca55108f5ab7a207b1f4bb453 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:30:37 +0100 Subject: [PATCH 16/23] Make the setup wizard's reachability answers match what they write The plain `socket manifest setup` did not tell its reachability step what the directory inherits, so under an ancestor socket.json that sets reachability.build to "compile" a no deleted the key instead of writing "none", and the build question defaulted to no. It now reads the ancestor socket.json files, and the build question defaults to the inherited value when the directory sets none. A no to the reachability JDK keeps a value already set; its label now says so and names the value, and says "leave unset" only when none is. --- .../manifest/setup-manifest-config.mts | 40 ++++++-- .../manifest/setup-manifest-config.test.mts | 91 ++++++++++++++++++- 2 files changed, 124 insertions(+), 7 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 620c36ec21..1eb63c8277 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -8,6 +8,8 @@ import { input, select } from '@socketsecurity/registry/lib/prompts' import { detectManifestActions } from './detect-manifest-actions.mts' import { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { + mergeSocketJsonChain, + readSocketJsonChain, readSocketJsonSync, writeSocketJson, } from '../../utils/socket-json.mts' @@ -17,13 +19,28 @@ import type { JvmReachabilityDefaults, ManifestDefaults, ReachabilityBuild, + SocketJson, } from '../../utils/socket-json.mts' +type ManifestDefaultsSection = NonNullable< + NonNullable['manifest'] +> + export type ReachabilityStepOptions = { // What the project inherits from ancestor socket.json files. inheritedReachabilityBuild?: ReachabilityBuild | undefined } +function ancestorManifestDefaults( + cwd: string, +): ManifestDefaultsSection | undefined { + const dir = path.resolve(cwd) + const parent = path.dirname(dir) + return parent === dir + ? undefined + : mergeSocketJsonChain(readSocketJsonChain(parent)).defaults?.manifest +} + // Whether the prompt was canceled. A blank answer clears a value set before // with null rather than deleting the key, so it doesn't silently start // inheriting an ancestor's value again. @@ -189,6 +206,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest = {} } + const inherited = ancestorManifestDefaults(cwd) let result: CResult<{ canceled: boolean }> switch (targetEco) { case 'conda': { @@ -202,28 +220,36 @@ export async function setupManifestConfig( if (!sockJson.defaults.manifest.dotnet) { sockJson.defaults.manifest.dotnet = {} } - result = await setupDotnet(sockJson.defaults.manifest.dotnet) + result = await setupDotnet(sockJson.defaults.manifest.dotnet, { + inheritedReachabilityBuild: inherited?.dotnet?.reachability?.build, + }) break } case 'gradle': { if (!sockJson.defaults.manifest.gradle) { sockJson.defaults.manifest.gradle = {} } - result = await setupGradle(sockJson.defaults.manifest.gradle) + result = await setupGradle(sockJson.defaults.manifest.gradle, { + inheritedReachabilityBuild: inherited?.gradle?.reachability?.build, + }) break } case 'maven': { if (!sockJson.defaults.manifest.maven) { sockJson.defaults.manifest.maven = {} } - result = await setupMaven(sockJson.defaults.manifest.maven) + result = await setupMaven(sockJson.defaults.manifest.maven, { + inheritedReachabilityBuild: inherited?.maven?.reachability?.build, + }) break } case 'sbt': { if (!sockJson.defaults.manifest.sbt) { sockJson.defaults.manifest.sbt = {} } - result = await setupSbt(sockJson.defaults.manifest.sbt) + result = await setupSbt(sockJson.defaults.manifest.sbt, { + inheritedReachabilityBuild: inherited?.sbt?.reachability?.build, + }) break } default: { @@ -776,7 +802,7 @@ async function setupReachability( description: 'Compile the project before reachability analysis', }, ], - default: reachability.build === 'compile', + default: (reachability.build ?? inheritedReachabilityBuild) === 'compile', }) if (wantsBuild === undefined || wantsBuild === null) { return canceledByUser() @@ -813,7 +839,9 @@ async function setupReachabilityJavaHome( { name: 'no', value: false, - description: 'Leave the JDK for reachability analysis unset', + description: reachability.javaHome + ? `Keep ${reachability.javaHome} as the JDK for reachability analysis` + : 'Leave the JDK for reachability analysis unset', }, { name: 'yes', diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 1be279a635..1bec7fa4ae 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -1,4 +1,8 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { promises as fs } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' // Simulates a real prompt: pressing Enter with nothing typed returns // whatever `default` was shown - the same contract inquirer honors. This is @@ -9,14 +13,20 @@ vi.mock('@socketsecurity/registry/lib/prompts', () => ({ select: vi.fn(async ({ default: def }: { default?: string }) => def ?? ''), })) +import { logger } from '@socketsecurity/registry/lib/logger' import { input, select } from '@socketsecurity/registry/lib/prompts' import { setupDotnet, setupGradle, + setupManifestConfig, setupMaven, setupSbt, } from './setup-manifest-config.mts' +import { + getDefaultSocketJson, + writeSocketJson, +} from '../../utils/socket-json.mts' describe('setup wizards', () => { it.for([ @@ -159,6 +169,30 @@ describe('reachability step', () => { expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) }) + it.for([ + [ + { javaHome: '/opt/jdk-17' }, + 'Keep /opt/jdk-17 as the JDK for reachability analysis', + ], + [{}, 'Leave the JDK for reachability analysis unset'], + ] as const)( + 'labels the no to the JDK %j by what it does', + async ({ 0: reachability, 1: label }) => { + answerReachability(false) + + await setupMaven({ reachability: { ...reachability } }) + + const asked = vi + .mocked(select) + .mock.calls.find(([{ message }]) => message === REACHABILITY_QUESTION) + expect( + asked?.[0].choices.find( + choice => typeof choice === 'object' && choice.name === 'no', + ), + ).toMatchObject({ description: label }) + }, + ) + it('offers the shown value as the default and clears it on a blank answer', async () => { vi.mocked(select).mockImplementation(async ({ default: def, message }) => message === REACHABILITY_QUESTION ? true : (def ?? ''), @@ -333,6 +367,61 @@ describe('reachability build step', () => { }) }) +describe('setupManifestConfig', () => { + const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' + let parent = '' + + beforeEach(async () => { + parent = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'setup-manifest-config-')), + ) + }) + afterEach(async () => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + await fs.rm(parent, { recursive: true, force: true }) + }) + + it('writes none after a no under an ancestor socket.json that sets compile, showing compile as the default', async () => { + await writeSocketJson(parent, { + ...getDefaultSocketJson(), + defaults: { manifest: { maven: { reachability: { build: 'compile' } } } }, + }) + const cwd = path.join(parent, 'app') + await fs.mkdir(cwd) + const shown: unknown[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message === 'Select ecosystem manifest generator to configure') { + return 'maven' + } + if (message === BUILD_QUESTION) { + shown.push(def) + return false + } + if (message.startsWith('Do you want to write the new config')) { + return true + } + return def ?? '' + }) + vi.spyOn(logger, 'log').mockImplementation(() => logger) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + + expect(await setupManifestConfig(cwd)).toEqual({ + ok: true, + data: undefined, + }) + + expect(shown).toEqual([true]) + const written = JSON.parse( + await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), + ) + expect(written.defaults.manifest.maven).toEqual({ + reachability: { build: 'none' }, + }) + }) +}) + describe('setupDotnet', () => { it('preserves explicit nulls on a blank re-prompt', async () => { const config: Record = { bin: null, dotnetOpts: null } From 79f18eb452f8f20681f0447e3fe74016dfc6194f Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:31:24 +0100 Subject: [PATCH 17/23] Restore the tests for socketFactsFileName They went with the records parser they read their entry files from; they now pass the entry files directly. --- .gitignore | 1 + .../manifest/scripts/build-tool.test.mts | 35 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 src/commands/manifest/scripts/build-tool.test.mts diff --git a/.gitignore b/.gitignore index 902c9807e0..9c85753eb0 100644 --- a/.gitignore +++ b/.gitignore @@ -509,6 +509,7 @@ !/src/commands/manifest/run-manifest-facts.mts !/src/commands/manifest/run-manifest-facts.test.mts !/src/commands/manifest/scripts/build-tool.mts +!/src/commands/manifest/scripts/build-tool.test.mts !/src/commands/manifest/setup-manifest-config.mts !/src/commands/manifest/setup-manifest-config.test.mts !/src/commands/manifest/setup-recursive-manifest-config.mts diff --git a/src/commands/manifest/scripts/build-tool.test.mts b/src/commands/manifest/scripts/build-tool.test.mts new file mode 100644 index 0000000000..7117274938 --- /dev/null +++ b/src/commands/manifest/scripts/build-tool.test.mts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' + +import { socketFactsFileName } from './build-tool.mts' + +describe('socketFactsFileName', () => { + it('names a directory-addressed build after its tool', () => { + expect(socketFactsFileName('gradle', undefined)).toBe( + 'gradle.socket.facts.json', + ) + expect(socketFactsFileName('sbt', undefined)).toBe('sbt.socket.facts.json') + }) + + it('names a file-addressed build after its entry file', () => { + expect(socketFactsFileName('maven', 'pom.xml')).toBe( + 'pom.xml.socket.facts.json', + ) + expect(socketFactsFileName('maven', 'other-pom.xml')).toBe( + 'other-pom.xml.socket.facts.json', + ) + expect(socketFactsFileName('dotnet', 'App.sln')).toBe( + 'App.sln.socket.facts.json', + ) + }) + + it('names a file-addressed build by the base name of an entry file path', () => { + expect(socketFactsFileName('maven', 'sub/pom.xml')).toBe( + 'pom.xml.socket.facts.json', + ) + }) + + it('cannot name a file-addressed build without an entry file', () => { + expect(socketFactsFileName('maven', undefined)).toBeUndefined() + expect(socketFactsFileName('dotnet', undefined)).toBeUndefined() + }) +}) From 2e5241e1a23aacd4485e5fa32c270d570415e88a Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:32:14 +0100 Subject: [PATCH 18/23] Correct and trim comments in facts generation and the setup wizard The comment on how the build tool command is resolved named a runner that no longer exists and left out that the standalone executable takes only the SOCKET_CLI_*_PATH override for JVM tools. Others restated their code and now keep only what it does not say. --- src/commands/manifest/run-manifest-facts.mts | 15 ++++++--------- src/commands/manifest/setup-manifest-config.mts | 5 ++--- src/utils/socket-json.mts | 6 ++---- 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 044f5d2382..f45b8adb21 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -262,9 +262,8 @@ export type SocketFactsRunOptions = SocketFactsRequestOptions & { context?: SocketFactsContext | undefined } -// `bin` is resolved as the build tool's own runner would: the -// SOCKET_CLI_*_PATH override first, then the given bin, the project wrapper, -// PATH. +// SOCKET_CLI_*_PATH, else `bin`, the project wrapper, then PATH; standalone, +// JVM tools take only SOCKET_CLI_*_PATH, as no JVM tooling is bundled. function toSocketFactsRequest({ bin, buildOpts, @@ -360,9 +359,8 @@ export async function listDotnetSolutionMembers({ ) } -// The projects a build loads, as the build reports them, without resolving its -// dependencies; undefined when the build cannot list them, after reporting -// why. +// Resolves nothing; undefined, after reporting why, when the build cannot list +// its projects. export async function listBuildProjects({ context = {}, ...options @@ -387,9 +385,8 @@ export async function listBuildProjects({ return result.status === 'listed' ? result.projects : undefined } -// Generates one build root's `.socket.facts.json` with Coana. With a -// work dir in `context`, also collects what a later Coana run reads of it. A -// failure sets a non-zero exit code; only a failed build is Coana's to report. +// A failure sets a non-zero exit code; only a failed build is Coana's to +// report. export async function runManifestFacts({ context = {}, ...options diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 1eb63c8277..79c25addd6 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -775,9 +775,8 @@ async function askForIgnoreUnresolvedFlag( }) } -// Settings only the reachability run reads. A "no" to the JDK leaves it as it -// is, so an inherited value is neither pinned nor cleared; a "no" to building -// unsets the build, and writes "none" only to override an inherited "compile". +// A "no" keeps the JDK as is, neither pinning nor clearing an inherited one; +// "none" is written only to override an inherited "compile". async function setupReachability( config: { reachability?: JvmReachabilityDefaults | undefined }, { diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 2d57b6b3eb..796e0f7fa1 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -273,10 +273,8 @@ function mergeBuildToolDefaults< return merged } -// Merges `defaults.manifest.` per ecosystem, and a build tool's -// `reachability` within it: fields set in `override` win, others fall through -// to `base`. Only this section cascades; everything else in `defaults` comes -// from `base` only. +// Only the tool sections of `defaults.manifest` cascade, field by field, and a +// build tool's `reachability` within one; everything else is `base`'s. function mergeManifestDefaults( base: SocketJson, override: SocketJson, From a8050c5fe10ce3e4000643f48c79d98a6aa9bbbb Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:33:53 +0100 Subject: [PATCH 19/23] Say why the walk shares its Coana options, and drop a restating comment --- src/commands/manifest/generate-recursive-manifests.mts | 3 +-- src/utils/socket-json.mts | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 5a6c1200c0..2f686412ca 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -661,8 +661,7 @@ async function warnUnappliedEntry( ) } -// How the walk runs Coana on a build root, whether to generate its facts or -// only to list what it loads. +// Shared by listing and generation, so both run the same Coana, org and hints. function runOptions( ctx: WalkContext, ecosystem: BuildTool, diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 796e0f7fa1..5837686f84 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -214,7 +214,6 @@ function validateSocketJson( return { ok: true, data: sockJson } } -// What is wrong with a `reachability` setting at `key`, if anything. export function reachabilityProblem( reachability: unknown, key: string, From a1c10e5a24477c62f8cc84bc989e415c8cf806a3 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:54:30 +0100 Subject: [PATCH 20/23] Show an inherited reachability JDK in manifest setup The "no" to the reachability JDK said it would leave the JDK unset even when a parent socket.json set one, which the scan then used. Setup now shows the inherited JDK, offers it as the default, and a blank answer clears it rather than falling back to it. Plain `socket manifest setup` also read every ancestor socket.json before any build tool was chosen, so an invalid one stopped setup for conda or on exit. It now reads them only for the build tool it sets up. --- .../manifest/setup-manifest-config.mts | 87 ++++++++++--------- .../manifest/setup-manifest-config.test.mts | 87 +++++++++++++++++-- .../setup-recursive-manifest-config.mts | 12 +-- 3 files changed, 133 insertions(+), 53 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 79c25addd6..967791ced1 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -18,27 +18,24 @@ import type { CResult } from '../../types.mts' import type { JvmReachabilityDefaults, ManifestDefaults, - ReachabilityBuild, - SocketJson, } from '../../utils/socket-json.mts' -type ManifestDefaultsSection = NonNullable< - NonNullable['manifest'] -> - export type ReachabilityStepOptions = { // What the project inherits from ancestor socket.json files. - inheritedReachabilityBuild?: ReachabilityBuild | undefined + inheritedReachability?: JvmReachabilityDefaults | undefined } -function ancestorManifestDefaults( +function inheritedReachabilityOf( cwd: string, -): ManifestDefaultsSection | undefined { + tool: 'dotnet' | 'gradle' | 'maven' | 'sbt', +): JvmReachabilityDefaults | undefined { const dir = path.resolve(cwd) const parent = path.dirname(dir) return parent === dir ? undefined - : mergeSocketJsonChain(readSocketJsonChain(parent)).defaults?.manifest + : mergeSocketJsonChain(readSocketJsonChain(parent)).defaults?.manifest?.[ + tool + ]?.reachability } // Whether the prompt was canceled. A blank answer clears a value set before @@ -206,7 +203,6 @@ export async function setupManifestConfig( sockJson.defaults.manifest = {} } - const inherited = ancestorManifestDefaults(cwd) let result: CResult<{ canceled: boolean }> switch (targetEco) { case 'conda': { @@ -221,7 +217,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.dotnet = {} } result = await setupDotnet(sockJson.defaults.manifest.dotnet, { - inheritedReachabilityBuild: inherited?.dotnet?.reachability?.build, + inheritedReachability: inheritedReachabilityOf(cwd, 'dotnet'), }) break } @@ -230,7 +226,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.gradle = {} } result = await setupGradle(sockJson.defaults.manifest.gradle, { - inheritedReachabilityBuild: inherited?.gradle?.reachability?.build, + inheritedReachability: inheritedReachabilityOf(cwd, 'gradle'), }) break } @@ -239,7 +235,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.maven = {} } result = await setupMaven(sockJson.defaults.manifest.maven, { - inheritedReachabilityBuild: inherited?.maven?.reachability?.build, + inheritedReachability: inheritedReachabilityOf(cwd, 'maven'), }) break } @@ -248,7 +244,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.sbt = {} } result = await setupSbt(sockJson.defaults.manifest.sbt, { - inheritedReachabilityBuild: inherited?.sbt?.reachability?.build, + inheritedReachability: inheritedReachabilityOf(cwd, 'sbt'), }) break } @@ -350,7 +346,7 @@ async function setupConda( export async function setupDotnet( config: ManifestDefaults<'dotnet'>, - { inheritedReachabilityBuild }: ReachabilityStepOptions = {}, + { inheritedReachability }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'dotnet'))) { return canceledByUser() @@ -382,7 +378,7 @@ export async function setupDotnet( return await setupReachability(config, { askJavaHome: false, - inheritedReachabilityBuild, + inheritedReachability, }) } @@ -392,7 +388,7 @@ export async function setupGradle( // pom-mode equivalent - skips the facts/pom question entirely. { factsOnly = false, - inheritedReachabilityBuild, + inheritedReachability, }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if ( @@ -443,7 +439,7 @@ export async function setupGradle( } if (generatesFacts) { - return await setupReachability(config, { inheritedReachabilityBuild }) + return await setupReachability(config, { inheritedReachability }) } return notCanceled() @@ -451,7 +447,7 @@ export async function setupGradle( export async function setupMaven( config: ManifestDefaults<'maven'>, - { inheritedReachabilityBuild }: ReachabilityStepOptions = {}, + { inheritedReachability }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'mvn'))) { return canceledByUser() @@ -488,7 +484,7 @@ export async function setupMaven( return canceledByUser() } - return await setupReachability(config, { inheritedReachabilityBuild }) + return await setupReachability(config, { inheritedReachability }) } export async function setupSbt( @@ -496,7 +492,7 @@ export async function setupSbt( // See setupGradle's matching parameter for why. { factsOnly = false, - inheritedReachabilityBuild, + inheritedReachability, }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'sbt'))) { @@ -573,7 +569,7 @@ export async function setupSbt( } if (generatesFacts) { - return await setupReachability(config, { inheritedReachabilityBuild }) + return await setupReachability(config, { inheritedReachability }) } return notCanceled() @@ -781,7 +777,7 @@ async function setupReachability( config: { reachability?: JvmReachabilityDefaults | undefined }, { askJavaHome = true, - inheritedReachabilityBuild, + inheritedReachability, }: ReachabilityStepOptions & { askJavaHome?: boolean | undefined } = {}, ): Promise> { const reachability = { ...config.reachability } @@ -801,21 +797,24 @@ async function setupReachability( description: 'Compile the project before reachability analysis', }, ], - default: (reachability.build ?? inheritedReachabilityBuild) === 'compile', + default: (reachability.build ?? inheritedReachability?.build) === 'compile', }) if (wantsBuild === undefined || wantsBuild === null) { return canceledByUser() } if (wantsBuild) { reachability.build = 'compile' - } else if (inheritedReachabilityBuild === 'compile') { + } else if (inheritedReachability?.build === 'compile') { reachability.build = 'none' } else { delete reachability.build } if (askJavaHome) { - const javaHome = await setupReachabilityJavaHome(reachability) + const javaHome = await setupReachabilityJavaHome( + reachability, + inheritedReachability?.javaHome, + ) if (!javaHome.ok || javaHome.data.canceled) { return javaHome } @@ -831,15 +830,20 @@ async function setupReachability( async function setupReachabilityJavaHome( reachability: JvmReachabilityDefaults, + inheritedJavaHome: string | null | undefined, ): Promise> { + const effective = + reachability.javaHome === undefined + ? inheritedJavaHome + : reachability.javaHome const wantsJavaHome = await select({ message: 'Use a different Java for reachability analysis?', choices: [ { name: 'no', value: false, - description: reachability.javaHome - ? `Keep ${reachability.javaHome} as the JDK for reachability analysis` + description: effective + ? `Keep ${effective} as the JDK for reachability analysis${reachability.javaHome ? '' : ', as a parent socket.json sets it'}` : 'Leave the JDK for reachability analysis unset', }, { @@ -848,24 +852,25 @@ async function setupReachabilityJavaHome( description: 'Set the JDK reachability analysis uses', }, ], - default: !!reachability.javaHome, + default: !!effective, }) if (wantsJavaHome === undefined || wantsJavaHome === null) { return canceledByUser() } - if ( - wantsJavaHome && - applyAnswer( - reachability, - 'javaHome', - await askForJavaHome( - reachability.javaHome || '', - 'What JDK should reachability analysis use?', - ), - ) - ) { + if (!wantsJavaHome) { + return notCanceled() + } + const answer = await askForJavaHome( + effective || '', + 'What JDK should reachability analysis use?', + ) + if (applyAnswer(reachability, 'javaHome', answer)) { return canceledByUser() } + // A blank answer must also clear an inherited JDK, not fall back to it. + if (answer === '' && inheritedJavaHome) { + reachability.javaHome = null + } return notCanceled() } diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 1bec7fa4ae..a5410aa5c2 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -172,15 +172,29 @@ describe('reachability step', () => { it.for([ [ { javaHome: '/opt/jdk-17' }, + {}, 'Keep /opt/jdk-17 as the JDK for reachability analysis', ], - [{}, 'Leave the JDK for reachability analysis unset'], + [{}, {}, 'Leave the JDK for reachability analysis unset'], + [ + {}, + { javaHome: '/opt/jdk-11' }, + 'Keep /opt/jdk-11 as the JDK for reachability analysis, as a parent socket.json sets it', + ], + [ + { javaHome: null }, + { javaHome: '/opt/jdk-11' }, + 'Leave the JDK for reachability analysis unset', + ], ] as const)( - 'labels the no to the JDK %j by what it does', - async ({ 0: reachability, 1: label }) => { + 'labels the no to the JDK %j, inheriting %j, by what it does', + async ({ 0: reachability, 1: inherited, 2: label }) => { answerReachability(false) - await setupMaven({ reachability: { ...reachability } }) + await setupMaven( + { reachability: { ...reachability } }, + { inheritedReachability: inherited }, + ) const asked = vi .mocked(select) @@ -215,6 +229,28 @@ describe('reachability step', () => { expect(config['reachability']).toEqual({ javaHome: null }) }) + it('offers an inherited JDK as the default and clears it on a blank answer', async () => { + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === REACHABILITY_QUESTION ? true : (def ?? ''), + ) + const shown: unknown[] = [] + vi.mocked(input).mockImplementation(async ({ default: def, message }) => { + if (message.startsWith('What JDK should reachability analysis use?')) { + shown.push(def) + return '' + } + return def ?? '' + }) + const config: Record = {} + + await setupMaven(config, { + inheritedReachability: { javaHome: '/opt/jdk-11' }, + }) + + expect(shown).toEqual(['/opt/jdk-11']) + expect(config['reachability']).toEqual({ javaHome: null }) + }) + it('does not ask in pom mode, where no facts reach a reachability run', async () => { const messages: string[] = [] vi.mocked(select).mockImplementation(async ({ default: def, message }) => { @@ -300,7 +336,7 @@ describe('reachability build step', () => { reachability: { build: 'compile' }, } - await setup(config, { inheritedReachabilityBuild: 'compile' }) + await setup(config, { inheritedReachability: { build: 'compile' } }) expect(shown).toEqual([true]) expect(config).toEqual({ reachability: { build: 'none' } }) @@ -311,7 +347,7 @@ describe('reachability build step', () => { answerBuild(false) const config: Record = { reachability: { build: 'none' } } - await setupGradle(config, { inheritedReachabilityBuild: 'none' }) + await setupGradle(config, { inheritedReachability: { build: 'none' } }) expect(config).toEqual({}) }) @@ -422,6 +458,45 @@ describe('setupManifestConfig', () => { }) }) +describe('setupManifestConfig with an invalid ancestor socket.json', () => { + let parent = '' + + beforeEach(async () => { + parent = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'setup-manifest-config-')), + ) + await fs.writeFile( + path.join(parent, 'socket.json'), + JSON.stringify({ + version: 1, + defaults: { manifest: { maven: { reachability: { javaHome: 17 } } } }, + }), + ) + }) + afterEach(async () => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + await fs.rm(parent, { recursive: true, force: true }) + }) + + it('exits without reading it when no build tool is chosen', async () => { + const cwd = path.join(parent, 'app') + await fs.mkdir(cwd) + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === 'Select ecosystem manifest generator to configure' + ? '' + : (def ?? ''), + ) + vi.spyOn(logger, 'log').mockImplementation(() => logger) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + + await expect(setupManifestConfig(cwd)).resolves.toMatchObject({ + ok: true, + data: { canceled: true }, + }) + }) +}) + describe('setupDotnet', () => { it('preserves explicit nulls on a blank re-prompt', async () => { const config: Record = { bin: null, dotnetOpts: null } diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index d6f84e4654..c7a48dd4d1 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -60,8 +60,8 @@ import type { BuildTool } from './scripts/build-tool.mts' import type { ReachabilityStepOptions } from './setup-manifest-config.mts' import type { CResult } from '../../types.mts' import type { + JvmReachabilityDefaults, ManifestDefaults, - ReachabilityBuild, SocketJson, SocketJsonInDir, } from '../../utils/socket-json.mts' @@ -108,12 +108,12 @@ function changedFields( return changed } -function inheritedReachabilityBuildOf( +function inheritedReachabilityOf( inherited: Record, -): ReachabilityBuild | undefined { +): JvmReachabilityDefaults | undefined { const reachability = inherited['reachability'] return isObjectObject(reachability) - ? (reachability['build'] as ReachabilityBuild | undefined) + ? (reachability as JvmReachabilityDefaults) : undefined } @@ -486,7 +486,7 @@ async function configureBuild( const seeded = Object.keys(seed) const result = await runEcosystemWizard(ecosystem, seed, { - inheritedReachabilityBuild: inheritedReachabilityBuildOf(inherited), + inheritedReachability: inheritedReachabilityOf(inherited), }) if (!result.ok || result.data.canceled) { return result @@ -954,7 +954,7 @@ async function setupRootDefaults( ) // eslint-disable-next-line no-await-in-loop const result = await runEcosystemWizard(ecosystem, section, { - inheritedReachabilityBuild: inheritedReachabilityBuildOf(inherited), + inheritedReachability: inheritedReachabilityOf(inherited), }) if (!result.ok || result.data.canceled) { return result From 262037bba1ac48cee5f0e6dc8848982fca96a4aa Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:54:40 +0100 Subject: [PATCH 21/23] Reject a reachability javaHome for .NET Reachability analysis of a .NET build takes no JDK, so the setting was accepted and then silently ignored, in a .NET section and in a `builds` entry for a solution or project file alike. --- src/commands/manifest/build-root-config.mts | 8 +++++--- .../manifest/build-root-config.test.mts | 4 ++++ src/utils/socket-json.mts | 5 +++++ src/utils/socket-json.test.mts | 17 +++++++++++++++++ 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index 57e4d4e3b6..e90fc36285 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -40,8 +40,8 @@ export type ResolvedBuildRootSettings = { } // Gradle and sbt name a build by any build file of its directory. -function namesBuildFile(key: string): boolean { - return BUILD_TOOLS.some(tool => { +function toolOfBuildFile(key: string): BuildTool | undefined { + return BUILD_TOOLS.find(tool => { const files = BUILD_FILES[tool] return files.byFile ? isBuildFile(tool, key) : files.names.includes(key) }) @@ -76,7 +76,8 @@ function validateBuilds({ dir, sockJson }: SocketJsonInDir): void { ) } for (const { 0: key, 1: entry } of Object.entries(builds)) { - if (key.includes('/') || key.includes('\\') || !namesBuildFile(key)) { + const tool = toolOfBuildFile(key) + if (key.includes('/') || key.includes('\\') || !tool) { throw new InputError( `${buildsSetting(key)} in ${file} must be keyed by the name of a build file in that directory, such as pom.xml or build.gradle.`, ) @@ -97,6 +98,7 @@ function validateBuilds({ dir, sockJson }: SocketJsonInDir): void { const problem = reachabilityProblem( entry['reachability'], `${buildsSetting(key)}.reachability`, + tool, ) if (problem) { throw new InputError(`Invalid ${file}: ${problem}.`) diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index 8abc4b8321..123c2e5e34 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -229,6 +229,10 @@ describe('createBuildRootSettingsResolver', () => { { 'pom.xml': { reachability: { javaHome: false } } }, '`defaults.manifest.builds["pom.xml"].reachability.javaHome` is false; set it to a JDK path', ], + [ + { 'App.csproj': { reachability: { javaHome: '/opt/jdk-17' } } }, + '`defaults.manifest.builds["App.csproj"].reachability.javaHome` does not apply to .NET', + ], ] as const)('rejects the entries %j', async ({ 0: builds, 1: reason }) => { await write('.', { builds }, ['pom.xml']) diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 5837686f84..210f83c023 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -202,6 +202,7 @@ function validateSocketJson( const problem = reachabilityProblem( sockJson.defaults?.manifest?.[tool]?.reachability, `defaults.manifest.${tool}.reachability`, + tool, ) if (problem) { return { @@ -217,6 +218,7 @@ function validateSocketJson( export function reachabilityProblem( reachability: unknown, key: string, + tool: (typeof REACHABILITY_BUILD_TOOLS)[number], ): string | undefined { if (reachability === undefined) { return undefined @@ -231,6 +233,9 @@ export function reachabilityProblem( ) { return `\`${key}.build\` is ${JSON.stringify(build)}; set it to ${REACHABILITY_BUILD_MODES.map(m => `"${m}"`).join(' or ')}, or remove it` } + if (tool === 'dotnet' && javaHome !== undefined) { + return `\`${key}.javaHome\` does not apply to .NET; remove it` + } if ( javaHome !== undefined && javaHome !== null && diff --git a/src/utils/socket-json.test.mts b/src/utils/socket-json.test.mts index 27cef9b0d2..431a965cff 100644 --- a/src/utils/socket-json.test.mts +++ b/src/utils/socket-json.test.mts @@ -367,6 +367,23 @@ describe('reachability validation', () => { }, ) + it.for(['/opt/jdk-17', null])( + 'rejects the .NET reachability javaHome %j, which .NET does not use', + async javaHome => { + await writeSocketJson(dir, { + version: 1, + defaults: { manifest: { dotnet: { reachability: { javaHome } } } }, + } as never) + + expect(readSocketJsonSync(dir)).toEqual({ + ok: false, + message: `Invalid socket.json at ${path.join(dir, 'socket.json')}`, + cause: + '`defaults.manifest.dotnet.reachability.javaHome` does not apply to .NET; remove it', + }) + }, + ) + it('accepts a null reachability javaHome, which clears an inherited one', async () => { await writeSocketJson(dir, { version: 1, From 2271bc66830227ddbebdda1b3cca18ed0b036b3b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:54:46 +0100 Subject: [PATCH 22/23] Name --exclude-paths in auto-manifest remedies only where it exists `socket ci --auto-manifest` shares auto-manifest generation with `socket scan create`, so Coana's error report told its users to pass --exclude-paths, which `socket ci` does not take. The invoking command now names the flag when it has one. --- src/commands/manifest/cmd-manifest-auto.mts | 2 ++ .../manifest/generate_auto_manifest.mts | 18 ++++++++++-------- .../manifest/generate_auto_manifest.test.mts | 16 ++++++++++++++++ src/commands/scan/cmd-scan-create.mts | 2 ++ src/commands/scan/handle-create-new-scan.mts | 4 ++++ 5 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/commands/manifest/cmd-manifest-auto.mts b/src/commands/manifest/cmd-manifest-auto.mts index cf4021a361..e6609805bd 100644 --- a/src/commands/manifest/cmd-manifest-auto.mts +++ b/src/commands/manifest/cmd-manifest-auto.mts @@ -6,6 +6,7 @@ import { logger } from '@socketsecurity/registry/lib/logger' import { detectManifestActions } from './detect-manifest-actions.mts' import { generateAutoManifest } from './generate_auto_manifest.mts' import { excludePathsFlag } from './manifest-flags.mts' +import { EXCLUDE_PATHS_FLAG } from './run-manifest-facts.mts' import constants from '../../constants.mts' import { commonFlags } from '../../flags.mts' import { cmdFlagValueToArray } from '../../utils/cmd.mts' @@ -128,6 +129,7 @@ async function run( detected, cwd, excludePaths, + excludePathsFlag: EXCLUDE_PATHS_FLAG, outputKind, verbose, }) diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 18e0641a57..09f69385c0 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -10,7 +10,6 @@ import { resolveEcosystemConfig } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' import { - EXCLUDE_PATHS_FLAG, REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, runManifestFacts, } from './run-manifest-facts.mts' @@ -33,7 +32,6 @@ import type { OutputKind } from '../../types.mts' // Auto-manifest reads every build option from the root socket.json. const AUTO_MANIFEST_HINTS: BuildOptionHints = { - excludePathsFlag: EXCLUDE_PATHS_FLAG, flags: new Set(), setupCommand: 'socket manifest setup', socketJson: SOCKET_JSON, @@ -73,6 +71,7 @@ export async function generateAutoManifest({ cwd, detected, excludePaths, + excludePathsFlag, outputKind, verbose, }: { @@ -81,17 +80,20 @@ export async function generateAutoManifest({ cwd: string // Scan-root-relative `--exclude-paths`: skip excluded subprojects. excludePaths?: string[] | undefined + // The invoking command's flag for `excludePaths`, when it takes one. + excludePathsFlag?: string | undefined outputKind: OutputKind verbose: boolean }): Promise { const sockJson = readOrDefaultSocketJson(cwd) const generatedFiles: string[] = [] - const hints: BuildOptionHints = context?.workDir?.withFiles - ? { - ...AUTO_MANIFEST_HINTS, - continueOnInstallErrorsFlag: REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, - } - : AUTO_MANIFEST_HINTS + const hints: BuildOptionHints = { + ...AUTO_MANIFEST_HINTS, + continueOnInstallErrorsFlag: context?.workDir?.withFiles + ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG + : undefined, + excludePathsFlag, + } if (verbose) { logger.info(`Using this ${SOCKET_JSON} for defaults:`, sockJson) diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index dd8614d4dd..f73f611e64 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -274,6 +274,22 @@ describe('generateAutoManifest — bazel branch', () => { expect(convertGradleToMaven).not.toHaveBeenCalled() }) + it.for([['--exclude-paths'], [undefined]] as const)( + 'names the exclude-paths flag %s in remedies only when the command takes one', + async ({ 0: excludePathsFlag }) => { + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, maven: true, count: 1 }, + excludePathsFlag, + outputKind: 'text', + verbose: false, + }) + expect(vi.mocked(runManifestFacts).mock.calls[0]?.[0].hints).toEqual( + expect.objectContaining({ excludePathsFlag }), + ) + }, + ) + it('passes each JVM build tool its socket.json reachability javaHome', async () => { vi.mocked(readOrDefaultSocketJson).mockReturnValue({ defaults: { diff --git a/src/commands/scan/cmd-scan-create.mts b/src/commands/scan/cmd-scan-create.mts index 90a10ef627..dceb4466e8 100644 --- a/src/commands/scan/cmd-scan-create.mts +++ b/src/commands/scan/cmd-scan-create.mts @@ -48,6 +48,7 @@ import { hasDefaultApiToken } from '../../utils/sdk.mts' import { readOrDefaultSocketJsonUp } from '../../utils/socket-json.mts' import { socketDashboardLink } from '../../utils/terminal-link.mts' import { detectManifestActions } from '../manifest/detect-manifest-actions.mts' +import { EXCLUDE_PATHS_FLAG } from '../manifest/run-manifest-facts.mts' import type { REPORT_LEVEL } from './types.mts' import type { MeowFlags } from '../../flags.mts' @@ -687,6 +688,7 @@ async function run( committers: (committers && String(committers)) || '', cwd, defaultBranch: Boolean(defaultBranch), + excludePathsFlag: EXCLUDE_PATHS_FLAG, generateScanFiles: uvMemberDirs ? () => generateUvMemberSboms(uvMemberDirs) : undefined, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index 51dc1d41d1..28fd6d6700 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -91,6 +91,8 @@ export type HandleCreateNewScanConfig = { committers: string cwd: string defaultBranch: boolean + // The invoking command's flag for `reach.excludePaths`, when it takes one. + excludePathsFlag?: string | undefined // Supplies the complete scan input and replaces manifest discovery. generateScanFiles?: (() => Promise) | undefined interactive: boolean @@ -122,6 +124,7 @@ async function createNewScan( committers, cwd, defaultBranch, + excludePathsFlag, interactive, orgSlug, outputKind, @@ -218,6 +221,7 @@ async function createNewScan( cwd, detected, excludePaths: reach.excludePaths, + excludePathsFlag, outputKind, verbose: false, }) From bb09d7f61e0722b58964c9259a1ca777a71661e7 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 07:54:52 +0100 Subject: [PATCH 23/23] Map build settings to Coana run options in one place The walk, uncovered build roots and the setup wizard each spelled out the same mapping from a build root's settings to Coana's run options. --- .../manifest/generate-recursive-manifests.mts | 95 +++++++++++-------- .../setup-recursive-manifest-config.mts | 14 +-- 2 files changed, 62 insertions(+), 47 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 2f686412ca..574e259073 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -228,6 +228,41 @@ export function buildToolScriptOptions( } } +export function socketFactsRunOptions( + ecosystem: BuildTool, + root: BuildRoot, + config: EcosystemBuildConfig, + { + context, + excludeBase, + excludePaths, + hints, + }: { + context?: SocketFactsContext | undefined + excludeBase: string | undefined + excludePaths: string[] | undefined + hints?: BuildOptionHints | undefined + }, +): SocketFactsRunOptions { + return { + bin: config.bin, + buildOpts: config.buildOpts, + context, + cwd: root.dir, + ecosystem, + entryFile: root.entryFile, + excludeBase, + excludeConfigs: config.excludeConfigs, + excludePaths, + hints, + ignoreUnresolved: config.ignoreUnresolved, + includeConfigs: config.includeConfigs, + javaHome: config.javaHome, + reachability: config.reachability, + verbose: config.verbose, + } +} + async function everyAsync( items: readonly T[], test: (item: T) => Promise, @@ -669,30 +704,23 @@ function runOptions( dirConfig: EcosystemBuildConfig, ): SocketFactsRunOptions { return { - bin: dirConfig.bin, - buildOpts: dirConfig.buildOpts, - context: ctx.context, - cwd: root.dir, - ecosystem, - entryFile: root.entryFile, - // Relative to the scan root: a build can reach modules outside its own - // directory (Maven `../x` modules, relocated Gradle projects). - excludeBase: ctx.realCwd, - excludeConfigs: dirConfig.excludeConfigs, - excludePaths: ctx.excludePaths, - hints: { - continueOnInstallErrorsFlag: ctx.context.workDir?.withFiles - ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG - : undefined, - excludePathsFlag: EXCLUDE_PATHS_FLAG, - flags: ctx.optionFlags, - setupCommand: DSI_SETUP_COMMAND, - socketJson: socketJsonPath(root.dir), - }, + ...socketFactsRunOptions(ecosystem, root, dirConfig, { + context: ctx.context, + // Relative to the scan root: a build can reach modules outside its own + // directory (Maven `../x` modules, relocated Gradle projects). + excludeBase: ctx.realCwd, + excludePaths: ctx.excludePaths, + hints: { + continueOnInstallErrorsFlag: ctx.context.workDir?.withFiles + ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG + : undefined, + excludePathsFlag: EXCLUDE_PATHS_FLAG, + flags: ctx.optionFlags, + setupCommand: DSI_SETUP_COMMAND, + socketJson: socketJsonPath(root.dir), + }, + }), ignoreUnresolved: ctx.ignoreUnresolved ?? dirConfig.ignoreUnresolved, - includeConfigs: dirConfig.includeConfigs, - javaHome: dirConfig.javaHome, - reachability: dirConfig.reachability, verbose: ctx.verbose || dirConfig.verbose, } } @@ -816,7 +844,6 @@ export async function buildUncoveredRoot({ hints?: BuildOptionHints | undefined root: BuildRoot }): Promise { - const { bin, buildOpts } = config if ( await isRootCovered( covered, @@ -828,21 +855,13 @@ export async function buildUncoveredRoot({ return 'covered' } const result = await runManifestFacts({ - bin, - buildOpts, - context, + ...socketFactsRunOptions(ecosystem, root, config, { + context, + excludeBase, + excludePaths, + hints, + }), cwd: cwd ?? root.dir, - ecosystem, - entryFile: root.entryFile, - excludeBase, - excludeConfigs: config.excludeConfigs, - excludePaths, - hints, - ignoreUnresolved: config.ignoreUnresolved, - includeConfigs: config.includeConfigs, - javaHome: config.javaHome, - reachability: config.reachability, - verbose: config.verbose, }) if (result) { addMembership(covered, await membershipOf(result.projects)) diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index c7a48dd4d1..1a9dbe5e1a 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -28,6 +28,7 @@ import { import { buildToolScriptOptions, resolveEcosystemConfig, + socketFactsRunOptions, } from './generate-recursive-manifests.mts' import { loadBuild, withModules } from './load-build.mts' import { DSI_SETUP_COMMAND } from './run-manifest-facts.mts' @@ -667,16 +668,11 @@ async function loadOrAsk( const config = buildConfig(walk, build) // eslint-disable-next-line no-await-in-loop const loaded = await loadBuild({ - bin: config.bin, - buildOpts: config.buildOpts, - cwd: build.root.dir, - ecosystem: build.ecosystem, - entryFile: build.root.entryFile, - excludeBase: walk.cwd, - excludePaths: walk.excludePaths, - javaHome: config.javaHome, + ...socketFactsRunOptions(build.ecosystem, build.root, config, { + excludeBase: walk.cwd, + excludePaths: walk.excludePaths, + }), scanRoot: walk.cwd, - verbose: config.verbose, }) if (loaded) { return { ok: true, data: { canceled: false, loaded } }