/* BARE_OS_BIN_API 1.0.0 — bump when staged /bin script semantics change (see developer guide). */ /** Shared helpers for drive-resident /bin scripts (prepended before each command). */ function bareStdin(ctx) { return typeof ctx.shellStdin === 'string' ? ctx.shellStdin : '' } /** @param {number} mode @param {'file' | 'directory' | 'symlink'} type */ function bareFormatModeString(mode, type) { const typeChar = type === 'directory' ? 'd' : type === 'symlink' ? 'l' : '-' const perm = mode & 0o777 const r = (bit) => (perm & bit ? 'r' : '-') const w = (bit) => (perm & bit ? 'w' : '-') const x = (bit) => (perm & bit ? 'x' : '-') return ( typeChar + r(0o400) + w(0o200) + x(0o100) + r(0o040) + w(0o020) + x(0o010) + r(0o004) + w(0o002) + x(0o001) ) } /** @param {number} mtimeMs @param {number} [nowMs] */ function bareFormatLsMtime(mtimeMs, nowMs) { const now = nowMs != null ? nowMs : Date.now() const d = new Date(mtimeMs) const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] const mon = months[d.getMonth()] const day = String(d.getDate()).padStart(2, ' ') const sixMo = 180 * 24 * 3600 * 1000 if (Math.abs(now - mtimeMs) > sixMo) { const yr = String(d.getFullYear()).padStart(4, ' ') return mon + ' ' + day + ' ' + yr } const hh = String(d.getHours()).padStart(2, '0') const mm = String(d.getMinutes()).padStart(2, '0') return mon + ' ' + day + ' ' + hh + ':' + mm } /** @param {number} size */ 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} 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 } /** Session env map (`vfs.env`, then `ctx.env`). Never throws. */ function bareOsEnv(ctx) { const v = ctx && ctx.vfs && ctx.vfs.env if (v && typeof v === 'object') return v const e = ctx && ctx.env if (e && typeof e === 'object') return e return {} } /** * Strict POSIX-ish decimal integer (no octal, no exponent, no empty). * @param {unknown} s * @returns {number} */ function bareOsParseDecInt(s) { const t = String(s == null ? '' : s).trim() if (!/^[+-]?(?:0|[1-9][0-9]*)$/.test(t)) return NaN const n = Number.parseInt(t, 10) return Number.isSafeInteger(n) ? n : NaN } /** @param {unknown} s */ function bareOsParseNonNegInt(s) { const n = bareOsParseDecInt(s) return n >= 0 ? n : NaN } /** * @param {Record} ctx * @param {string} name * @param {number} fallback * @param {number} [min] * @param {number} [max] */ function bareOsEnvInt(ctx, name, fallback, min, max) { const raw = bareOsEnv(ctx)[name] if (raw == null || raw === '') return fallback const n = Number.parseInt(String(raw), 10) if (!Number.isFinite(n)) return fallback let v = n if (min != null && v < min) v = min if (max != null && v > max) v = max return v } /** * @param {Record} ctx * @param {string} msg * @param {number} [code] */ function bareOsFail(ctx, msg, code) { if (msg) ctx.console.error(msg) ctx.exitCode = code == null ? 1 : code } /** @param {unknown} e */ function bareOsIsNotFoundErr(e) { const code = e && typeof e === 'object' ? e.code : '' if (code === 'ENOENT') return true const msg = String((e && e.message) || e || '') return /ENOENT|No such file|not found/i.test(msg) } /** * @param {Record} ctx * @param {unknown} buf * @returns {Uint8Array} */ function bareOsToU8(ctx, buf) { if (!buf) return new Uint8Array(0) if (buf instanceof Uint8Array) return buf if (ctx && ctx.b4a && typeof ctx.b4a.from === 'function') return ctx.b4a.from(buf) return new Uint8Array(buf) } /** @param {string} dir @param {string} name */ function bareOsJoinPath(dir, name) { const d = String(dir || '').replace(/\/+$/, '') const n = String(name || '').replace(/^\/+/, '') if (!d || d === '/') return '/' + n return d + '/' + n } /** @param {string} p */ function bareOsBaseName(p) { const t = String(p || '').replace(/\/+$/, '') if (!t || t === '/') return t === '/' ? '/' : '' const i = t.lastIndexOf('/') return i < 0 ? t : t.slice(i + 1) || t } /** @param {string} p */ function bareOsParentDir(p) { const t = String(p || '').replace(/\/+$/, '') || '/' if (t === '/') return '/' const i = t.lastIndexOf('/') return i <= 0 ? '/' : t.slice(0, i) || '/' } /** @param {string} p */ function bareOsNormPath(p) { return String(p || '').replace(/\/+$/, '') || '/' } /** * @param {Record} ctx * @param {string} p */ function bareOsResolvePath(ctx, p) { if (ctx && ctx.vfs && typeof ctx.vfs.resolveLogical === 'function') { try { return String(ctx.vfs.resolveLogical(p) || p) } catch { /* fall through */ } } return String(p || '') } /** * True when dest is src or lives under src (self-copy / self-move). * @param {Record} ctx * @param {string} src * @param {string} dest */ function bareOsDestInsideSrc(ctx, src, dest) { const s = bareOsNormPath(bareOsResolvePath(ctx, src)) const d = bareOsNormPath(bareOsResolvePath(ctx, dest)) if (s === d) return true if (s === '/') return d !== '/' return d === s || d.startsWith(s + '/') } const BARE_OS_B64_ALPH = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' /** @param {Uint8Array} u8 */ function bareOsB64Encode(u8) { let out = '' let i = 0 for (; i + 2 < u8.length; i += 3) { const n = (u8[i] << 16) | (u8[i + 1] << 8) | u8[i + 2] out += BARE_OS_B64_ALPH[(n >> 18) & 63] + BARE_OS_B64_ALPH[(n >> 12) & 63] + BARE_OS_B64_ALPH[(n >> 6) & 63] + BARE_OS_B64_ALPH[n & 63] } const rest = u8.length - i if (rest === 1) { const n = u8[i] << 16 out += BARE_OS_B64_ALPH[(n >> 18) & 63] + BARE_OS_B64_ALPH[(n >> 12) & 63] + '==' } else if (rest === 2) { const n = (u8[i] << 16) | (u8[i + 1] << 8) out += BARE_OS_B64_ALPH[(n >> 18) & 63] + BARE_OS_B64_ALPH[(n >> 12) & 63] + BARE_OS_B64_ALPH[(n >> 6) & 63] + '=' } return out } /** * RFC 4648 Base64 decode (also accepts URL-safe alphabet). Rejects junk. * @param {string} s * @returns {Uint8Array} */ function bareOsB64Decode(s) { const t = String(s).replace(/\s+/g, '') if (!t) return new Uint8Array(0) if (t.length % 4 === 1) throw new Error('invalid base64 length') let pad = 0 if (t.endsWith('==')) pad = 2 else if (t.endsWith('=')) pad = 1 const body = pad ? t.slice(0, t.length - pad) : t const bytes = [] let buf = 0 let bits = 0 for (let i = 0; i < body.length; i++) { const c = body[i] let v = BARE_OS_B64_ALPH.indexOf(c) if (v < 0) { if (c === '-') v = 62 else if (c === '_') v = 63 else throw new Error('invalid base64 character') } buf = (buf << 6) | v bits += 6 if (bits >= 8) { bits -= 8 bytes.push((buf >> bits) & 255) } } if (pad) { const want = Math.floor((body.length * 6) / 8) if (bytes.length > want) bytes.length = want } return new Uint8Array(bytes) } /** * @param {string} s * @returns {Uint8Array} */ function bareOsHexDecode(s) { const t = String(s).replace(/\s+/g, '') if (t.length % 2 !== 0) throw new Error('odd hex length') const out = new Uint8Array(t.length / 2) for (let i = 0; i < out.length; i++) { const pair = t.slice(i * 2, i * 2 + 2) if (!/^[0-9a-fA-F]{2}$/.test(pair)) throw new Error('invalid hex') out[i] = Number.parseInt(pair, 16) } return out } /** @param {Uint8Array} u8 */ function bareOsHexEncode(u8) { let s = '' for (let i = 0; i < u8.length; i++) s += u8[i].toString(16).padStart(2, '0') return s } /** * tail — last lines/bytes of files; -f/--follow with vfs.watch or poll. * Test/limit: BARE_OS_TAIL_F_POLL_MS, BARE_OS_TAIL_F_MAX_ROUNDS (empty = unlimited). */ function bareTailSleep(ms) { return new Promise((r) => setTimeout(r, ms)) } function bareTailEnv(ctx) { return (ctx.vfs && ctx.vfs.env) || ctx.env || {} } function bareTailPollMs(env) { const n = Number.parseInt(String(env.BARE_OS_TAIL_F_POLL_MS || '1000'), 10) return Number.isFinite(n) && n >= 0 ? n : 1000 } function bareTailMaxRounds(env) { const raw = env.BARE_OS_TAIL_F_MAX_ROUNDS if (raw == null || raw === '') return Number.POSITIVE_INFINITY const n = Number.parseInt(String(raw), 10) return Number.isFinite(n) && n >= 0 ? n : Number.POSITIVE_INFINITY } function bareTailUseWatch(ctx, vfs) { if (typeof vfs.watch !== 'function') return false const caps = ctx.bareOsRuntimeCaps if (caps && caps.features && caps.features.vfsWatch === false) return false return true } /** @param {string} s */ function bareTailSplitLines(s) { const lines = s.split('\n') if (s.endsWith('\n') && lines.length && lines[lines.length - 1] === '') lines.pop() return lines } /** * @param {Uint8Array} u8 * @param {'end' | 'start'} which * @param {number} n count or 1-based start (+ mode) */ function bareTailBytesSlice(u8, which, n, fromPlus) { if (!u8 || !u8.byteLength) return new Uint8Array(0) if (which === 'end') { if (n <= 0) return new Uint8Array(0) const start = Math.max(0, u8.byteLength - n) return u8.subarray(start) } /* from start (+): GNU tail -c +K starts at byte K (1-based) */ const idx = fromPlus ? Math.max(0, n - 1) : 0 return idx >= u8.byteLength ? new Uint8Array(0) : u8.subarray(idx) } /** * @param {string} s * @param {'end' | 'start'} which * @param {number} n * @param {boolean} fromPlus * @param {*} b4a */ function bareTailLinesText(s, which, n, fromPlus, b4a) { const lines = bareTailSplitLines(s) if (which === 'end') { if (n <= 0) return '' const slice = lines.length <= n ? lines : lines.slice(-n) return slice.join('\n') } /* +N: from line N (1-based) */ const start = fromPlus ? Math.max(0, n - 1) : 0 const slice = lines.slice(start) return slice.join('\n') } /** * Emit follow chunks as full lines via console.log (tests capture log). * @param {string} chunk * @param {{ partial: string }} state */ function bareTailFollowEmit(ctx, chunk, state) { const combined = state.partial + chunk const lines = combined.split('\n') state.partial = lines.pop() || '' for (const ln of lines) ctx.console.log(ln) } function bareTailFollowFlush(ctx, state) { if (state.partial !== '') { ctx.console.log(state.partial) state.partial = '' } } /** * @param {*} ctx * @param {string} path * @param {*} vfs * @param {number} startOffset byte offset after initial read (next byte to emit) */ async function bareTailFollow(ctx, path, vfs, startOffset) { const env = bareTailEnv(ctx) const pollMs = bareTailPollMs(env) const maxRounds = bareTailMaxRounds(env) const state = { partial: '' } let offset = startOffset let rounds = 0 const pumpOnce = async () => { const buf = await vfs.readFile(path) if (!buf) { offset = 0 return } const u8 = buf instanceof Uint8Array ? buf : ctx.b4a.from(buf) if (u8.byteLength < offset) { offset = 0 } if (u8.byteLength > offset) { const piece = u8.subarray(offset) offset = u8.byteLength bareTailFollowEmit(ctx, ctx.b4a.toString(piece), state) } } if ( bareTailUseWatch(ctx, vfs) && maxRounds === Number.POSITIVE_INFINITY ) { let handle = null try { handle = await vfs.watch(path) } catch { handle = null } if (handle && handle.watcher) { try { for await (const _ of handle.watcher) { await pumpOnce() } } finally { if (typeof handle.destroy === 'function') handle.destroy() } bareTailFollowFlush(ctx, state) return } } while (rounds < maxRounds) { await bareTailSleep(pollMs) await pumpOnce() rounds++ } bareTailFollowFlush(ctx, state) } async function run(ctx, argv) { const vfs = ctx.vfs let follow = false /** @type {'lines' | 'bytes'} */ let mode = 'lines' let count = 10 let fromPlus = false let i = 1 while (i < argv.length) { const a = argv[i] if (a === '--') { i++ break } if (a === '-f' || a === '--follow') { follow = true i++ continue } if (a === '-F') { follow = true i++ continue } if (a === '-n' || a === '--lines') { const v = argv[i + 1] if (v == null) { ctx.console.error('tail: option requires an argument -- n') ctx.exitCode = 1 return } i++ mode = 'lines' if (v.startsWith('+')) { fromPlus = true count = bareOsParseNonNegInt(v.slice(1)) if (!Number.isFinite(count) || count < 1) count = 1 } else { fromPlus = false count = bareOsParseNonNegInt(v.startsWith('-') ? v.slice(1) : v) if (!Number.isFinite(count)) { ctx.console.error('tail: invalid number of lines: ' + v) ctx.exitCode = 1 return } } i++ continue } if (a.startsWith('-n') && a.length > 2) { const v = a.slice(2) mode = 'lines' if (v.startsWith('+')) { fromPlus = true count = bareOsParseNonNegInt(v.slice(1)) if (!Number.isFinite(count) || count < 1) count = 1 } else { fromPlus = false count = bareOsParseNonNegInt(v.startsWith('-') ? v.slice(1) : v) if (!Number.isFinite(count)) { ctx.console.error('tail: invalid number of lines: ' + v) ctx.exitCode = 1 return } } i++ continue } if (a === '-c' || a === '--bytes') { const v = argv[i + 1] if (v == null) { ctx.console.error('tail: option requires an argument -- c') ctx.exitCode = 1 return } i++ mode = 'bytes' if (v.startsWith('+')) { fromPlus = true count = bareOsParseNonNegInt(v.slice(1)) if (!Number.isFinite(count) || count < 1) count = 1 } else { fromPlus = false count = bareOsParseNonNegInt(v.startsWith('-') ? v.slice(1) : v) if (!Number.isFinite(count)) { ctx.console.error('tail: invalid number of bytes: ' + v) ctx.exitCode = 1 return } } i++ continue } if (a.startsWith('-c') && a.length > 2) { const v = a.slice(2) mode = 'bytes' if (v.startsWith('+')) { fromPlus = true count = bareOsParseNonNegInt(v.slice(1)) if (!Number.isFinite(count) || count < 1) count = 1 } else { fromPlus = false count = bareOsParseNonNegInt(v.startsWith('-') ? v.slice(1) : v) if (!Number.isFinite(count)) { ctx.console.error('tail: invalid number of bytes: ' + v) ctx.exitCode = 1 return } } i++ continue } if (a.startsWith('-') && /^-\d+$/.test(a)) { mode = 'lines' fromPlus = false count = Number.parseInt(a.slice(1), 10) || 10 i++ continue } if (a.startsWith('-')) { ctx.console.error('tail: unrecognized option: ' + a) ctx.exitCode = 1 return } break } const files = argv.slice(i).filter((x) => x !== '--') if (follow && !files.length) { ctx.console.error( 'tail: --follow is not supported for stdin on Bare OS (stdin is a captured string)' ) ctx.exitCode = 1 return } if (follow && files.length > 1) { ctx.console.error( 'tail: following multiple files is not supported (use one path)' ) ctx.exitCode = 1 return } if (!files.length) { const s = bareStdin(ctx) if (mode === 'bytes') { const u8 = ctx.b4a.from(s, 'utf8') const slice = bareTailBytesSlice( u8, fromPlus ? 'start' : 'end', count, fromPlus ) const out = ctx.b4a.toString(slice) if (out) ctx.console.log(out) } else { const out = bareTailLinesText( s, fromPlus ? 'start' : 'end', count, fromPlus, ctx.b4a ) if (out) ctx.console.log(out) } return } for (const f of files) { const buf = await vfs.readFile(f) if (!buf) { ctx.console.error('tail: ' + f + ': No such file') ctx.exitCode = 1 continue } if (files.length > 1) ctx.console.log('==> ' + f + ' <==') const u8 = buf instanceof Uint8Array ? buf : ctx.b4a.from(buf) const text = ctx.b4a.toString(u8) if (!follow) { if (mode === 'bytes') { const slice = bareTailBytesSlice( u8, fromPlus ? 'start' : 'end', count, fromPlus ) const out = ctx.b4a.toString(slice) if (out) ctx.console.log(out) } else { const out = bareTailLinesText( text, fromPlus ? 'start' : 'end', count, fromPlus, ctx.b4a ) if (out) ctx.console.log(out) } continue } if (mode === 'bytes') { const slice = bareTailBytesSlice( u8, fromPlus ? 'start' : 'end', count, fromPlus ) const out = ctx.b4a.toString(slice) if (out) ctx.console.log(out) await bareTailFollow(ctx, f, vfs, u8.byteLength) } else { const out = bareTailLinesText( text, fromPlus ? 'start' : 'end', count, fromPlus, ctx.b4a ) if (out) ctx.console.log(out) const startOffset = u8.byteLength await bareTailFollow(ctx, f, vfs, startOffset) } } }