|
| 1 | +import { program } from "commander"; |
1 | 2 | import { promises as fs } from "node:fs"; |
2 | | -import process from "node:process"; |
3 | 3 |
|
4 | | -const argv = process.argv.slice(2); |
| 4 | +program |
| 5 | + .name("check-for-ls") |
| 6 | + .description("Implement my own version of ls") |
| 7 | + .argument("[paths...]", "The file paths to process") |
| 8 | + .option("-1, --one", "This lists one file per line") |
| 9 | + .option("-a", "This shows all files"); |
5 | 10 |
|
6 | | -const flags = []; |
7 | | -const paths = []; |
| 11 | +program.parse(); |
8 | 12 |
|
9 | | -for (const arg of argv) { |
10 | | - if (arg.startsWith("-")) { |
11 | | - flags.push(arg); |
12 | | - } else { |
13 | | - paths.push(arg); |
14 | | - } |
15 | | -} |
| 13 | +const showOneLine = program.opts().one; |
| 14 | +const showAllFiles = program.opts().a; |
16 | 15 |
|
17 | | -const showOnePerLine = flags.includes("-1"); |
18 | | -const showHiddenFiles = flags.includes("-a"); |
| 16 | +const paths = program.args; |
19 | 17 |
|
20 | | -let targets = paths; |
21 | | -if (targets.length === 0) { |
22 | | - targets = ["."]; |
| 18 | +let filePath = paths; |
| 19 | +if (filePath.length === 0) { |
| 20 | + filePath = ["."]; |
23 | 21 | } |
24 | 22 |
|
25 | | -for (const target of targets) { |
| 23 | +for (const target of filePath) { |
26 | 24 | const info = await fs.stat(target); |
27 | 25 |
|
28 | | - let namesToShow; |
29 | | - |
| 26 | + let showFiles; |
30 | 27 | if (info.isDirectory()) { |
31 | | - namesToShow = await fs.readdir(target); |
| 28 | + showFiles = await fs.readdir(target); |
32 | 29 |
|
33 | | - if (showHiddenFiles) { |
34 | | - namesToShow = [".", "..", ...namesToShow]; |
| 30 | + if (showAllFiles) { |
| 31 | + showFiles = [".", "..", ...showFiles]; |
35 | 32 | } else { |
36 | | - namesToShow = namesToShow.filter((name) => !name.startsWith(".")); |
| 33 | + showFiles = showFiles.filter((name) => !name.startsWith(".")); |
37 | 34 | } |
38 | | - |
39 | | - namesToShow.sort(); |
| 35 | + showFiles.sort(); |
40 | 36 | } else { |
41 | | - namesToShow = [target]; |
| 37 | + showFiles = [target]; |
42 | 38 | } |
43 | 39 |
|
44 | | - for (const name of namesToShow) { |
45 | | - console.log(name); |
| 40 | + for (const file of showFiles) { |
| 41 | + console.log(file); |
46 | 42 | } |
47 | 43 | } |
0 commit comments