@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
76 lines • 3.03 kB
JavaScript
import { constants } from "node:fs";
import { copyFile, link } from "node:fs/promises";
function errorCode(error) {
return error instanceof Error && "code" in error ? error.code : undefined;
}
const FILE_OPERATIONS = { copyFile, link };
/** Clones go through the filesystem's metadata path, which stops scaling past a few in flight. */
const COPY_CONCURRENCY = 8;
function nextCopyMode(mode, error, platform) {
const code = errorCode(error);
// A missing source or an occupied target is about this file, not about what the filesystem can do.
if (code === "ENOENT" || code === "ENOTDIR" || code === "EEXIST")
return undefined;
switch (mode) {
case "clone":
// Node on macOS cannot force a clone (ENOSYS), but its plain clone request clones on APFS
// and copies elsewhere, which is exactly the order wanted without ever sharing an inode.
return platform === "darwin" && code === "ENOSYS" ? "clone-or-copy" : "link";
case "link":
return "copy";
case "clone-or-copy":
case "copy":
return undefined;
}
}
/**
* A file copier that starts with the cheapest independent copy and settles on the first mode the
* filesystem accepts, so a snapshot of thousands of files pays for a refused mode once.
*/
export function createSnapshotFileCopier(platform = process.platform, operations = FILE_OPERATIONS) {
let mode = "clone";
const attempt = (current, source, target) => {
switch (current) {
case "clone":
return operations.copyFile(source, target, constants.COPYFILE_FICLONE_FORCE);
case "clone-or-copy":
return operations.copyFile(source, target, constants.COPYFILE_FICLONE);
case "link":
return operations.link(source, target);
case "copy":
return operations.copyFile(source, target, 0);
}
};
return {
get mode() {
return mode;
},
async copy(source, target) {
for (let current = mode;;) {
try {
await attempt(current, source, target);
return;
}
catch (error) {
const next = nextCopyMode(current, error, platform);
if (next === undefined)
throw error;
current = next;
mode = next;
}
}
},
};
}
export async function copyFiles(pairs, copier) {
let next = 0;
const worker = async () => {
for (let index = next++; index < pairs.length; index = next++) {
const [source, target] = pairs[index] ?? [];
if (source !== undefined && target !== undefined)
await copier.copy(source, target);
}
};
await Promise.all(Array.from({ length: Math.min(COPY_CONCURRENCY, pairs.length) }, worker));
}
//# sourceMappingURL=file-copier.js.map