diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ebe5908..7631cdb 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.10.1", + "version": "0.10.2", "description": "Generische agentische Dev-Loop-Kette: /devloop:specify|spec-to-tests|implement|critic|loop + Bindungs-Anker (Wächter-Vorbedingung, content-gebundene Stopps, CI-Required-Check). Projektübergreifend.", "author": { "name": "Tobias Mogdans" } } diff --git a/dist/cli/verify-unskip.js b/dist/cli/verify-unskip.js index 241bad6..d519f7e 100644 --- a/dist/cli/verify-unskip.js +++ b/dist/cli/verify-unskip.js @@ -15,6 +15,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { isAllowedTestEdit, isSpecBranch } from "../core/unskip.js"; import { parseNulPaths } from "../core/diff-paths.js"; +import { readTreeEntry, TreeEntryReadError } from "../core/tree-entry.js"; import { MANAGED_TESTS_PATH, isManagedTestPath, parseManagedTestGlobs, } from "../core/managed-tests.js"; const repo = process.argv[2] ?? "."; const base = process.argv[3] ?? "origin/main"; @@ -25,19 +26,6 @@ if (isSpecBranch(headBranch)) { process.stdout.write(JSON.stringify({ ok: true, skipped: "spec-PR (devloop/spec/*)" }) + "\n"); process.exit(0); } -const gitSafe = (args) => { - try { - // stderr ignored: `git show :` legitimately fails for every file the PR adds - // (and for an absent config) — the "fatal: path ... does not exist" noise is not a finding. - return execFileSync("git", ["-C", repo, ...args], { - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - }); - } - catch { - return ""; - } -}; const TEST_FILE = /\.(test|spec)\.[jt]sx?$/; // The glob list is read from the BASE ref first: the scope that is already on the protected // branch decides, so a PR cannot loosen the seam for itself. Only if the file does not exist on @@ -51,10 +39,27 @@ const readWorktree = (rel) => { return ""; } }; -const fromBase = gitSafe(["show", `${base}:${MANAGED_TESTS_PATH}`]); -const fromWorktree = fromBase === "" ? readWorktree(MANAGED_TESTS_PATH) : ""; -const managedRaw = fromBase !== "" ? fromBase : fromWorktree; -const managedSource = fromBase !== "" ? "base" : fromWorktree !== "" ? "worktree" : "default"; +// Read errors fail closed (exit 1) — never "empty", never a fallback to the PR's own worktree. +const fail = (msg) => { + process.stderr.write(`verify-unskip: ${msg}\n`); + process.exit(1); +}; +const entryAt = (ref, path) => { + try { + return readTreeEntry(repo, ref, path); + } + catch (e) { + return fail(e instanceof TreeEntryReadError ? e.message : `cannot read ${path} @ ${ref}: ${String(e)}`); + } +}; +const cfg = entryAt(base, MANAGED_TESTS_PATH); +if (cfg.kind !== "missing" && cfg.kind !== "file") { + fail(`${MANAGED_TESTS_PATH} @ ${base} exists but is not a regular file (${cfg.kind}); refusing to guess the scope`); +} +const fromBase = cfg.kind === "file" ? cfg.content : ""; +const fromWorktree = cfg.kind === "missing" ? readWorktree(MANAGED_TESTS_PATH) : ""; +const managedRaw = cfg.kind === "file" ? fromBase : fromWorktree; +const managedSource = cfg.kind === "file" ? "base" : fromWorktree !== "" ? "worktree" : "default"; const managedGlobs = parseManagedTestGlobs(managedRaw); // The changed paths: NUL-separated (-z: no quoting of non-ASCII/special characters) and without // rename detection (a rename shows BOTH the old and the new path, so the old one is judged as a @@ -75,9 +80,36 @@ const testFiles = changedPaths().filter((f) => TEST_FILE.test(f)); const changed = testFiles.filter((f) => isManagedTestPath(f, managedGlobs)); const unmanaged = testFiles.filter((f) => !isManagedTestPath(f, managedGlobs)); const violations = []; +const describe = (e) => e.kind === "symlink" + ? "symlink" + : e.kind === "submodule" + ? "submodule (gitlink)" + : e.kind === "other" + ? e.type + : null; +const contentOf = (e) => (e.kind === "file" ? e.content : ""); // "" = absent for (const file of changed) { - const oldContent = gitSafe(["show", `${base}:${file}`]); // "" if the file is new - const newContent = gitSafe(["show", `HEAD:${file}`]); + const oldEntry = entryAt(base, file); + const newEntry = entryAt("HEAD", file); + // The diff reported this path as changed, so it exists in base or HEAD. Missing in both means + // the read missed it (e.g. a name that did not survive decoding): a read error, never "empty". + if (oldEntry.kind === "missing" && newEntry.kind === "missing") { + fail(`changed test path ${JSON.stringify(file)} was found in neither ${base} nor HEAD (read error)`); + } + const oldType = describe(oldEntry); + const newType = describe(newEntry); + if (oldType !== null || newType !== null) { + const where = [oldType !== null ? `${oldType} in base` : "", newType !== null ? `${newType} in HEAD` : ""] + .filter((x) => x !== "") + .join(", "); + violations.push({ + file, + reason: `managed test path is not a regular file (${where}); only regular test files are allowed`, + }); + continue; + } + const oldContent = contentOf(oldEntry); // "" if the file is new + const newContent = contentOf(newEntry); if (!isAllowedTestEdit(oldContent, newContent)) { violations.push({ file, diff --git a/dist/core/tree-entry.js b/dist/core/tree-entry.js new file mode 100644 index 0000000..4b7cf08 --- /dev/null +++ b/dist/core/tree-entry.js @@ -0,0 +1,60 @@ +// Reads the ENTRY of a path in a git ref (type + mode + full content), without a shell. +// "Path absent in this ref" is a normal result ({kind:"missing"}); every other failure to +// determine the entry or its content THROWS (a read error must never look like "empty"). +import { execFileSync } from "node:child_process"; +// Contents up to this size are read completely; larger ones are a read error (fail-closed). +export const MAX_BLOB_BYTES = 64 * 1024 * 1024; +export class TreeEntryReadError extends Error { +} +const git = (repo, args, maxBuffer) => { + try { + // --literal-pathspecs: a path such as ":(top)x" or ":/x" is a file name here, never pathspec magic. + return execFileSync("git", ["-C", repo, "--literal-pathspecs", ...args], { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + maxBuffer, + }); + } + catch (e) { + const err = e; + const detail = err.code === "ENOBUFS" + ? `content exceeds the read limit of ${Math.round(maxBuffer / (1024 * 1024))} MiB (ENOBUFS)` + : String(err.stderr ?? "").trim() || err.message || String(e); + throw new TreeEntryReadError(detail); + } +}; +export function readTreeEntry(repo, ref, path) { + const where = `${path} @ ${ref}`; + try { + const raw = git(repo, ["ls-tree", "-z", ref, "--", path], 16 * 1024 * 1024); + const records = raw.split("\0").filter((r) => r !== ""); + if (records.length === 0) + return { kind: "missing" }; + // Exact path match: never trust "some line came back". + let found; + for (const rec of records) { + const m = /^(\d+) (\w+) ([0-9a-f]+)\t([\s\S]*)$/.exec(rec); + if (!m) + throw new TreeEntryReadError(`unparsable ls-tree record`); + if (m[4] === path) + found = { mode: m[1], type: m[2], oid: m[3] }; + } + if (!found) + throw new TreeEntryReadError("ls-tree returned no entry for the exact path"); + if (found.mode === "120000") + return { kind: "symlink" }; + if (found.mode === "160000" || found.type === "commit") + return { kind: "submodule" }; + if (found.mode === "100644" || found.mode === "100755") { + const content = git(repo, ["cat-file", "blob", found.oid], MAX_BLOB_BYTES); + return { kind: "file", mode: found.mode, content }; + } + return { kind: "other", type: found.type }; + } + catch (e) { + if (e instanceof TreeEntryReadError) { + throw new TreeEntryReadError(`cannot read ${where}: ${e.message}`); + } + throw e; + } +} diff --git a/docs/2026-11-25-verify-unskip-inhalte-design.md b/docs/2026-11-25-verify-unskip-inhalte-design.md new file mode 100644 index 0000000..68294a8 --- /dev/null +++ b/docs/2026-11-25-verify-unskip-inhalte-design.md @@ -0,0 +1,115 @@ +# verify-unskip: Inhalte vollständig und nur aus regulären Dateien lesen — Design + +> devloop, Issues #19 und #20. Nach #12 kommen alle geänderten Testpfade an; geprüft wird aber +> der Inhalt, den `git show` liefert. Zwei Wege lassen einen aktiven Test trotzdem durch. +> Status: **abgenommen** (2026-11-25); Nachtrag nach Critic-Runde 1 (REQ-UNSKIPCONTENT-7, Grenzen) abgenommen 2026-11-25; +> Nachtrag „Bekannte Grenzen“ nach Critic-Runde 2 (accepted) abgenommen 2026-11-25. + +## Ist-Zustand (main, 86c0be9) + +`src/cli/verify-unskip.ts`: `gitSafe(["show", `${ref}:${file}`])` für Basis und HEAD. +`gitSafe` ruft `execFileSync` **ohne `maxBuffer`** (Node-Default 1 MiB) und liefert bei **jedem** +Fehler `""`. `""` bedeutet für die Bewertung „Datei existiert in diesem Ref nicht". + +1. **#19 – Größe.** Eine neue Testdatei > 1 MiB: `git show` scheitert (ENOBUFS), Inhalt `""`, + `isAllowedTestEdit("", "")` → erlaubt. Gemessen: aktiver `test("evil")` + 1,2 MB Kommentar → + `ok: true`, vitest führt den Test aus. Ist ein verwalteter Test schon auf der Basis > 1 MiB, + geht jede Änderung an ihm durch. +2. **#20 – Symlink.** Neue Datei `test/c.test.ts` als Symlink auf `test/helper.ts` (aktiver Test). + `git show` liefert den Zielpfad `helper.ts` als Text, darin kein aktiver Test → `ok: true`. + vitest folgt dem Link und führt den Test aus. (Eine *bestehende* Testdatei durch einen Symlink + zu ersetzen, fällt schon heute auf.) +3. **Gleiche Klasse bei der Config:** `managed-tests.json` wird per `gitSafe` aus der Basis gelesen; + scheitert das Lesen aus einem anderen Grund als „fehlt", fällt der Code auf den Arbeitsbaum + (PR-HEAD) zurück — der PR bestimmte dann seinen Scope selbst. + +## Begriffe + +- **Eintrag eines Pfads in einem Ref:** Typ und Modus des Pfads im Baum dieses Refs, wie Git ihn + führt: fehlt / reguläre Datei (Modus `100644` oder `100755`) / Symlink (`120000`) / + Submodul (`160000`) / Verzeichnis. +- **Lesefehler:** jeder Fehlschlag beim Ermitteln von Eintrag oder Inhalt, der nicht „Pfad fehlt + in diesem Ref" ist. + +## Anforderungen (EARS) + +- **REQ-UNSKIPCONTENT-1** *(ubiquitous)* — `verify-unskip` soll für jeden geprüften Testpfad den + Inhalt in Basis und HEAD vollständig lesen, unabhängig von der Dateigröße (mindestens bis + 64 MiB je Datei). +- **REQ-UNSKIPCONTENT-2** *(ubiquitous)* — `verify-unskip` soll „Pfad fehlt in diesem Ref" (Inhalt + leer: neue bzw. gelöschte Datei) von einem Lesefehler unterscheiden. +- **REQ-UNSKIPCONTENT-3** *(unwanted)* — Wenn beim Lesen eines geprüften Testpfads ein Lesefehler + auftritt, soll `verify-unskip` mit Exit 1 fehlschlagen und Pfad und Ref nennen. +- **REQ-UNSKIPCONTENT-4** *(unwanted)* — Wenn ein geprüfter (verwalteter) Testpfad in Basis oder + HEAD vorhanden, aber keine reguläre Datei ist (Symlink, Submodul, anderer Typ), soll + `verify-unskip` ihn als Verstoß werten, mit einer Meldung, die den Typ nennt. +- **REQ-UNSKIPCONTENT-5** *(unwanted)* — Wenn `managed-tests.json` in der Basis vorhanden ist, aber + nicht gelesen werden kann (Lesefehler oder keine reguläre Datei), soll `verify-unskip` mit + Exit 1 fehlschlagen, statt auf den Arbeitsbaum zurückzufallen. Fehlt sie in der Basis, bleibt + das bisherige Verhalten (Arbeitsbaum, sonst Default „alle Testdateien"). +- **REQ-UNSKIPCONTENT-6** *(ubiquitous)* — Alles andere bleibt unverändert: Pfadermittlung aus #12, + No-op auf `devloop/spec/*`, Scope, Bewertung per `isAllowedTestEdit`, Ausgabeformat (Felder + dürfen ergänzt werden). Unverwaltete Testpfade werden nicht gelesen und nicht bewertet. +- **REQ-UNSKIPCONTENT-7** *(unwanted)* — Wenn ein vom Diff gemeldeter, geprüfter Testpfad weder in + der Basis noch im HEAD gefunden wird, soll `verify-unskip` das als Lesefehler werten (Exit 1, + Pfad genannt). Ein Pfad, den der Diff als geändert meldet, existiert in mindestens einem der + beiden Stände; „fehlt in beiden" heißt, das Lesen hat den Pfad verfehlt. + (Anlass Critic-Runde 1, B1: `ls-tree` las `:(top)evil.test.ts` als Pathspec-Magic, der Pfad galt + in beiden Refs als fehlend, ein aktiver Test ging durch — Regression gegenüber main. B2: + Nicht-UTF-8-Dateinamen, gleiches Muster, bestand schon vorher.) + +## Detektoren (Wirkung) und Mutationsproben + +CLI-Tests gegen `dist/cli/verify-unskip.js` in echten temporären Git-Repos: + +| Fall | Erwartung | tötet Mutation | +|---|---|---| +| neue Testdatei 1,2 MB mit aktivem Test | Exit 1, Datei in `violations` | `maxBuffer` entfernt | +| neue Testdatei 1,2 MB, alle Tests geskippt | Exit 0, Datei in `checked` | Größe pauschal als Verstoß | +| Basis-Test 1,2 MB geskippt; PR ändert eine Assertion | Exit 1 | `maxBuffer` entfernt | +| Basis-Test 1,2 MB geskippt; PR entfernt nur `.skip` | Exit 0 | dto. (Gegenprobe) | +| neue `test/c.test.ts` als Symlink auf Datei mit aktivem Test | Exit 1, Meldung nennt Symlink | Typprüfung entfernt | +| neue `test/c.test.ts` als Symlink auf Datei **ohne** aktiven Test | Exit 1 (Typ allein genügt) | Typprüfung nur bei aktivem Ziel | +| bestehende Testdatei durch Symlink ersetzt | Exit 1 (wie bisher) | — | +| verwalteter Testpfad als Submodul (gitlink) im HEAD | Exit 1 | Typprüfung nur für Symlinks | +| Lesefehler simuliert (Objekt des Blobs fehlt im Repo, z. B. per gelöschter loose-object-Datei) | Exit 1, nennt Pfad | Fehler wieder als `""` | +| Basis-`managed-tests.json` als Symlink bzw. unlesbar, Arbeitsbaum mit engem Scope | Exit 1 | Rückfall auf den Arbeitsbaum | +| Basis ohne `managed-tests.json`, Arbeitsbaum mit Scope | wie bisher (Quelle `worktree`) | — | +| unverwalteter Symlink-Test (außerhalb des Scopes) | Exit 0, in `unmanaged` | Scope ignoriert | +| Spec-Branch mit allen obigen Konstruktionen | Exit 0 (No-op) | — | +| neue `:(top)evil.test.ts` bzw. `:/evil.test.ts` mit aktivem Test (Default-Scope) | Exit 1 | Pfad als Pathspec statt literal lesen | +| Diff meldet Pfad, Leser findet ihn in keinem Ref (z. B. Nicht-UTF-8-Name oder Leser-Mutation) | Exit 1 | „fehlt in beiden" als erlaubt | +| ausführbare Testdatei (Modus `100755`), nur `.skip` entfernt | Exit 0 | `100755` nicht als reguläre Datei | + +## Bekannte Grenzen + +- **Inhalte über 64 MiB** je Datei: Lesefehler → Exit 1 (fail-closed, kein stilles Grün). +- **Import-Alias / andere Schreibweisen** umgehen `hasActiveTest` weiterhin (#21). +- **Ein Symlink außerhalb der Test-Endung** (`helper.ts`), auf den ein *unveränderter* Test + verweist, wird nicht geprüft — das ist kein Testpfad. Der Weg über einen neuen Symlink-Test ist + durch REQ-4 geschlossen. +- Glob-Matching für den Scope hängt weiter an #15 (`s`-Flag). +- **Datei in PR und Basis gelöscht:** Löscht der PR eine Testdatei, die auch die (weitergelaufene) + Basis inzwischen gelöscht hat, fehlt sie in beiden Refs → nach REQ-7 rot. Selten; fail-closed. +- **Replace-Refs auf dem Runner** (`refs/replace/*`) verfälschen gelesene Inhalte; das müsste ein + Mensch im CI setzen, `actions/checkout` holt sie nicht (Critic-Runde 1, B4). +- **Laufzeit etwa verdoppelt** gegenüber v0.10.1 (vier statt zwei Git-Prozesse je geprüfter + Datei). Gemessen auf macOS: 100 Testdateien typisch 4,8 s (vorher 2,5 s), 1000 Dateien Maximum + 43,6 s (vorher 17,1 s). Kein Fehlalarm; ein Batch-Leser (`cat-file --batch`) wäre ein eigener + Schritt (Critic-Runde 1, B6). +- **Meldung über 64 MiB** nennt nur `ENOBUFS`, nicht die Grenze (B5). +- **Nicht-UTF-8-Pfade werden abgewiesen, nicht bewertet.** Node übergibt Argumente an Git als + UTF-8; der Originalpfad erreicht `ls-tree` nicht. REQ-7 macht daraus Exit 1 (fail-closed). + Liegt neben dem Nicht-UTF-8-Namen eine Datei, deren Name der verlustbehafteten Dekodierung + entspricht (U+FFFD), lesen beide Seiten diese Zwillingsdatei und REQ-7 greift nicht. Node + dekodiert beim Laden genauso; auf APFS nicht herstellbar (Critic-Runde 2, D1). +- **macOS-Runner mit `core.precomposeunicode=true` und NFD-Dateinamen:** eine neue, nur + geskippte NFD-Testdatei wird rot („found in neither"). Falsch rot, sichere Richtung; auf Linux + kein Unterschied. Zugleich ist der main-Bypass (NFD-Test aktiv geändert) geschlossen (D2). +- **Doppelte Baumeinträge** (Baum mit zweimal demselben Namen, `git fsck` meldet + `duplicateEntries`): Der Leser nimmt den letzten Eintrag, wie `checkout`. Kein Test pinnt das; + ob GitHub solche Bäume beim Push annimmt, ist nicht geprüft (D3). +- **Leere `managed-tests.json` in der Basis** gilt jetzt als Quelle „base" (Default: alles + verwaltet), statt auf den Arbeitsbaum zurückzufallen. Strenger, entspricht REQ-5 (D4). +- **Testdatei-Endungen:** `.mts/.cts/.mjs/.cjs` erkennt die Naht nicht als Testdatei, vitest + schon. Bestand schon vorher, Pfaderkennung ist hier eingefroren (REQ-6); eigener Fix (#23). diff --git a/package.json b/package.json index 8f966a8..f539377 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.10.1", + "version": "0.10.2", "private": true, "type": "module", "license": "MIT", diff --git a/src/cli/verify-unskip.ts b/src/cli/verify-unskip.ts index 9e1eb6a..820808e 100644 --- a/src/cli/verify-unskip.ts +++ b/src/cli/verify-unskip.ts @@ -16,6 +16,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { isAllowedTestEdit, isSpecBranch } from "../core/unskip.js"; import { parseNulPaths } from "../core/diff-paths.js"; +import { readTreeEntry, TreeEntryReadError, type TreeEntry } from "../core/tree-entry.js"; import { MANAGED_TESTS_PATH, isManagedTestPath, @@ -33,19 +34,6 @@ if (isSpecBranch(headBranch)) { process.exit(0); } -const gitSafe = (args: string[]): string => { - try { - // stderr ignored: `git show :` legitimately fails for every file the PR adds - // (and for an absent config) — the "fatal: path ... does not exist" noise is not a finding. - return execFileSync("git", ["-C", repo, ...args], { - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - }); - } catch { - return ""; - } -}; - const TEST_FILE = /\.(test|spec)\.[jt]sx?$/; // The glob list is read from the BASE ref first: the scope that is already on the protected @@ -59,10 +47,27 @@ const readWorktree = (rel: string): string => { return ""; } }; -const fromBase = gitSafe(["show", `${base}:${MANAGED_TESTS_PATH}`]); -const fromWorktree = fromBase === "" ? readWorktree(MANAGED_TESTS_PATH) : ""; -const managedRaw = fromBase !== "" ? fromBase : fromWorktree; -const managedSource = fromBase !== "" ? "base" : fromWorktree !== "" ? "worktree" : "default"; +// Read errors fail closed (exit 1) — never "empty", never a fallback to the PR's own worktree. +const fail = (msg: string): never => { + process.stderr.write(`verify-unskip: ${msg}\n`); + process.exit(1); +}; +const entryAt = (ref: string, path: string): TreeEntry => { + try { + return readTreeEntry(repo, ref, path); + } catch (e) { + return fail(e instanceof TreeEntryReadError ? e.message : `cannot read ${path} @ ${ref}: ${String(e)}`); + } +}; + +const cfg = entryAt(base, MANAGED_TESTS_PATH); +if (cfg.kind !== "missing" && cfg.kind !== "file") { + fail(`${MANAGED_TESTS_PATH} @ ${base} exists but is not a regular file (${cfg.kind}); refusing to guess the scope`); +} +const fromBase = cfg.kind === "file" ? cfg.content : ""; +const fromWorktree = cfg.kind === "missing" ? readWorktree(MANAGED_TESTS_PATH) : ""; +const managedRaw = cfg.kind === "file" ? fromBase : fromWorktree; +const managedSource = cfg.kind === "file" ? "base" : fromWorktree !== "" ? "worktree" : "default"; const managedGlobs = parseManagedTestGlobs(managedRaw); // The changed paths: NUL-separated (-z: no quoting of non-ASCII/special characters) and without @@ -92,9 +97,38 @@ const changed = testFiles.filter((f) => isManagedTestPath(f, managedGlobs)); const unmanaged = testFiles.filter((f) => !isManagedTestPath(f, managedGlobs)); const violations: { file: string; reason: string }[] = []; +const describe = (e: TreeEntry): string | null => + e.kind === "symlink" + ? "symlink" + : e.kind === "submodule" + ? "submodule (gitlink)" + : e.kind === "other" + ? e.type + : null; +const contentOf = (e: TreeEntry): string => (e.kind === "file" ? e.content : ""); // "" = absent + for (const file of changed) { - const oldContent = gitSafe(["show", `${base}:${file}`]); // "" if the file is new - const newContent = gitSafe(["show", `HEAD:${file}`]); + const oldEntry = entryAt(base, file); + const newEntry = entryAt("HEAD", file); + // The diff reported this path as changed, so it exists in base or HEAD. Missing in both means + // the read missed it (e.g. a name that did not survive decoding): a read error, never "empty". + if (oldEntry.kind === "missing" && newEntry.kind === "missing") { + fail(`changed test path ${JSON.stringify(file)} was found in neither ${base} nor HEAD (read error)`); + } + const oldType = describe(oldEntry); + const newType = describe(newEntry); + if (oldType !== null || newType !== null) { + const where = [oldType !== null ? `${oldType} in base` : "", newType !== null ? `${newType} in HEAD` : ""] + .filter((x) => x !== "") + .join(", "); + violations.push({ + file, + reason: `managed test path is not a regular file (${where}); only regular test files are allowed`, + }); + continue; + } + const oldContent = contentOf(oldEntry); // "" if the file is new + const newContent = contentOf(newEntry); if (!isAllowedTestEdit(oldContent, newContent)) { violations.push({ file, diff --git a/src/core/tree-entry.ts b/src/core/tree-entry.ts new file mode 100644 index 0000000..e6ba8dd --- /dev/null +++ b/src/core/tree-entry.ts @@ -0,0 +1,63 @@ +// Reads the ENTRY of a path in a git ref (type + mode + full content), without a shell. +// "Path absent in this ref" is a normal result ({kind:"missing"}); every other failure to +// determine the entry or its content THROWS (a read error must never look like "empty"). +import { execFileSync } from "node:child_process"; + +// Contents up to this size are read completely; larger ones are a read error (fail-closed). +export const MAX_BLOB_BYTES = 64 * 1024 * 1024; + +export type TreeEntry = + | { kind: "missing" } + | { kind: "file"; mode: string; content: string } + | { kind: "symlink" } + | { kind: "submodule" } + | { kind: "other"; type: string }; + +export class TreeEntryReadError extends Error {} + +const git = (repo: string, args: string[], maxBuffer: number): string => { + try { + // --literal-pathspecs: a path such as ":(top)x" or ":/x" is a file name here, never pathspec magic. + return execFileSync("git", ["-C", repo, "--literal-pathspecs", ...args], { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + maxBuffer, + }); + } catch (e) { + const err = e as { stderr?: unknown; message?: string; code?: string }; + const detail = + err.code === "ENOBUFS" + ? `content exceeds the read limit of ${Math.round(maxBuffer / (1024 * 1024))} MiB (ENOBUFS)` + : String(err.stderr ?? "").trim() || err.message || String(e); + throw new TreeEntryReadError(detail); + } +}; + +export function readTreeEntry(repo: string, ref: string, path: string): TreeEntry { + const where = `${path} @ ${ref}`; + try { + const raw = git(repo, ["ls-tree", "-z", ref, "--", path], 16 * 1024 * 1024); + const records = raw.split("\0").filter((r) => r !== ""); + if (records.length === 0) return { kind: "missing" }; + // Exact path match: never trust "some line came back". + let found: { mode: string; type: string; oid: string } | undefined; + for (const rec of records) { + const m = /^(\d+) (\w+) ([0-9a-f]+)\t([\s\S]*)$/.exec(rec); + if (!m) throw new TreeEntryReadError(`unparsable ls-tree record`); + if (m[4] === path) found = { mode: m[1], type: m[2], oid: m[3] }; + } + if (!found) throw new TreeEntryReadError("ls-tree returned no entry for the exact path"); + if (found.mode === "120000") return { kind: "symlink" }; + if (found.mode === "160000" || found.type === "commit") return { kind: "submodule" }; + if (found.mode === "100644" || found.mode === "100755") { + const content = git(repo, ["cat-file", "blob", found.oid], MAX_BLOB_BYTES); + return { kind: "file", mode: found.mode, content }; + } + return { kind: "other", type: found.type }; + } catch (e) { + if (e instanceof TreeEntryReadError) { + throw new TreeEntryReadError(`cannot read ${where}: ${e.message}`); + } + throw e; + } +} diff --git a/test/cli/verify-unskip-inhalte-extra.test.ts b/test/cli/verify-unskip-inhalte-extra.test.ts new file mode 100644 index 0000000..85ea73e --- /dev/null +++ b/test/cli/verify-unskip-inhalte-extra.test.ts @@ -0,0 +1,64 @@ +import { test, expect, beforeEach, afterEach } from "vitest"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync, unlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { dirname, join, resolve } from "node:path"; + +// Additions of the implementation station (the given tests stay untouched): they pin two +// things the given suite lets slip through (found by mutation). + +const cli = resolve(dirname(fileURLToPath(import.meta.url)), "../../dist/cli/verify-unskip.js"); +let repo: string; +const git = (...a: string[]) => + execFileSync("git", ["-C", repo, ...a], { + encoding: "utf8", + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }); +const commit = (m: string) => git("-c", "commit.gpgsign=false", "commit", "-q", "-m", m); +const put = (rel: string, c: string) => { + mkdirSync(dirname(join(repo, rel)), { recursive: true }); + writeFileSync(join(repo, rel), c); +}; +const run = () => spawnSync("node", [cli, repo, "main"], { encoding: "utf8" }); + +beforeEach(() => { + repo = mkdtempSync(join(tmpdir(), "devloop-unskipcontent-x-")); + git("init", "-q", "-b", "main"); + git("config", "user.name", "t"); + git("config", "user.email", "t@t"); +}); +afterEach(() => rmSync(repo, { recursive: true, force: true })); + +test("[REQ-UNSKIPCONTENT-5] base managed-tests.json as a symlink: exit 1 with NO result JSON (not a default-scope verdict)", () => { + put("a.test.ts", "// x\n"); + mkdirSync(join(repo, ".devloop"), { recursive: true }); + symlinkSync("[]", join(repo, ".devloop/managed-tests.json")); + git("add", "-A"); + commit("base"); + git("checkout", "-q", "-b", "devloop/impl"); + put("tools/x.test.ts", 'import { test } from "vitest";\ntest("evil", () => {});\n'); + git("add", "-A"); + commit("impl"); + const r = run(); + expect(r.status).toBe(1); + expect(r.stdout).toBe(""); + expect(r.stderr).toContain("managed-tests.json"); + expect(r.stderr).toMatch(/symlink/); +}); + +test("[REQ-UNSKIPCONTENT-4] a managed test file replaced by a directory: violation naming the type", () => { + put("d.test.ts", 'import { test } from "vitest";\ntest.skip("REQ-X-1 a", () => {});\n'); + git("add", "-A"); + commit("base"); + git("checkout", "-q", "-b", "devloop/impl"); + unlinkSync(join(repo, "d.test.ts")); + put("d.test.ts/inner.ts", "export {};\n"); + git("add", "-A"); + commit("impl"); + const r = run(); + expect(r.status).toBe(1); + const v = JSON.parse(r.stdout).violations as { file: string; reason: string }[]; + const d = v.find((x) => x.file === "d.test.ts"); + expect(d?.reason).toMatch(/tree/); +}); diff --git a/test/cli/verify-unskip-inhalte.test.ts b/test/cli/verify-unskip-inhalte.test.ts new file mode 100644 index 0000000..0559c7b --- /dev/null +++ b/test/cli/verify-unskip-inhalte.test.ts @@ -0,0 +1,426 @@ +import { test, expect, beforeEach, afterEach } from "vitest"; +import { execFileSync, spawnSync } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync, unlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { dirname, join, resolve } from "node:path"; + +// Issues #19/#20: verify-unskip must read contents completely (any size), tell "path absent" +// from a read error, and treat non-regular entries (symlink, gitlink) as violations. +// Real git repos, no git stub. + +const cli = resolve(dirname(fileURLToPath(import.meta.url)), "../../dist/cli/verify-unskip.js"); +const MIB = 1_048_576; + +let repo: string; +const git = (...args: string[]) => + execFileSync("git", ["-C", repo, ...args], { + encoding: "utf8", + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }); +const gitOk = (...args: string[]): boolean => { + try { + execFileSync("git", ["-C", repo, ...args], { stdio: "ignore" }); + return true; + } catch { + return false; + } +}; +const commit = (m: string) => git("-c", "commit.gpgsign=false", "commit", "-q", "-m", m); +const put = (rel: string, content: string) => { + mkdirSync(dirname(join(repo, rel)), { recursive: true }); + writeFileSync(join(repo, rel), content); +}; +const run = (headBranch?: string) => + spawnSync("node", [cli, repo, "main", ...(headBranch ? [headBranch] : [])], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); +const files = (list: { file: string }[]) => list.map((v) => v.file); +const startPr = () => git("checkout", "-q", "-b", "devloop/impl"); + +const SKIPPED = `import { test, expect } from "vitest"; +test.skip("REQ-X-1 first behaviour", () => { expect(first()).toBe(1); }); +test.skip("REQ-X-2 second behaviour", () => { expect(second()).toBe(2); }); +`; +const ACTIVE = `import { test, expect } from "vitest"; +test("evil", () => { expect(1).toBe(1); }); +`; +// ~1.2 MB of comment lines: above the 1 MiB default maxBuffer of execFileSync +const PADDING = ("// " + "x".repeat(77) + "\n").repeat(15_000); +const blobSize = (spec: string) => Number(git("cat-file", "-s", spec).trim()); +const modeOf = (rel: string, ref = "HEAD") => git("ls-tree", ref, "--", rel).split(" ")[0]; +const looseObject = (spec: string) => { + const sha = git("rev-parse", spec).trim(); + return join(repo, ".git/objects", sha.slice(0, 2), sha.slice(2)); +}; + +beforeEach(() => { + repo = mkdtempSync(join(tmpdir(), "devloop-unskipcontent-")); + git("init", "-q", "-b", "main"); + git("config", "user.name", "t"); + git("config", "user.email", "t@t"); + git("config", "core.quotePath", "true"); + put("a.test.ts", SKIPPED); + git("add", "-A"); + commit("base: skipped test on main"); +}); +afterEach(() => rmSync(repo, { recursive: true, force: true })); + +// ---------- REQ-1: size ---------- + +test("[REQ-UNSKIPCONTENT-1] new 1.2 MB test file with an ACTIVE test is a violation", () => { + startPr(); + put("big.test.ts", ACTIVE + PADDING); + git("add", "-A"); + commit("implement: evil test hidden in a big file"); + expect(blobSize("HEAD:big.test.ts")).toBeGreaterThan(MIB); + const r = run(); + expect(r.status).toBe(1); + const out = JSON.parse(r.stdout); + expect(out.ok).toBe(false); + expect(files(out.violations)).toEqual(["big.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-1] counter-probe: new 1.2 MB file with all tests skipped passes and is checked (already green: today an empty read is 'allowed' by accident)", () => { + startPr(); + put("big.test.ts", SKIPPED + PADDING); + git("add", "-A"); + commit("spec-like: big skipped file"); + expect(blobSize("HEAD:big.test.ts")).toBeGreaterThan(MIB); + const r = run(); + expect(r.status).toBe(0); + const out = JSON.parse(r.stdout); + expect(out.violations).toEqual([]); + expect(out.checked).toEqual(["big.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-1] base test of 1.2 MB, skipped: changing an assertion is a violation", () => { + put("big.test.ts", SKIPPED + PADDING); + git("add", "-A"); + commit("base: big managed test"); + startPr(); + put("big.test.ts", (SKIPPED + PADDING).replace("toBe(1)", "toBe(99)").replaceAll("test.skip(", "test(")); + git("add", "-A"); + commit("implement: tamper with the big test"); + expect(blobSize("main:big.test.ts")).toBeGreaterThan(MIB); + expect(blobSize("HEAD:big.test.ts")).toBeGreaterThan(MIB); + const r = run(); + expect(r.status).toBe(1); + expect(files(JSON.parse(r.stdout).violations)).toEqual(["big.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-1] counter-probe: base test of 1.2 MB, only .skip removed passes (already green: both reads fail identically today)", () => { + put("big.test.ts", SKIPPED + PADDING); + git("add", "-A"); + commit("base: big managed test"); + startPr(); + put("big.test.ts", (SKIPPED + PADDING).replaceAll("test.skip(", "test(")); + git("add", "-A"); + commit("implement: activate the big test"); + expect(blobSize("main:big.test.ts")).toBeGreaterThan(MIB); + const r = run(); + expect(r.status).toBe(0); + const out = JSON.parse(r.stdout); + expect(out.violations).toEqual([]); + expect(out.checked).toEqual(["big.test.ts"]); +}); + +// ---------- REQ-4: symlink / gitlink ---------- + +test("[REQ-UNSKIPCONTENT-4] new test/c.test.ts as a symlink to a helper with an ACTIVE test: violation naming the symlink", () => { + startPr(); + put("test/helper.ts", ACTIVE); + symlinkSync("helper.ts", join(repo, "test/c.test.ts")); + git("add", "-A"); + commit("implement: symlink smuggles an active test"); + expect(modeOf("test/c.test.ts")).toBe("120000"); + const r = run(); + expect(r.status).toBe(1); + const v = JSON.parse(r.stdout).violations; + expect(files(v)).toEqual(["test/c.test.ts"]); + expect(v[0].reason).toMatch(/symlink/i); +}); + +test("[REQ-UNSKIPCONTENT-4] new test symlink to a helper WITHOUT an active test is a violation too (the type alone decides)", () => { + startPr(); + put("test/helper.ts", SKIPPED); + symlinkSync("helper.ts", join(repo, "test/c.test.ts")); + git("add", "-A"); + commit("implement: harmless-looking symlink"); + expect(modeOf("test/c.test.ts")).toBe("120000"); + const r = run(); + expect(r.status).toBe(1); + const v = JSON.parse(r.stdout).violations; + expect(files(v)).toEqual(["test/c.test.ts"]); + expect(v[0].reason).toMatch(/symlink/i); +}); + +test("[REQ-UNSKIPCONTENT-4] an existing test file replaced by a symlink is a violation (already red-free today: the text differs)", () => { + startPr(); + put("helper.ts", ACTIVE); + unlinkSync(join(repo, "a.test.ts")); + symlinkSync("helper.ts", join(repo, "a.test.ts")); + git("add", "-A"); + commit("implement: replace a managed test by a symlink"); + expect(modeOf("a.test.ts")).toBe("120000"); + const r = run(); + expect(r.status).toBe(1); + expect(files(JSON.parse(r.stdout).violations)).toContain("a.test.ts"); +}); + +test("[REQ-UNSKIPCONTENT-4] managed test path as a submodule (gitlink) in HEAD is a violation", () => { + startPr(); + git("update-index", "--add", "--cacheinfo", "160000,1234567890123456789012345678901234567890,test/x.test.ts"); + commit("implement: gitlink at a managed test path"); + expect(modeOf("test/x.test.ts")).toBe("160000"); + const r = run(); + expect(r.status).toBe(1); + const v = JSON.parse(r.stdout).violations; + expect(files(v)).toEqual(["test/x.test.ts"]); + expect(v[0].reason).toMatch(/submodule|gitlink/i); +}); + +// The link target text equals the new file content, so a content-only comparison sees "no change". +test("[REQ-UNSKIPCONTENT-4] a symlink in the BASE replaced by a regular file whose content equals the link target text is a violation", () => { + symlinkSync("x", join(repo, "s.test.ts")); + git("add", "-A"); + commit("base: symlinked test"); + expect(modeOf("s.test.ts", "main")).toBe("120000"); + startPr(); + unlinkSync(join(repo, "s.test.ts")); + put("s.test.ts", "x"); + git("add", "-A"); + commit("implement: replace the symlink by a regular file"); + expect(modeOf("s.test.ts")).toBe("100644"); + expect(git("show", "main:s.test.ts")).toBe(git("show", "HEAD:s.test.ts")); + const r = run(); + expect(r.status).toBe(1); + expect(files(JSON.parse(r.stdout).violations)).toEqual(["s.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-4] a regular test replaced by a symlink whose target text equals its old content is a violation", () => { + put("e.test.ts", "x"); + git("add", "-A"); + commit("base: regular file"); + startPr(); + unlinkSync(join(repo, "e.test.ts")); + symlinkSync("x", join(repo, "e.test.ts")); + git("add", "-A"); + commit("implement: swap in a symlink"); + expect(modeOf("e.test.ts")).toBe("120000"); + expect(git("show", "main:e.test.ts")).toBe(git("show", "HEAD:e.test.ts")); + const r = run(); + expect(r.status).toBe(1); + expect(files(JSON.parse(r.stdout).violations)).toEqual(["e.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-6] unmanaged symlink test (outside managed-tests.json) is not read and not judged: exit 0, in unmanaged", () => { + put(".devloop/managed-tests.json", JSON.stringify(["services/**/*.test.ts"]) + "\n"); + git("add", "-A"); + commit("scope the seam to services"); + startPr(); + put("tools/helper.ts", ACTIVE); + symlinkSync("helper.ts", join(repo, "tools/c.test.ts")); + git("add", "-A"); + commit("chore: unmanaged symlink test"); + expect(modeOf("tools/c.test.ts")).toBe("120000"); + const r = run(); + expect(r.status).toBe(0); + const out = JSON.parse(r.stdout); + expect(out.unmanaged).toEqual(["tools/c.test.ts"]); + expect(out.checked).toEqual([]); + expect(out.violations).toEqual([]); +}); + +// ---------- REQ-2/3: read errors ---------- + +test("[REQ-UNSKIPCONTENT-3] HEAD blob of a new test file is missing from the object store: exit 1 naming path and ref", () => { + startPr(); + put("new.test.ts", ACTIVE + "// unique head content 7f3a\n"); + git("add", "-A"); + commit("implement: new test"); + const obj = looseObject("HEAD:new.test.ts"); + rmSync(obj); + // Preconditions: the blob is unreadable, the path diff still works (it needs trees only). + expect(gitOk("cat-file", "-e", "HEAD:new.test.ts")).toBe(false); + expect(git("diff", "--no-renames", "-z", "--name-only", "main...HEAD")).toContain("new.test.ts"); + const r = run(); + expect(r.status).toBe(1); + const all = r.stdout + r.stderr; + expect(all).toContain("new.test.ts"); + expect(all).toContain("HEAD"); + expect(r.stdout).not.toMatch(/"ok":\s*true/); +}); + +test("[REQ-UNSKIPCONTENT-3] BASE blob of an existing test file is missing: exit 1 naming the path (HEAD stays skipped, so an empty base read would be 'allowed')", () => { + const BASE = SKIPPED + "// unique base content 91bc\n"; + put("m.test.ts", BASE); + git("add", "-A"); + commit("base: managed test"); + startPr(); + put("m.test.ts", BASE.replace("toBe(1)", "toBe(99)")); // edited assertion, still skipped + git("add", "-A"); + commit("implement: edit while staying skipped"); + rmSync(looseObject("main:m.test.ts")); + expect(gitOk("cat-file", "-e", "main:m.test.ts")).toBe(false); + expect(git("diff", "--no-renames", "-z", "--name-only", "main...HEAD")).toContain("m.test.ts"); + const r = run(); + expect(r.status).toBe(1); + expect(r.stdout + r.stderr).toContain("m.test.ts"); + expect(r.stdout).not.toMatch(/"ok":\s*true/); +}); + +test("[REQ-UNSKIPCONTENT-2] a plainly absent path (new file: absent in base) is NOT a read error: exit 0 for a new skipped file", () => { + startPr(); + put("n.test.ts", SKIPPED); + git("add", "-A"); + commit("spec-like: new skipped test"); + const r = run(); + expect(r.status).toBe(0); + expect(JSON.parse(r.stdout).checked).toEqual(["n.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-2] a deleted file (absent in HEAD) is judged as a deletion, not reported as a read error", () => { + startPr(); + git("rm", "-q", "a.test.ts"); + commit("implement: delete"); + const r = run(); + expect(r.status).toBe(1); + const v = JSON.parse(r.stdout).violations; + expect(files(v)).toEqual(["a.test.ts"]); + expect(v[0].reason).toMatch(/delet|emptied|remov/i); +}); + +// ---------- REQ-5: managed-tests.json in base ---------- + +const MANAGED = ".devloop/managed-tests.json"; + +test("[REQ-UNSKIPCONTENT-5] base managed-tests.json is a symlink: exit 1 instead of trusting its target text or the worktree", () => { + // The link target is literally "[]" -> git show would yield the valid JSON text "[]" (manage nothing). + mkdirSync(join(repo, ".devloop"), { recursive: true }); + symlinkSync("[]", join(repo, MANAGED)); + git("add", "-A"); + commit("base: managed-tests.json as a symlink"); + expect(modeOf(MANAGED, "main")).toBe("120000"); + startPr(); + unlinkSync(join(repo, MANAGED)); + put(MANAGED, JSON.stringify(["nothing/**"]) + "\n"); // the PR's own narrow scope in the worktree + put("tools/x.test.ts", ACTIVE); + git("add", "-A"); + commit("implement: narrow own scope, add an active test"); + const r = run(); + expect(r.status).toBe(1); + expect(r.stdout + r.stderr).toContain("managed-tests.json"); + expect(r.stdout).not.toMatch(/"ok":\s*true/); +}); + +test("[REQ-UNSKIPCONTENT-5] base managed-tests.json blob unreadable: exit 1, no fallback to the PR's own worktree scope", () => { + put(MANAGED, JSON.stringify(["**/*.test.ts"]) + "\n"); + git("add", "-A"); + commit("base: manage every test"); + startPr(); + put(MANAGED, JSON.stringify(["nothing/**"]) + "\n"); + put("b.test.ts", ACTIVE); + git("add", "-A"); + commit("implement: widen own exemption, add an active test"); + rmSync(looseObject(`main:${MANAGED}`)); + expect(gitOk("cat-file", "-e", `main:${MANAGED}`)).toBe(false); + expect(git("diff", "--no-renames", "-z", "--name-only", "main...HEAD")).toContain("b.test.ts"); + const r = run(); + expect(r.status).toBe(1); + expect(r.stdout + r.stderr).toContain("managed-tests.json"); + expect(r.stdout).not.toMatch(/"ok":\s*true/); +}); + +test("[REQ-UNSKIPCONTENT-5] counter-probe: base WITHOUT managed-tests.json still falls back to the worktree scope (source worktree)", () => { + startPr(); + put(MANAGED, JSON.stringify(["services/**/*.test.ts"]) + "\n"); + put("tools/x.test.ts", ACTIVE); + git("add", "-A"); + commit("chore: adopt the scope"); + const r = run(); + expect(r.status).toBe(0); + const out = JSON.parse(r.stdout); + expect(out.managedSource).toBe("worktree"); + expect(out.unmanaged).toEqual(["tools/x.test.ts"]); +}); + +// ---------- REQ-4/6: spec branch ---------- + +test("[REQ-UNSKIPCONTENT-6] spec branch with big active file, symlink and gitlink is a no-op pass (exit 0)", () => { + git("checkout", "-q", "-b", "devloop/spec/x"); + put("big.test.ts", ACTIVE + PADDING); + put("test/helper.ts", ACTIVE); + symlinkSync("helper.ts", join(repo, "test/c.test.ts")); + git("add", "-A"); + git("update-index", "--add", "--cacheinfo", "160000,1234567890123456789012345678901234567890,test/x.test.ts"); + commit("spec PR: all constructions"); + const r = run("devloop/spec/x"); + expect(r.status).toBe(0); + const out = JSON.parse(r.stdout); + expect(out.ok).toBe(true); + expect(out.skipped).toMatch(/spec/i); +}); + +// ---------- REQ-7: paths the reader cannot resolve; pathspec-magic names; executable files ---------- + +const lsFiles = (): string[] => git("ls-files", "-z").split("\0").filter(Boolean); + +test("[REQ-UNSKIPCONTENT-7] new file ':(top)evil.test.ts' with an ACTIVE test (default scope) is a violation", () => { + startPr(); + put(":(top)evil.test.ts", ACTIVE); + git("add", "-A"); + commit("implement: pathspec-magic file name"); + expect(lsFiles()).toContain(":(top)evil.test.ts"); // committed literally, not interpreted + const r = run(); + expect(r.status).toBe(1); + const out = JSON.parse(r.stdout); + expect(out.ok).toBe(false); + expect(files(out.violations)).toEqual([":(top)evil.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-7] new file ':/evil.test.ts' (directory named ':') with an ACTIVE test is a violation", () => { + startPr(); + put(":/evil.test.ts", ACTIVE); + git("add", "-A"); + commit("implement: pathspec-magic via a directory named colon"); + expect(lsFiles()).toContain(":/evil.test.ts"); + const r = run(); + expect(r.status).toBe(1); + expect(files(JSON.parse(r.stdout).violations)).toEqual([":/evil.test.ts"]); +}); + +test("[REQ-UNSKIPCONTENT-7] diff reports a path the reader finds in no ref (non-UTF-8 file name, built by plumbing): exit 1 naming the path", () => { + startPr(); + // APFS refuses non-UTF-8 names in the worktree, so the entry is written straight into the index. + const oid = execFileSync("git", ["-C", repo, "hash-object", "-w", "--stdin"], { input: ACTIVE, encoding: "utf8" }).trim(); + const entry = Buffer.concat([Buffer.from(`100644 ${oid}\t`), Buffer.from("test/ev"), Buffer.from([0xff]), Buffer.from("il.test.ts\0")]); + execFileSync("git", ["-C", repo, "update-index", "--add", "-z", "--index-info"], { input: entry }); + commit("implement: non-UTF-8 test file name"); + // Preconditions: the raw diff reports the path with the 0xFF byte; the blob is a plain regular file. + const raw = execFileSync("git", ["-C", repo, "diff", "--no-renames", "-z", "--name-only", "main...HEAD"]); + expect(raw.includes(Buffer.from([0x65, 0x76, 0xff, 0x69, 0x6c]))).toBe(true); // "ev" 0xFF "il" + expect(git("ls-tree", "HEAD", "test/").length).toBeGreaterThan(0); + const r = run(); + expect(r.status).toBe(1); + const all = r.stdout + r.stderr; + expect(all).toContain("test/ev"); + expect(all).toContain("il.test.ts"); + expect(r.stdout).not.toMatch(/"ok":\s*true/); +}); + +test("[REQ-UNSKIPCONTENT-7] counter-probe: an executable (100755) managed test with only .skip removed passes and is checked", () => { + put("x.test.ts", SKIPPED); + chmodSync(join(repo, "x.test.ts"), 0o755); + git("add", "-A"); + commit("base: executable test"); + expect(modeOf("x.test.ts", "main")).toBe("100755"); + startPr(); + put("x.test.ts", SKIPPED.replaceAll("test.skip(", "test(")); + git("add", "-A"); + commit("implement: activate"); + expect(modeOf("x.test.ts")).toBe("100755"); + const r = run(); + expect(r.status).toBe(0); + const out = JSON.parse(r.stdout); + expect(out.violations).toEqual([]); + expect(out.checked).toEqual(["x.test.ts"]); +}); diff --git a/test/core/tree-entry.test.ts b/test/core/tree-entry.test.ts new file mode 100644 index 0000000..97a7aad --- /dev/null +++ b/test/core/tree-entry.test.ts @@ -0,0 +1,65 @@ +import { test, expect, beforeEach, afterEach } from "vitest"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { readTreeEntry, TreeEntryReadError } from "../../src/core/tree-entry.js"; + +let repo: string; +const git = (...a: string[]) => + execFileSync("git", ["-C", repo, ...a], { + encoding: "utf8", + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }); +const put = (rel: string, c: string) => { + mkdirSync(dirname(join(repo, rel)), { recursive: true }); + writeFileSync(join(repo, rel), c); +}; + +beforeEach(() => { + repo = mkdtempSync(join(tmpdir(), "devloop-treeentry-")); + git("init", "-q", "-b", "main"); + put("a.txt", "hello\n"); + put("dir/b.txt", "b"); + put("größe [x]*.txt", "odd"); + put("big.txt", "y".repeat(2 * 1024 * 1024)); + symlinkSync("a.txt", join(repo, "link")); + git("add", "-A"); + git("update-index", "--add", "--cacheinfo", "160000,1234567890123456789012345678901234567890,sub"); + git("-c", "commit.gpgsign=false", "commit", "-q", "-m", "x"); +}); +afterEach(() => rmSync(repo, { recursive: true, force: true })); + +test("regular file: full content, also above 1 MiB", () => { + expect(readTreeEntry(repo, "HEAD", "a.txt")).toEqual({ kind: "file", mode: "100644", content: "hello\n" }); + const big = readTreeEntry(repo, "HEAD", "big.txt"); + expect(big.kind === "file" && big.content.length).toBe(2 * 1024 * 1024); +}); + +test("symlink, submodule and directory are not read as files", () => { + expect(readTreeEntry(repo, "HEAD", "link")).toEqual({ kind: "symlink" }); + expect(readTreeEntry(repo, "HEAD", "sub")).toEqual({ kind: "submodule" }); + expect(readTreeEntry(repo, "HEAD", "dir")).toEqual({ kind: "other", type: "tree" }); +}); + +test("absent path is missing, not an error", () => { + expect(readTreeEntry(repo, "HEAD", "nope.txt")).toEqual({ kind: "missing" }); + expect(readTreeEntry(repo, "HEAD", "a.txt/inside")).toEqual({ kind: "missing" }); +}); + +test("special characters are literal, not pathspec magic", () => { + expect(readTreeEntry(repo, "HEAD", "größe [x]*.txt")).toMatchObject({ kind: "file", content: "odd" }); + expect(readTreeEntry(repo, "HEAD", "*.txt")).toEqual({ kind: "missing" }); +}); + +test("unresolvable ref and missing blob throw, naming path and ref", () => { + expect(() => readTreeEntry(repo, "gibtsnicht", "a.txt")).toThrow(TreeEntryReadError); + expect(() => readTreeEntry(repo, "gibtsnicht", "a.txt")).toThrow(/a\.txt @ gibtsnicht/); + const sha = git("rev-parse", "HEAD:a.txt").trim(); + rmSync(join(repo, ".git/objects", sha.slice(0, 2), sha.slice(2))); + expect(() => readTreeEntry(repo, "HEAD", "a.txt")).toThrow(/a\.txt @ HEAD/); +}); + +test("a pathspec that lists children (trailing slash) is not accepted as the entry of that path", () => { + expect(() => readTreeEntry(repo, "HEAD", "dir/")).toThrow(/exact path/); +});