|
| 1 | +import { program } from "commander"; |
| 2 | +import { promises as fs } from "node:fs"; |
| 3 | + |
| 4 | +const argv = process.argv.slice(2); |
| 5 | + |
| 6 | +const flags = argv.filter((arg) => arg.startsWith("-")); |
| 7 | +const paths = argv.filter((arg) => !arg.startsWith("-")); |
| 8 | + |
| 9 | +const showLines = flags.includes("-l"); |
| 10 | +const showWords = flags.includes("-w"); |
| 11 | +const showBytes = flags.includes("-c"); |
| 12 | + |
| 13 | +const noFlagsGiven = !showLines && !showWords && !showBytes; |
| 14 | + |
| 15 | +const columns = []; |
| 16 | +if (noFlagsGiven || showLines) columns.push("lines"); |
| 17 | +if (noFlagsGiven || showWords) columns.push("words"); |
| 18 | +if (noFlagsGiven || showBytes) columns.push("bytes"); |
| 19 | + |
| 20 | +function countStats(content) { |
| 21 | + const lines = (content.match(/\n/g) || []).length; |
| 22 | + const words = content.split(/\s+/).filter((w) => w.length > 0).length; |
| 23 | + const bytes = Buffer.byteLength(content, "utf-8"); |
| 24 | + return { lines, words, bytes }; |
| 25 | +} |
| 26 | + |
| 27 | +// Read every file and collect its stats |
| 28 | +const rows = []; |
| 29 | +for (const path of paths) { |
| 30 | + const content = await fs.readFile(path, "utf-8"); |
| 31 | + rows.push({ path, stats: countStats(content) }); |
| 32 | +} |
| 33 | + |
| 34 | +// If there's more than one file, we also need a "total" row at the end |
| 35 | +if (rows.length > 1) { |
| 36 | + const total = { lines: 0, words: 0, bytes: 0 }; |
| 37 | + for (const { stats } of rows) { |
| 38 | + total.lines += stats.lines; |
| 39 | + total.words += stats.words; |
| 40 | + total.bytes += stats.bytes; |
| 41 | + } |
| 42 | + rows.push({ path: "total", stats: total }); |
| 43 | +} |
| 44 | + |
| 45 | +const needsAlignment = columns.length > 1 || rows.length > 1; |
| 46 | + |
| 47 | +let width = 0; |
| 48 | +if (needsAlignment) { |
| 49 | + for (const { stats } of rows) { |
| 50 | + for (const col of columns) { |
| 51 | + width = Math.max(width, String(stats[col]).length); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + width = Math.max(width, 3); |
| 56 | +} |
| 57 | + |
| 58 | +for (const { path, stats } of rows) { |
| 59 | + const parts = columns.map((col, index) => { |
| 60 | + const text = String(stats[col]); |
| 61 | + if (!needsAlignment) { |
| 62 | + return text; |
| 63 | + } |
| 64 | + const padded = text.padStart(width, " "); |
| 65 | + |
| 66 | + return index === 0 ? padded : " " + padded; |
| 67 | + }); |
| 68 | + |
| 69 | + console.log(`${parts.join("")} ${path}`); |
| 70 | +} |
0 commit comments