Skip to content

Commit e4a3380

Browse files
committed
Clean up syntax for some scripts.
1 parent aba74bd commit e4a3380

7 files changed

Lines changed: 115 additions & 87 deletions

File tree

Tools/scripts/byext.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import sys
77

8+
89
class Stats:
910

1011
def __init__(self):
@@ -28,12 +29,11 @@ def statdir(self, dir):
2829
sys.stderr.write("Can't list %s: %s\n" % (dir, err))
2930
self.addstats("<dir>", "unlistable", 1)
3031
return
31-
names.sort()
32-
for name in names:
32+
for name in sorted(names):
3333
if name.startswith(".#"):
34-
continue # Skip CVS temp files
34+
continue # Skip CVS temp files
3535
if name.endswith("~"):
36-
continue# Skip Emacs backup files
36+
continue # Skip Emacs backup files
3737
full = os.path.join(dir, name)
3838
if os.path.islink(full):
3939
self.addstats("<lnk>", "links", 1)
@@ -46,26 +46,25 @@ def statfile(self, filename):
4646
head, ext = os.path.splitext(filename)
4747
head, base = os.path.split(filename)
4848
if ext == base:
49-
ext = "" # E.g. .cvsignore is deemed not to have an extension
49+
ext = "" # E.g. .cvsignore is deemed not to have an extension
5050
ext = os.path.normcase(ext)
5151
if not ext:
5252
ext = "<none>"
5353
self.addstats(ext, "files", 1)
5454
try:
55-
f = open(filename, "rb")
55+
with open(filename, "rb") as f:
56+
data = f.read()
5657
except IOError as err:
5758
sys.stderr.write("Can't open %s: %s\n" % (filename, err))
5859
self.addstats(ext, "unopenable", 1)
5960
return
60-
data = f.read()
61-
f.close()
6261
self.addstats(ext, "bytes", len(data))
6362
if b'\0' in data:
6463
self.addstats(ext, "binary", 1)
6564
return
6665
if not data:
6766
self.addstats(ext, "empty", 1)
68-
#self.addstats(ext, "chars", len(data))
67+
# self.addstats(ext, "chars", len(data))
6968
lines = str(data, "latin-1").splitlines()
7069
self.addstats(ext, "lines", len(lines))
7170
del lines
@@ -105,17 +104,20 @@ def report(self):
105104
for ext in exts:
106105
self.stats[ext]["ext"] = ext
107106
cols.insert(0, "ext")
107+
108108
def printheader():
109109
for col in cols:
110110
print("%*s" % (colwidth[col], col), end=' ')
111111
print()
112+
112113
printheader()
113114
for ext in exts:
114115
for col in cols:
115116
value = self.stats[ext].get(col, "")
116117
print("%*s" % (colwidth[col], value), end=' ')
117118
print()
118-
printheader() # Another header at the bottom
119+
printheader() # Another header at the bottom
120+
119121

120122
def main():
121123
args = sys.argv[1:]
@@ -125,5 +127,6 @@ def main():
125127
s.statargs(args)
126128
s.report()
127129

130+
128131
if __name__ == "__main__":
129132
main()

Tools/scripts/patchcheck.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ def n_files_str(count):
99
"""Return 'N file(s)' with the proper plurality on 'file'."""
1010
return "{} file{}".format(count, "s" if count != 1 else "")
1111

12+
1213
def status(message, modal=False, info=None):
1314
"""Decorator to output status info to stdout."""
1415
def decorated_fxn(fxn):
@@ -21,32 +22,25 @@ def call_fxn(*args, **kwargs):
2122
elif info:
2223
print(info(result))
2324
else:
24-
if result:
25-
print("yes")
26-
else:
27-
print("NO")
25+
print("yes" if result else "NO")
2826
return result
2927
return call_fxn
3028
return decorated_fxn
3129

30+
3231
@status("Getting the list of files that have been added/changed",
3332
info=lambda x: n_files_str(len(x)))
3433
def changed_files():
3534
"""Run ``svn status`` and return a set of files that have been
36-
changed/added."""
35+
changed/added.
36+
"""
3737
cmd = 'svn status --quiet --non-interactive --ignore-externals'
3838
svn_st = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
3939
svn_st.wait()
40-
output = [x.decode().rstrip() for x in svn_st.stdout.readlines()]
41-
files = set()
42-
for line in output:
43-
if not line[0] in ('A', 'M'):
44-
continue
45-
line_parts = line.split()
46-
path = line_parts[-1]
47-
if os.path.isfile(path):
48-
files.add(path)
49-
return files
40+
output = (x.decode().rstrip().rsplit(None, 1)[-1]
41+
for x in svn_st.stdout if x[0] in b'AM')
42+
return set(path for path in output if os.path.isfile(path))
43+
5044

5145
def report_modified_files(file_paths):
5246
count = len(file_paths)
@@ -58,6 +52,7 @@ def report_modified_files(file_paths):
5852
lines.append(" {}".format(path))
5953
return "\n".join(lines)
6054

55+
6156
@status("Fixing whitespace", info=report_modified_files)
6257
def normalize_whitespace(file_paths):
6358
"""Make sure that the whitespace for .py files have been normalized."""
@@ -68,16 +63,19 @@ def normalize_whitespace(file_paths):
6863
fixed.append(path)
6964
return fixed
7065

66+
7167
@status("Docs modified", modal=True)
7268
def docs_modified(file_paths):
7369
"""Report if any file in the Doc directory has been changed."""
7470
return bool(file_paths)
7571

72+
7673
@status("Misc/ACKS updated", modal=True)
7774
def credit_given(file_paths):
7875
"""Check if Misc/ACKS has been changed."""
7976
return 'Misc/ACKS' in file_paths
8077

78+
8179
@status("Misc/NEWS updated", modal=True)
8280
def reported_news(file_paths):
8381
"""Check if Misc/NEWS has been changed."""

Tools/scripts/reindent.py

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -42,26 +42,27 @@
4242
__version__ = "1"
4343

4444
import tokenize
45-
import os, shutil
45+
import os
46+
import shutil
4647
import sys
4748

48-
verbose = 0
49-
recurse = 0
50-
dryrun = 0
49+
verbose = False
50+
recurse = False
51+
dryrun = False
5152
makebackup = True
5253

54+
5355
def usage(msg=None):
54-
if msg is not None:
55-
print(msg, file=sys.stderr)
56-
print(__doc__, file=sys.stderr)
56+
if msg is None:
57+
msg = __doc__
58+
print(msg, file=sys.stderr)
59+
5760

5861
def errprint(*args):
59-
sep = ""
60-
for arg in args:
61-
sys.stderr.write(sep + str(arg))
62-
sep = " "
62+
sys.stderr.write(" ".join(str(arg) for arg in args))
6363
sys.stderr.write("\n")
6464

65+
6566
def main():
6667
import getopt
6768
global verbose, recurse, dryrun, makebackup
@@ -73,13 +74,13 @@ def main():
7374
return
7475
for o, a in opts:
7576
if o in ('-d', '--dryrun'):
76-
dryrun += 1
77+
dryrun = True
7778
elif o in ('-r', '--recurse'):
78-
recurse += 1
79+
recurse = True
7980
elif o in ('-n', '--nobackup'):
8081
makebackup = False
8182
elif o in ('-v', '--verbose'):
82-
verbose += 1
83+
verbose = True
8384
elif o in ('-h', '--help'):
8485
usage()
8586
return
@@ -91,6 +92,7 @@ def main():
9192
for arg in args:
9293
check(arg)
9394

95+
9496
def check(file):
9597
if os.path.isdir(file) and not os.path.islink(file):
9698
if verbose:
@@ -108,13 +110,12 @@ def check(file):
108110
if verbose:
109111
print("checking", file, "...", end=' ')
110112
try:
111-
f = open(file)
113+
with open(file) as f:
114+
r = Reindenter(f)
112115
except IOError as msg:
113116
errprint("%s: I/O Error: %s" % (file, str(msg)))
114117
return
115118

116-
r = Reindenter(f)
117-
f.close()
118119
if r.run():
119120
if verbose:
120121
print("changed.")
@@ -126,9 +127,8 @@ def check(file):
126127
shutil.copyfile(file, bak)
127128
if verbose:
128129
print("backed up", file, "to", bak)
129-
f = open(file, "w")
130-
r.write(f)
131-
f.close()
130+
with open(file, "w") as f:
131+
r.write(f)
132132
if verbose:
133133
print("wrote new", file)
134134
return True
@@ -137,6 +137,7 @@ def check(file):
137137
print("unchanged.")
138138
return False
139139

140+
140141
def _rstrip(line, JUNK='\n \t'):
141142
"""Return line stripped of trailing spaces, tabs, newlines.
142143
@@ -146,10 +147,11 @@ def _rstrip(line, JUNK='\n \t'):
146147
"""
147148

148149
i = len(line)
149-
while i > 0 and line[i-1] in JUNK:
150+
while i > 0 and line[i - 1] in JUNK:
150151
i -= 1
151152
return line[:i]
152153

154+
153155
class Reindenter:
154156

155157
def __init__(self, f):
@@ -192,9 +194,9 @@ def run(self):
192194
# we see a line with *something* on it.
193195
i = stats[0][0]
194196
after.extend(lines[1:i])
195-
for i in range(len(stats)-1):
197+
for i in range(len(stats) - 1):
196198
thisstmt, thislevel = stats[i]
197-
nextstmt = stats[i+1][0]
199+
nextstmt = stats[i + 1][0]
198200
have = getlspace(lines[thisstmt])
199201
want = thislevel * 4
200202
if want < 0:
@@ -206,7 +208,7 @@ def run(self):
206208
want = have2want.get(have, -1)
207209
if want < 0:
208210
# Then it probably belongs to the next real stmt.
209-
for j in range(i+1, len(stats)-1):
211+
for j in range(i + 1, len(stats) - 1):
210212
jline, jlevel = stats[j]
211213
if jlevel >= 0:
212214
if have == getlspace(lines[jline]):
@@ -216,11 +218,11 @@ def run(self):
216218
# comment like this one,
217219
# in which case we should shift it like its base
218220
# line got shifted.
219-
for j in range(i-1, -1, -1):
221+
for j in range(i - 1, -1, -1):
220222
jline, jlevel = stats[j]
221223
if jlevel >= 0:
222-
want = have + getlspace(after[jline-1]) - \
223-
getlspace(lines[jline])
224+
want = have + (getlspace(after[jline - 1]) -
225+
getlspace(lines[jline]))
224226
break
225227
if want < 0:
226228
# Still no luck -- leave it alone.
@@ -295,12 +297,14 @@ def tokeneater(self, type, token, slinecol, end, line,
295297
if line: # not endmarker
296298
self.stats.append((slinecol[0], self.level))
297299

300+
298301
# Count number of leading blanks.
299302
def getlspace(line):
300303
i, n = 0, len(line)
301304
while i < n and line[i] == " ":
302305
i += 1
303306
return i
304307

308+
305309
if __name__ == '__main__':
306310
main()

Tools/scripts/rgrep.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
import re
1010
import getopt
1111

12+
1213
def main():
13-
bufsize = 64*1024
14+
bufsize = 64 * 1024
1415
reflags = 0
1516
opts, args = getopt.getopt(sys.argv[1:], "i")
1617
for o, a in opts:
@@ -24,11 +25,11 @@ def main():
2425
try:
2526
prog = re.compile(pattern, reflags)
2627
except re.error as msg:
27-
usage("error in regular expression: %s" % str(msg))
28+
usage("error in regular expression: %s" % msg)
2829
try:
2930
f = open(filename)
3031
except IOError as msg:
31-
usage("can't open %s: %s" % (repr(filename), str(msg)), 1)
32+
usage("can't open %r: %s" % (filename, msg), 1)
3233
f.seek(0, 2)
3334
pos = f.tell()
3435
leftover = None
@@ -49,16 +50,17 @@ def main():
4950
del lines[0]
5051
else:
5152
leftover = None
52-
lines.reverse()
53-
for line in lines:
53+
for line in reversed(lines):
5454
if prog.search(line):
5555
print(line)
5656

57+
5758
def usage(msg, code=2):
5859
sys.stdout = sys.stderr
5960
print(msg)
6061
print(__doc__)
6162
sys.exit(code)
6263

64+
6365
if __name__ == '__main__':
6466
main()

0 commit comments

Comments
 (0)