This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfoldersize.py
333 lines (275 loc) · 10.5 KB
/
foldersize.py
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
import os
import re
import unicodedata
from enum import Enum
class FolderSize:
def __init__(self, path):
self.__path = path
# [((dir,size),[(file,size),(file,size)]),((dir,size),[(file,size)])]
self.__dirlist = []
self.__dirlist_history = []
self.__dirlist_view = []
self.__lastprinted = ViewType
def scan_dir(self):
dirlist = self.__scan(self.__path)
self.__dirlist = dirlist[::-1]
def __scan(self, path):
# Check
if not os.path.exists(path):
raise Exception("The path doesn't exist")
dirlist = []
templist = []
temppath = path
try:
for direntry in os.scandir(path):
dirpath, basename = os.path.split(direntry.path)
fullpath = direntry.path
if temppath != dirpath:
templist_sorted = sorted(
templist, key=lambda x: x[1], reverse=True)
dirlist.append(
((temppath, self.__calc_size(temppath, isfile=False)), templist_sorted))
temppath = dirpath
if direntry.is_file():
templist.append((basename, self.__calc_size(fullpath)))
elif direntry.is_dir():
sublist = self.__scan(fullpath)
sublist += dirlist
dirlist = sublist
else:
templist_sorted = sorted(
templist, key=lambda x: x[1], reverse=True)
dirlist.append(
((temppath, self.__calc_size(temppath, isfile=False)), templist_sorted))
except:
pass
return dirlist
def __calc_size(self, path, isfile=True):
if isfile:
return os.path.getsize(path)
totalsize = 0
try:
for direntry in os.scandir(path):
if direntry.is_file():
totalsize += self.__calc_size(direntry.path)
elif direntry.is_dir():
totalsize += self.__calc_size(direntry.path, False)
return totalsize
except:
return 0
def create_dir_list(self, full=False, number=10):
self.__check_dirlist()
dlist = [ditem[0] for ditem in self.__dirlist]
dlist_sorted = sorted(dlist, key=lambda x: x[1], reverse=True)
if number > len(dlist_sorted) or full:
number = len(dlist_sorted)
elif number <= 0:
raise Exception('Index overflowed')
dlist_selected = [dlist_sorted[item] for item in range(0, number)]
self.__dirlist_view = dlist_selected
def create_file_list(self, full=False, number=10):
self.__check_dirlist()
flist = []
for ditem in self.__dirlist:
dirname = ditem[0][0]
for fitem in ditem[1]:
filename = fitem[0]
filesize = fitem[1]
flist.append((os.path.join(dirname, filename), filesize))
flist_sorted = sorted(flist, key=lambda x: x[1], reverse=True)
if number > len(flist_sorted) or full:
number = len(flist_sorted)
elif number <= 0:
raise Exception('Index overflowed')
flist_selected = [flist_sorted[item] for item in range(0, number)]
self.__dirlist_view = flist_selected
def get_elem(self, index):
self.__check_dirlist()
if self.__lastprinted == ViewType.Tree:
return self.__get_dir_tree_elem(index)
elif self.__lastprinted == ViewType.DirList or self.__lastprinted == ViewType.FileList:
return self.__get_list_elem(index)
def __get_dir_tree_elem(self, index):
indexcnt = -1
rootdir = self.__dirlist[0][0][0]
rootdepth = calc_depth(rootdir)
for ditem in self.__dirlist:
dirpath = ditem[0][0]
dirdepth = calc_depth(dirpath)
reldepth = dirdepth - rootdepth
if reldepth == 1:
indexcnt += 1
if index == indexcnt:
return dirpath
raise Exception('Index overflowed')
def __get_list_elem(self, index):
if index > len(self.__dirlist_view):
raise Exception('Index overflowed')
return self.__dirlist_view[index][0]
def movein(self, index):
self.__check_dirlist()
if self.__lastprinted == ViewType.Tree:
self.__tree_movein(index)
elif self.__lastprinted == ViewType.DirList:
self.__check_dirlist_view()
self.__list_movein(index)
elif self.__lastprinted == ViewType.FileList:
raise Exception('Only folders can be moved in')
else:
raise Exception('Print a treeview/listview first')
def __tree_movein(self, index):
newdirlist = []
indexcnt = -1
isstarted = False
rootpath = self.__dirlist[0][0][0]
rootdepth = calc_depth(rootpath)
for ditem in self.__dirlist:
dirpath = ditem[0][0]
dirdepth = calc_depth(dirpath)
reldepth = dirdepth - rootdepth
if reldepth == 1:
if isstarted:
break
else:
indexcnt += 1
if index == indexcnt:
isstarted = True
newdirlist.append(ditem)
# Check
if not newdirlist:
raise Exception('Index overflowed')
else:
self.__dirlist_history.append(self.__dirlist)
self.__dirlist = newdirlist
def __list_movein(self, index):
newdirlist = []
rootpath = self.__dirlist_view[index][0]
rootdepth = calc_depth(rootpath)
isstarted = False
for ditem in self.__dirlist:
dirpath = ditem[0][0]
dirdepth = calc_depth(dirpath)
if isstarted and dirdepth <= rootdepth:
break
if dirpath == rootpath:
isstarted = True
if isstarted:
newdirlist.append(ditem)
# Check
if not newdirlist:
raise Exception('Index overflowed')
else:
self.__dirlist_history.append(self.__dirlist)
self.__dirlist = newdirlist
def back_action(self):
self.__check_dirlist()
self.__check_dirlist_history()
self.__dirlist = self.__dirlist_history.pop()
def print_treeview(self, collapse=True, level=5):
self.__check_dirlist()
dirind = '│ '
fileind = ' '
symbol = '├──'
indexcnt = -1
collapsecnt = 0
rootpath = self.__dirlist[0][0][0]
rootdepth = calc_depth(rootpath)
if level < 2:
level = 2
for i, ditem in enumerate(self.__dirlist):
dirpath = ditem[0][0]
dirname = os.path.basename(dirpath)
dirsize = bytes_convert(ditem[0][1])
dirdepth = calc_depth(dirpath)
reldepth = dirdepth - rootdepth
if i != 0:
if collapse:
if level <= reldepth <= level + 1:
collapsecnt += 1
continue
elif reldepth > level + 1:
continue
elif collapsecnt != 0:
print(f'{dirind * level}{symbol} ...{collapsecnt} folders collapsed')
collapsecnt = 0
if reldepth == 1:
indexcnt += 1
dirname = f'[{indexcnt}]{dirname}'
dirname = f'{len_adjust(dirname)}{os.path.sep}'
print(f'{dirind * reldepth}{symbol} {dirname:<{44 - len_diff(dirname)}}{dirsize:>12}')
else: # print rootdir
dirname = f'{len_adjust(dirpath)}{os.path.sep}'
print(f'{dirname:<{48 - len_diff(dirname)}}{dirsize:>12}')
for j, fitem in enumerate(ditem[1]):
if collapse and i != 0:
if reldepth >= 3:
print(f'{fileind * (reldepth + 1)}{symbol} ...{len(ditem[1])} files collapsed')
break
elif j > 2:
print(f'{fileind * (reldepth + 1)}{symbol} ...{len(ditem[1]) - 3} files collapsed')
break
filename = len_adjust(fitem[0])
filesize = bytes_convert(fitem[1])
print(f'{fileind * (reldepth + 1)}{symbol} {filename:<{40 - len_diff(filename)}}{filesize:>12}')
else:
if collapse and collapsecnt != 0:
print(f'{dirind * level}{symbol} ...{collapsecnt} folders collapsed')
self.__lastprinted = ViewType.Tree
def print_listview(self, viewtype: 'ViewType'):
self.__check_dirlist_view()
[print(f'{i:>3}. {bytes_convert(item[1]):>10} {item[0]}')
for i, item in enumerate(self.__dirlist_view)]
if viewtype == ViewType.DirList:
self.__lastprinted = ViewType.DirList
elif viewtype == ViewType.FileList:
self.__lastprinted = ViewType.FileList
else:
raise Exception("viewtype's type must be ViewType")
def __check_dirlist(self):
if not self.__dirlist:
raise Exception('Do not have any scan results')
def __check_dirlist_history(self):
if not self.__dirlist_history:
raise Exception('Already at the top of the folder')
def __check_dirlist_view(self):
if not self.__dirlist_view:
raise Exception('Do not have any listview results')
class ViewType(Enum):
Tree = 1
DirList = 2
FileList = 3
def calc_depth(path):
if os.path.sep == '\\':
sep = r'\\'
else:
sep = os.path.sep
return len(re.findall(sep, path))
def len_adjust(string):
if len_count(string) > 40:
return string[0:17 - len_diff(string[0:17])] + '...' + \
string[-20 + len_diff(string[-20:]):]
return string
def len_count(string):
count = 0
for char in string:
if unicodedata.east_asian_width(char) in 'FW':
count += 2
else:
count += 1
return count
def len_diff(string):
count = 0
for char in string:
if unicodedata.east_asian_width(char) in 'FWA':
count += 1
return count
def bytes_convert(size):
kb = 1024
mb = 1024 ** 2
gb = 1024 ** 3
if size < mb:
return f'{size / kb:>5.2f} KB'
elif mb <= size < gb:
return f'{size / mb:>5.2f} MB'
elif gb <= size:
return f'{size / gb:>5.2f} GB'