blob: 3322b7afbf73fadee5c78b28fe44bebfe5258c79 [file] [log] [blame]
Guido van Rossum0af9a281992-01-01 18:38:21 +00001#! /ufs/guido/bin/sgi/python
2#! /usr/local/python
3
Guido van Rossum318a91c1992-01-01 19:22:25 +00004# Fix Python source files to use the new equality test operator, i.e.,
Guido van Rossum0af9a281992-01-01 18:38:21 +00005# if x = y: ...
Guido van Rossum318a91c1992-01-01 19:22:25 +00006# is changed to
7# if x == y: ...
8# The script correctly tokenizes the Python program to reliably
9# distinguish between assignments and equality tests.
Guido van Rossum0af9a281992-01-01 18:38:21 +000010#
11# Command line arguments are files or directories to be processed.
12# Directories are searched recursively for files whose name looks
13# like a python module.
14# Symbolic links are always ignored (except as explicit directory
15# arguments). Of course, the original file is kept as a back-up
16# (with a "~" attached to its name).
17#
18# Changes made are reported to stdout in a diff-like format.
19#
20# Undoubtedly you can do this using find and sed or perl, but this is
21# a nice example of Python code that recurses down a directory tree
22# and uses regular expressions. Also note several subtleties like
23# preserving the file's mode and avoiding to even write a temp file
24# when no changes are needed for a file.
25#
26# NB: by changing only the function fixline() you can turn this
27# into a program for a different change to Python programs...
28
29import sys
30import regex
31import posix
32import path
33from stat import *
34
35err = sys.stderr.write
36dbg = err
37rep = sys.stdout.write
38
39def main():
40 bad = 0
41 if not sys.argv[1:]: # No arguments
42 err('usage: ' + argv[0] + ' file-or-directory ...\n')
43 sys.exit(2)
44 for arg in sys.argv[1:]:
45 if path.isdir(arg):
46 if recursedown(arg): bad = 1
47 elif path.islink(arg):
48 err(arg + ': will not process symbolic links\n')
49 bad = 1
50 else:
51 if fix(arg): bad = 1
52 sys.exit(bad)
53
54ispythonprog = regex.compile('^[a-zA-Z0-9_]+\.py$')
55def ispython(name):
56 return ispythonprog.match(name) >= 0
57
58def recursedown(dirname):
59 dbg('recursedown(' + `dirname` + ')\n')
60 bad = 0
61 try:
62 names = posix.listdir(dirname)
63 except posix.error, msg:
64 err(dirname + ': cannot list directory: ' + `msg` + '\n')
65 return 1
66 names.sort()
67 subdirs = []
68 for name in names:
69 if name in ('.', '..'): continue
70 fullname = path.join(dirname, name)
71 if path.islink(fullname): pass
72 elif path.isdir(fullname):
73 subdirs.append(fullname)
74 elif ispython(name):
75 if fix(fullname): bad = 1
76 for fullname in subdirs:
77 if recursedown(fullname): bad = 1
78 return bad
79
80def fix(filename):
Guido van Rossum318a91c1992-01-01 19:22:25 +000081## dbg('fix(' + `filename` + ')\n')
Guido van Rossum0af9a281992-01-01 18:38:21 +000082 try:
83 f = open(filename, 'r')
84 except IOError, msg:
85 err(filename + ': cannot open: ' + `msg` + '\n')
86 return 1
87 head, tail = path.split(filename)
88 tempname = path.join(head, '@' + tail)
89 g = None
90 # If we find a match, we rewind the file and start over but
91 # now copy everything to a temp file.
92 lineno = 0
93 while 1:
94 line = f.readline()
95 if not line: break
96 lineno = lineno + 1
97 while line[-2:] == '\\\n':
98 nextline = f.readline()
99 if not nextline: break
100 line = line + nextline
101 lineno = lineno + 1
102 newline = fixline(line)
103 if newline != line:
104 if g is None:
105 try:
106 g = open(tempname, 'w')
107 except IOError, msg:
108 f.close()
109 err(tempname+': cannot create: '+\
110 `msg`+'\n')
111 return 1
112 f.seek(0)
113 lineno = 0
114 rep(filename + ':\n')
115 continue # restart from the beginning
116 rep(`lineno` + '\n')
117 rep('< ' + line)
118 rep('> ' + newline)
119 if g is not None:
120 g.write(newline)
121
122 # End of file
123 f.close()
124 if not g: return 0 # No changes
125
126 # Finishing touch -- move files
127
128 # First copy the file's mode to the temp file
129 try:
130 statbuf = posix.stat(filename)
131 posix.chmod(tempname, statbuf[ST_MODE] & 07777)
132 except posix.error, msg:
133 err(tempname + ': warning: chmod failed (' + `msg` + ')\n')
134 # Then make a backup of the original file as filename~
135 try:
136 posix.rename(filename, filename + '~')
137 except posix.error, msg:
138 err(filename + ': warning: backup failed (' + `msg` + ')\n')
139 # Now move the temp file to the original file
140 try:
141 posix.rename(tempname, filename)
142 except posix.error, msg:
143 err(filename + ': rename failed (' + `msg` + ')\n')
144 return 1
145 # Return succes
146 return 0
147
Guido van Rossum318a91c1992-01-01 19:22:25 +0000148
149from tokenize import tokenprog
150
151match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \
152 '(':')', '[':']', '{':'}', '`':'`'}
Guido van Rossum0af9a281992-01-01 18:38:21 +0000153
154def fixline(line):
Guido van Rossum318a91c1992-01-01 19:22:25 +0000155 # Quick check for easy case
156 if '=' not in line: return line
157
158 i, n = 0, len(line)
159 stack = []
160 while i < n:
161 j = tokenprog.match(line, i)
162 if j < 0:
163 # A bad token; forget about the rest of this line
164 print '(Syntax error:)'
165 print line,
166 return line
167 a, b = tokenprog.regs[3] # Location of the token proper
168 token = line[a:b]
169 i = i+j
170 if stack and token == stack[-1]:
171 del stack[-1]
172 elif match.has_key(token):
173 stack.append(match[token])
174 elif token == '=' and stack:
175 line = line[:a] + '==' + line[b:]
176 i, n = a + len('=='), len(line)
177 elif token == '==' and not stack:
178 print '(Warning: \'==\' at top level:)'
179 print line,
Guido van Rossum0af9a281992-01-01 18:38:21 +0000180 return line
181
Guido van Rossum318a91c1992-01-01 19:22:25 +0000182
Guido van Rossum0af9a281992-01-01 18:38:21 +0000183main()