Skip to content

Commit 94a9be8

Browse files
committed
fixed ls
1 parent 9945453 commit 94a9be8

File tree

1 file changed

+24
-4
lines changed
  • implement-shell-tools/ls

1 file changed

+24
-4
lines changed

implement-shell-tools/ls/ls.js

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@ program
55
.name("list files and directories")
66
.option("-a", "show hidden files")
77
.option("-1", "force displaying each item in a new line")
8-
.argument("<paths...>", "path of directory");
8+
.argument("[paths...]", "path of directory");
99

1010
program.parse();
1111

1212
const showHiddenFiles = program.opts()["a"];
1313
const showFilesInLines = program.opts()["1"];
14-
const fetchedDirectories = await fetchDirectoriesFunc(program.args);
14+
const paths = program.args.length ? program.args : ["."];
15+
16+
const fetchedDirectories = await fetchDirectoriesFunc(paths);
1517

1618
console.log(formatDisplay(fetchedDirectories));
1719

@@ -35,9 +37,27 @@ async function fetchDirectoriesFunc(directories) {
3537
for (const folderName of directories) {
3638
let files = await fs.readdir(folderName);
3739

38-
if (showHiddenFiles) files.unshift(".", "..");
40+
// sort by name + but those starting with . at the end
41+
files.sort((a, b) => {
42+
const isHiddenA = a.startsWith(".");
43+
const isHiddenB = b.startsWith(".");
44+
45+
if (isHiddenA !== isHiddenB) {
46+
return isHiddenA ? 1 : -1;
47+
}
48+
49+
const cleanA = a.replace(/^\.+/, "");
50+
const cleanB = b.replace(/^\.+/, "");
51+
52+
return cleanA.localeCompare(cleanB);
53+
});
54+
55+
if (showHiddenFiles) {
56+
files.unshift(".", "..");
57+
} else {
58+
files = files.filter((fileName) => !fileName.startsWith("."));
59+
}
3960

40-
files.sort((a, b) => a.localeCompare(b));
4161
result.push({
4262
folderName,
4363
files,

0 commit comments

Comments
 (0)