Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
67 changes: 67 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

program
.name("cat")
.description("Concatenate and print files")
.argument("<paths...>", "The file paths to process")
.option("-n", "Number lines")
.option("-b", "Number non-blank lines");

program.parse();

function parseNumberMode(options) {
if (options.b) {
return "non-blank";
} else if (options.n) {
return "all";
} else {
return "none";
}
}

function calculatePrefix(
numberMode,
nonBlankLineNumber,
lineNumberIncludingBlanks,
thisLineIsBlank,
) {
if (numberMode === "none") {
return "";
}
let lineNumber;
if (numberMode === "all") {
lineNumber = lineNumberIncludingBlanks;
} else {
if (thisLineIsBlank) {
return "";
} else {
lineNumber = nonBlankLineNumber;
}
}
return lineNumber.toString().padStart(6, " ") + " ";
}

const numberMode = parseNumberMode(program.opts());

for (const path of program.args) {
const content = await fs.readFile(path, "utf-8");
const lines = content.split("\n");
let nonBlankLineNumber = 1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (i === lines.length - 1 && line === "") {
break;
}
const prefix = calculatePrefix(
Comment thread
mirabellemorah marked this conversation as resolved.
Outdated
numberMode,
nonBlankLineNumber,
i + 1,
line === "",
);
console.log(`${prefix}${line}`);
if (line !== "") {
nonBlankLineNumber += 1;
}
}
}
21 changes: 21 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.

6 changes: 6 additions & 0 deletions implement-shell-tools/cat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"dependencies": {
"commander": "^15.0.0"
}
}
47 changes: 47 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { promises as fs } from "node:fs";
import process from "node:process";

const argv = process.argv.slice(2);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason you used commander in the cat example, but not here


const flags = [];
const paths = [];

for (const arg of argv) {
if (arg.startsWith("-")) {
flags.push(arg);
} else {
paths.push(arg);
}
}

const showOnePerLine = flags.includes("-1");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does the showOnePerLine const do?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now showOneLine (line 13), when true it loops through all the files and prints them on a single line if -1 flag is passed (line 39-45), if not they'd print as it often does in multiple columns in vs code

const showHiddenFiles = flags.includes("-a");

let targets = paths;
if (targets.length === 0) {
targets = ["."];
}

for (const target of targets) {
const info = await fs.stat(target);

let namesToShow;

if (info.isDirectory()) {
namesToShow = await fs.readdir(target);

if (showHiddenFiles) {
namesToShow = [".", "..", ...namesToShow];
} else {
namesToShow = namesToShow.filter((name) => !name.startsWith("."));
}

namesToShow.sort();
} else {
namesToShow = [target];
}

for (const name of namesToShow) {
console.log(name);
}
}
21 changes: 21 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.

6 changes: 6 additions & 0 deletions implement-shell-tools/ls/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"dependencies": {
"commander": "^15.0.0"
}
}
21 changes: 21 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.

6 changes: 6 additions & 0 deletions implement-shell-tools/wc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"dependencies": {
"commander": "^15.0.0"
}
}
70 changes: 70 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { program } from "commander";
import { promises as fs } from "node:fs";

const argv = process.argv.slice(2);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You import the commander program api, but don't use it. Is there a reason for that?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been corrected now to include arguments and options


const flags = argv.filter((arg) => arg.startsWith("-"));
const paths = argv.filter((arg) => !arg.startsWith("-"));

const showLines = flags.includes("-l");
const showWords = flags.includes("-w");
const showBytes = flags.includes("-c");

const noFlagsGiven = !showLines && !showWords && !showBytes;

const columns = [];
if (noFlagsGiven || showLines) columns.push("lines");
if (noFlagsGiven || showWords) columns.push("words");
if (noFlagsGiven || showBytes) columns.push("bytes");

function countStats(content) {
const lines = (content.match(/\n/g) || []).length;
const words = content.split(/\s+/).filter((w) => w.length > 0).length;
const bytes = Buffer.byteLength(content, "utf-8");
return { lines, words, bytes };
}

// Read every file and collect its stats
const rows = [];
for (const path of paths) {
const content = await fs.readFile(path, "utf-8");
rows.push({ path, stats: countStats(content) });
}

// If there's more than one file, we also need a "total" row at the end
if (rows.length > 1) {
const total = { lines: 0, words: 0, bytes: 0 };
for (const { stats } of rows) {
total.lines += stats.lines;
total.words += stats.words;
total.bytes += stats.bytes;
}
rows.push({ path: "total", stats: total });
}

const needsAlignment = columns.length > 1 || rows.length > 1;

let width = 0;
if (needsAlignment) {
for (const { stats } of rows) {
for (const col of columns) {
width = Math.max(width, String(stats[col]).length);
}
}

width = Math.max(width, 3);
}

for (const { path, stats } of rows) {
const parts = columns.map((col, index) => {
const text = String(stats[col]);
if (!needsAlignment) {
return text;
}
const padded = text.padStart(width, " ");

return index === 0 ? padded : " " + padded;
});

console.log(`${parts.join("")} ${path}`);
}
Loading