/** * Golden-style checks for high-traffic XCU utilities (bounded POSIX Issue 7 alignment). */ 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 /** * @param {string} name */ async function loadBin(name) { const runtime = await readFile( path.join(__dirname, '../lib/runtime.js'), 'utf8' ) const bodyRaw = await readFile( path.join(__dirname, `../src/${name}.js`), 'utf8' ) const body = bodyRaw.replace(/^export\s+\{[^}]*\}\s*;?\s*$/gm, '') return new AsyncFunction( 'ctx', 'argv', `${runtime}\n${body}\nif (typeof run === 'function') return await run(ctx, argv)\n` ) } function createCtx() { const logs = [] return { b4a, exitCode: 0, vfs: { async stat() { return null } }, console: { log: (m) => logs.push(String(m)), error: (m) => logs.push(String(m)) }, _logs: logs } } test('/bin/test: string equality and unary -z', async (t) => { const run = await loadBin('test') const c1 = createCtx() await run(c1, ['test', 'ab', '=', 'ab']) t.is(c1.exitCode, 0) const c2 = createCtx() await run(c2, ['test', 'ab', '!=', 'cd']) t.is(c2.exitCode, 0) const c3 = createCtx() await run(c3, ['test', '-z', '']) t.is(c3.exitCode, 0) }) test('/bin/expr: integer arithmetic and comparison', async (t) => { const run = await loadBin('expr') const c = createCtx() await run(c, ['expr', '3', '+', '4']) t.is(c.exitCode, 0) t.is(c._logs.join('\n'), '7') const c2 = createCtx() await run(c2, ['expr', '5', '>', '2']) t.is(c2.exitCode, 0) t.is(c2._logs.join('\n'), '1') }) test('/bin/printf: %d and literal percent', async (t) => { const run = await loadBin('printf') const c = createCtx() await run(c, ['printf', '%d%%\n', '42']) t.is(c.exitCode, 0) t.is(c._logs.join(''), '42%\n') }) test('/bin/printf: zero-pad negative int, %x %X %u %o %c', async (t) => { const run = await loadBin('printf') const c1 = createCtx() await run(c1, ['printf', '%05d', '-3']) t.is(c1.exitCode, 0) t.is(c1._logs.join(''), '-0003') const c2 = createCtx() await run(c2, ['printf', '%08x', '255']) t.is(c2._logs.join(''), '000000ff') const c3 = createCtx() await run(c3, ['printf', '%4X', '65535']) t.is(c3._logs.join(''), 'FFFF') const c4 = createCtx() await run(c4, ['printf', '%u', '-1']) t.is(c4._logs.join(''), '4294967295') const c5 = createCtx() await run(c5, ['printf', '%o', '8']) t.is(c5._logs.join(''), '10') const c6 = createCtx() await run(c6, ['printf', '%c', 'A']) t.is(c6._logs.join(''), 'A') }) test('/bin/printf: %b backslash escapes', async (t) => { const run = await loadBin('printf') const c = createCtx() await run(c, ['printf', '%b', 'a\\tb']) t.is(c.exitCode, 0) t.is(c._logs.join(''), 'a\tb') })