Skip to content

Commit 3f81d49

Browse files
committed
feat(ls): support multiple file paths and improve visibility filtering
1 parent b9817fc commit 3f81d49

1 file changed

Lines changed: 42 additions & 9 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.js

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ program
55
.name("ls")
66
.description("List directory contents")
77
.argument(
8-
"[path]",
8+
"[paths...]",
99
"The file path to process (defaults to current directory)",
1010
)
1111
.option("-a", "Include directory entries whose names begin with a dot ('.').")
@@ -14,20 +14,53 @@ program
1414
program.parse();
1515

1616
try {
17+
let filePaths = program.args;
18+
if (!filePaths || filePaths.length === 0) {
19+
filePaths = ["."];
20+
}
21+
1722
const options = program.opts();
18-
const [filePathArg] = program.args;
23+
const includeHidden = Boolean(options.a);
24+
const onePerLine = Boolean(options["1"]);
25+
26+
const result = { files: [], dirs: {} };
27+
28+
for (const filePath of filePaths) {
29+
const stats = await fs.stat(filePath);
30+
if (stats.isFile()) result.files.push(filePath);
31+
if (stats.isDirectory()) {
32+
result.dirs[filePath] = await fs.readdir(filePath);
33+
}
34+
}
1935

20-
const filePath = filePathArg || process.cwd();
21-
let files = await fs.readdir(filePath);
36+
const filterHidden = (files) => files.filter((file) => !file.startsWith("."));
2237

23-
if (!options.a) files = files.filter((file) => !file.startsWith("."));
38+
const getVisibleEntries = (files) =>
39+
includeHidden ? files : filterHidden(files);
2440

25-
if (options["1"]) {
26-
for (const file of files) {
27-
console.log(file);
41+
const formatEntries = (files) => {
42+
if (files.length === 0) return;
43+
console.log(files.join(onePerLine ? "\n" : "\t"));
44+
};
45+
46+
result.files = getVisibleEntries(result.files);
47+
48+
if (filePaths.length === 1) {
49+
let entries = [...result.files];
50+
51+
for (const [dir, contents] of Object.entries(result.dirs)) {
52+
const filtered = getVisibleEntries(contents);
53+
entries = entries.concat(filtered);
2854
}
55+
formatEntries(entries);
2956
} else {
30-
console.log(...files);
57+
formatEntries(result.files);
58+
59+
for (const [dir, contents] of Object.entries(result.dirs)) {
60+
console.log("\n" + dir + ":");
61+
const filtered = getVisibleEntries(contents);
62+
formatEntries(filtered);
63+
}
3164
}
3265
} catch (err) {
3366
console.error(err.message);

0 commit comments

Comments
 (0)