This repository has been archived by the owner on Jan 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsi
executable file
·346 lines (294 loc) · 13.2 KB
/
lsi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/env python3
"""ls command alternative.
Output is either cleanly formatted table or
string of null terminated file names parseable by xargs command.
Default behaviour is to show only non-hidden files and directories of
directory passed or current directory if no directory is given, in table format.
Learn more by passing -h or --help option.
NOTE: requires python v3.3+; written for UNIX like OS
REAL Programmers don't need comments, for them the code itself is obvious,
but if you aren't one of them, here you go.
"""
import argparse
import os
import sys
import shutil
# get size of the terminal for output in table format
terminal_column_size, terminal_row_size = shutil.get_terminal_size()
parser = argparse.ArgumentParser(description="""ls command alternative.
Output is either cleanly formatted table or
string of null terminated file names parseable by xargs command.
Default behaviour is to show only non-hidden files and directories of
directory passed or current directory if no directory is given, in table format.
""")
output_format = parser.add_mutually_exclusive_group()
output_format.add_argument("-1", dest="one", action="store_true",
help="output one file per line")
output_format.add_argument('-x', '--xargs', action="store_true",
help="output will be string of null terminated file names; can be used as input to other \
commands like xargs")
file_visibility = parser.add_mutually_exclusive_group()
file_visibility.add_argument("-n", "--non-hidden", action='store_true', dest="non_hidden",
help="show files and/or directories with names that does not start with a dot; \
this is default")
file_visibility.add_argument("-i", "--hidden", action='store_true',
help="show files and/or directories with names starting with a dot")
file_visibility.add_argument("-a", "--include-hidden", action='store_true', dest="include_hidden",
help="show all files and/or directories")
file_directory = parser.add_mutually_exclusive_group()
file_directory.add_argument("-d", "--only-dir", action="store_true", dest="only_dir",
help="show directories only and not regular file")
file_directory.add_argument("-f", "--only-files", action="store_true", dest="only_files",
help="show only regular files and not directories")
sorting_options = parser.add_mutually_exclusive_group()
sorting_options.add_argument("-s", action="store_true",
help="sort contents of given directories alphabetically in ascending order; \
this is default")
sorting_options.add_argument("-u", action="store_true",
help="sort contents of given directories by access time, newest first")
sorting_options.add_argument("-t", action="store_true",
help="sort contents of given directories by modification time, newest first")
sorting_options.add_argument("-c", action="store_true",
help="sort contents of given directories by time of last modification of file status \
information, newest first")
sorting_options.add_argument("-z", action="store_true",
help="sort contents of given directories by their size, largest first, \
note this works well only with regular files")
parser.add_argument("-r", action="store_true",
help="reverse order while sorting; can be used in conjuction with option -s, -u, -t or -c; \
in absense of these options, sort alphabetically in descending order")
parser.add_argument("files", metavar="FILE", nargs='*',
help="space separated list of any numbers of files and/or directories; \
if not given, current directory will be assumed")
parser.add_argument("-v", "--version",
help="output version information and exit", action="store_true")
"""function declarations STARTS here"""
def version(args):
"""Print version, license and exit"""
print("""lsi version 2
Copyright (c) 2018 js-d-coder (www.github.com/js-d-coder)
This project is free software released under the MIT/X11 license:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
""")
sys.exit(0)
class Directory():
"""takes name of directory.
instance when called returns name of directory passed.
when called in for loop returns iterable list of files and directory inside the passed directory"""
def __init__(self, name):
self.name = str(name)
self.dir_contents = os.listdir(self.name)
def __iter__(self):
for file in self.dir_contents:
yield file
def __repr__(self):
return self.name
def __add__(self, b):
return self.name + b
def __len__(self):
return len(self.name)
def process_cmd_line_args(args):
"""process command line arguments passed"""
files_list = []
did_error_occur_local = 0
files = args.files
if not len(files):
files = ['.']
for file in files:
try:
if not os.path.exists(file):
did_error_occur_local = 1
raise FileNotFoundError('{}: cannot access {}: no such file or directory'.format(
os.path.basename(sys.argv[0]), file))
if os.path.isdir(file):
file = Directory(file)
except FileNotFoundError as err:
did_error_occur_local = 1
print(err, file=sys.stderr, end="\n")
except PermissionError as err:
did_error_occur_local = 1
print('{}: Permission denied: {}'.format(os.path.basename(
sys.argv[0]), file), file=sys.stderr, end="\n\n")
except Exception as err:
did_error_occur_local = 1
print('{}: Unexpected error: {}'.format(os.path.basename(
sys.argv[0]), sys.exc_info()[0]), file=sys.stderr)
else:
files_list.append(file)
if len(files_list):
for file in files_list:
if isinstance(file, Directory):
directory = file
if args.non_hidden:
files = [file for file in directory.dir_contents if not os.path.isdir(
directory + "/" + file) and file[0] != '.']
dirs = [
file + "/" for file in directory.dir_contents if os.path.isdir(directory + "/" + file)
and file[0] != '.']
elif args.hidden:
files = [file for file in directory.dir_contents if not os.path.isdir(
directory + "/" + file) and file[0] == '.']
dirs = [
file + "/" for file in directory.dir_contents if os.path.isdir(directory + "/" + file)
and file[0] == '.']
else:
files = [file for file in directory.dir_contents if not os.path.isdir(
directory + "/" + file)]
dirs = [
file + "/" for file in directory.dir_contents if os.path.isdir(directory + "/" + file)]
if args.only_files:
directory.dir_contents = files
elif args.only_dir:
directory.dir_contents = dirs
else:
directory.dir_contents = files + dirs
return (did_error_occur_local, files_list)
def sort_alphabetically(files_list, reverse):
"""sort files alphabetically in ascending order"""
for file in files_list:
if isinstance(file, Directory):
file.dir_contents.sort(reverse=reverse)
return files_list
def sort_access_time(files_list, reverse):
"""sort files by access time, newest first"""
reverse = not reverse
for file in files_list:
if isinstance(file, Directory):
file.dir_contents.sort(key=lambda x: os.stat(file + '/' + x).st_atime, reverse=reverse)
return files_list
def sort_modification_time(files_list, reverse):
"""sort files by modification time, newest first"""
reverse = not reverse
for file in files_list:
if isinstance(file, Directory):
file.dir_contents.sort(key=lambda x: os.stat(file + '/' + x).st_mtime, reverse=reverse)
return files_list
def sort_status_info(files_list, reverse):
"""sort files by time of last modification of file status information"""
reverse = not reverse
for file in files_list:
if isinstance(file, Directory):
file.dir_contents.sort(key=lambda x: os.stat(file + '/' + x).st_ctime, reverse=reverse)
return files_list
def sort_size(files_list, reverse):
"""sort files by their size, largest first"""
reverse = not reverse
for file in files_list:
if isinstance(file, Directory):
file.dir_contents.sort(key=lambda x: os.stat(file + '/' + x).st_size, reverse=reverse)
return files_list
def print_one_per_line(files_list):
"""print one file per line"""
flag = 0
for file in files_list:
if flag:
print()
flag = 1
if isinstance(file, Directory):
if len(files_list) > 1:
print(file, end=":\n")
for f in file:
print('{!r}'.format(f))
else:
print(file)
def print_for_xargs(files_list):
"""create string of null terminated file names for processing by xargs command"""
output_string = ""
for file in files_list:
if isinstance(file, Directory):
for f in file:
output_string += file + "/" + f + "\0"
else:
output_string += file + "\0"
print(output_string, end="")
def pretty_print(files_list):
a = 0
for file in files_list:
if a:
print()
a = 1
if isinstance(file, Directory):
if len(files_list) > 1:
print(file, ":", sep="")
maxlen = 0
for f in file:
if len(f) > maxlen:
maxlen = len(f)
# 2 for enclosing single qoutes, 2 for spaces after filename
col_width = maxlen + 4
no_of_col = int(int(terminal_column_size)/col_width)
if no_of_col == 0 or no_of_col == 1:
for f in file:
print("{!r}".format(f))
else:
nth_col = 0
for f in file:
nth_col += 1
print('{!r}'.format(f).ljust(col_width), end="")
if nth_col == no_of_col:
print()
nth_col = 0
if nth_col != no_of_col and nth_col != 0:
print()
else:
print(file)
def main():
did_error_occur = 0 # flag showing error occured or not
args = parser.parse_args()
if args.version:
version(args)
# non-hidden is default option
if not args.non_hidden and not args.hidden and not args.include_hidden:
args.non_hidden = True
# sorting option
if not args.s and not args.u and not args.t and not args.c and not args.z:
args.s = True
did_error_occur, files_list = process_cmd_line_args(args)
if did_error_occur and len(files_list):
print()
if not len(files_list):
sys.exit(1)
"""don't print anything if output is request for xargs
and there is an error with accessing files"""
if args.xargs and did_error_occur:
sys.exit(1)
reverse = False
if args.r:
reverse = True
if args.s:
files_list = sort_alphabetically(files_list, reverse)
elif args.u:
files_list = sort_access_time(files_list, reverse)
elif args.t:
files_list = sort_modification_time(files_list, reverse)
elif args.c:
files_list = sort_status_info(files_list, reverse)
elif args.z:
files_list = sort_size(files_list, reverse)
elif args.r:
files_list = sort_alphabetically(files_list, reverse)
if args.one:
print_one_per_line(files_list)
elif args.xargs:
print_for_xargs(files_list)
else:
pretty_print(files_list)
if did_error_occur:
sys.exit(1)
else:
sys.exit(0)
main()