import { readFile } from 'node:fs/promises' import path from 'node:path' import { fileURLToPath } from 'node:url' import test from 'brittle' import b4a from 'b4a' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor async function loadMvBin() { const runtime = await readFile( path.join(__dirname, '../lib/runtime.js'), 'utf8' ) const body = await readFile(path.join(__dirname, '../src/mv.js'), 'utf8') return new AsyncFunction( 'ctx', 'argv', `${runtime}\n${body}\nif (typeof run === 'function') return await run(ctx, argv)\n` ) } test('/bin/mv cross-drive failure injection preserves source and exits non-zero', async (t) => { const run = await loadMvBin() const errors = [] let sourceRemoved = false const writes = [] const ctx = { b4a, exitCode: 0, console: { log() {}, error(msg) { errors.push(String(msg)) } }, vfs: { resolveLogical(p) { return String(p) }, async lstat(p) { if (p === '/mnt/a/file.txt') return { type: 'file' } return null }, async stat() { return null }, async readFile(p) { if (p === '/mnt/a/file.txt') return b4a.from('payload') return null }, async writeFile(p, buf) { writes.push([String(p), b4a.toString(buf)]) if (String(p).startsWith('/mnt/b/')) { const e = new Error('EXDEV: cross-device link not permitted') e.code = 'EXDEV' throw e } }, async unlink() {}, async rm(p) { if (p === '/mnt/a/file.txt') sourceRemoved = true }, async readdir() { return [] }, async mkdir() {} } } await run(ctx, ['mv', '/mnt/a/file.txt', '/mnt/b/file.txt']) t.is(ctx.exitCode, 1) t.absent(sourceRemoved, 'source should remain when cross-drive write fails') t.ok(errors.some((m) => m.includes('EXDEV'))) t.ok( writes.some((w) => w[0].startsWith('/mnt/b/.bare-os-mv-tmp.')), 'staging write attempted on destination drive' ) })