xref: /openbmc/openbmc/poky/scripts/tiny/dirsize.py (revision 82c905dc)
1#!/usr/bin/env python3
2#
3# Copyright (c) 2011, Intel Corporation.
4#
5# SPDX-License-Identifier: GPL-2.0-or-later
6#
7# Display details of the root filesystem size, broken up by directory.
8# Allows for limiting by size to focus on the larger files.
9#
10# Author: Darren Hart <dvhart@linux.intel.com>
11#
12
13import os
14import sys
15import stat
16
17class Record:
18    def create(path):
19        r = Record(path)
20
21        s = os.lstat(path)
22        if stat.S_ISDIR(s.st_mode):
23            for p in os.listdir(path):
24                pathname = path + "/" + p
25                ss = os.lstat(pathname)
26                if not stat.S_ISLNK(ss.st_mode):
27                    r.records.append(Record.create(pathname))
28                    r.size += r.records[-1].size
29            r.records.sort(reverse=True)
30        else:
31            r.size = os.lstat(path).st_size
32
33        return r
34    create = staticmethod(create)
35
36    def __init__(self, path):
37        self.path = path
38        self.size = 0
39        self.records = []
40
41    def __lt__(this, that):
42        if that is None:
43            return False
44        if not isinstance(that, Record):
45            raise TypeError
46        if len(this.records) > 0 and len(that.records) == 0:
47            return False
48        if this.size > that.size:
49            return False
50        return True
51
52    def show(self, minsize):
53        total = 0
54        if self.size <= minsize:
55            return 0
56        print("%10d %s" % (self.size, self.path))
57        for r in self.records:
58            total += r.show(minsize)
59        if len(self.records) == 0:
60            total = self.size
61        return total
62
63
64def main():
65    minsize = 0
66    if len(sys.argv) == 2:
67        minsize = int(sys.argv[1])
68    rootfs = Record.create(".")
69    total = rootfs.show(minsize)
70    print("Displayed %d/%d bytes (%.2f%%)" % \
71          (total, rootfs.size, 100 * float(total) / rootfs.size))
72
73
74if __name__ == "__main__":
75    main()
76