aboutsummaryrefslogtreecommitdiff
path: root/src/shared/command.js
diff options
context:
space:
mode:
authorLily <[email protected]>2026-07-28 16:12:21 +1000
committerGitHub <[email protected]>2026-07-28 16:12:21 +1000
commitc11e17573334dfb487a8e1cc25fa84fa9e138f5c (patch)
treee91dbd19b524f9432da6bcb86b1fc193e0d02e26 /src/shared/command.js
parent6a2f098e72e71437154ec00506e8e736aa8e1026 (diff)
downloadbnu-c11e17573334dfb487a8e1cc25fa84fa9e138f5c.tar.gz
bnu-c11e17573334dfb487a8e1cc25fa84fa9e138f5c.zip
Refactor coreutils into single-call command modules (#1)
* Refactor to single call
Diffstat (limited to 'src/shared/command.js')
-rw-r--r--src/shared/command.js28
1 files changed, 28 insertions, 0 deletions
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;
+}