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
20 changes: 18 additions & 2 deletions src/git/git-diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,17 @@ function readFileAtSha(sha: string, path: string, repoPath: string | undefined):
return result.stdout;
}

/** Root entries include directories and gitlinks, which recursive file inventories can omit. */
function readRootPathsAtSha(sha: string, repoPath: string | undefined): ReadonlySet<string> | undefined {
const result = runGit(["ls-tree", "--full-tree", "--name-only", "-z", sha], repoPath);
if (result.status !== 0 || !result.stdout.endsWith("\0")) return undefined;
const paths = result.stdout.slice(0, -1).split("\0");
// An absence decision needs a complete listing. Keep whitespace and backslashes literal.
if (paths.some((path) => !path || path === "." || path === ".." || path.includes("/"))) return undefined;
const roots = new Set(paths);
return roots.size === paths.length ? roots : undefined;
}

export function computeAnalysis(files: ChangedFile[]): GitDeltaAnalysis {
const paths = files.flatMap((f) =>
f.oldPath ? [f.path, f.oldPath] : [f.path],
Expand Down Expand Up @@ -674,8 +685,13 @@ export async function analyzeGitDelta(
const afterDirect = yarnDirectDependencies(newPackageJson);
// A second package manager or alternate Yarn install layout is outside this model, even when
// its configuration did not change in this delta.
const unsupportedLayout = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "bun.lock", "bun.lockb", ".yarnrc", ".yarnrc.yml", ".pnp.js", ".pnp.cjs"]
.some((path) => [baseSha, headSha].some((sha) => readFileAtSha(sha, path, repoPath) !== undefined));
const alternateLayouts = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "bun.lock", "bun.lockb", ".yarnrc", ".yarnrc.yml", ".pnp.js", ".pnp.cjs"];
const unsupportedLayout = [baseSha, headSha].some((sha) => {
const roots = readRootPathsAtSha(sha, repoPath);
// Either revision can rule out narrowing, including a layout deleted before HEAD.
// An unavailable or malformed listing cannot prove that these paths are absent.
return !roots || alternateLayouts.some((path) => roots.has(path));
});
const affected = beforeDirect && afterDirect && !unsupportedLayout
? yarnLockAffectedDependencies(readFileAtSha(baseSha, "yarn.lock", repoPath), readFileAtSha(headSha, "yarn.lock", repoPath), beforeDirect, afterDirect)
: undefined;
Expand Down
177 changes: 174 additions & 3 deletions tests/repo/yarn-lockfile.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
// SPDX-License-Identifier: MIT
/** Conservative Yarn Classic attribution, including peer edges absent from yarn.lock. */
import { strict as assert } from "node:assert";
import { execFileSync, spawnSync } from "node:child_process";
import childProcess, { execFileSync, spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, it } from "node:test";
import { describe, it, mock } from "node:test";
import { analyzeCheckout } from "../../src/analyze.js";
import { analyzeGitDelta } from "../../src/git/git-diff.js";
import { yarnLockAffectedDependencies } from "../../src/repo/yarn-lockfile.js";

const header = "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n";
const roots = { consumer: "^1.0.0", host: "^1.0.0" };
const alternateLayouts = ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "bun.lock", "bun.lockb", ".yarnrc", ".yarnrc.yml", ".pnp.js", ".pnp.cjs"];
function entry(name: string, version = "1.0.0", range = "^1.0.0", extra = ""): string {
return `${JSON.stringify(`${name}@${range}`)}:\n version ${JSON.stringify(version)}\n resolved ${JSON.stringify(`https://registry.yarnpkg.com/${name}/-/${name.split("/").at(-1)}-${version}.tgz#${version === "1.0.0" ? "1" : "2"}111111111111111111111111111111111111111`)}\n${extra}\n`;
}
Expand Down Expand Up @@ -82,6 +84,30 @@ function install(dir: string, value: string, version: string) {
});
}

const isRootListing = (args: readonly string[]) => args[0] === "ls-tree" && !args.includes("-r");
async function traceGit<T>(run: (calls: string[][]) => Promise<T>, inject?: (args: readonly string[], result: ReturnType<typeof spawnSync>) => ReturnType<typeof spawnSync>) {
const realSpawnSync = childProcess.spawnSync;
const calls: string[][] = [];
const spy = mock.method(childProcess, "spawnSync", ((...args: Parameters<typeof spawnSync>) => {
const result = realSpawnSync(...args);
if (args[0] !== "git" || !Array.isArray(args[1])) return result;
calls.push([...args[1]]);
return inject ? inject(args[1], result) : result;
}) as typeof spawnSync);
syncBuiltinESMExports();
try { return await run(calls); }
finally { spy.mock.restore(); syncBuiltinESMExports(); }
}

/** Git trees can contain empty directories and names that the host filesystem cannot create. */
function withTreeEntries(dir: string, parent: string, entries: string[]): string {
const tree = execFileSync("git", ["mktree", "-z"], {
cwd: dir, encoding: "utf8",
input: execFileSync("git", ["ls-tree", "-z", parent], { cwd: dir, encoding: "utf8" }) + entries.join("\0") + "\0",
}).trim();
return git(dir, "commit-tree", tree, "-p", parent, "-m", "synthetic root entries");
}

describe("yarnLockAffectedDependencies", () => {
it("returns every direct root for a direct change because Classic does not record peer edges", () => {
assert.deepEqual(yarnLockAffectedDependencies(lock(), lock("1.0.1"), roots, roots), ["consumer", "host"]);
Expand Down Expand Up @@ -189,6 +215,151 @@ describe("yarnLockAffectedDependencies", () => {
}
});

describe("Yarn layout inventories", () => {
it("uses two root listings instead of eighteen absent layout reads without changing selection", async () => {
await fixture(async (dir, base) => {
write(dir, { "yarn.lock": lock("1.0.1") });
const head = commit(dir, "head");
await traceGit(async (calls) => {
const result = await analyzeGitDelta({ repoPath: dir, baseSha: base, headSha: head });
assert.ok(result.success);
assert.equal(result.delta.analysis.lockfileChanged, false);
assert.deepEqual(result.delta.analysis.changedDependencies, ["consumer", "host"]);
assert.deepEqual(calls.filter(isRootListing), [
["ls-tree", "--full-tree", "--name-only", "-z", base], ["ls-tree", "--full-tree", "--name-only", "-z", head],
]);
assert.deepEqual(calls.filter((args) => args[0] === "ls-tree" && args.includes("-r")), [
["ls-tree", "-r", "--name-only", "-z", head],
]);
assert.ok(result.inventory?.files.has("src/consumer.test.js"));
assert.deepEqual(calls.filter((args) => args[0] === "show" && alternateLayouts.some((path) => args.includes(`${base}:${path}`) || args.includes(`${head}:${path}`))), []);
});
const result = await analyzeCheckout({ repoPath: dir, base, head });
assert.equal(result.plan.mode, "SELECTIVE");
assert.deepEqual(result.plan.selectedTests, ["src/consumer.test.js", "src/host.test.js"]);
});
});

for (const path of [".pnp.js", ".pnp.cjs"]) {
for (const state of ["added", "deleted"] as const) {
it(`keeps the lock signal when ${path} is ${state}`, async () => {
await fixture(async (dir, base) => {
const { delta, result } = await changed(dir, base, {
"yarn.lock": lock("1.0.1"), [path]: state === "added" ? "module.exports = {};\n" : undefined,
});
assert.equal(delta.analysis.lockfileChanged, true);
assert.equal(delta.analysis.dependencyLockfile, undefined);
assert.equal(result.impact.fallbackRequired, true);
assert.equal(result.plan.mode, "FULL");
}, state === "deleted" ? { [path]: "module.exports = {};\n" } : {});
});
}
}

it("counts a root directory as an unsupported layout", async () => {
await fixture(async (dir, base) => {
const { delta, result } = await changed(dir, base, { "yarn.lock": lock("1.0.1") });
assert.equal(delta.analysis.lockfileChanged, true);
assert.equal(result.plan.mode, "FULL");
}, { ".pnp.cjs/settings.txt": "directory layout\n" });
});

it("checks the repository root when delta analysis starts in a nested directory", async () => {
await fixture(async (dir, base) => {
write(dir, { "yarn.lock": lock("1.0.1") });
const head = commit(dir, "head");
const result = await analyzeGitDelta({ repoPath: join(dir, "src"), baseSha: base, headSha: head });
assert.ok(result.success);
assert.equal(result.delta.analysis.lockfileChanged, true);
assert.equal(result.delta.analysis.dependencyLockfile, undefined);
}, { ".pnp.cjs": "module.exports = {};\n" });
});

it("sees a deleted base-only empty layout tree that recursive file listings omit", async () => {
await fixture(async (dir, base) => {
const emptyTree = execFileSync("git", ["hash-object", "-w", "-t", "tree", "--stdin"], { cwd: dir, input: "", encoding: "utf8" }).trim();
const baseWithLayout = withTreeEntries(dir, base, [`040000 tree ${emptyTree}\t.pnp.cjs`]);
const { delta, result } = await changed(dir, baseWithLayout, { "yarn.lock": lock("1.0.1") });
// There is no deleted file to trigger a separate fallback and hide a missed base layout.
assert.deepEqual(delta.files.map((file) => file.path), ["yarn.lock"]);
assert.equal(delta.analysis.lockfileChanged, true);
assert.equal(result.plan.mode, "FULL");
});
});

it("preserves whitespace and backslashes in valid root names", async () => {
await fixture(async (dir, base) => {
const blob = git(dir, "rev-parse", `${base}:.gitignore`);
const entries = [" .pnp.cjs", ".pnp.cjs ", "tab\tname.md", "line\nbreak.md", "back\\slash.md"].map((name) => `100644 blob ${blob}\t${name}`);
const unusualBase = withTreeEntries(dir, base, entries);
write(dir, { "yarn.lock": lock("1.0.1") });
const unusualHead = withTreeEntries(dir, commit(dir, "head"), entries);
const result = await analyzeGitDelta({ repoPath: dir, baseSha: unusualBase, headSha: unusualHead });
assert.ok(result.success);
assert.equal(result.delta.analysis.lockfileChanged, false);
assert.deepEqual(result.delta.analysis.changedDependencies, ["consumer", "host"]);
});
});

const invalidListings: Array<[string, Partial<ReturnType<typeof spawnSync>>]> = [
["nonzero status", { status: 1, stderr: "injected root listing failure" }],
["spawn failure", { status: null, error: new Error("injected spawn failure") }],
["empty output", { stdout: "" }],
["unparseable output", { stdout: "not a NUL-delimited listing\n" }],
["truncated output", { stdout: "package.json\0yarn.lock" }],
["duplicate root", { stdout: "package.json\0yarn.lock\0package.json\0" }],
["empty root", { stdout: "package.json\0\0yarn.lock\0" }],
["nested path", { stdout: "package.json\0src/nested\0yarn.lock\0" }],
["dot root", { stdout: "package.json\0.\0yarn.lock\0" }],
["parent root", { stdout: "package.json\0..\0yarn.lock\0" }],
];
for (const side of ["base", "head"] as const) {
for (const [name, replacement] of invalidListings) {
it(`retains full fallback for ${side} root listing ${name}`, async () => {
await fixture(async (dir, base) => {
write(dir, { "yarn.lock": lock("1.0.1") });
const head = commit(dir, "head");
const target = side === "base" ? base : head;
let injected = 0;
await traceGit(async () => {
const delta = await analyzeGitDelta({ repoPath: dir, baseSha: base, headSha: head });
assert.ok(delta.success);
assert.equal(delta.delta.analysis.lockfileChanged, true);
assert.equal(delta.delta.analysis.dependencyLockfile, undefined);
const result = await analyzeCheckout({ repoPath: dir, base, head });
assert.equal(result.impact.fallbackRequired, true);
assert.equal(result.plan.mode, "FULL");
assert.ok(result.impact.fallbackReasons.some((reason) => /Lockfile changed/.test(reason)));
assert.ok(injected > 0, "the intended root listing was intercepted");
}, (args, result) => {
if (args.length !== 5 || args[0] !== "ls-tree" || args[1] !== "--full-tree" || args[2] !== "--name-only" || args[3] !== "-z" || args[4] !== target) return result;
injected++;
return { ...result, ...replacement };
});
});
});
}
}

it("does not add root listings to non-Yarn changes", async () => {
for (const change of [
{ "src/unrelated.test.js": files["src/unrelated.test.js"] + "// source change\n" },
{ "package-lock.json": "{}\n" },
{ "pnpm-lock.yaml": "lockfileVersion: '9.0'\n" },
]) {
await fixture(async (dir, base) => {
write(dir, change);
const head = commit(dir, "head");
await traceGit(async (calls) => {
const result = await analyzeGitDelta({ repoPath: dir, baseSha: base, headSha: head });
assert.ok(result.success);
assert.deepEqual(calls.filter(isRootListing), []);
});
});
}
});
});

describe("Yarn Classic dependency changes end to end", () => {
it("keeps a failing peer consumer in the public CLI selection and skips a dependency-free test", async () => {
await fixture(async (dir, base) => {
Expand Down Expand Up @@ -357,7 +528,7 @@ describe("Yarn Classic dependency changes end to end", () => {
});
}

for (const path of ["package-lock.json", "pnpm-lock.yaml", ".yarnrc", ".yarnrc.yml", ".pnp.cjs"]) {
for (const path of alternateLayouts) {
it(`does not narrow when ${path} is present and unchanged`, async () => {
await fixture(async (dir, base) => {
const { delta, result } = await changed(dir, base, { "yarn.lock": lock("1.0.1") });
Expand Down