This commit is contained in:
Raven Scott
2026-04-03 20:19:08 -04:00
parent 58d1571627
commit ae6b7f8652
18 changed files with 903 additions and 72 deletions
+8 -2
View File
@@ -1,4 +1,4 @@
import { randomUUID, randomBytes } from 'node:crypto'
import bareCrypto from 'bare-crypto'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import b4a from 'b4a'
@@ -9,6 +9,7 @@ import { topicKey, parseMbr } from 'bare-os-protocol'
import { SwarmDisk } from './lib/swarm-disk.js'
import { runKernelFromSource, runBinCommand } from './lib/kernel-runner.js'
import { createVfs } from './lib/vfs.js'
import { createBareOsIpc } from './lib/bare-os-ipc.js'
import { execShellLine, syncBareOsExitStatusEnv } from './lib/shell.js'
import { packageRootDir, defaultBootCorestorePath } from './lib/paths.js'
import {
@@ -44,6 +45,8 @@ import { BARE_OS_CTX_API_VERSION } from './lib/bare-os-ctx-api.js'
import { buildBareOsRuntimeCaps } from './lib/bare-os-runtime-caps.js'
import './lib/bare-cron.js'
const { randomUUID, randomBytes } = bareCrypto
const _pkg = packageRootDir(import.meta.url)
/**
@@ -283,6 +286,7 @@ async function executeKernel(disk, store, swarm, initSource) {
/** @type {{ getMounts: () => Map<string, { drive: import('hyperdrive').default, writable: boolean }> }} */
const vfsMountRef = { getMounts: () => new Map() }
const bootStartedMs = Date.now()
const bareOsIpc = createBareOsIpc()
const vfs = createVfs(disk.drive, disk.personalDrive, shellEnv, vfsMountRef, {
procSnapshot: {
version: BARE_OS_CTX_API_VERSION,
@@ -324,7 +328,8 @@ async function executeKernel(disk, store, swarm, initSource) {
},
secureRandomBytes(n) {
return new Uint8Array(randomBytes(Math.min(65536, Math.max(1, n | 0))))
}
},
bareOsIpc
})
const hdmsController = new HdmsController()
@@ -346,6 +351,7 @@ async function executeKernel(disk, store, swarm, initSource) {
drive: disk.drive,
personalDrive: disk.personalDrive,
vfs,
bareOsIpc,
env: shellEnv,
console,
b4a,
+112
View File
@@ -0,0 +1,112 @@
/**
* In-memory named FIFOs under logical `/run/bare-os/ipc/<name>`.
* One write wakes one blocking read; queued writes are delivered in order.
*/
class FifoChannel {
constructor() {
/** @type {Uint8Array[]} */
this.queue = []
/** @type {((v: Uint8Array) => void)[]} */
this.waiters = []
}
/**
* @param {Uint8Array | ArrayBuffer} buf
*/
push(buf) {
const u8 = buf instanceof Uint8Array ? buf : new Uint8Array(buf)
if (this.waiters.length > 0) {
const resolve = this.waiters.shift()
resolve(u8)
} else {
this.queue.push(u8)
}
}
/**
* @returns {Promise<Uint8Array>}
*/
take() {
if (this.queue.length > 0) {
return Promise.resolve(this.queue.shift())
}
return new Promise((resolve) => {
this.waiters.push(resolve)
})
}
}
/**
* @param {string} name
*/
function assertSafeIpcName(name) {
if (!name || name.length > 128) {
throw new Error('invalid fifo name')
}
if (!/^[a-zA-Z0-9._-]+$/.test(name)) {
throw new Error('fifo name must match [a-zA-Z0-9._-]+')
}
}
/**
* @returns {{
* create: (name: string) => void,
* has: (name: string) => boolean,
* list: () => string[],
* remove: (name: string) => void,
* push: (name: string, buf: Uint8Array | ArrayBuffer) => void,
* take: (name: string) => Promise<Uint8Array>
* }}
*/
export function createBareOsIpc() {
/** @type {Map<string, FifoChannel>} */
const channels = new Map()
return {
/**
* @param {string} name
*/
create(name) {
assertSafeIpcName(name)
if (!channels.has(name)) channels.set(name, new FifoChannel())
},
/**
* @param {string} name
*/
has(name) {
return channels.has(name)
},
list() {
return [...channels.keys()].sort()
},
/**
* @param {string} name
*/
remove(name) {
channels.delete(name)
},
/**
* @param {string} name
* @param {Uint8Array | ArrayBuffer} buf
*/
push(name, buf) {
const ch = channels.get(name)
if (!ch) throw new Error('no such fifo: ' + name)
ch.push(buf)
},
/**
* @param {string} name
*/
take(name) {
const ch = channels.get(name)
if (!ch) return Promise.reject(new Error('no such fifo: ' + name))
return ch.take()
}
}
}
@@ -40,6 +40,7 @@ export const BARE_OS_PSEUDO_FS_PATHS = Object.freeze([
'/run/bare-os/ready',
'/run/bare-os/session',
'/run/bare-os/units',
'/run/bare-os/ipc',
'/sys',
'/sys/fs',
'/sys/fs/bare_os',
@@ -85,6 +86,8 @@ export function buildBareOsRuntimeCaps(shellEnv) {
systemctlDelegate: true,
jobControl: true,
shellHereString: true,
shellHereDocument: true,
ipcFifoSimulated: true,
bootReadyPseudoFs: true,
sessionStatsProc: true,
initdRequiresWants: true,
+58 -1
View File
@@ -340,6 +340,11 @@ export function tokenize(line) {
i += 3
continue
}
if (line[i + 1] === '<') {
tokens.push({ type: 'op', value: '<<' })
i += 2
continue
}
tokens.push({ type: 'op', value: '<' })
i++
continue
@@ -526,6 +531,13 @@ function parseSimpleCommand(seg) {
continue
}
}
if (t.value === '<<') {
const n = seg[w + 1]
if (n && n.type === 'word') {
w += 2
continue
}
}
if (t.value === '<<<') {
const n = seg[w + 1]
if (n && n.type === 'word') {
@@ -598,6 +610,10 @@ function parseSimpleCommand(seg) {
argvWords.splice(i, 2)
continue
}
if (argvWords[i] === '<<') {
argvWords.splice(i, 2)
continue
}
i++
}
@@ -712,6 +728,9 @@ async function execParsedPipeline(ctx, pipeline) {
const p = expandWord(cmd.redirIn, env)
const buf = await vfs.readFile(p)
stdinText = buf ? ctx.b4a.toString(buf) : ''
} else if (pi === 0 && typeof ctx.shellHeredocOnce === 'string') {
stdinText = ctx.shellHeredocOnce
delete ctx.shellHeredocOnce
}
const outChunks = []
@@ -1345,7 +1364,45 @@ export async function execShellLine(ctx, line) {
const raw = line.trim()
if (!raw) return 'ok'
const tokens = tokenize(raw)
let execLine = raw
const readL = ctx.readLine
if (typeof readL === 'function') {
const hm = raw.match(/^(.*?)<<\s*(?:'([^']+)'|"([^"]+)"|(\S+))\s*$/)
if (hm) {
const prefix = hm[1].trimEnd()
if (!prefix) {
ctx.console.error(
'shell: here-document requires a command before << on the same line'
)
ctx.exitCode = 2
syncBareOsExitStatusEnv(ctx)
return 'ok'
}
const delim = hm[2] ?? hm[3] ?? hm[4]
const singleQuoted = hm[2] != null
/** @type {string[]} */
const bodyLines = []
for (;;) {
const ln = await readL('> ')
if (ln == null) break
if (ln === delim) break
bodyLines.push(ln)
}
const vfs = ctx.vfs
const env = vfs?.env && typeof vfs.env === 'object' ? vfs.env : {}
let body = bodyLines.join('\n')
if (!singleQuoted) {
body = bodyLines.map((l) => expandWord(l, env)).join('\n')
}
ctx.shellHeredocOnce = body
if (body.length > 0 && !body.endsWith('\n')) {
ctx.shellHeredocOnce += '\n'
}
execLine = prefix
}
}
const tokens = tokenize(execLine)
if (!tokens.length) return 'ok'
const statements = splitTopLevelStatements(tokens)
+84 -4
View File
@@ -39,7 +39,8 @@ const DIR_MARKER = '.bareos_empty'
* bootReadyMarkerText?: () => string,
* bootReadyJsonText?: () => string,
* buildIdText?: () => string,
* secureRandomBytes?: (n: number) => Uint8Array
* secureRandomBytes?: (n: number) => Uint8Array,
* bareOsIpc?: ReturnType<import('./bare-os-ipc.js').createBareOsIpc> | null
* }} [vfsOptions]
*/
export function createVfs(
@@ -86,6 +87,7 @@ export function createVfs(
typeof vfsOptions.secureRandomBytes === 'function'
? vfsOptions.secureRandomBytes
: null
const bareOsIpc = vfsOptions.bareOsIpc ?? null
const HOME = () => env.HOME || '/home/guest'
let cwd = env.PWD || HOME()
@@ -217,7 +219,7 @@ export function createVfs(
}
/**
* When the booter supplies `secureRandomBytes` (e.g. node:crypto), reads are suitable
* When the booter supplies `secureRandomBytes` (e.g. bare-crypto), reads are suitable
* for cryptographic use; otherwise falls back to Math.random (not crypto-grade).
*/
function pseudoUrandomBytes() {
@@ -376,6 +378,32 @@ export function createVfs(
file: 'boot_json'
}
}
if (n === '/run/bare-os/ipc') {
if (!bareOsIpc) {
return { virtualPseudo: true, kind: 'run', node: 'enoent' }
}
return { virtualPseudo: true, kind: 'run', node: 'dir', dir: 'bare_ipc' }
}
const ipcPref = '/run/bare-os/ipc/'
if (n.startsWith(ipcPref)) {
if (!bareOsIpc) {
return { virtualPseudo: true, kind: 'run', node: 'enoent' }
}
const seg = n.slice(ipcPref.length).replace(/\/+$/, '')
if (!seg || seg.includes('/')) {
return { virtualPseudo: true, kind: 'run', node: 'enoent' }
}
if (!bareOsIpc.has(seg)) {
return { virtualPseudo: true, kind: 'run', node: 'enoent' }
}
return {
virtualPseudo: true,
kind: 'run',
node: 'file',
file: 'ipc',
ipcName: seg
}
}
return { virtualPseudo: true, kind: 'run', node: 'enoent' }
}
if (n === '/dev' || n.startsWith('/dev/')) {
@@ -418,7 +446,17 @@ export function createVfs(
if (!r.virtualPseudo) return null
if (r.node === 'enoent') return null
if (r.node === 'root' || r.node === 'dir') {
return { ...synthesizeStat(abs, false, env, 'directory'), path: abs }
const personalDir =
r.kind === 'run' && r.node === 'dir' && r.dir === 'bare_ipc'
return {
...synthesizeStat(abs, personalDir, env, 'directory'),
path: abs
}
}
if (r.file === 'ipc') {
const st = { ...synthesizeStat(abs, true, env, 'file'), path: abs }
st.size = 0
return st
}
const body = pseudoFileBytes(r)
const st = { ...synthesizeStat(abs, false, env, 'file'), path: abs }
@@ -926,7 +964,23 @@ export function createVfs(
return ['bare-os']
}
if (pr.kind === 'run' && pr.node === 'dir' && pr.dir === 'bare_os') {
return ['boot.json', 'boot_profile', 'ready', 'session', 'units']
const base = [
'boot.json',
'boot_profile',
'ipc',
'ready',
'session',
'units'
]
return bareOsIpc ? base : base.filter((x) => x !== 'ipc')
}
if (
pr.kind === 'run' &&
pr.node === 'dir' &&
pr.dir === 'bare_ipc' &&
bareOsIpc
) {
return bareOsIpc.list()
}
if (pr.kind === 'dev' && pr.node === 'root') {
return ['null', 'urandom', 'zero']
@@ -1051,6 +1105,17 @@ export function createVfs(
) {
return
}
if (
r.virtualPseudo &&
r.kind === 'run' &&
r.node === 'file' &&
r.file === 'ipc' &&
bareOsIpc
) {
await assertTraverseTo(abs, 'write')
bareOsIpc.push(r.ipcName, buf)
return
}
if (
r.virtualHomeDir ||
r.virtualMntRoot ||
@@ -1123,6 +1188,10 @@ export function createVfs(
await assertTraverseTo(abs, 'read')
return null
}
if (r.node === 'file' && r.file === 'ipc' && bareOsIpc) {
await assertTraverseTo(abs, 'read')
return bareOsIpc.take(r.ipcName)
}
if (r.node === 'file') {
await assertTraverseTo(abs, 'read')
return pseudoFileBytes(r)
@@ -1143,6 +1212,17 @@ export function createVfs(
async unlink(userPath) {
const abs = resolveLogical(userPath)
const r = route(abs)
if (
r.virtualPseudo &&
r.kind === 'run' &&
r.node === 'file' &&
r.file === 'ipc' &&
bareOsIpc
) {
await assertTraverseTo(abs, 'write')
bareOsIpc.remove(r.ipcName)
return
}
if (
r.virtualHomeDir ||
r.virtualMntRoot ||
+45 -3
View File
@@ -12,6 +12,7 @@ import { createGitFsFromVfs } from './lib/git-fs-adapter.js'
import { runGitCli } from './lib/git-cli.js'
import { createStreamLineReader } from './lib/cli-readline.js'
import { createVfs } from './lib/vfs.js'
import { createBareOsIpc } from './lib/bare-os-ipc.js'
import {
tokenize,
expandWord,
@@ -86,11 +87,13 @@ function testCtx(drive, personal, env) {
BARE_OS_EXIT_STATUS: '0',
...env
}
const vfs = createVfs(drive, personal, shellEnv)
const bareOsIpc = createBareOsIpc()
const vfs = createVfs(drive, personal, shellEnv, null, { bareOsIpc })
return {
drive,
personalDrive: personal,
vfs,
bareOsIpc,
env: shellEnv,
console,
b4a
@@ -677,12 +680,14 @@ test('vfs /proc /sys read-only pseudo files; write rejected', async (t) => {
BARE_OS_CTX_API_VERSION: '9.9.9-test'
}
const mntMap = new Map()
const bareOsIpc = createBareOsIpc()
const vfs = createVfs(sys, personal, env, { getMounts: () => mntMap }, {
procSnapshot: { version: '1.2.3-test', cmdline: 'unit-test' },
bootStartedMs: Date.now() - 4000,
bootProfileText: () => 'mini\n',
sessionText: () => 'test-session-id\n',
initdRunText: () => 'demo-unit\tactive\t1\tdemo\n'
initdRunText: () => 'demo-unit\tactive\t1\tdemo\n',
bareOsIpc
})
const root = await vfs.readdir('/')
t.ok(root.includes('proc'))
@@ -744,10 +749,19 @@ test('vfs /proc /sys read-only pseudo files; write rejected', async (t) => {
t.alike(await vfs.readdir('/run/bare-os').then((a) => [...a].sort()), [
'boot.json',
'boot_profile',
'ipc',
'ready',
'session',
'units'
])
t.alike(await vfs.readdir('/run/bare-os/ipc'), [])
bareOsIpc.create('q1')
t.alike(await vfs.readdir('/run/bare-os/ipc'), ['q1'])
const readP = vfs.readFile('/run/bare-os/ipc/q1')
await vfs.writeFile('/run/bare-os/ipc/q1', b4a.from('ping'))
t.is(b4a.toString(await readP), 'ping')
await vfs.unlink('/run/bare-os/ipc/q1')
t.alike(await vfs.readdir('/run/bare-os/ipc'), [])
t.is(b4a.toString(await vfs.readFile('/run/bare-os/boot_profile')), 'mini\n')
t.is(b4a.toString(await vfs.readFile('/run/bare-os/session')), 'test-session-id\n')
const units = b4a.toString(await vfs.readFile('/run/bare-os/units'))
@@ -1011,6 +1025,7 @@ test('buildBareOsRuntimeCaps matches ctx API version and pipeline env', async (t
t.ok(Array.isArray(caps.pseudoFsPaths))
t.ok(caps.pseudoFsPaths.includes('/proc/version'))
t.ok(caps.pseudoFsPaths.includes('/run/bare-os/boot_profile'))
t.ok(caps.pseudoFsPaths.includes('/run/bare-os/ipc'))
t.ok(caps.pseudoFsPaths.includes('/run/bare-os/session'))
t.ok(caps.pseudoFsPaths.includes('/proc/mounts'))
t.is(caps.features.simulatedPipelines, true)
@@ -1611,7 +1626,7 @@ test('tier-1 cat from system drive', async (t) => {
rmSync(dir, { recursive: true, force: true })
})
test('tier-1 grep from system drive', async (t) => {
test('tier-1 grep and mkfifo from system drive', async (t) => {
const dir = testCorestoreDir('grep')
const store = new Corestore(dir)
const drive = new Hyperdrive(store)
@@ -1619,6 +1634,7 @@ test('tier-1 grep from system drive', async (t) => {
await drive.ready()
await personal.ready()
await drive.put('/bin/grep', b4a.from(await readBuiltBin('grep')))
await drive.put('/bin/mkfifo', b4a.from(await readBuiltBin('mkfifo')))
const lines = []
const ctx = testCtx(drive, personal)
ctx.exitCode = 0
@@ -1669,6 +1685,32 @@ test('tier-1 grep from system drive', async (t) => {
t.is(ctx.exitCode, 0)
t.is(lines[0], 'beta')
lines.length = 0
ctx.exitCode = 0
await runBinCommand(ctx, ['grep', '-x', '-F', 'aaa', 'w.txt'])
t.is(ctx.exitCode, 0)
t.is(lines[0], 'aaa')
lines.length = 0
ctx.exitCode = 0
await runBinCommand(ctx, ['grep', '-m', '1', '-F', 'needle', 'w.txt'])
t.is(ctx.exitCode, 0)
t.is(lines.length, 1)
lines.length = 0
ctx.exitCode = 0
await runBinCommand(ctx, ['grep', '-o', 'ee', 'w.txt'])
t.is(ctx.exitCode, 0)
t.ok(lines.includes('ee'))
lines.length = 0
ctx.exitCode = 0
await runBinCommand(ctx, ['mkfifo', '/run/bare-os/ipc/t1'])
t.is(ctx.exitCode, 0)
const readP = ctx.vfs.readFile('/run/bare-os/ipc/t1')
await ctx.vfs.writeFile('/run/bare-os/ipc/t1', b4a.from('ok'))
t.is(b4a.toString(await readP), 'ok')
await store.close()
rmSync(dir, { recursive: true, force: true })
})
+2 -2
View File
@@ -35,11 +35,11 @@ Or `node packages/bare-os-coreutils/build.mjs`.
`awk`, `basename`, `cat`, `chgrp`, `chmod`, `chown`, `cksum`, `clear`, `cp`, `crontab`, `cut`, `date`, `dirname`, `du`, `echo`, `env`, `exit`, `false`, `find`, `getconf`, `grep`, `head`, `hdms`, `help`, `hostname`, `id`, `ln`, `login`, `logout`, `logname`, `ls`, `man`, `mkdir`, `mkfifo`, `mv`, `nl`, `od`, `pathchk`, `printenv`, `printf`, `pwd`, `readlink`, `rm`, `rmdir`, `savevault`, `sed`, `seq`, `sleep`, `sort`, `stat`, `tail`, `tee`, `test`, `time`, `touch`, `tr`, `true`, `tty`, `uname`, `wc`, `which`, `whoami`, `xargs`
**`grep`** uses JavaScript **`RegExp`** (and **`-F`** fixed strings); POSIX/GNU-like **subset**.
**`grep`** uses JavaScript **`RegExp`** (and **`-F`** fixed strings); POSIX/GNU-like **subset** (including **`-x`**, **`-m`**, **`-o`** among common flags).
**`sed`** / **`awk`** use large interpreters in **`lib/sed-engine.js`** and **`lib/awk-engine.js`** — capable, but not guaranteed to match every POSIX or GNU edge case.
**Stubs** (**`chown`**, **`chgrp`**, **`mkfifo`**) print a clear error and exit non-zero. **`getconf`** and **`xargs`** implement a documented Bare-specific subset (see `src/getconf.js`, `src/xargs.js`).
**`mkfifo`** creates simulated named pipes under **`/run/bare-os/ipc/<name>`** (in-memory; see booter VFS). **`getconf`** and **`xargs`** implement a documented Bare-specific subset (see `src/getconf.js`, `src/xargs.js`).
See [handbook §6 — Kernel and `/bin`](../../handbook/06-kernel-and-binaries.md), [handbook §9 — POSIX alignment](../../handbook/09-posix-utilities-shell-and-vfs.md), and [handbook §10 — `man` and online help](../../handbook/10-manpages-and-online-help.md).
@@ -11,7 +11,7 @@ import { COREUTILS_COMMANDS, MAN_EXTRA_PAGES } from '../lib/commands.mjs'
const __dirname = dirname(fileURLToPath(import.meta.url))
const pagesDir = join(__dirname, '../man/pages')
const STUB = new Set(['chgrp', 'chown', 'mkfifo'])
const STUB = new Set(['chgrp', 'chown'])
const POSIX_TITLE = {
awk: 'pattern scanning and processing language',
+158 -12
View File
@@ -17,13 +17,17 @@ async function run(ctx, argv) {
let forceFilename = false
let noFilename = false
let word = false
let fullLine = false
let onlyMatching = false
/** @type {number} */
let maxMatchLines = Number.POSITIVE_INFINITY
const args = argv.slice(1)
let i = 0
function usage() {
ctx.console.error(
'usage: grep [-E|-F] [-i] [-v] [-w] [-n] [-c] [-l] [-q] [-s] [-H|-h] [-e pat] ... [-f file] ... [pattern] [file...]'
'usage: grep [-E|-F] [-i] [-v] [-w] [-x] [-n] [-c] [-l] [-o] [-m NUM] [-q] [-s] [-H|-h] [-e pat] ... [-f file] ... [pattern] [file...]'
)
ctx.exitCode = 2
}
@@ -42,6 +46,33 @@ async function run(ctx, argv) {
return
}
if (a === '-m') {
if (i + 1 >= args.length) {
usage()
return
}
const n = Number.parseInt(args[++i], 10)
if (!Number.isFinite(n) || n < 0) {
ctx.console.error('grep: invalid -m value')
ctx.exitCode = 2
return
}
maxMatchLines = n === 0 ? Number.POSITIVE_INFINITY : n
i++
continue
}
if (/^-m\d+$/.test(a)) {
const n = Number.parseInt(a.slice(2), 10)
if (!Number.isFinite(n) || n < 0) {
ctx.console.error('grep: invalid -m value')
ctx.exitCode = 2
return
}
maxMatchLines = n === 0 ? Number.POSITIVE_INFINITY : n
i++
continue
}
if (a === '-e') {
if (i + 1 >= args.length) {
usage()
@@ -111,6 +142,26 @@ async function run(ctx, argv) {
case 'w':
word = true
break
case 'x':
fullLine = true
break
case 'o':
onlyMatching = true
break
case 'm': {
let num = ''
let jj = j + 1
while (jj < rest.length && /[0-9]/.test(rest[jj])) num += rest[jj++]
if (!num) {
ctx.console.error('grep: option requires an argument -- m')
ctx.exitCode = 2
return
}
const n = Number.parseInt(num, 10)
maxMatchLines = n === 0 ? Number.POSITIVE_INFINITY : n
j = jj - 1
break
}
default:
ctx.console.error('grep: invalid option -- ' + c)
ctx.exitCode = 2
@@ -159,7 +210,7 @@ async function run(ctx, argv) {
let matchers
try {
matchers = buildMatchers(patterns, { fixed, icase, word })
matchers = buildMatchers(patterns, { fixed, icase, word, fullLine })
} catch (e) {
ctx.console.error('grep: ' + (e.message || e))
ctx.exitCode = 2
@@ -172,6 +223,7 @@ async function run(ctx, argv) {
let anyMatch = false
let fatal = false
let matchingLinesTotal = 0
for (const { label, path } of inputs) {
let text
@@ -201,15 +253,31 @@ async function run(ctx, argv) {
const out = []
for (let li = 0; li < lines.length; li++) {
if (matchingLinesTotal >= maxMatchLines) break
const line = stripCr(lines[li])
const lineNum = li + 1
const matched = matchers.some((fn) => fn(line))
const hit = invert ? !matched : matched
if (hit) {
fileMatched = true
anyMatch = true
count++
if (!quiet && !countOnly && !listFiles) {
if (!hit) continue
matchingLinesTotal++
fileMatched = true
anyMatch = true
count++
if (quiet) continue
if (!countOnly && !listFiles) {
if (onlyMatching && !invert) {
const parts = extractOnlyMatching(line, patterns, { fixed, icase, word })
for (const part of parts) {
let chunk = part
if (numbers) chunk = lineNum + ':' + chunk
if (showName && label != null) chunk = label + ':' + chunk
else if (showName && label == null && useStdin)
chunk = '(standard input):' + chunk
out.push(chunk)
}
} else {
let chunk = line
if (numbers) chunk = lineNum + ':' + chunk
if (showName && label != null) chunk = label + ':' + chunk
@@ -246,7 +314,7 @@ async function run(ctx, argv) {
/**
* @param {string[]} patterns
* @param {{ fixed: boolean, icase: boolean, word?: boolean }} o
* @param {{ fixed: boolean, icase: boolean, word?: boolean, fullLine?: boolean }} o
*/
function buildMatchers(patterns, o) {
if (patterns.length === 0) throw new Error('no pattern')
@@ -254,22 +322,34 @@ function buildMatchers(patterns, o) {
const pats = o.icase
? patterns.map((p) => p.toLowerCase())
: patterns.slice()
return pats.map((p) => {
return pats.map((p, idx) => {
const orig = patterns[idx]
if (o.fullLine) {
return (line) => {
const cmpL = o.icase ? line.toLowerCase() : line
const cmpP = o.icase ? p : orig
return cmpL === cmpP
}
}
if (o.word) {
const esc = p.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
const flags = o.icase ? 'i' : ''
const re = new RegExp('(?:^|[^0-9A-Za-z_])' + esc + '(?:$|[^0-9A-Za-z_])', flags)
const re = new RegExp(
'(?:^|[^0-9A-Za-z_])' + esc + '(?:$|[^0-9A-Za-z_])',
flags
)
return (line) => re.test(line)
}
return (line) =>
o.icase ? line.toLowerCase().includes(p) : line.includes(p)
o.icase ? line.toLowerCase().includes(p) : line.includes(orig)
})
}
const flags = o.icase ? 'i' : ''
return patterns.map((p) => {
try {
const body = o.word ? '\\b(?:' + p + ')\\b' : p
const re = new RegExp(body, flags)
const wrapped = o.fullLine ? '^(?:' + body + ')$' : body
const re = new RegExp(wrapped, flags)
return (line) => re.test(line)
} catch (e) {
throw new Error('invalid regex: ' + (e.message || e))
@@ -277,6 +357,72 @@ function buildMatchers(patterns, o) {
})
}
/**
* @param {string} line
* @param {string[]} patterns
* @param {{ fixed: boolean, icase: boolean, word: boolean }} o
*/
function extractOnlyMatching(line, patterns, o) {
/** @type {{ start: number, end: number, text: string }[]} */
const raw = []
if (o.fixed) {
for (const pat of patterns) {
const needle = o.icase ? pat.toLowerCase() : pat
const hay = o.icase ? line.toLowerCase() : line
let pos = 0
while (pos <= hay.length) {
const idx = hay.indexOf(needle, pos)
if (idx === -1) break
const end = idx + needle.length
if (o.word) {
const before = idx > 0 ? hay[idx - 1] : ' '
const after = end < hay.length ? hay[end] : ' '
if (/[0-9A-Za-z_]/.test(before) || /[0-9A-Za-z_]/.test(after)) {
pos = idx + 1
continue
}
}
raw.push({ start: idx, end, text: line.slice(idx, end) })
pos = idx + 1
}
}
} else {
const flags = o.icase ? 'i' : ''
for (const p of patterns) {
const body = o.word ? '\\b(?:' + p + ')\\b' : p
let re
try {
re = new RegExp(body, flags + 'g')
} catch (e) {
throw new Error('invalid regex: ' + (e.message || e))
}
let m
while ((m = re.exec(line)) !== null) {
raw.push({
start: m.index,
end: m.index + m[0].length,
text: m[0]
})
if (m[0] === '') {
re.lastIndex++
if (re.lastIndex > line.length) break
}
}
}
}
raw.sort((a, b) => a.start - b.start || b.end - a.end)
/** @type {string[]} */
const out = []
let lastEnd = -1
for (const c of raw) {
if (c.start >= lastEnd) {
out.push(c.text)
lastEnd = c.end
}
}
return out
}
/** @param {string} text */
function splitLines(text) {
if (text === '') return ['']
+34 -2
View File
@@ -1,4 +1,36 @@
async function run(ctx, argv) {
ctx.console.error('mkfifo: FIFOs are not supported in this JavaScript VFS.')
ctx.exitCode = 1
const path = argv[1]
if (!path) {
ctx.console.error('usage: mkfifo PATH')
ctx.exitCode = 1
return
}
const ipc = ctx.bareOsIpc
if (!ipc) {
ctx.console.error('mkfifo: simulated FIFOs are not available in this environment')
ctx.exitCode = 1
return
}
const vfs = ctx.vfs
const abs = vfs.resolveLogical(path)
const prefix = '/run/bare-os/ipc/'
if (!abs.startsWith(prefix)) {
ctx.console.error(
`mkfifo: only ${prefix}<name> is supported (e.g. ${prefix}demo)`
)
ctx.exitCode = 1
return
}
const name = abs.slice(prefix.length).replace(/\/+$/, '')
if (!name || name.includes('/')) {
ctx.console.error('mkfifo: invalid fifo name')
ctx.exitCode = 1
return
}
try {
ipc.create(name)
} catch (e) {
ctx.console.error('mkfifo: ' + (e.message || e))
ctx.exitCode = 1
}
}
+158 -12
View File
@@ -79,13 +79,17 @@ async function run(ctx, argv) {
let forceFilename = false
let noFilename = false
let word = false
let fullLine = false
let onlyMatching = false
/** @type {number} */
let maxMatchLines = Number.POSITIVE_INFINITY
const args = argv.slice(1)
let i = 0
function usage() {
ctx.console.error(
'usage: grep [-E|-F] [-i] [-v] [-w] [-n] [-c] [-l] [-q] [-s] [-H|-h] [-e pat] ... [-f file] ... [pattern] [file...]'
'usage: grep [-E|-F] [-i] [-v] [-w] [-x] [-n] [-c] [-l] [-o] [-m NUM] [-q] [-s] [-H|-h] [-e pat] ... [-f file] ... [pattern] [file...]'
)
ctx.exitCode = 2
}
@@ -104,6 +108,33 @@ async function run(ctx, argv) {
return
}
if (a === '-m') {
if (i + 1 >= args.length) {
usage()
return
}
const n = Number.parseInt(args[++i], 10)
if (!Number.isFinite(n) || n < 0) {
ctx.console.error('grep: invalid -m value')
ctx.exitCode = 2
return
}
maxMatchLines = n === 0 ? Number.POSITIVE_INFINITY : n
i++
continue
}
if (/^-m\d+$/.test(a)) {
const n = Number.parseInt(a.slice(2), 10)
if (!Number.isFinite(n) || n < 0) {
ctx.console.error('grep: invalid -m value')
ctx.exitCode = 2
return
}
maxMatchLines = n === 0 ? Number.POSITIVE_INFINITY : n
i++
continue
}
if (a === '-e') {
if (i + 1 >= args.length) {
usage()
@@ -173,6 +204,26 @@ async function run(ctx, argv) {
case 'w':
word = true
break
case 'x':
fullLine = true
break
case 'o':
onlyMatching = true
break
case 'm': {
let num = ''
let jj = j + 1
while (jj < rest.length && /[0-9]/.test(rest[jj])) num += rest[jj++]
if (!num) {
ctx.console.error('grep: option requires an argument -- m')
ctx.exitCode = 2
return
}
const n = Number.parseInt(num, 10)
maxMatchLines = n === 0 ? Number.POSITIVE_INFINITY : n
j = jj - 1
break
}
default:
ctx.console.error('grep: invalid option -- ' + c)
ctx.exitCode = 2
@@ -221,7 +272,7 @@ async function run(ctx, argv) {
let matchers
try {
matchers = buildMatchers(patterns, { fixed, icase, word })
matchers = buildMatchers(patterns, { fixed, icase, word, fullLine })
} catch (e) {
ctx.console.error('grep: ' + (e.message || e))
ctx.exitCode = 2
@@ -234,6 +285,7 @@ async function run(ctx, argv) {
let anyMatch = false
let fatal = false
let matchingLinesTotal = 0
for (const { label, path } of inputs) {
let text
@@ -263,15 +315,31 @@ async function run(ctx, argv) {
const out = []
for (let li = 0; li < lines.length; li++) {
if (matchingLinesTotal >= maxMatchLines) break
const line = stripCr(lines[li])
const lineNum = li + 1
const matched = matchers.some((fn) => fn(line))
const hit = invert ? !matched : matched
if (hit) {
fileMatched = true
anyMatch = true
count++
if (!quiet && !countOnly && !listFiles) {
if (!hit) continue
matchingLinesTotal++
fileMatched = true
anyMatch = true
count++
if (quiet) continue
if (!countOnly && !listFiles) {
if (onlyMatching && !invert) {
const parts = extractOnlyMatching(line, patterns, { fixed, icase, word })
for (const part of parts) {
let chunk = part
if (numbers) chunk = lineNum + ':' + chunk
if (showName && label != null) chunk = label + ':' + chunk
else if (showName && label == null && useStdin)
chunk = '(standard input):' + chunk
out.push(chunk)
}
} else {
let chunk = line
if (numbers) chunk = lineNum + ':' + chunk
if (showName && label != null) chunk = label + ':' + chunk
@@ -308,7 +376,7 @@ async function run(ctx, argv) {
/**
* @param {string[]} patterns
* @param {{ fixed: boolean, icase: boolean, word?: boolean }} o
* @param {{ fixed: boolean, icase: boolean, word?: boolean, fullLine?: boolean }} o
*/
function buildMatchers(patterns, o) {
if (patterns.length === 0) throw new Error('no pattern')
@@ -316,22 +384,34 @@ function buildMatchers(patterns, o) {
const pats = o.icase
? patterns.map((p) => p.toLowerCase())
: patterns.slice()
return pats.map((p) => {
return pats.map((p, idx) => {
const orig = patterns[idx]
if (o.fullLine) {
return (line) => {
const cmpL = o.icase ? line.toLowerCase() : line
const cmpP = o.icase ? p : orig
return cmpL === cmpP
}
}
if (o.word) {
const esc = p.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
const flags = o.icase ? 'i' : ''
const re = new RegExp('(?:^|[^0-9A-Za-z_])' + esc + '(?:$|[^0-9A-Za-z_])', flags)
const re = new RegExp(
'(?:^|[^0-9A-Za-z_])' + esc + '(?:$|[^0-9A-Za-z_])',
flags
)
return (line) => re.test(line)
}
return (line) =>
o.icase ? line.toLowerCase().includes(p) : line.includes(p)
o.icase ? line.toLowerCase().includes(p) : line.includes(orig)
})
}
const flags = o.icase ? 'i' : ''
return patterns.map((p) => {
try {
const body = o.word ? '\\b(?:' + p + ')\\b' : p
const re = new RegExp(body, flags)
const wrapped = o.fullLine ? '^(?:' + body + ')$' : body
const re = new RegExp(wrapped, flags)
return (line) => re.test(line)
} catch (e) {
throw new Error('invalid regex: ' + (e.message || e))
@@ -339,6 +419,72 @@ function buildMatchers(patterns, o) {
})
}
/**
* @param {string} line
* @param {string[]} patterns
* @param {{ fixed: boolean, icase: boolean, word: boolean }} o
*/
function extractOnlyMatching(line, patterns, o) {
/** @type {{ start: number, end: number, text: string }[]} */
const raw = []
if (o.fixed) {
for (const pat of patterns) {
const needle = o.icase ? pat.toLowerCase() : pat
const hay = o.icase ? line.toLowerCase() : line
let pos = 0
while (pos <= hay.length) {
const idx = hay.indexOf(needle, pos)
if (idx === -1) break
const end = idx + needle.length
if (o.word) {
const before = idx > 0 ? hay[idx - 1] : ' '
const after = end < hay.length ? hay[end] : ' '
if (/[0-9A-Za-z_]/.test(before) || /[0-9A-Za-z_]/.test(after)) {
pos = idx + 1
continue
}
}
raw.push({ start: idx, end, text: line.slice(idx, end) })
pos = idx + 1
}
}
} else {
const flags = o.icase ? 'i' : ''
for (const p of patterns) {
const body = o.word ? '\\b(?:' + p + ')\\b' : p
let re
try {
re = new RegExp(body, flags + 'g')
} catch (e) {
throw new Error('invalid regex: ' + (e.message || e))
}
let m
while ((m = re.exec(line)) !== null) {
raw.push({
start: m.index,
end: m.index + m[0].length,
text: m[0]
})
if (m[0] === '') {
re.lastIndex++
if (re.lastIndex > line.length) break
}
}
}
}
raw.sort((a, b) => a.start - b.start || b.end - a.end)
/** @type {string[]} */
const out = []
let lastEnd = -1
for (const c of raw) {
if (c.start >= lastEnd) {
out.push(c.text)
lastEnd = c.end
}
}
return out
}
/** @param {string} text */
function splitLines(text) {
if (text === '') return ['']
+34 -2
View File
@@ -61,6 +61,38 @@ function barePosixBlocks(size) {
}
async function run(ctx, argv) {
ctx.console.error('mkfifo: FIFOs are not supported in this JavaScript VFS.')
ctx.exitCode = 1
const path = argv[1]
if (!path) {
ctx.console.error('usage: mkfifo PATH')
ctx.exitCode = 1
return
}
const ipc = ctx.bareOsIpc
if (!ipc) {
ctx.console.error('mkfifo: simulated FIFOs are not available in this environment')
ctx.exitCode = 1
return
}
const vfs = ctx.vfs
const abs = vfs.resolveLogical(path)
const prefix = '/run/bare-os/ipc/'
if (!abs.startsWith(prefix)) {
ctx.console.error(
`mkfifo: only ${prefix}<name> is supported (e.g. ${prefix}demo)`
)
ctx.exitCode = 1
return
}
const name = abs.slice(prefix.length).replace(/\/+$/, '')
if (!name || name.includes('/')) {
ctx.console.error('mkfifo: invalid fifo name')
ctx.exitCode = 1
return
}
try {
ipc.create(name)
} catch (e) {
ctx.console.error('mkfifo: ' + (e.message || e))
ctx.exitCode = 1
}
}
File diff suppressed because one or more lines are too long