Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions implement-shell-tools/cat/cat.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

program.name("cat");
program.description("simple cat clone");
program.option("-n, --number", "number all output lines");
program.option("-b, --number-nonblank", "number non-empty output lines");
program.argument("[paths...]", "file(s) to process");
program.parse();

const { number, numberNonblank } = program.opts();
const paths = program.args;

async function processFile(path) {
try {
const stat = await fs.stat(path);

if (stat.isDirectory()) {
console.error(`${path}: Is a directory`);
return;
}

const content = await fs.readFile(path, { encoding: "utf-8" });
const lines = content.split("\n");
const hasTrailingNewLine = content.endsWith("\n");
const effectiveLines = hasTrailingNewLine ? lines.slice(0, -1) : lines;
let lineNumber = 1;

const processed = effectiveLines.map((line) => {
if (numberNonblank) {
if (line.trim() !== "") {
const result = `${lineNumber}\t${line}`;
lineNumber += 1;
return result;
}

return line;
}

if (number) {
const result = `${lineNumber}\t${line}`;
lineNumber += 1;
return result;
}

return line;
});

const output = processed.join("\n");
console.log(output);
} catch (error) {
console.error(`${path}: ${error.message}`);
}
}

try {
for (const path of paths) {
await processFile(path);
}
} catch (error) {
console.error(error.message);
}
25 changes: 25 additions & 0 deletions implement-shell-tools/cat/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions implement-shell-tools/cat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "cat",
"version": "1.0.0",
"type": "module",
"description": "You should already be familiar with the `cat` command line tool.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"commander": "^14.0.3"
}
}
45 changes: 45 additions & 0 deletions implement-shell-tools/ls/ls.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { program } from "commander";
import { promises as fs } from "node:fs";
import process from "node:process";

program.name("ls");
program.description("simple ls clone");
program.option("-1", "list one file per line");
program.option("-a", "show hidden files");
program.argument("<path>");
program.parse();

const argv = program.args;

if (argv.length != 1) {
console.error(`Expected exactly 1 argument (a path) to be passed but got ${argv.length}`);
process.exit(1);
}

const options = program.opts();
const path = argv[0];

try {
const stat = await fs.stat(path);

if (stat.isDirectory()) {
let files = await fs.readdir(path);

if (!options.a) {
files = files.filter((file) => !file.startsWith("."));
}

if (options["1"]) {
for (const file of files) {
console.log(file);
}
} else {
const output = files.join("\t");
console.log(output);
}
} else {
console.log(path);
}
} catch (err) {
console.log(err.message);
}
25 changes: 25 additions & 0 deletions implement-shell-tools/ls/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions implement-shell-tools/ls/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "commander",
"version": "1.0.0",
"type": "module",
"description": "You should already be familiar with the `ls` command line tool.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "^14.0.3"
}
}
25 changes: 25 additions & 0 deletions implement-shell-tools/wc/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions implement-shell-tools/wc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "wc",
"version": "1.0.0",
"type": "module",
"description": "You should already be familiar with the `wc` command line tool.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"commander": "^14.0.3"
}
}
75 changes: 75 additions & 0 deletions implement-shell-tools/wc/wc.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

program.name("wc");
program.description("simple wc clone");
program.option("-w, --words", "print word count");
program.option("-l, --lines", "print line count");
program.option("-c, --bytes", "print byte count");
program.argument("[paths...]", "file(s) to process");
program.parse();

const options = program.opts();
const paths = program.args;

const noFlags = !options.words && !options.lines && !options.bytes;
const showWords = options.words || noFlags;
const showLines = options.lines || noFlags;
const showBytes = options.bytes || noFlags;

function count(content) {
const lines = content.split("\n").length - 1;
const words = content.trim().split(/\s+/).filter(Boolean).length;
const bytes = Buffer.byteLength(content);

return { lines, words, bytes };
}

function formatCounts({ lines, words, bytes }, label = "") {
const output = [];

if (showLines) {
output.push(lines.toString().padStart(8));
}

if (showWords) {
output.push(words.toString().padStart(8));
}

if (showBytes) {
output.push(bytes.toString().padStart(8));
}

if (label) {
output.push(label);
}

return output.join(" ");
}

async function processFile(path) {
try {
const stat = await fs.stat(path);

if (stat.isDirectory()) {
console.error(`${path}: Is a directory`);
return;
}

const content = await fs.readFile(path, { encoding: "utf-8" });
const counts = count(content);
const output = formatCounts(counts, path);

console.log(output);
} catch (err) {
console.error(`${path}: ${err.message}`);
}
}

try {
for (const path of paths) {
await processFile(path);
}
} catch (err) {
console.error(err.message);
}
Loading