Skip to content

Commit 129b9d7

Browse files
committed
finished custom ls logic but it can be improved
1 parent f8cd206 commit 129b9d7

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

implement-shell-tools/ls/custom_ls.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,40 @@
22
import os
33
import re
44

5+
def sort_list(file_list):
6+
return sorted(file_list, key=lambda file_name: re.sub(r"^\.", "", file_name).lower())
7+
8+
def format_list(file_list):
9+
return [f"\033[1;34m{file}\033[0m" if os.path.isdir(os.path.join(args.path, file)) else file for file in file_list]
10+
511
parser = argparse.ArgumentParser(
612
prog="custom ls in python",
713
description="trying to match behaviour as the actual ls"
814
)
915

10-
parser.add_argument("-a", "--show_hidden", help="show hidden files")
16+
parser.add_argument("-a", "--show_hidden", action="store_true", help="show hidden files")
17+
parser.add_argument("-1", "--one_item", action="store_true", help="show one item per one line")
1118
parser.add_argument("path", help="directory path to process", nargs="?", default=".")
1219

1320
args = parser.parse_args()
1421

1522
files_array = os.listdir(args.path)
1623

24+
sorted_files_array = sort_list(files_array)
25+
1726
if (not args.show_hidden):
18-
filtered_list = [file for file in files_array if re.match(r"^(?!\.)", file)]
19-
sorted_file_list = sorted(filtered_list, key=lambda file_name: file_name.lower())
20-
formatted_list = [f"\033[1;34m{file}\033[0m" if os.path.isdir(os.path.join(args.path, file)) else file for file in sorted_file_list]
21-
print(" ".join(formatted_list))
27+
filtered_list = [file for file in sorted_files_array if re.match(r"^(?!\.)", file)]
28+
formatted_list = format_list(filtered_list)
29+
if (args.one_item):
30+
for item in formatted_list:
31+
print(item)
32+
else:
33+
print(" ".join(formatted_list))
34+
else:
35+
sorted_hidden_list = [".", "..", *sorted_files_array]
36+
formatted_hidden_list = format_list(sorted_hidden_list)
37+
if (args.one_item):
38+
for item in formatted_hidden_list:
39+
print(item)
40+
else:
41+
print(" ".join(formatted_hidden_list))

0 commit comments

Comments
 (0)