Skip to content

Commit 481e074

Browse files
committed
fix: handle per-file errors and empty file word count
Continue processing remaining files after an error. Set the process exit code to 1 if any file fails. Count zero words for empty files.
1 parent 3f651c8 commit 481e074

1 file changed

Lines changed: 24 additions & 18 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.mjs

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,15 @@ const total = {
2020
wordsCounter: 0,
2121
characterCounter: 0,
2222
};
23-
24-
try {
25-
for (const path of paths) {
23+
let hadError = false;
24+
for (const path of paths) {
25+
try {
2626
const content = await fs.readFile(path, "utf-8");
2727

2828
const linesCounter = content.split("\n").length - 1;
29-
const wordsCounter = content.trim().split(/\s+/).length;
29+
const trimmedContent = content.trim();
30+
const wordsCounter =
31+
trimmedContent === "" ? 0 : trimmedContent.split(/\s+/).length;
3032
const characterCounter = content.length;
3133

3234
total.linesCounter += linesCounter;
@@ -45,20 +47,24 @@ try {
4547
else {
4648
console.log(results.join(" ") + " " + path);
4749
}
50+
} catch (error) {
51+
console.error(error.message);
52+
hadError = true;
4853
}
49-
if (paths.length > 1) {
50-
if (!options.l && !options.w && !options.c) {
51-
console.log(
52-
` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`,
53-
);
54-
} else {
55-
const totalWithFlags = [];
56-
if (options.l) totalWithFlags.push(total.linesCounter);
57-
if (options.w) totalWithFlags.push(total.wordsCounter);
58-
if (options.c) totalWithFlags.push(total.characterCounter);
59-
console.log(totalWithFlags.join(" ") + " total");
60-
}
54+
}
55+
if (paths.length > 1) {
56+
if (!options.l && !options.w && !options.c) {
57+
console.log(
58+
` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`,
59+
);
60+
} else {
61+
const totalWithFlags = [];
62+
if (options.l) totalWithFlags.push(total.linesCounter);
63+
if (options.w) totalWithFlags.push(total.wordsCounter);
64+
if (options.c) totalWithFlags.push(total.characterCounter);
65+
console.log(totalWithFlags.join(" ") + " total");
6166
}
62-
} catch (error) {
63-
console.error(error.message);
67+
}
68+
if (hadError) {
69+
process.exitCode = 1;
6470
}

0 commit comments

Comments
 (0)