-
Notifications
You must be signed in to change notification settings - Fork 6
/
cleanSource.py
executable file
·79 lines (63 loc) · 2.24 KB
/
cleanSource.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
#
# Call this with a list of files to consider.
import optparse, os, sys, re, tempfile
parser = optparse.OptionParser(description = """This script cleans a source
file. It does (1) remove trailing white space characters, and (2) replace a
TAB character with space characters in cases where the TAB character follows a
leading space character.""")
parser.add_option("--pretend",
help = "Just check, but not change any files",
action = "store_true",
default = False,
dest = "pretend")
parser.add_option("--tab",
help = "Replace a TAB character with N spaces (default N = 8)",
default = 8,
type = "int",
dest = "tab",
metavar = "N")
options, arguments = parser.parse_args()
if len(arguments) == 0:
print("what files should I fix?")
sys.exit(1)
for file in arguments:
if not os.path.isfile(file):
continue
try:
fd = open(file)
lines = fd.readlines()
fd.close()
except:
print("error opening file " + file)
sys.exit(1)
lineNumber = 0
fileNeedsFixing = False
for lineNumber in range(len(lines)):
if re.compile("[ \t]+$").search(lines[lineNumber]):
fileNeedsFixing = True
print("trailing whitespace in file " + file + " on line " + str(lineNumber+1) + ": " + lines[lineNumber].rstrip())
if not options.pretend:
lines[lineNumber] = lines[lineNumber].rstrip()
if re.compile("^ +\t+").search(lines[lineNumber]):
fileNeedsFixing = True
print("indent SP followed by TAB in file " + file + " on line " + str(lineNumber+1) + ": " + lines[lineNumber].rstrip())
lineCopy = lines[lineNumber]
tabInSpace = ""
for i in range(options.tab):
tabInSpace += " "
while True:
result = re.compile("^( +)\t").search(lineCopy)
if result:
lineCopy = re.sub("^ +\t", result.group(1) + tabInSpace, lineCopy)
else:
break
print("fixed SP followed by TAB in file " + file + " on line " + str(lineNumber+1) + ": " + lineCopy.rstrip())
if not options.pretend:
line[lineNumber] = lineCopy
if not options.pretend and fileNeedsFixing:
print("writing out fixed file " + file)
fd = open(file, "w")
for line in lines:
print >> fd, line.rstrip()
fd.close()