1#! /usr/bin/env python3
2# Format du output in a tree shape
3
4import os, sys, errno
5
6def main():
7    total, d = None, {}
8    with os.popen('du ' + ' '.join(sys.argv[1:])) as p:
9        for line in p:
10            i = 0
11            while line[i] in '0123456789': i = i+1
12            size = eval(line[:i])
13            while line[i] in ' \t': i = i+1
14            filename = line[i:-1]
15            comps = filename.split('/')
16            if comps[0] == '': comps[0] = '/'
17            if comps[len(comps)-1] == '': del comps[len(comps)-1]
18            total, d = store(size, comps, total, d)
19    try:
20        display(total, d)
21    except IOError as e:
22        if e.errno != errno.EPIPE:
23            raise
24
25def store(size, comps, total, d):
26    if comps == []:
27        return size, d
28    if comps[0] not in d:
29        d[comps[0]] = None, {}
30    t1, d1 = d[comps[0]]
31    d[comps[0]] = store(size, comps[1:], t1, d1)
32    return total, d
33
34def display(total, d):
35    show(total, d, '')
36
37def show(total, d, prefix):
38    if not d: return
39    list = []
40    sum = 0
41    for key in d.keys():
42        tsub, dsub = d[key]
43        list.append((tsub, key))
44        if tsub is not None: sum = sum + tsub
45##  if sum < total:
46##      list.append((total - sum, os.curdir))
47    list.sort()
48    list.reverse()
49    width = len(repr(list[0][0]))
50    for tsub, key in list:
51        if tsub is None:
52            psub = prefix
53        else:
54            print(prefix + repr(tsub).rjust(width) + ' ' + key)
55            psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
56        if key in d:
57            show(tsub, d[key][1], psub)
58
59if __name__ == '__main__':
60    main()
61