Skip to content

Commit 05ee2d4

Browse files
committed
Review-ls
1 parent 5b8f305 commit 05ee2d4

1 file changed

Lines changed: 14 additions & 20 deletions

File tree

implement-shell-tools/ls/script-ls.py

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,50 +6,44 @@
66

77

88
def list_directory(path, show_all):
9-
"""List contents of a directory, respecting the -a and -1 options."""
10-
119
try:
12-
entries = os.listdir(path)
13-
except FileNotFoundError:
14-
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
10+
if os.path.isfile(path):
11+
# ls file.txt → just print the file name
12+
print(path)
13+
return
14+
15+
if os.path.isdir(path):
16+
entries = os.listdir(path)
17+
else:
18+
print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr)
19+
return
20+
21+
except PermissionError:
22+
print(f"ls: cannot open directory '{path}': Permission denied", file=sys.stderr)
1523
return
1624

1725
# If -a is not provided, hide dotfiles
1826
if not show_all:
1927
entries = [e for e in entries if not e.startswith(".")]
2028

21-
# Sort alphabetically like ls normally does
2229
entries.sort()
2330

24-
# Print one entry per line (-1 behaviour)
2531
for entry in entries:
2632
print(entry)
2733

28-
2934
def main():
3035
parser = argparse.ArgumentParser(description="Simple ls implementation")
3136
parser.add_argument(
3237
"-a",
3338
action="store_true",
3439
help="include directory entries whose names begin with a dot",
3540
)
36-
parser.add_argument(
37-
"-1",
38-
dest="one_per_line",
39-
action="store_true",
40-
help="list one file per line",
41-
)
41+
4242
parser.add_argument("path", nargs="?", default=".", help="directory to list")
4343

4444
args = parser.parse_args()
4545

46-
# Only -1 is supported, but it's always required in this assignment
47-
if not args.one_per_line:
48-
print("This program only supports the -1 option.", file=sys.stderr)
49-
sys.exit(1)
50-
5146
list_directory(args.path, show_all=args.a)
5247

53-
5448
if __name__ == "__main__":
5549
main()

0 commit comments

Comments
 (0)