generated from CodeYourFuture/Module-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 42
London | SDC-Nov-25 | Pezhman Azizi | Sprint 3 | Implement shell tools (cat, ls, wc) In JavaScript With NodeJS #302
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Pezhman-Azizi
wants to merge
3
commits into
CodeYourFuture:main
Choose a base branch
from
Pezhman-Azizi:implement-shell-tools-js
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| // A simple reimplementation of `cat` in NodeJS. | ||
| // Supports: | ||
| // node cat.js sample-files/1.txt | ||
| // node cat.js -n sample-files/1.txt | ||
| // node cat.js -b sample-files/3.txt | ||
| // node cat.js sample-files/*.txt | ||
| // | ||
| // -n : number all lines | ||
| // -b : number non-empty lines | ||
|
|
||
| const fs = require("fs"); | ||
| const path = require("path"); | ||
|
|
||
| // -------- argument parsing -------- | ||
| const args = process.argv.slice(2); | ||
|
|
||
| if (args.length === 0) { | ||
| console.error("Usage: node cat.js [-n | -b] <file> [<file> ...]"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| let numberAll = false; | ||
| let numberNonBlank = false; | ||
| let fileArgs = []; | ||
|
|
||
| // Very small argument parser: | ||
| // We only care about -n or -b as the FIRST arg (like the coursework examples). | ||
| if (args[0] === "-n") { | ||
| numberAll = true; | ||
| fileArgs = args.slice(1); | ||
| } else if (args[0] === "-b") { | ||
| numberNonBlank = true; | ||
| fileArgs = args.slice(1); | ||
| } else { | ||
| fileArgs = args; | ||
| } | ||
|
|
||
| if (fileArgs.length === 0) { | ||
| console.error("cat.js: no input files"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // -------- helper functions -------- | ||
|
|
||
| /** | ||
| * Format a single line with the correct line number, if needed. | ||
| * | ||
| * @param {string} line - line text (without the trailing newline) | ||
| * @param {number} currentLineNumber - global line counter | ||
| * @param {boolean} numberAll - true if -n | ||
| * @param {boolean} numberNonBlank - true if -b | ||
| * @returns {{ text: string, nextLineNumber: number }} | ||
| */ | ||
| function formatLine(line, currentLineNumber, numberAll, numberNonBlank) { | ||
| let output = ""; | ||
| let nextLineNumber = currentLineNumber; | ||
|
|
||
| const isBlank = line === ""; | ||
|
|
||
| if (numberAll) { | ||
| // Always number every line | ||
| output = | ||
| currentLineNumber.toString().padStart(6, " ") + "\t" + line; | ||
| nextLineNumber++; | ||
| } else if (numberNonBlank) { | ||
| // Number only non-blank lines | ||
| if (isBlank) { | ||
| output = line; // No number, just the blank line | ||
| } else { | ||
| output = | ||
| currentLineNumber.toString().padStart(6, " ") + "\t" + line; | ||
| nextLineNumber++; | ||
| } | ||
| } else { | ||
| // No numbering | ||
| output = line; | ||
| } | ||
|
|
||
| return { text: output, nextLineNumber }; | ||
| } | ||
|
|
||
| /** | ||
| * Print a file to stdout according to the options. | ||
| * | ||
| * @param {string} filePath | ||
| * @param {number} startLineNumber | ||
| * @returns {number} next line number | ||
| */ | ||
| function printFile(filePath, startLineNumber) { | ||
| let content; | ||
|
|
||
| try { | ||
| content = fs.readFileSync(filePath, "utf8"); | ||
| } catch (err) { | ||
| console.error(`cat.js: ${filePath}: ${err.message}`); | ||
| return startLineNumber; | ||
| } | ||
|
|
||
| const lines = content.split("\n"); | ||
| let lineNumber = startLineNumber; | ||
|
|
||
| for (let i = 0; i < lines.length; i++) { | ||
| const line = lines[i]; | ||
| const { text, nextLineNumber } = formatLine( | ||
| line, | ||
| lineNumber, | ||
| numberAll, | ||
| numberNonBlank | ||
| ); | ||
| lineNumber = nextLineNumber; | ||
|
|
||
| // Re-add the newline we lost when splitting | ||
| process.stdout.write(text); | ||
|
|
||
| // Avoid adding an extra newline at very end if the file | ||
| // doesn't end with \n — Node's split keeps the last segment. | ||
| if (i < lines.length - 1 || content.endsWith("\n")) { | ||
| process.stdout.write("\n"); | ||
| } | ||
| } | ||
|
|
||
| return lineNumber; | ||
| } | ||
|
|
||
| // -------- main execution -------- | ||
|
|
||
| let globalLineNumber = 1; | ||
|
|
||
| for (const file of fileArgs) { | ||
| // Shell expands *.txt, so here we just get each file path. | ||
| const resolvedPath = path.resolve(file); | ||
| globalLineNumber = printFile(resolvedPath, globalLineNumber); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| const fs = require("fs"); | ||
| const path = require("path"); | ||
|
|
||
| // -------- args parsing -------- | ||
| const args = process.argv.slice(2); | ||
|
|
||
| let onePerLine = false; // -1 | ||
| let showAll = false; // -a | ||
| let targets = []; | ||
|
|
||
| for (const arg of args) { | ||
| if (arg === "-1") onePerLine = true; | ||
| else if (arg === "-a") showAll = true; | ||
| else targets.push(arg); | ||
| } | ||
|
|
||
| // Coursework only tests -1 variants, so enforce it clearly | ||
| if (!onePerLine) { | ||
| console.error("Usage: node ls.js -1 [-a] [path]"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| if (targets.length === 0) targets = ["."]; | ||
| if (targets.length > 1) { | ||
| console.error("ls.js: only one path is supported in this exercise"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const target = targets[0]; | ||
|
|
||
| // -------- helpers -------- | ||
| function sortLikeLs(names) { | ||
| return names.sort((a, b) => a.localeCompare(b)); | ||
| } | ||
|
|
||
| function listDir(dirPath) { | ||
| let entries; | ||
| try { | ||
| entries = fs.readdirSync(dirPath, { withFileTypes: false }); | ||
| } catch (err) { | ||
| console.error(`ls.js: cannot access '${dirPath}': ${err.message}`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // readdirSync does NOT include "." and ".." — ls -a does. | ||
| if (showAll) { | ||
| // keep dotfiles + add . and .. | ||
| entries = [".", "..", ...entries]; | ||
| } else { | ||
| // hide dotfiles | ||
| entries = entries.filter((name) => !name.startsWith(".")); | ||
| } | ||
|
|
||
| entries = sortLikeLs(entries); | ||
|
|
||
| // -1 => one per line | ||
| for (const name of entries) { | ||
| process.stdout.write(name + "\n"); | ||
| } | ||
| } | ||
|
|
||
| function listFile(filePath) { | ||
| // ls -1 file => prints the file name | ||
| process.stdout.write(path.basename(filePath) + "\n"); | ||
| } | ||
|
|
||
| // -------- main -------- | ||
| let stat; | ||
| try { | ||
| stat = fs.statSync(target); | ||
| } catch (err) { | ||
| console.error(`ls.js: cannot access '${target}': ${err.message}`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| if (stat.isDirectory()) listDir(target); | ||
| else listFile(target); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| const fs = require("fs"); | ||
| const path = require("path"); | ||
|
|
||
| // -------- argument parsing -------- | ||
| const args = process.argv.slice(2); | ||
|
|
||
| let countLines = false; | ||
| let countWords = false; | ||
| let countBytes = false; | ||
| let files = []; | ||
|
|
||
| // flags can appear in any order | ||
| for (const arg of args) { | ||
| if (arg === "-l") countLines = true; | ||
| else if (arg === "-w") countWords = true; | ||
| else if (arg === "-c") countBytes = true; | ||
| else files.push(arg); | ||
| } | ||
|
|
||
| if (files.length === 0) { | ||
| console.error("Usage: wc [-l] [-w] [-c] <file> [file...]"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // If no flags → behave like plain `wc` | ||
| if (!countLines && !countWords && !countBytes) { | ||
| countLines = true; | ||
| countWords = true; | ||
| countBytes = true; | ||
| } | ||
|
|
||
| // -------- helpers -------- | ||
| function countFile(filePath) { | ||
| let content; | ||
| let buffer; | ||
|
|
||
| try { | ||
| buffer = fs.readFileSync(filePath); | ||
| content = buffer.toString("utf8"); | ||
| } catch (err) { | ||
| console.error(`wc.js: ${filePath}: ${err.message}`); | ||
| return null; | ||
| } | ||
|
|
||
| const lines = content.split("\n").length - 1; | ||
| const words = content.trim() === "" | ||
| ? 0 | ||
| : content.trim().split(/\s+/).length; | ||
| const bytes = buffer.length; | ||
|
|
||
| return { lines, words, bytes }; | ||
| } | ||
|
|
||
| function formatOutput(counts, fileName) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea to move this to its own function! |
||
| const parts = []; | ||
|
|
||
| if (countLines) parts.push(counts.lines.toString().padStart(7, " ")); | ||
| if (countWords) parts.push(counts.words.toString().padStart(7, " ")); | ||
| if (countBytes) parts.push(counts.bytes.toString().padStart(7, " ")); | ||
|
|
||
| parts.push(" " + fileName); | ||
| return parts.join(""); | ||
| } | ||
|
|
||
| // -------- main -------- | ||
| let total = { lines: 0, words: 0, bytes: 0 }; | ||
| let validFileCount = 0; | ||
|
|
||
| for (const file of files) { | ||
| const counts = countFile(file); | ||
| if (!counts) continue; | ||
|
|
||
| validFileCount++; | ||
|
|
||
| total.lines += counts.lines; | ||
| total.words += counts.words; | ||
| total.bytes += counts.bytes; | ||
|
|
||
| process.stdout.write(formatOutput(counts, file) + "\n"); | ||
| } | ||
|
|
||
| // Print total if multiple files | ||
| if (validFileCount > 1) { | ||
| process.stdout.write(formatOutput(total, "total") + "\n"); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 only focus on -1 here?