blob: 49e37041b03c81c9571602ae715d2a7279b40049 [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).
Guido van Rossumbecdad31992-03-02 16:18:31 +000017# It complains about binaries (files containing null bytes)
18# and about files that are ostensibly not Python files: if the first
19# line starts with '#!' and does not contain the string 'python'.
Guido van Rossum0af9a281992-01-01 18:38:21 +000020#
21# Changes made are reported to stdout in a diff-like format.
22#
23# Undoubtedly you can do this using find and sed or perl, but this is
24# a nice example of Python code that recurses down a directory tree
25# and uses regular expressions. Also note several subtleties like
26# preserving the file's mode and avoiding to even write a temp file
27# when no changes are needed for a file.
28#
29# NB: by changing only the function fixline() you can turn this
30# into a program for a different change to Python programs...
31
32import sys
33import regex
Guido van Rossumb2ac8091992-03-30 11:12:23 +000034import os
Guido van Rossum0af9a281992-01-01 18:38:21 +000035from stat import *
Guido van Rossumbecdad31992-03-02 16:18:31 +000036import string
Guido van Rossum0af9a281992-01-01 18:38:21 +000037
38err = sys.stderr.write
39dbg = err
40rep = sys.stdout.write
41
42def main():
43 bad = 0
44 if not sys.argv[1:]: # No arguments
45 err('usage: ' + argv[0] + ' file-or-directory ...\n')
46 sys.exit(2)
47 for arg in sys.argv[1:]:
Guido van Rossumb2ac8091992-03-30 11:12:23 +000048 if os.path.isdir(arg):
Guido van Rossum0af9a281992-01-01 18:38:21 +000049 if recursedown(arg): bad = 1
Guido van Rossumb2ac8091992-03-30 11:12:23 +000050 elif os.path.islink(arg):
Guido van Rossum0af9a281992-01-01 18:38:21 +000051 err(arg + ': will not process symbolic links\n')
52 bad = 1
53 else:
54 if fix(arg): bad = 1
55 sys.exit(bad)
56
57ispythonprog = regex.compile('^[a-zA-Z0-9_]+\.py$')
58def ispython(name):
59 return ispythonprog.match(name) >= 0
60
61def recursedown(dirname):
62 dbg('recursedown(' + `dirname` + ')\n')
63 bad = 0
64 try:
Guido van Rossumb2ac8091992-03-30 11:12:23 +000065 names = os.listdir(dirname)
66 except os.error, msg:
Guido van Rossum0af9a281992-01-01 18:38:21 +000067 err(dirname + ': cannot list directory: ' + `msg` + '\n')
68 return 1
69 names.sort()
70 subdirs = []
71 for name in names:
Guido van Rossumb2ac8091992-03-30 11:12:23 +000072 if name in (os.curdir, os.pardir): continue
73 fullname = os.path.join(dirname, name)
74 if os.path.islink(fullname): pass
75 elif os.path.isdir(fullname):
Guido van Rossum0af9a281992-01-01 18:38:21 +000076 subdirs.append(fullname)
77 elif ispython(name):
78 if fix(fullname): bad = 1
79 for fullname in subdirs:
80 if recursedown(fullname): bad = 1
81 return bad
82
83def fix(filename):
Guido van Rossum318a91c1992-01-01 19:22:25 +000084## dbg('fix(' + `filename` + ')\n')
Guido van Rossum0af9a281992-01-01 18:38:21 +000085 try:
86 f = open(filename, 'r')
87 except IOError, msg:
88 err(filename + ': cannot open: ' + `msg` + '\n')
89 return 1
Guido van Rossumb2ac8091992-03-30 11:12:23 +000090 head, tail = os.path.split(filename)
91 tempname = os.path.join(head, '@' + tail)
Guido van Rossum0af9a281992-01-01 18:38:21 +000092 g = None
93 # If we find a match, we rewind the file and start over but
94 # now copy everything to a temp file.
95 lineno = 0
96 while 1:
97 line = f.readline()
98 if not line: break
99 lineno = lineno + 1
Guido van Rossumbecdad31992-03-02 16:18:31 +0000100 if g is None and '\0' in line:
101 # Check for binary files
102 err(filename + ': contains null bytes; not fixed\n')
103 f.close()
104 return 1
105 if lineno == 1 and g is None and line[:2] == '#!':
106 # Check for non-Python scripts
107 words = string.split(line[2:])
108 if words and regex.search('[pP]ython', words[0]) < 0:
109 msg = filename + ': ' + words[0]
110 msg = msg + ' script; not fixed\n'
111 err(msg)
112 f.close()
113 return 1
Guido van Rossum0af9a281992-01-01 18:38:21 +0000114 while line[-2:] == '\\\n':
115 nextline = f.readline()
116 if not nextline: break
117 line = line + nextline
118 lineno = lineno + 1
119 newline = fixline(line)
120 if newline != line:
121 if g is None:
122 try:
123 g = open(tempname, 'w')
124 except IOError, msg:
125 f.close()
126 err(tempname+': cannot create: '+\
127 `msg`+'\n')
128 return 1
129 f.seek(0)
130 lineno = 0
131 rep(filename + ':\n')
132 continue # restart from the beginning
133 rep(`lineno` + '\n')
134 rep('< ' + line)
135 rep('> ' + newline)
136 if g is not None:
137 g.write(newline)
138
139 # End of file
140 f.close()
141 if not g: return 0 # No changes
142
143 # Finishing touch -- move files
144
145 # First copy the file's mode to the temp file
146 try:
Guido van Rossumb2ac8091992-03-30 11:12:23 +0000147 statbuf = os.stat(filename)
148 os.chmod(tempname, statbuf[ST_MODE] & 07777)
149 except os.error, msg:
Guido van Rossum0af9a281992-01-01 18:38:21 +0000150 err(tempname + ': warning: chmod failed (' + `msg` + ')\n')
151 # Then make a backup of the original file as filename~
152 try:
Guido van Rossumb2ac8091992-03-30 11:12:23 +0000153 os.rename(filename, filename + '~')
154 except os.error, msg:
Guido van Rossum0af9a281992-01-01 18:38:21 +0000155 err(filename + ': warning: backup failed (' + `msg` + ')\n')
156 # Now move the temp file to the original file
157 try:
Guido van Rossumb2ac8091992-03-30 11:12:23 +0000158 os.rename(tempname, filename)
159 except os.error, msg:
Guido van Rossum0af9a281992-01-01 18:38:21 +0000160 err(filename + ': rename failed (' + `msg` + ')\n')
161 return 1
162 # Return succes
163 return 0
164
Guido van Rossum318a91c1992-01-01 19:22:25 +0000165
166from tokenize import tokenprog
167
168match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \
169 '(':')', '[':']', '{':'}', '`':'`'}
Guido van Rossum0af9a281992-01-01 18:38:21 +0000170
171def fixline(line):
Guido van Rossum318a91c1992-01-01 19:22:25 +0000172 # Quick check for easy case
173 if '=' not in line: return line
174
175 i, n = 0, len(line)
176 stack = []
177 while i < n:
178 j = tokenprog.match(line, i)
179 if j < 0:
180 # A bad token; forget about the rest of this line
181 print '(Syntax error:)'
182 print line,
183 return line
184 a, b = tokenprog.regs[3] # Location of the token proper
185 token = line[a:b]
186 i = i+j
187 if stack and token == stack[-1]:
188 del stack[-1]
189 elif match.has_key(token):
190 stack.append(match[token])
191 elif token == '=' and stack:
192 line = line[:a] + '==' + line[b:]
193 i, n = a + len('=='), len(line)
194 elif token == '==' and not stack:
195 print '(Warning: \'==\' at top level:)'
196 print line,
Guido van Rossum0af9a281992-01-01 18:38:21 +0000197 return line
198
Guido van Rossum318a91c1992-01-01 19:22:25 +0000199
Guido van Rossum0af9a281992-01-01 18:38:21 +0000200main()