histoire
Version:
A fast story book powered by Vite
53 lines (52 loc) • 2.25 kB
JavaScript
import { Buffer } from 'node:buffer';
import { readFile, rm, stat, writeFile } from 'node:fs/promises';
import path from 'pathe';
import { guardProjectPath } from '../../config/codemod/security.js';
import { findWorkspaceRoot, lockfiles } from '../changes/package-manager.js';
/** Captures every supported lock name, including absent locks created on failure. */
export async function snapshotProject(root) {
const boundary = await findWorkspaceRoot(root);
const files = [];
let bytes = 0;
for (let directory = path.resolve(root);; directory = path.dirname(directory)) {
for (const name of ['package.json', ...lockfiles]) {
const file = await guardProjectPath(path.join(directory, name), boundary);
try {
const info = await stat(file);
if (!info.isFile())
throw new Error('Package manifest or lockfile is not a regular file');
bytes += info.size;
if (bytes > 10 * 1024 * 1024)
throw new Error('Package snapshots exceed safe receipt capacity. Run the change manually.');
files.push({ file, bytes: (await readFile(file)).toString('base64'), mode: info.mode });
}
catch (error) {
if (error.code !== 'ENOENT')
throw error;
files.push({ file, bytes: null });
}
}
if (directory === boundary)
break;
}
return { root: boundary, files };
}
/** Restores exact bytes; returns destinations that could not safely be restored. */
export async function restoreProject(snapshot) {
const leftovers = [];
for (const entry of snapshot.files) {
try {
const file = await guardProjectPath(entry.file, snapshot.root);
if (file !== entry.file)
throw new Error('Package path changed');
if (entry.bytes === null)
await rm(file, { force: true });
else
await writeFile(file, Buffer.from(entry.bytes, 'base64'), { mode: entry.mode });
}
catch {
leftovers.push(path.relative(snapshot.root, entry.file));
}
}
return leftovers;
}