Skip to content

Commit cc40d4b

Browse files
committed
Complete implementing ls shell-tools.
1 parent 8b8a2e6 commit cc40d4b

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
const fs = require("fs");
2+
const pathModule = require("path");
3+
4+
const args = process.argv.slice(2);
5+
6+
let mode = "normal";
7+
let showHidden = false;
8+
let paths = [];
9+
10+
for (const arg of args) {
11+
if (arg === "-1") {
12+
mode = "onePerLine";
13+
} else if (arg === "-a") {
14+
showHidden = true;
15+
} else {
16+
paths.push(arg);
17+
}
18+
}
19+
20+
if (paths.length === 0) {
21+
paths.push(".");
22+
}
23+
24+
function listDirectory(dir) {
25+
let items = fs.readdirSync(dir);
26+
27+
if (showHidden) {
28+
items.unshift(".", "..");
29+
} else {
30+
items = items.filter(item => !item.startsWith("."));
31+
}
32+
33+
if (mode === "onePerLine") {
34+
items.forEach(item => console.log(item));
35+
} else {
36+
console.log(items.join(" "));
37+
}
38+
}
39+
40+
function expandWildcard(input) {
41+
if (!input.includes("*")) {
42+
return [input];
43+
}
44+
const dir = pathModule.dirname(input);
45+
const pattern = pathModule.basename(input);
46+
const files = fs.readdirSync(dir);
47+
48+
return files
49+
.filter(file => {
50+
if (pattern === "*") {
51+
return showHidden || !file.startsWith(".");
52+
}
53+
54+
return file === pattern;
55+
})
56+
.map(file => pathModule.join(dir, file));
57+
}
58+
59+
for (const originalPath of paths) {
60+
61+
const expandedPaths = expandWildcard(originalPath);
62+
63+
for (const currentPath of expandedPaths) {
64+
65+
const info = fs.statSync(currentPath);
66+
67+
if (info.isDirectory()) {
68+
listDirectory(currentPath);
69+
}
70+
71+
else if (info.isFile()) {
72+
console.log(pathModule.basename(currentPath));
73+
}
74+
75+
}
76+
77+
}

0 commit comments

Comments
 (0)