Skip to content

Commit 91a136b

Browse files
committed
complete ls exercise
1 parent 49c33ed commit 91a136b

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

  • implement-shell-tools/ls

implement-shell-tools/ls/ls.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#!/usr/bin/env python3
2+
3+
import locale
4+
import os
5+
import sys
6+
7+
8+
def parse_args(args):
9+
one_per_line = False
10+
show_all = False
11+
paths = []
12+
13+
for arg in args:
14+
if arg.startswith("-") and arg != "-":
15+
for flag in arg[1:]:
16+
if flag == "1":
17+
one_per_line = True
18+
elif flag == "a":
19+
show_all = True
20+
else:
21+
print(f"ls: invalid option -- '{flag}'", file=sys.stderr)
22+
sys.exit(1)
23+
else:
24+
paths.append(arg)
25+
26+
if not one_per_line:
27+
print("Usage: ls.py -1 [-a] [path]", file=sys.stderr)
28+
sys.exit(1)
29+
30+
if len(paths) > 1:
31+
print("Usage: ls.py -1 [-a] [path]", file=sys.stderr)
32+
sys.exit(1)
33+
34+
return show_all, (paths[0] if paths else ".")
35+
36+
37+
def list_entries(path, show_all):
38+
try:
39+
entries = os.listdir(path)
40+
except FileNotFoundError:
41+
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
42+
sys.exit(1)
43+
except NotADirectoryError:
44+
print(os.path.basename(path))
45+
return
46+
47+
if show_all:
48+
entries = [".", ".."] + entries
49+
else:
50+
entries = [name for name in entries if not name.startswith(".")]
51+
52+
locale.setlocale(locale.LC_COLLATE, "")
53+
entries = sorted(entries, key=locale.strxfrm)
54+
55+
for entry in entries:
56+
print(entry)
57+
58+
59+
def main():
60+
show_all, path = parse_args(sys.argv[1:])
61+
list_entries(path, show_all)
62+
63+
64+
if __name__ == "__main__":
65+
main()

0 commit comments

Comments
 (0)