|
5 | 5 | import argparse |
6 | 6 |
|
7 | 7 |
|
8 | | -def list_directory(path, show_all): |
| 8 | +def list_directory(path, show_all, one_per_line): |
9 | 9 | try: |
| 10 | + # If path is a file, just print it |
10 | 11 | if os.path.isfile(path): |
11 | | - # ls file.txt → just print the file name |
12 | 12 | print(path) |
13 | 13 | return |
14 | 14 |
|
| 15 | + # If path is a directory, list its contents |
15 | 16 | if os.path.isdir(path): |
16 | 17 | entries = os.listdir(path) |
17 | 18 | else: |
18 | | - print(f"ls: cannot access '{path}': No such file or directory", file=sys.stderr) |
| 19 | + print( |
| 20 | + f"ls: cannot access '{path}': No such file or directory", |
| 21 | + file=sys.stderr, |
| 22 | + ) |
19 | 23 | return |
20 | 24 |
|
21 | 25 | except PermissionError: |
22 | | - print(f"ls: cannot open directory '{path}': Permission denied", file=sys.stderr) |
| 26 | + print( |
| 27 | + f"ls: cannot open directory '{path}': Permission denied", |
| 28 | + file=sys.stderr, |
| 29 | + ) |
23 | 30 | return |
24 | 31 |
|
25 | | - # If -a is not provided, hide dotfiles |
| 32 | + # Hide dotfiles unless -a is used |
26 | 33 | if not show_all: |
27 | 34 | entries = [e for e in entries if not e.startswith(".")] |
28 | 35 |
|
29 | 36 | entries.sort() |
30 | 37 |
|
31 | | - for entry in entries: |
32 | | - print(entry) |
| 38 | + # Output formatting |
| 39 | + if one_per_line: |
| 40 | + for entry in entries: |
| 41 | + print(entry) |
| 42 | + else: |
| 43 | + print(" ".join(entries)) |
| 44 | + |
33 | 45 |
|
34 | 46 | def main(): |
35 | 47 | parser = argparse.ArgumentParser(description="Simple ls implementation") |
| 48 | + |
36 | 49 | parser.add_argument( |
37 | 50 | "-a", |
38 | 51 | action="store_true", |
39 | 52 | help="include directory entries whose names begin with a dot", |
40 | 53 | ) |
41 | 54 |
|
42 | | - parser.add_argument("path", nargs="?", default=".", help="directory to list") |
| 55 | + parser.add_argument( |
| 56 | + "-1", |
| 57 | + dest="one_per_line", |
| 58 | + action="store_true", |
| 59 | + help="list one file per line", |
| 60 | + ) |
| 61 | + |
| 62 | + parser.add_argument( |
| 63 | + "path", |
| 64 | + nargs="?", |
| 65 | + default=".", |
| 66 | + help="directory or file to list", |
| 67 | + ) |
43 | 68 |
|
44 | 69 | args = parser.parse_args() |
45 | 70 |
|
46 | | - list_directory(args.path, show_all=args.a) |
| 71 | + list_directory( |
| 72 | + args.path, |
| 73 | + show_all=args.a, |
| 74 | + one_per_line=args.one_per_line, |
| 75 | + ) |
| 76 | + |
47 | 77 |
|
48 | 78 | if __name__ == "__main__": |
49 | 79 | main() |
0 commit comments