diff --git a/implement-shell-tools/cat/cat.js b/implement-shell-tools/cat/cat.js new file mode 100644 index 000000000..f456dada3 --- /dev/null +++ b/implement-shell-tools/cat/cat.js @@ -0,0 +1,51 @@ +import { program } from "commander"; +import { promises as fs } from "node:fs"; + +program + .argument("", "List of files to concatenate") + .name("cat") + .description("Concatenate FILE(s) to standard output.") + .option("-n", "Number all input lines") + .option("-b", "Number non-blank input lines"); + +program.parse(); + +const files = program.args; +const { n, b } = program.opts(); + +async function main() { + let catAllData = ""; + + for (const file of files) { + const data = await fs.readFile(file, "utf8"); + catAllData += data; + } + + const endsWithNewline = catAllData.endsWith("\n"); + let dataArray = catAllData === "" ? [] : catAllData.split("\n"); + + // A trailing newline produces a final empty element in the split array. + // Drop it so it isn't numbered as a phantom line; the newline is restored + // when the lines are joined back together. + if (endsWithNewline) { + dataArray.pop(); + } + + if (b) { + let lineNumber = 1; + dataArray = dataArray.map((line) => + line ? `${lineNumber++}\t${line}` : line, + ); + } else if (n) { + dataArray = dataArray.map((line, index) => `${index + 1}\t${line}`); + } + + process.stdout.write( + dataArray.join("\n") + (endsWithNewline ? "\n" : ""), + ); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/implement-shell-tools/cat/package-lock.json b/implement-shell-tools/cat/package-lock.json new file mode 100644 index 000000000..c75cf85fd --- /dev/null +++ b/implement-shell-tools/cat/package-lock.json @@ -0,0 +1,25 @@ +{ + "name": "cat", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "cat", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "commander": "^15.1.0" + } + }, + "node_modules/commander": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.1.0.tgz", + "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==", + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + } + } +} diff --git a/implement-shell-tools/cat/package.json b/implement-shell-tools/cat/package.json new file mode 100644 index 000000000..8916cb6e2 --- /dev/null +++ b/implement-shell-tools/cat/package.json @@ -0,0 +1,15 @@ +{ + "name": "cat", + "version": "1.0.0", + "description": "JS implementation of the `cat` command line tool.", + "license": "ISC", + "author": "", + "type": "module", + "main": "cat.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { + "commander": "^15.1.0" + } +} diff --git a/implement-shell-tools/ls/ls.js b/implement-shell-tools/ls/ls.js new file mode 100644 index 000000000..5221a3f73 --- /dev/null +++ b/implement-shell-tools/ls/ls.js @@ -0,0 +1,71 @@ +import { program } from "commander"; +import { promises as fs } from "node:fs"; + +program + .argument("[paths...]", "Paths to list files.", ["."]) + .name("ls") + .description( + "List information about the FILEs (the current directory by default).", + ) + .option("-1, --one", "List one file per line") + .option("-a, --all", "Do not ignore entries starting with ."); + +program.parse(); + +const paths = program.args.length ? program.args : ["."]; +const { one, all } = program.opts(); + +const sortNames = (a, b) => + a.localeCompare(b, undefined, { ignorePunctuation: true }); + +async function main() { + const files = []; + const dirs = []; + + for (const p of paths) { + const stats = await fs.stat(p); + if (stats.isDirectory()) { + dirs.push(p); + } else { + files.push(p); + } + } + + files.sort(sortNames); + dirs.sort(sortNames); + + const sep = one ? "\n" : " "; + + if (files.length > 0) { + console.log(files.join(sep)); + } + + for (let i = 0; i < dirs.length; i++) { + const dir = dirs[i]; + + if (files.length > 0 || i > 0) { + console.log(); + } + + if (paths.length > 1) { + console.log(`${dir}:`); + } + + let fileNames = await fs.readdir(dir); + if (all) { + fileNames.unshift(".", ".."); + } else { + fileNames = fileNames.filter((name) => !name.startsWith(".")); + } + fileNames.sort(sortNames); + + if (fileNames.length > 0) { + console.log(fileNames.join(sep)); + } + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/implement-shell-tools/ls/package-lock.json b/implement-shell-tools/ls/package-lock.json new file mode 100644 index 000000000..16d106dd8 --- /dev/null +++ b/implement-shell-tools/ls/package-lock.json @@ -0,0 +1,25 @@ +{ + "name": "ls", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ls", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "commander": "^15.1.0" + } + }, + "node_modules/commander": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.1.0.tgz", + "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==", + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + } + } +} diff --git a/implement-shell-tools/ls/package.json b/implement-shell-tools/ls/package.json new file mode 100644 index 000000000..5b98a4502 --- /dev/null +++ b/implement-shell-tools/ls/package.json @@ -0,0 +1,15 @@ +{ + "name": "ls", + "version": "1.0.0", + "description": "Implementation of the `ls` shell command", + "license": "ISC", + "author": "", + "type": "module", + "main": "ls.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { + "commander": "^15.1.0" + } +} diff --git a/implement-shell-tools/wc/package-lock.json b/implement-shell-tools/wc/package-lock.json new file mode 100644 index 000000000..a0de73d74 --- /dev/null +++ b/implement-shell-tools/wc/package-lock.json @@ -0,0 +1,25 @@ +{ + "name": "wc", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "wc", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "commander": "^15.1.0" + } + }, + "node_modules/commander": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.1.0.tgz", + "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==", + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + } + } +} diff --git a/implement-shell-tools/wc/package.json b/implement-shell-tools/wc/package.json new file mode 100644 index 000000000..7ffa695a5 --- /dev/null +++ b/implement-shell-tools/wc/package.json @@ -0,0 +1,15 @@ +{ + "name": "wc", + "version": "1.0.0", + "description": "Implementation of the `wc` tool in NodeJS", + "license": "ISC", + "author": "", + "type": "module", + "main": "wc.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { + "commander": "^15.1.0" + } +} diff --git a/implement-shell-tools/wc/wc.js b/implement-shell-tools/wc/wc.js new file mode 100644 index 000000000..431871e9b --- /dev/null +++ b/implement-shell-tools/wc/wc.js @@ -0,0 +1,76 @@ +import { program } from "commander"; +import { promises as fs } from "node:fs"; + +program + .argument("", "Files to count") + .name("wc") + .description("Print newline, word, and byte counts for each FILE.") + .option("-l, --lines", "Print the newline counts") + .option("-w, --words", "Print the word counts") + .option("-c, --bytes", "Print the byte counts"); + +program.parse(); + +const files = program.args; +const opts = program.opts(); + +const noFlags = !opts.lines && !opts.words && !opts.bytes; +const showLines = noFlags || Boolean(opts.lines); +const showWords = noFlags || Boolean(opts.words); +const showBytes = noFlags || Boolean(opts.bytes); + +function countBuffer(buffer) { + let lines = 0; + for (const byte of buffer) { + if (byte === 0x0a) lines++; + } + + const text = buffer.toString("utf8").trim(); + const words = text ? text.split(/\s+/).length : 0; + const bytes = buffer.length; + + return { lines, words, bytes }; +} + +function formatRow(counts, name, width) { + const cols = []; + if (showLines) cols.push(String(counts.lines).padStart(width, " ")); + if (showWords) cols.push(String(counts.words).padStart(width, " ")); + if (showBytes) cols.push(String(counts.bytes).padStart(width, " ")); + cols.push(name); + return cols.join(" "); +} + +async function main() { + const results = []; + const total = { lines: 0, words: 0, bytes: 0 }; + + for (const file of files) { + const buffer = await fs.readFile(file); + const counts = countBuffer(buffer); + results.push({ name: file, ...counts }); + total.lines += counts.lines; + total.words += counts.words; + total.bytes += counts.bytes; + } + + const columnCount = + Number(showLines) + Number(showWords) + Number(showBytes); + const width = + results.length === 1 && columnCount === 1 + ? 1 + : String(total.bytes).length; + + for (const result of results) { + console.log(formatRow(result, result.name, width)); + } + + if (results.length > 1) { + console.log(formatRow(total, "total", width)); + } +} + +main().catch((err) => { + console.error(err); + process.exit(1); +});