feat(generators): byte-identical snapshot machinery + realtime snapshot
This commit is contained in:
19
turbo/generators/lib/snapshot.test.ts
Normal file
19
turbo/generators/lib/snapshot.test.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { computeSnapshot } from "./snapshot";
|
||||
|
||||
describe("computeSnapshot", () => {
|
||||
it("returns sorted file paths + sha256 hashes", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "snapshot-"));
|
||||
mkdirSync(join(tmp, "src"));
|
||||
writeFileSync(join(tmp, "package.json"), `{ "name": "x" }\n`);
|
||||
writeFileSync(join(tmp, "src", "index.ts"), `export {};\n`);
|
||||
const snap = computeSnapshot(tmp);
|
||||
expect(snap).toEqual([
|
||||
{ path: "package.json", sha256: expect.any(String) },
|
||||
{ path: "src/index.ts", sha256: expect.any(String) },
|
||||
]);
|
||||
});
|
||||
});
|
||||
33
turbo/generators/lib/snapshot.ts
Normal file
33
turbo/generators/lib/snapshot.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join, relative } from "node:path";
|
||||
|
||||
export type SnapshotEntry = { path: string; sha256: string };
|
||||
|
||||
/**
|
||||
* Recursively collect all files under root, sorted by relative path, with
|
||||
* sha256 of post-normalized contents (LF line endings, single trailing
|
||||
* newline). Used by the byte-identical reconstruction test.
|
||||
*/
|
||||
export function computeSnapshot(root: string): SnapshotEntry[] {
|
||||
const out: SnapshotEntry[] = [];
|
||||
walk(root, root, out);
|
||||
out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
||||
return out;
|
||||
}
|
||||
|
||||
function walk(root: string, dir: string, out: SnapshotEntry[]): void {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const full = join(dir, name);
|
||||
const stat = statSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
if (name === "node_modules" || name === ".turbo") continue;
|
||||
walk(root, full, out);
|
||||
} else if (stat.isFile()) {
|
||||
const raw = readFileSync(full, "utf8");
|
||||
const normalized = raw.replace(/\r\n/g, "\n").replace(/\n*$/, "\n");
|
||||
const sha = createHash("sha256").update(normalized).digest("hex");
|
||||
out.push({ path: relative(root, full).replace(/\\/g, "/"), sha256: sha });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user