3 """Show file statistics by extension."""
13 def statargs(self, args):
15 if os.path.isdir(arg):
17 elif os.path.isfile(arg):
20 sys.stderr.write("Can't find %s\n" % arg)
21 self.addstats("<???>", "unknown", 1)
23 def statdir(self, dir):
24 self.addstats("<dir>", "dirs", 1)
26 names = sorted(os.listdir(dir))
27 except os.error as err:
28 sys.stderr.write("Can't list %s: %s\n" % (dir, err))
29 self.addstats("<dir>", "unlistable", 1)
32 if name.startswith(".#"):
33 continue # Skip CVS temp files
34 if name.endswith("~"):
35 continue# Skip Emacs backup files
36 full = os.path.join(dir, name)
37 if os.path.islink(full):
38 self.addstats("<lnk>", "links", 1)
39 elif os.path.isdir(full):
44 def statfile(self, filename):
45 head, ext = os.path.splitext(filename)
46 head, base = os.path.split(filename)
48 ext = "" # E.g. .cvsignore is deemed not to have an extension
49 ext = os.path.normcase(ext)
52 self.addstats(ext, "files", 1)
54 f = open(filename, "rb")
55 except IOError as err:
56 sys.stderr.write("Can't open %s: %s\n" % (filename, err))
57 self.addstats(ext, "unopenable", 1)
61 self.addstats(ext, "bytes", len(data))
63 self.addstats(ext, "binary", 1)
66 self.addstats(ext, "empty", 1)
67 #self.addstats(ext, "chars", len(data))
68 lines = data.splitlines()
69 self.addstats(ext, "lines", len(lines))
72 self.addstats(ext, "words", len(words))
74 def addstats(self, ext, key, n):
75 d = self.stats.setdefault(ext, {})
76 d[key] = d.get(key, 0) + n
79 exts = sorted(self.stats.keys())
83 columns.update(self.stats[ext])
84 cols = sorted(columns.keys())
86 colwidth["ext"] = max([len(ext) for ext in exts])
88 self.stats["TOTAL"] = {}
91 cw = max(minwidth, len(col))
93 value = self.stats[ext].get(col)
100 cw = max(cw, len(str(total)))
102 self.stats["TOTAL"][col] = total
105 self.stats[ext]["ext"] = ext
106 cols.insert(0, "ext")
109 print("%*s" % (colwidth[col], col), end=" ")
114 value = self.stats[ext].get(col, "")
115 print("%*s" % (colwidth[col], value), end=" ")
117 printheader() # Another header at the bottom
127 if __name__ == "__main__":