|
| 1 | +import { program } from "commander"; |
| 2 | +import { promises as fs } from "node:fs"; |
| 3 | + |
| 4 | +program |
| 5 | + .name("cat") |
| 6 | + .description("concatenate and print files") |
| 7 | + .option("-n, --number", "number all output lines") |
| 8 | + .option("-b, --number-nonblank", "number nonempty output lines") |
| 9 | + .argument("<paths...>", "the file paths to process"); |
| 10 | + |
| 11 | +program.parse(); |
| 12 | + |
| 13 | +const options = program.opts(); |
| 14 | +const paths = program.args; |
| 15 | + |
| 16 | +const numberAll = options.number; |
| 17 | +const numberNonBlank = options.numberNonblank; |
| 18 | + |
| 19 | +const shouldNumberAll = numberNonBlank ? false : numberAll; |
| 20 | + |
| 21 | +let lineNumber = 1; |
| 22 | +let nonBlankNumber = 1; |
| 23 | + |
| 24 | +for (const filePath of paths) { |
| 25 | + try { |
| 26 | + const content = await fs.readFile(filePath, "utf8"); |
| 27 | + process.stdout.write(formatContent(content)); |
| 28 | + } catch (error) { |
| 29 | + process.exitCode = 1; |
| 30 | + process.stderr.write(`cat: ${filePath}: ${error.message}\n`); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +function formatContent(text) { |
| 35 | + const normalized = text.replace(/\r\n/g, "\n"); |
| 36 | + const endsWithNewline = normalized.endsWith("\n"); |
| 37 | + const lines = endsWithNewline |
| 38 | + ? normalized.slice(0, -1).split("\n") |
| 39 | + : normalized.split("\n"); |
| 40 | + |
| 41 | + const output = []; |
| 42 | + |
| 43 | + for (const line of lines) { |
| 44 | + if (numberNonBlank) { |
| 45 | + if (line === "") { |
| 46 | + output.push(""); |
| 47 | + } else { |
| 48 | + output.push(`${String(nonBlankNumber++).padStart(6, " ")}\t${line}`); |
| 49 | + } |
| 50 | + } else if (shouldNumberAll) { |
| 51 | + output.push(`${String(lineNumber++).padStart(6, " ")}\t${line}`); |
| 52 | + } else { |
| 53 | + output.push(line); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + let result = output.join("\n"); |
| 58 | + |
| 59 | + if (endsWithNewline) { |
| 60 | + result += "\n"; |
| 61 | + } |
| 62 | + |
| 63 | + return result; |
| 64 | +} |
0 commit comments