Skip to content

Commit 46111db

Browse files
committed
feat: implement ls with -a and -1 flags.
1 parent 87d907b commit 46111db

File tree

1 file changed

+45
-0
lines changed
  • implement-shell-tools/ls

1 file changed

+45
-0
lines changed

implement-shell-tools/ls/ls.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import os
2+
import sys
3+
4+
# assign flags
5+
show_all = "-a" in sys.argv
6+
one_column = "-1" in sys.argv
7+
8+
# Argument Filtering
9+
args = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
10+
# if no path given we use the current path
11+
path = args[0] if args else "."
12+
13+
try:
14+
# Get directory contents
15+
entries = os.listdir(path)
16+
17+
# Handle the -a flag
18+
if show_all:
19+
entries.extend([".", ".."])
20+
21+
# 5. Sort alphabetically, should used in ls.js as well
22+
entries.sort()
23+
24+
# Printing Logic
25+
for entry in entries:
26+
# Skip hidden files unless -a is passed
27+
if not show_all and entry.startswith("."):
28+
continue
29+
30+
if one_column:
31+
# -1 flag: Print vertically
32+
print(entry)
33+
else:
34+
# Standard: Print horizontally with spaces
35+
print(entry, end=" ")
36+
37+
# newline only if we not print horizontally
38+
if not one_column:
39+
print()
40+
41+
except FileNotFoundError:
42+
print(f"ls: cannot access '{path}': No such file or directory")
43+
except NotADirectoryError:
44+
# if a file ls just prints the filename
45+
print(path)

0 commit comments

Comments
 (0)