Skip to content

Commit 437d359

Browse files
committed
supporting on/off -1
1 parent 05ee2d4 commit 437d359

1 file changed

Lines changed: 39 additions & 9 deletions

File tree

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

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,75 @@
55
import argparse
66

77

8-
def list_directory(path, show_all):
8+
def list_directory(path, show_all, one_per_line):
99
try:
10+
# If path is a file, just print it
1011
if os.path.isfile(path):
11-
# ls file.txt → just print the file name
1212
print(path)
1313
return
1414

15+
# If path is a directory, list its contents
1516
if os.path.isdir(path):
1617
entries = os.listdir(path)
1718
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+
)
1923
return
2024

2125
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+
)
2330
return
2431

25-
# If -a is not provided, hide dotfiles
32+
# Hide dotfiles unless -a is used
2633
if not show_all:
2734
entries = [e for e in entries if not e.startswith(".")]
2835

2936
entries.sort()
3037

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+
3345

3446
def main():
3547
parser = argparse.ArgumentParser(description="Simple ls implementation")
48+
3649
parser.add_argument(
3750
"-a",
3851
action="store_true",
3952
help="include directory entries whose names begin with a dot",
4053
)
4154

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+
)
4368

4469
args = parser.parse_args()
4570

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+
4777

4878
if __name__ == "__main__":
4979
main()

0 commit comments

Comments
 (0)