22import os
33import 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+
511parser = 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" )
1118parser .add_argument ("path" , help = "directory path to process" , nargs = "?" , default = "." )
1219
1320args = parser .parse_args ()
1421
1522files_array = os .listdir (args .path )
1623
24+ sorted_files_array = sort_list (files_array )
25+
1726if (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