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
+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
}
}