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
45 changes: 45 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";

async function main() {
const { values, positionals: files } = parseArgs({
options: {
number: { type: "boolean", short: "n" },
numberNonBlank: { type: "boolean", short: "b" },
},
allowPositionals: true,
});

for (const file of files) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

What does cat output when it receives no filenames, such as in a pipeline?

To "like" or "dislike" this comment, please follow this link

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.

With no filenames, cat reads from standard input and prints what it receives. In a pipeline, that’s the output from the previous command. My version currently prints nothing because the file loop never runs.

try {
const contents = await readFile(file);

if (!values.number && !values.numberNonBlank) {
process.stdout.write(contents);
continue;
}

const lines = contents.toString("utf8").match(/[^\n]*\n|[^\n]+$/g) ?? [];
let lineNumber = 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

How should line numbering behave across two files that cat -n prints as one stream?

To "like" or "dislike" this comment, please follow this link

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.

The numbering should carry on across both files. If the first file doesn’t end with a newline, the second file’s text continues on the same numbered line.


for (const line of lines) {
if (values.numberNonBlank && line === "\n") {
process.stdout.write(line);
continue;
}

const number = String(lineNumber).padStart(6);
process.stdout.write(`${number}\t${line}`);
lineNumber += 1;
}
} catch (error) {
console.error(`cat: ${error.message}`);
process.exitCode = 1;
}
}
}

main().catch((error) => {
console.error(`cat: ${error.message}`);
process.exitCode = 1;
});
76 changes: 76 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { readdir, stat } from "node:fs/promises";
import { parseArgs } from "node:util";

function printEntries(entries, onePerLine) {
if (entries.length === 0) return;

if (onePerLine || !process.stdout.isTTY) {
console.log(entries.join("\n"));
return;
}

const longestName = Math.max(...entries.map((entry) => entry.length));
const columnWidth = Math.ceil((longestName + 1) / 8) * 8;
const columns = Math.max(1, Math.floor(process.stdout.columns / columnWidth));
const rows = Math.ceil(entries.length / columns);

for (let row = 0; row < rows; row += 1) {
let line = "";

for (let index = row; index < entries.length; index += rows) {
const entry = entries[index];
line += entry;

if (index + rows < entries.length) {
const tabs = Math.ceil((columnWidth - entry.length) / 8);
line += "\t".repeat(tabs);
}
}

console.log(line);
}
}

async function main() {
const { values, positionals } = parseArgs({
options: {
"one-per-line": { type: "boolean", short: "1" },
all: { type: "boolean", short: "a" },
},
allowPositionals: true,
});

const paths = positionals.length === 0 ? ["."] : positionals;
const files = [];
const directories = [];

for (const path of [...paths].sort()) {
const info = await stat(path);

if (info.isDirectory()) {
directories.push(path);
} else {
files.push(path);
}
}

const onePerLine = values["one-per-line"];
printEntries(files, onePerLine);

for (const [index, directory] of directories.entries()) {
if (files.length > 0 || index > 0) console.log("");
if (paths.length > 1) console.log(`${directory}:`);

const names = await readdir(directory);
const entries = values.all
? [".", "..", ...names]
: names.filter((name) => !name.startsWith("."));

printEntries(entries.sort(), onePerLine);
}
}

main().catch((error) => {
console.error(`ls: ${error.message}`);
process.exitCode = 1;
});
60 changes: 60 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";

function count(contents) {
const text = contents.toString("utf8");

return {
lines: (text.match(/\n/g) ?? []).length,
words: (text.match(/\S+/g) ?? []).length,
bytes: contents.length,
};
}

async function main() {
const { values, positionals: files } = parseArgs({
options: {
lines: { type: "boolean", short: "l" },
words: { type: "boolean", short: "w" },
bytes: { type: "boolean", short: "c" },
},
allowPositionals: true,
});

const showAll = !values.lines && !values.words && !values.bytes;
const totals = { lines: 0, words: 0, bytes: 0 };

function printCounts(counts, label) {
const columns = [];

if (showAll || values.lines) columns.push(counts.lines);
if (showAll || values.words) columns.push(counts.words);
if (showAll || values.bytes) columns.push(counts.bytes);

const formattedCounts = columns
.map((number) => String(number).padStart(8))
.join("");

console.log(`${formattedCounts} ${label}`);
}

for (const file of files) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

What counts does wc produce when it receives piped input without any filenames?

To "like" or "dislike" this comment, please follow this link

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.

wc reads from standard input when I give it no filenames. By default it prints the line, word, and byte counts. My version prints nothing because the file loop never runs.

const contents = await readFile(file);
const counts = count(contents);

printCounts(counts, file);

totals.lines += counts.lines;
totals.words += counts.words;
totals.bytes += counts.bytes;
}

if (files.length > 1) {
printCounts(totals, "total");
}
}

main().catch((error) => {
console.error(`wc: ${error.message}`);
process.exitCode = 1;
});
Loading