Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ccaa749

Browse files
committed
Add du for checking disk usage.
Refactor sizeof_fmt function and move it to libcore.
1 parent 20d4117 commit ccaa749

File tree

3 files changed

+93
-17
lines changed

3 files changed

+93
-17
lines changed

bin/du.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import os
2+
import sys
3+
from argparse import ArgumentParser
4+
from fnmatch import fnmatch
5+
6+
7+
def is_excluded(path, pattern):
8+
if pattern:
9+
while path != '':
10+
prefix, tail = os.path.split(path)
11+
if fnmatch(tail, pattern):
12+
return True
13+
else:
14+
path = prefix
15+
return False
16+
else:
17+
return False
18+
19+
20+
def main(args):
21+
ap = ArgumentParser(
22+
description='Summarize disk usage of the set of FILEs, recursively for directories.'
23+
)
24+
ap.add_argument('-s', '--summarize', action='store_true',
25+
help='display only a total for each argument')
26+
ap.add_argument('--exclude', dest='exclude_pattern',
27+
metavar='PATTERN',
28+
help='exclude files that match PATTERN')
29+
ap.add_argument('FILEs', nargs='*', default=['.'],
30+
help='files to summarize (default to current working directory')
31+
32+
ns = ap.parse_args(args)
33+
34+
exclude_pattern = ns.exclude_pattern if ns.exclude_pattern else None
35+
36+
sizeof_fmt = globals()['_stash'].libcore.sizeof_fmt
37+
38+
for path in ns.FILEs:
39+
40+
path_base = os.path.dirname(path)
41+
42+
# Use relative path because of the following facts:
43+
# du A/B --exclude="B" -> no output
44+
# du A/B --exclude="A" -> normal output
45+
if is_excluded(os.path.relpath(path, path_base), exclude_pattern):
46+
continue
47+
48+
if os.path.isdir(path):
49+
dirs_dict = {}
50+
# We need to walk the tree from the bottom up so that a directory can have easy
51+
# access to the size of its subdirectories.
52+
for root, dirs, files in os.walk(path, topdown=False):
53+
# This is to make sure the directory is not exclude from its ancestor
54+
if is_excluded(os.path.relpath(root, path_base), exclude_pattern):
55+
continue
56+
57+
# Loop through every non directory file in this directory and sum their sizes
58+
size = sum(os.path.getsize(os.path.join(root, name))
59+
for name in files if not is_excluded(name, exclude_pattern))
60+
61+
# Look at all of the subdirectories and add up their sizes from the `dirs_dict`
62+
subdir_size = sum(dirs_dict[os.path.join(root, d)]
63+
for d in dirs if not is_excluded(d, exclude_pattern))
64+
65+
# store the size of this directory (plus subdirectories) in a dict so we
66+
# can access it later
67+
my_size = dirs_dict[root] = size + subdir_size
68+
69+
if ns.summarize and root != path:
70+
continue
71+
72+
print '%-8s %s' % (sizeof_fmt(my_size), root)
73+
else:
74+
print '%-8s %s' % (sizeof_fmt(os.path.getsize(path)), path)
75+
76+
77+
if __name__ == '__main__':
78+
main(sys.argv[1:])

bin/ls.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,36 +8,27 @@
88
from argparse import ArgumentParser
99

1010

11-
def sizeof_fmt(num):
12-
for x in ['B', 'KB', 'MB', 'GB']:
13-
if num < 1024.0:
14-
if (x == 'bytes'):
15-
return "%s %s" % (num, x)
16-
else:
17-
return "%3.1f %s" % (num, x)
18-
num /= 1024.0
19-
return "%3.1f%s" % (num, 'TB')
20-
21-
2211
def main(args):
2312

2413
ap = ArgumentParser()
2514
ap.add_argument('-1', '--one-line', action='store_true', help='List one file per line')
2615
ap.add_argument('-a', '--all', action='store_true', help='do not ignore entries starting with .')
2716
ap.add_argument('-l', '--long', action='store_true', help='use a long listing format')
2817
ap.add_argument('files', nargs='*', help='files to be listed')
29-
args = ap.parse_args(args)
18+
ns = ap.parse_args(args)
19+
20+
sizeof_fmt = globals()['_stash'].libcore.sizeof_fmt
3021

31-
joiner = '\n' if args.one_line or args.long else ' '
22+
joiner = '\n' if ns.one_line or ns.long else ' '
3223

33-
if args.all:
24+
if ns.all:
3425
def _filter(filename):
3526
return True
3627
else:
3728
def _filter(filename):
3829
return False if filename.startswith('.') else True
3930

40-
if args.long:
31+
if ns.long:
4132
def _fmt(filename, dirname=''):
4233
_stat = os.stat(os.path.join(dirname, filename))
4334

@@ -71,15 +62,15 @@ def _fmt(filename, dirname=''):
7162
else:
7263
return filename
7364

74-
if len(args.files) == 0:
65+
if len(ns.files) == 0:
7566
out = joiner.join(_fmt(f) for f in os.listdir('.') if _filter(f))
7667
print out
7768

7869
else:
7970
out_dir = []
8071
out_file = []
8172
out_miss = []
82-
for f in args.files:
73+
for f in ns.files:
8374
if not os.path.exists(f):
8475
out_miss.append('ls: %s: No such file or directory' % f)
8576
elif os.path.isdir(f):

lib/libcore.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,10 @@ def input_stream(files=()):
5959
finally:
6060
fileinput.close()
6161

62+
63+
def sizeof_fmt(num):
64+
for unit in ['B', 'K', 'M', 'G']:
65+
if num < 1024:
66+
return "%3.1f%s" % (num, unit)
67+
num /= 1024.0
68+
return "%3.1f%s" % (num, 'T')

0 commit comments

Comments
 (0)