blob: e65eb01a0f35031b638b92a1e9d443ab65e13038 [file] [log] [blame]
Guido van Rossum6f73c1a1998-03-20 19:23:04 +00001#! /usr/bin/env python
2
3"""The Tab Police watches for possibly inconsistent indentation."""
4
5import os
6import sys
7import getopt
8import string
9import tokenize
10
11verbose = 0
12
13def main():
14 global verbose
15 try:
16 opts, args = getopt.getopt(sys.argv[1:], "v")
17 except getopt.error, msg:
18 print msg
19 for o, a in opts:
20 if o == '-v':
21 verbose = verbose + 1
22 for arg in args:
23 check(arg)
24
25def check(file):
26 if os.path.isdir(file) and not os.path.islink(file):
27 if verbose:
28 print "%s: listing directory" % `file`
29 names = os.listdir(file)
30 for name in names:
31 fullname = os.path.join(file, name)
32 if (os.path.isdir(fullname) and
33 not os.path.islink(fullname) or
34 os.path.normcase(name[-3:]) == ".py"):
35 check(fullname)
36 return
37
38 try:
39 f = open(file)
40 except IOError, msg:
41 print "%s: I/O Error: %s" % (`file`, str(msg))
42 return
43
44 if verbose > 1:
45 print "checking", `file`, "with tabsize 8..."
46 tokens = []
47 tokenize.tabsize = 8
48 try:
49 tokenize.tokenize(f.readline, tokens.append)
50 except tokenize.TokenError, msg:
51 print "%s: Token Error: %s" % (`file`, str(msg))
52
53 if verbose > 1:
Guido van Rossum3db0e371998-03-24 04:58:04 +000054 print "checking", `file`, "with tabsize 1..."
Guido van Rossum6f73c1a1998-03-20 19:23:04 +000055 f.seek(0)
56 alttokens = []
Guido van Rossum3db0e371998-03-24 04:58:04 +000057 tokenize.tabsize = 1
Guido van Rossum6f73c1a1998-03-20 19:23:04 +000058 try:
59 tokenize.tokenize(f.readline, alttokens.append)
60 except tokenize.TokenError, msg:
61 print "%s: Token Error: %s" % (`file`, str(msg))
62 f.close()
63
64 if tokens != alttokens:
Guido van Rossum3db0e371998-03-24 04:58:04 +000065 badline = 0
66 n, altn = len(tokens), len(alttokens)
67 for i in range(max(n, altn)):
68 if i >= n:
69 x = None
70 else:
71 x = tokens[i]
72 if i >= altn:
73 y = None
74 else:
75 y = alttokens[i]
76 if x != y:
77 if x:
78 kind, token, start, end, line = x
79 else:
80 kind, token, start, end, line = y
81 badline = start[0]
82 break
Guido van Rossum6f73c1a1998-03-20 19:23:04 +000083 if verbose:
Guido van Rossum3db0e371998-03-24 04:58:04 +000084 print "%s: *** Line %d: trouble in tab city! ***" % (
85 `file`, badline)
86 print "offending line:", `line`
Guido van Rossum6f73c1a1998-03-20 19:23:04 +000087 else:
Guido van Rossum3db0e371998-03-24 04:58:04 +000088 print file, badline, `line`
Guido van Rossum6f73c1a1998-03-20 19:23:04 +000089 else:
90 if verbose:
91 print "%s: Clean bill of health." % `file`
92
93if __name__ == '__main__':
94 main()