core utils updates

This commit is contained in:
Raven Scott
2026-04-03 22:34:08 -04:00
parent 32d3eaa833
commit 35ac6633ea
206 changed files with 12728 additions and 1080 deletions
+68 -2
View File
@@ -60,10 +60,38 @@ function barePosixBlocks(size) {
return Math.ceil(Number(size) / 512) || 0
}
/**
* Raw stdout for NUL/binary when **`process.stdout.write`** is missing.
* If **`ctx.bareOsBinWrite(Uint8Array|string)`** is set (tests / host), use it.
* @param {Record<string, unknown>} ctx
* @param {string | Uint8Array} chunk
* @returns {boolean}
*/
function bareOsEmitRaw(ctx, chunk) {
if (typeof ctx.bareOsBinWrite === 'function') {
const b4 = ctx.b4a
const u8 =
typeof chunk === 'string'
? b4 && typeof b4.from === 'function'
? b4.from(chunk)
: new TextEncoder().encode(chunk)
: chunk
ctx.bareOsBinWrite(u8 instanceof Uint8Array ? u8 : new Uint8Array(u8))
return true
}
const w = globalThis.process?.stdout?.write
if (typeof w === 'function') {
w.call(globalThis.process.stdout, chunk)
return true
}
return false
}
/**
* Bounded xargs for Bare OS: invokes ctx.runBinCommand only (no host spawn).
* Limits: stdin 256KiB, 4096 whitespace/null tokens, 128 args per invocation,
* 64 invocations per run. Exceeding limits is a fatal error (exit 125).
* Supports -0/--null, -n, -I repl (replace repl in utility argv; implies -n 1 unless -n given).
*/
const MAX_STDIN = 256 * 1024
@@ -82,6 +110,9 @@ async function run(ctx, argv) {
const args = argv.slice(1)
let nullSep = false
let maxBatch = MAX_PER_INVOCATION
/** @type {string | null} */
let repl = null
let nExplicit = false
let i = 0
while (i < args.length && args[i].startsWith('-')) {
@@ -103,20 +134,38 @@ async function run(ctx, argv) {
return
}
maxBatch = Math.min(Number(n), MAX_PER_INVOCATION)
nExplicit = true
i += 2
continue
}
if (a.startsWith('-n') && a.length > 2 && /^\d+$/.test(a.slice(2))) {
const n = Number(a.slice(2))
maxBatch = Math.min(n, MAX_PER_INVOCATION)
nExplicit = true
i++
continue
}
if (a === '-I' || a === '-i') {
repl = args[i + 1] != null ? String(args[i + 1]) : '{}'
i += 2
if (!nExplicit) maxBatch = 1
continue
}
if (
(a.startsWith('-I') || a.startsWith('-i')) &&
a.length > 2 &&
a[2] !== '-'
) {
repl = a.slice(2) || '{}'
i++
if (!nExplicit) maxBatch = 1
continue
}
ctx.console.error('xargs: unsupported option: ' + a)
ctx.console.error(
'xargs: Bare OS supports: -0/--null, -n N (max ' +
MAX_PER_INVOCATION +
' per run)'
' per run), -I repl'
)
ctx.exitCode = 1
return
@@ -151,8 +200,25 @@ async function run(ctx, argv) {
return
}
/**
* @param {string[]} batch
*/
const runOne = async (batch) => {
await ctx.runBinCommand(cmd.concat(batch))
const subst = batch.join(' ')
/** @type {string[]} */
const toRun =
repl == null
? cmd.concat(batch)
: cmd.map((c) => {
let o = c
let guard = 0
while (o.includes(repl) && guard < 4096) {
o = o.split(repl).join(subst)
guard++
}
return o
})
await ctx.runBinCommand(toRun)
}
if (pieces.length === 0) {