import { randomUUID } from "node:crypto"; import { promises as fs } from "node:fs"; import path from "node:path"; const writesInProgress = new Set(); interface StackFile { path: string; content: string; mode: number; } interface PreparedFile { target: string; next: string; backup?: string; preserveBackup: boolean; } /** Replace the pair only after staging both files, and restore committed files on failure. */ export async function saveStackFiles(files: StackFile[], owner?: { uid: number; gid: number }, beforeCommit?: () => void): Promise { const prepared: PreparedFile[] = []; const committed: PreparedFile[] = []; const lockedPaths: string[] = []; try { for (const file of files) { const link = await fs.lstat(file.path).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") { throw error; } return undefined; }); const target = link?.isSymbolicLink() ? await fs.realpath(file.path) : file.path; if (prepared.some(item => path.resolve(item.target) === path.resolve(target))) { throw new Error("editorFileConflict"); } const resolved = path.resolve(target); const key = process.platform === "win32" ? resolved.toLowerCase() : resolved; if (writesInProgress.has(key)) { throw new Error("Another operation is already running, please try again later."); } writesInProgress.add(key); lockedPaths.push(key); const stat = link ? await fs.stat(target) : undefined; if (stat && !stat.isFile()) { throw new Error("editorFileNotRegular"); } const item: PreparedFile = { target, next: target + ".dockge-" + randomUUID() + ".tmp", preserveBackup: false, }; prepared.push(item); const mode = stat ? stat.mode & 0o777 : file.mode; await fs.writeFile(item.next, file.content, { flag: "wx", mode, }); if (stat) { item.backup = target + ".dockge-" + randomUUID() + ".bak"; await fs.copyFile(target, item.backup); await fs.chmod(item.backup, mode); } const fileOwner = owner ?? stat; if (process.platform !== "win32" && fileOwner) { await fs.chown(item.next, fileOwner.uid, fileOwner.gid); if (item.backup && stat) { await fs.chown(item.backup, stat.uid, stat.gid); } } } beforeCommit?.(); try { for (const item of prepared) { await fs.rename(item.next, item.target); committed.push(item); } } catch (error) { let recoveryFailed = false; for (const item of committed.reverse()) { try { if (item.backup) { await fs.rename(item.backup, item.target); } else { await fs.unlink(item.target); } } catch { item.preserveBackup = true; recoveryFailed = true; } } if (recoveryFailed) { throw new Error("editorSaveRecoveryFailed"); } throw error; } } finally { for (const item of prepared) { await fs.rm(item.next, { force: true }).catch(() => {}); if (item.backup && !item.preserveBackup) { await fs.rm(item.backup, { force: true }).catch(() => {}); } } for (const key of lockedPaths) { writesInProgress.delete(key); } } }