Skip to content

Commit 97b42cb

Browse files
Implement 'ls' command alternative with directory listing and options for hidden files
1 parent 85c60fc commit 97b42cb

1 file changed

Lines changed: 139 additions & 0 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.py

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import os
2+
import argparse
3+
import locale
4+
5+
6+
#set locale to the machine default setting
7+
locale.setlocale(locale.LC_ALL, '')
8+
9+
10+
parser = argparse.ArgumentParser(
11+
prog="ls",
12+
description="An alternative to the 'ls' command",
13+
)
14+
15+
parser.add_argument("directory", nargs="?", default=".", help="The directory to list (defaults to the current directory)")
16+
parser.add_argument("-1", "--single-column", action="store_true", help="List all files, one per line")
17+
parser.add_argument("-a", "--all", action="store_true", help="Include hidden files (those starting with .) in the listing")
18+
19+
args = parser.parse_args()
20+
21+
# check if path exists
22+
if not os.path.exists(args.directory):
23+
print(f"ls: cannot access '${args.directory}': No such file or directory")
24+
exit(1)
25+
26+
# check if path is a directory
27+
if os.path.isdir(args.directory):
28+
entries = os.listdir(args.directory)
29+
30+
# if -a flag set
31+
if args.all:
32+
entries.extend(['.', '..'])
33+
34+
# filter hidden files if -a (all) flag not set
35+
if not args.all:
36+
entries = [entry for entry in entries if not entry.startswith(".")]
37+
38+
# sort the entries using locale-aware comparison
39+
entries.sort(key =locale.strxfrm)
40+
41+
# print entries
42+
if args.single_column:
43+
for entry in entries:
44+
print(entry)
45+
else:
46+
print(" ".join(entries))
47+
48+
49+
50+
51+
52+
53+
54+
55+
56+
57+
58+
# .argument("[directory]", "The directory to list")
59+
# // Commander stores -1 as a string key that is accessed using options['1']
60+
# .option("-1", "List all files, one per line")
61+
# .option("-a, --all", "Include hidden files (those starting with .) in the listing")
62+
# .action(async (directory, options) => {
63+
# try {
64+
# // default to current directory if none is specified
65+
# const dir = directory || ".";
66+
67+
# await newLs(dir, options['1'], options.all);
68+
# } catch (err) {
69+
# console.error(`Error: ${err.message}`);
70+
# }
71+
# });
72+
73+
# program.parse(process.argv);
74+
75+
76+
# // filter files based on visibility (includeHidden = true includes all files)
77+
# function filterFiles(entries, includeHidden) {
78+
# return entries.filter(name =>
79+
# includeHidden ? true : !name.startsWith(".")
80+
# );
81+
# }
82+
83+
# // sort entries: directories first, then files,
84+
# function sortEntries(entries) {
85+
# const dirs = entries.filter(entry => {
86+
# try {
87+
# return fs.statSync(entry).isDirectory();
88+
# } catch (err) {
89+
# return false;
90+
# }
91+
# });
92+
93+
# const files = entries.filter(entry => {
94+
# try {
95+
# return fs.statSync(entry).isFile();
96+
# } catch (err) {
97+
# return false;
98+
# }
99+
# });
100+
# // localeCompare = take into account rules of system language/region for ordering
101+
# // undefined = uses the system default, numeric = regular number sorting, base = ignore case & accents
102+
# return entries.sort((a, b) =>
103+
# a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })
104+
# );
105+
# }
106+
107+
108+
# // print entries either one per line (-1 flag)
109+
# function printEntries(entries) {
110+
# entries.forEach(entry => console.log(entry));
111+
# }
112+
113+
114+
# async function newLs(directory, oneFlag, allFlag) {
115+
# try {
116+
# // check if path exists and determine if file or directory
117+
# const stats = await fs.stat(directory);
118+
119+
# // if a file, just print the name
120+
# if (stats.isFile()) {
121+
# console.log(directory);
122+
# return;
123+
# }
124+
125+
# // reads directory contents
126+
# const entries = await fs.readdir(directory);
127+
128+
# // Filter out hidden files if no -a flag
129+
# const filteredEntries = filterFiles(entries, allFlag);
130+
131+
# // Sort the entries using the sortEntries helper
132+
# const sortedEntries = sortEntries(filteredEntries);
133+
134+
# // print entries for -1 flag (one per line)
135+
# printEntries(sortedEntries);
136+
# } catch (err) {
137+
# console.error(`ls: cannot access '${directory}': ${err.message}`);
138+
# }
139+
# }

0 commit comments

Comments
 (0)