dutree.py 1.6 KB
Newer Older
1
#! /usr/bin/env python3
Guido van Rossum's avatar
Guido van Rossum committed
2 3
# Format du output in a tree shape

4
import os, sys, errno
Guido van Rossum's avatar
Guido van Rossum committed
5 6

def main():
Tim Peters's avatar
Tim Peters committed
7
    total, d = None, {}
8 9 10 11 12 13 14 15 16 17 18
    with os.popen('du ' + ' '.join(sys.argv[1:])) as p:
        for line in p:
            i = 0
            while line[i] in '0123456789': i = i+1
            size = eval(line[:i])
            while line[i] in ' \t': i = i+1
            filename = line[i:-1]
            comps = filename.split('/')
            if comps[0] == '': comps[0] = '/'
            if comps[len(comps)-1] == '': del comps[len(comps)-1]
            total, d = store(size, comps, total, d)
Tim Peters's avatar
Tim Peters committed
19 20
    try:
        display(total, d)
21
    except IOError as e:
Tim Peters's avatar
Tim Peters committed
22 23
        if e.errno != errno.EPIPE:
            raise
Guido van Rossum's avatar
Guido van Rossum committed
24 25

def store(size, comps, total, d):
Tim Peters's avatar
Tim Peters committed
26 27
    if comps == []:
        return size, d
28
    if comps[0] not in d:
Tim Peters's avatar
Tim Peters committed
29 30 31 32
        d[comps[0]] = None, {}
    t1, d1 = d[comps[0]]
    d[comps[0]] = store(size, comps[1:], t1, d1)
    return total, d
Guido van Rossum's avatar
Guido van Rossum committed
33 34

def display(total, d):
Tim Peters's avatar
Tim Peters committed
35
    show(total, d, '')
Guido van Rossum's avatar
Guido van Rossum committed
36 37

def show(total, d, prefix):
Tim Peters's avatar
Tim Peters committed
38 39 40 41 42 43 44
    if not d: return
    list = []
    sum = 0
    for key in d.keys():
        tsub, dsub = d[key]
        list.append((tsub, key))
        if tsub is not None: sum = sum + tsub
45 46
##  if sum < total:
##      list.append((total - sum, os.curdir))
Tim Peters's avatar
Tim Peters committed
47 48
    list.sort()
    list.reverse()
49
    width = len(repr(list[0][0]))
Tim Peters's avatar
Tim Peters committed
50 51 52 53
    for tsub, key in list:
        if tsub is None:
            psub = prefix
        else:
54
            print(prefix + repr(tsub).rjust(width) + ' ' + key)
Tim Peters's avatar
Tim Peters committed
55
            psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
56
        if key in d:
Tim Peters's avatar
Tim Peters committed
57
            show(tsub, d[key][1], psub)
Guido van Rossum's avatar
Guido van Rossum committed
58

59 60
if __name__ == '__main__':
    main()