61 lines
1.5 KiB
JavaScript
61 lines
1.5 KiB
JavaScript
async function run(ctx, argv) {
|
|
let width = 80
|
|
const paths = []
|
|
for (let i = 1; i < argv.length; i++) {
|
|
const a = argv[i]
|
|
if (a === '-h' || a === '--help') {
|
|
ctx.console.log('usage: fold [-w WIDTH] [FILE]...\nWrap each input line to WIDTH columns.')
|
|
return
|
|
}
|
|
if ((a === '-w' || a === '--width') && argv[i + 1]) {
|
|
width = parseInt(argv[++i], 10)
|
|
if (!Number.isFinite(width) || width < 1) width = 80
|
|
continue
|
|
}
|
|
if (a.startsWith('-') && a !== '-') {
|
|
ctx.console.error('fold: unsupported option ' + a)
|
|
ctx.exitCode = 1
|
|
return
|
|
}
|
|
paths.push(a)
|
|
}
|
|
const b4 = ctx.b4a
|
|
function wrapLine(line) {
|
|
if (line.length <= width) return [line]
|
|
const rows = []
|
|
let rest = line
|
|
while (rest.length > width) {
|
|
rows.push(rest.slice(0, width))
|
|
rest = rest.slice(width)
|
|
}
|
|
if (rest.length) rows.push(rest)
|
|
return rows
|
|
}
|
|
function proc(text) {
|
|
const lines = text.split('\n')
|
|
for (let li = 0; li < lines.length; li++) {
|
|
const isLast = li === lines.length - 1
|
|
const line = lines[li]
|
|
if (isLast && line === '' && lines.length > 1) continue
|
|
for (const row of wrapLine(line)) ctx.console.log(row)
|
|
}
|
|
}
|
|
if (!paths.length) {
|
|
proc(bareStdin(ctx))
|
|
return
|
|
}
|
|
for (const p of paths) {
|
|
if (p === '-') {
|
|
proc(bareStdin(ctx))
|
|
continue
|
|
}
|
|
const b = await ctx.vfs.readFile(p)
|
|
if (!b) {
|
|
ctx.console.error('fold: ' + p + ': No such file')
|
|
ctx.exitCode = 1
|
|
continue
|
|
}
|
|
proc(b4.toString(b))
|
|
}
|
|
}
|