Skip to content

Commit 06aacde

Browse files
committed
improved logic for sorting the file order and added function for formatting directory
1 parent ae796c4 commit 06aacde

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

implement-shell-tools/ls/customLs.js

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,53 @@ const argumentsArray = program.args;
1515

1616
const path = argumentsArray[0] || "./";
1717

18+
async function formatFileName(base, fileName) {
19+
try {
20+
const fullPath = `${base.endsWith("/") ? base : base + "/"}${fileName}`;
21+
const stats = await fs.stat(fullPath);
22+
if (stats.isDirectory()) {
23+
return `\x1b[1;34m${fileName}\x1b[0m`;
24+
}
25+
return fileName;
26+
} catch (error) {
27+
return fileName;
28+
}
29+
}
30+
1831
try {
1932
const files = await fs.readdir(path);
2033

21-
const sortedFiles = files.sort((a, b) => a.localeCompare(b));
34+
const sortedFiles = files.sort((a, b) => {
35+
const cleanA = a.replace(/^\./, "");
36+
const cleanB = b.replace(/^\./, "");
37+
return cleanA.localeCompare(cleanB, undefined, { sensitivity: "base" });
38+
});
2239

2340
const options = program.opts();
2441

2542
let renderingFiles = [];
2643

2744
if (options.showHidden) {
28-
renderingFiles = sortedFiles;
45+
renderingFiles = [".", "..", ...sortedFiles];
2946
} else {
3047
renderingFiles = sortedFiles.filter((file) => !/^\./.test(file));
3148
}
3249

3350
if (options.oneFile) {
3451
for (let file of renderingFiles) {
35-
console.log(file);
52+
console.log(await formatFileName(path, file));
3653
}
3754
} else {
38-
console.log(renderingFiles.join(" "));
55+
const formatted = await Promise.all(
56+
renderingFiles.map((fileName) => {
57+
return formatFileName(path, fileName);
58+
}),
59+
);
60+
console.log(formatted.join(" "));
3961
}
4062
} catch (error) {
41-
const state = await fs.stat(path).catch(() => null);
42-
if (state && state.isFile()) {
63+
const stats = await fs.stat(path).catch(() => null);
64+
if (stats && stats.isFile()) {
4365
console.log(path);
4466
} else {
4567
console.log(

0 commit comments

Comments
 (0)