From c11e17573334dfb487a8e1cc25fa84fa9e138f5c Mon Sep 17 00:00:00 2001 From: Lily <129828376+Soccera1@users.noreply.github.com> Date: Tue, 28 Jul 2026 16:12:21 +1000 Subject: Refactor coreutils into single-call command modules (#1) * Refactor to single call --- src/shared/command.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/shared/command.js (limited to 'src/shared/command.js') diff --git a/src/shared/command.js b/src/shared/command.js new file mode 100644 index 0000000..0d7666d --- /dev/null +++ b/src/shared/command.js @@ -0,0 +1,28 @@ +import { readFileSync } from "node:fs"; +import { executeCommand } from "./runtime.js"; +import { hasCommand } from "./catalog.js"; + +export function defineCommand(name, implementation, metaOption) { + if (!hasCommand(name)) throw new Error(`Unknown BNU command: ${name}`); + return (args) => executeCommand(name, implementation, metaOption, args); +} + +export async function runAsMain(command, args = singleCallArgs()) { + globalThis[Symbol.for("bnu.cli")] = true; + process.exit(await command(args)); +} + +// Bun consumes a leading `--` between the script name and its arguments. GNU +// utilities need to see that separator because it changes option parsing. +function singleCallArgs() { + const args = Bun.argv.slice(2); + try { + const parts = readFileSync("/proc/self/cmdline").subarray(0, -1).toString("binary").split("\0"); + let scriptIndex = parts.indexOf(Bun.argv[1]); + if (scriptIndex === -1 && parts.length > 1) scriptIndex = 1; + if (parts[scriptIndex + 1] === "--" && args[0] !== "--") return ["--", ...args]; + } catch { + // Non-Linux platforms retain Bun's decoded argument list. + } + return args; +} -- cgit v1.3