// Publish a set of CLI output files together. Keep each old file until every new file is // in place. Temporary siblings let the final rename stay on the destination's filesystem. import { constants } from 'node:fs'; import { chmod, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; const WRITE_FAILURES = { EACCES: 'permission was denied', EPERM: 'permission was denied', EROFS: 'the disk is read-only', ENOSPC: 'the disk is full', EISDIR: 'a folder has that name', ENOTDIR: 'a folder in its path is a file', EEXIST: 'something of that name appeared while this ran', ENAMETOOLONG: 'the name is too long', ENOENT: 'this system cannot make that path (a name too long, a character it does not allow or a drive that is not there)', EINVAL: 'the name has a character this system does not allow', EBUSY: 'the file is in use by another program' }; export const writeFailure = error => WRITE_FAILURES[error.code] ?? error.code ?? error.message; const readEntry = file => lstat(file, { bigint: true }).catch(error => { if (error.code === 'ENOENT') return null; throw error; }); const same = (a, b) => a && b && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs; // Record newly created folders for writers that have to undo a whole group. export async function ensureOutputFolder(folder, folders) { // Record each successful mkdir, so even a failure halfway through a new path leaves no empty parents. const missing = []; for (let dir = folder; ; dir = path.dirname(dir)) { try { await stat(dir); break; } catch (error) { if (error.code !== 'ENOENT' || path.dirname(dir) === dir) throw error; missing.push(dir); } } for (const dir of missing.reverse()) { try { await mkdir(dir); folders.add(dir); } catch (error) { if (error.code !== 'EEXIST' || !(await stat(dir)).isDirectory()) throw error; } } } export async function removeEmptyOutputFolders(folders) { for (const dir of [...folders].sort((a, b) => b.length - a.length)) await rmdir(dir).catch(() => {}); } // Keep exclusive creation on volumes that do not support hard links. async function linkOrCopy(source, target) { try { await link(source, target); return true; } catch (error) { if (!['EPERM', 'EACCES', 'ENOTSUP', 'ENOSYS', 'EMLINK', 'EXDEV'].includes(error.code)) throw error; await copyFile(source, target, constants.COPYFILE_EXCL); return false; } } // Builds can finish independent groups even if another entry is refused. Keep those groups reversible until // their common lockfile is saved. A throwing publisher puts each earlier successful group back in reverse order. export async function withFileGroups(work) { const groups = []; try { return await work(groups); } catch (error) { const recovery = []; for (const group of groups.slice().reverse()) recovery.push(...await group.undo()); if (recovery.length) error.message += '. ' + recovery.join('. '); throw error; } finally { for (const group of groups.reverse()) await group.close(); } } export async function writeFileGroup(entries, force, groups) { const scratch = new Map(), folders = new Set(), staged = [], placed = [], retain = new Set(); let current; async function temporaryFolder(folder) { if (scratch.has(folder)) return scratch.get(folder); await ensureOutputFolder(folder, folders); const temp = await mkdtemp(path.join(folder, '.pixelbolt-')); scratch.set(folder, temp); return temp; } async function undo() { const recovery = []; for (const item of placed.reverse()) { try { const now = await readEntry(item.disk); if (item.written ? !same(item.written, now) : now !== null) throw new Error('the file changed again'); if (item.backup) await rename(item.backup, item.disk); else await rm(item.disk); } catch (undo) { if (item.backup) retain.add(path.dirname(item.backup)); recovery.push(`${item.file}: ${undo.message}${item.backup ? '. Original kept at ' + item.backup : ''}`); } } return recovery; } async function close() { for (const dir of scratch.values()) if (!retain.has(dir)) await rm(dir, { recursive: true, force: true }); // A successful write keeps its folders. Only empty folders created by this call can be removed. await removeEmptyOutputFolders(folders); } try { for (const entry of entries) { current = entry.file; const original = entry.previous ?? current, named = await readEntry(original); if (Object.hasOwn(entry, 'expected')) { const bytes = named ? await readFile(original) : null; if (entry.expected === null ? bytes !== null : !bytes?.equals(entry.expected)) { throw Object.assign(new Error('the file changed before delivery'), { code: 'ESTALE' }); } } if (entry.remove) { if (!named) continue; if (!named.isFile() && !named.isSymbolicLink()) throw new Error('expected a file to remove'); const folder = await temporaryFolder(path.dirname(original)); staged.push({ file: current, disk: original, before: named, backup: path.join(folder, staged.length + '.old'), remove: true }); continue; } const replaceLink = entry.replaceLink && named?.isSymbolicLink(); const disk = named?.isSymbolicLink() && !replaceLink ? await realpath(original) : original; const before = disk === original ? named : await readEntry(disk); if (before) { if (!force) throw Object.assign(new Error('output already exists'), { code: 'EEXIST' }); if (!before.isFile() && !replaceLink) throw Object.assign(new Error('expected a regular output file'), { code: 'EISDIR' }); // Renaming into a writable folder could bypass the read-only attribute of the file itself. if (!replaceLink) await (await open(disk, constants.O_WRONLY)).close(); } const folder = await temporaryFolder(path.dirname(disk)); const temp = path.join(folder, String(staged.length)), backup = before && temp + '.old'; const bytes = typeof entry.data === 'function' ? await entry.data() : entry.data; await writeFile(temp, bytes, { flag: 'wx' }); if (before && !replaceLink) await chmod(temp, Number(before.mode & 0o777n)); staged.push({ file: current, disk, temp, backup, before, replaceEntry: replaceLink || (original !== current && !named?.isSymbolicLink()) }); } for (const item of staged) { current = item.file; if (item.before && !same(item.before, await readEntry(item.disk))) throw new Error('the output changed while preparing the files'); // Move a removed entry, an old spelling or a link being replaced aside under its original identity. if (item.remove || item.replaceEntry) { await rename(item.disk, item.backup); placed.push({ disk: item.disk, file: item.file, backup: item.backup, written: null }); if (item.remove) continue; } const disk = item.replaceEntry ? item.file : item.disk; let written = await stat(item.temp, { bigint: true }); if (item.before && !item.replaceEntry) { await linkOrCopy(disk, item.backup); await rename(item.temp, disk); } else if (!await linkOrCopy(item.temp, disk)) { written = await stat(disk, { bigint: true }); } placed.push({ disk, file: item.file, backup: item.replaceEntry ? null : item.backup, written }); } } catch (error) { const recovery = await undo(); await close(); throw Object.assign(error, { output: current, recovery }); } if (groups) groups.push({ undo, close }); else await close(); }