blob: 5edf584548c54c2b73fd0082595531b97f50bb29 [file] [log] [blame]
Martin v. Löwisef04c442008-03-19 05:04:44 +00001# Copyright 2006 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Refactoring framework.
5
6Used as a main program, this can refactor any number of files and/or
7recursively descend down directories. Imported as a module, this
8provides infrastructure to write your own refactoring tool.
9"""
10
11__author__ = "Guido van Rossum <guido@python.org>"
12
13
14# Python imports
15import os
16import sys
Martin v. Löwisef04c442008-03-19 05:04:44 +000017import logging
Benjamin Peterson8951b612008-09-03 02:27:16 +000018import operator
Benjamin Peterson3059b002009-07-20 16:42:03 +000019import collections
20import io
21import warnings
Christian Heimes81ee3ef2008-05-04 22:42:01 +000022from itertools import chain
Martin v. Löwisef04c442008-03-19 05:04:44 +000023
24# Local imports
Benjamin Peterson3059b002009-07-20 16:42:03 +000025from .pgen2 import driver, tokenize, token
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000026from . import pytree, pygram
Martin v. Löwisef04c442008-03-19 05:04:44 +000027
Martin v. Löwisef04c442008-03-19 05:04:44 +000028
Benjamin Peterson8951b612008-09-03 02:27:16 +000029def get_all_fix_names(fixer_pkg, remove_prefix=True):
30 """Return a sorted list of all available fix names in the given package."""
31 pkg = __import__(fixer_pkg, [], [], ["*"])
32 fixer_dir = os.path.dirname(pkg.__file__)
Martin v. Löwisef04c442008-03-19 05:04:44 +000033 fix_names = []
Benjamin Peterson206e3072008-10-19 14:07:49 +000034 for name in sorted(os.listdir(fixer_dir)):
Martin v. Löwisef04c442008-03-19 05:04:44 +000035 if name.startswith("fix_") and name.endswith(".py"):
Benjamin Peterson8951b612008-09-03 02:27:16 +000036 if remove_prefix:
37 name = name[4:]
38 fix_names.append(name[:-3])
Martin v. Löwisef04c442008-03-19 05:04:44 +000039 return fix_names
40
Benjamin Peterson3059b002009-07-20 16:42:03 +000041
42class _EveryNode(Exception):
43 pass
44
45
46def _get_head_types(pat):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000047 """ Accepts a pytree Pattern Node and returns a set
48 of the pattern types which will match first. """
49
50 if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
51 # NodePatters must either have no type and no content
52 # or a type and content -- so they don't get any farther
53 # Always return leafs
Benjamin Peterson3059b002009-07-20 16:42:03 +000054 if pat.type is None:
55 raise _EveryNode
Christian Heimes81ee3ef2008-05-04 22:42:01 +000056 return set([pat.type])
57
58 if isinstance(pat, pytree.NegatedPattern):
59 if pat.content:
Benjamin Peterson3059b002009-07-20 16:42:03 +000060 return _get_head_types(pat.content)
61 raise _EveryNode # Negated Patterns don't have a type
Christian Heimes81ee3ef2008-05-04 22:42:01 +000062
63 if isinstance(pat, pytree.WildcardPattern):
64 # Recurse on each node in content
65 r = set()
66 for p in pat.content:
67 for x in p:
Benjamin Peterson3059b002009-07-20 16:42:03 +000068 r.update(_get_head_types(x))
Christian Heimes81ee3ef2008-05-04 22:42:01 +000069 return r
70
71 raise Exception("Oh no! I don't understand pattern %s" %(pat))
72
Benjamin Peterson3059b002009-07-20 16:42:03 +000073
74def _get_headnode_dict(fixer_list):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000075 """ Accepts a list of fixers and returns a dictionary
76 of head node type --> fixer list. """
Benjamin Peterson3059b002009-07-20 16:42:03 +000077 head_nodes = collections.defaultdict(list)
78 every = []
Christian Heimes81ee3ef2008-05-04 22:42:01 +000079 for fixer in fixer_list:
Benjamin Peterson3059b002009-07-20 16:42:03 +000080 if fixer.pattern:
81 try:
82 heads = _get_head_types(fixer.pattern)
83 except _EveryNode:
84 every.append(fixer)
85 else:
86 for node_type in heads:
87 head_nodes[node_type].append(fixer)
88 else:
89 if fixer._accept_type is not None:
90 head_nodes[fixer._accept_type].append(fixer)
91 else:
92 every.append(fixer)
93 for node_type in chain(pygram.python_grammar.symbol2number.values(),
94 pygram.python_grammar.tokens):
95 head_nodes[node_type].extend(every)
96 return dict(head_nodes)
97
Christian Heimes81ee3ef2008-05-04 22:42:01 +000098
Benjamin Peterson8951b612008-09-03 02:27:16 +000099def get_fixers_from_package(pkg_name):
100 """
101 Return the fully qualified names for fixers in the package pkg_name.
102 """
103 return [pkg_name + "." + fix_name
104 for fix_name in get_all_fix_names(pkg_name, False)]
105
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000106def _identity(obj):
107 return obj
108
109if sys.version_info < (3, 0):
110 import codecs
111 _open_with_encoding = codecs.open
112 # codecs.open doesn't translate newlines sadly.
113 def _from_system_newlines(input):
114 return input.replace("\r\n", "\n")
115 def _to_system_newlines(input):
116 if os.linesep != "\n":
117 return input.replace("\n", os.linesep)
118 else:
119 return input
120else:
121 _open_with_encoding = open
122 _from_system_newlines = _identity
123 _to_system_newlines = _identity
124
Martin v. Löwisef04c442008-03-19 05:04:44 +0000125
Benjamin Peterson3059b002009-07-20 16:42:03 +0000126def _detect_future_print(source):
127 have_docstring = False
128 gen = tokenize.generate_tokens(io.StringIO(source).readline)
129 def advance():
130 tok = next(gen)
131 return tok[0], tok[1]
132 ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT))
133 try:
134 while True:
135 tp, value = advance()
136 if tp in ignore:
137 continue
138 elif tp == token.STRING:
139 if have_docstring:
140 break
141 have_docstring = True
142 elif tp == token.NAME:
143 if value == "from":
144 tp, value = advance()
145 if tp != token.NAME and value != "__future__":
146 break
147 tp, value = advance()
148 if tp != token.NAME and value != "import":
149 break
150 tp, value = advance()
151 if tp == token.OP and value == "(":
152 tp, value = advance()
153 while tp == token.NAME:
154 if value == "print_function":
155 return True
156 tp, value = advance()
157 if tp != token.OP and value != ",":
158 break
159 tp, value = advance()
160 else:
161 break
162 else:
163 break
164 except StopIteration:
165 pass
166 return False
167
168
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000169class FixerError(Exception):
170 """A fixer could not be loaded."""
171
172
Martin v. Löwisef04c442008-03-19 05:04:44 +0000173class RefactoringTool(object):
174
Benjamin Peterson3059b002009-07-20 16:42:03 +0000175 _default_options = {}
Benjamin Peterson8951b612008-09-03 02:27:16 +0000176
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000177 CLASS_PREFIX = "Fix" # The prefix for fixer classes
178 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
179
180 def __init__(self, fixer_names, options=None, explicit=None):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000181 """Initializer.
182
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000183 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000184 fixer_names: a list of fixers to import
185 options: an dict with configuration.
186 explicit: a list of fixers to run even if they are explicit.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000187 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000188 self.fixers = fixer_names
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000189 self.explicit = explicit or []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000190 self.options = self._default_options.copy()
191 if options is not None:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000192 if "print_function" in options:
193 warnings.warn("the 'print_function' option is deprecated",
194 DeprecationWarning)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000195 self.options.update(options)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000196 self.errors = []
197 self.logger = logging.getLogger("RefactoringTool")
198 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000199 self.wrote = False
Martin v. Löwisef04c442008-03-19 05:04:44 +0000200 self.driver = driver.Driver(pygram.python_grammar,
201 convert=pytree.convert,
202 logger=self.logger)
203 self.pre_order, self.post_order = self.get_fixers()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000204
Benjamin Peterson3059b002009-07-20 16:42:03 +0000205 self.pre_order_heads = _get_headnode_dict(self.pre_order)
206 self.post_order_heads = _get_headnode_dict(self.post_order)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000207
Martin v. Löwisef04c442008-03-19 05:04:44 +0000208 self.files = [] # List of files that were or should be modified
209
210 def get_fixers(self):
211 """Inspects the options to load the requested patterns and handlers.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000212
Martin v. Löwisef04c442008-03-19 05:04:44 +0000213 Returns:
214 (pre_order, post_order), where pre_order is the list of fixers that
215 want a pre-order AST traversal, and post_order is the list that want
216 post-order traversal.
217 """
218 pre_order_fixers = []
219 post_order_fixers = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000220 for fix_mod_path in self.fixers:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000221 mod = __import__(fix_mod_path, {}, {}, ["*"])
Benjamin Peterson8951b612008-09-03 02:27:16 +0000222 fix_name = fix_mod_path.rsplit(".", 1)[-1]
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000223 if fix_name.startswith(self.FILE_PREFIX):
224 fix_name = fix_name[len(self.FILE_PREFIX):]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000225 parts = fix_name.split("_")
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000226 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000227 try:
228 fix_class = getattr(mod, class_name)
229 except AttributeError:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000230 raise FixerError("Can't find %s.%s" % (fix_name, class_name))
231 fixer = fix_class(self.options, self.fixer_log)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000232 if fixer.explicit and self.explicit is not True and \
233 fix_mod_path not in self.explicit:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000234 self.log_message("Skipping implicit fixer: %s", fix_name)
235 continue
236
Benjamin Peterson8951b612008-09-03 02:27:16 +0000237 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000238 if fixer.order == "pre":
239 pre_order_fixers.append(fixer)
240 elif fixer.order == "post":
241 post_order_fixers.append(fixer)
242 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000243 raise FixerError("Illegal fixer order: %r" % fixer.order)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000244
Benjamin Peterson8951b612008-09-03 02:27:16 +0000245 key_func = operator.attrgetter("run_order")
246 pre_order_fixers.sort(key=key_func)
247 post_order_fixers.sort(key=key_func)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000248 return (pre_order_fixers, post_order_fixers)
249
250 def log_error(self, msg, *args, **kwds):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000251 """Called when an error occurs."""
252 raise
Martin v. Löwisef04c442008-03-19 05:04:44 +0000253
254 def log_message(self, msg, *args):
255 """Hook to log a message."""
256 if args:
257 msg = msg % args
258 self.logger.info(msg)
259
Benjamin Peterson8951b612008-09-03 02:27:16 +0000260 def log_debug(self, msg, *args):
261 if args:
262 msg = msg % args
263 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000264
Benjamin Peterson3059b002009-07-20 16:42:03 +0000265 def print_output(self, old_text, new_text, filename, equal):
266 """Called with the old version, new version, and filename of a
267 refactored file."""
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000268 pass
269
Benjamin Peterson8951b612008-09-03 02:27:16 +0000270 def refactor(self, items, write=False, doctests_only=False):
271 """Refactor a list of files and directories."""
272 for dir_or_file in items:
273 if os.path.isdir(dir_or_file):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000274 self.refactor_dir(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000275 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000276 self.refactor_file(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000277
278 def refactor_dir(self, dir_name, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000279 """Descends down a directory and refactor every Python file found.
280
281 Python files are assumed to have a .py extension.
282
283 Files and subdirectories starting with '.' are skipped.
284 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000285 for dirpath, dirnames, filenames in os.walk(dir_name):
286 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000287 dirnames.sort()
288 filenames.sort()
289 for name in filenames:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000290 if not name.startswith(".") and \
291 os.path.splitext(name)[1].endswith("py"):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000292 fullname = os.path.join(dirpath, name)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000293 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000294 # Modify dirnames in-place to remove subdirs with leading dots
295 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
296
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000297 def _read_python_source(self, filename):
298 """
299 Do our best to decode a Python source file correctly.
300 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000301 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000302 f = open(filename, "rb")
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000303 except IOError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000304 self.log_error("Can't open %s: %s", filename, err)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000305 return None, None
Martin v. Löwisef04c442008-03-19 05:04:44 +0000306 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000307 encoding = tokenize.detect_encoding(f.readline)[0]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000308 finally:
309 f.close()
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000310 with _open_with_encoding(filename, "r", encoding=encoding) as f:
311 return _from_system_newlines(f.read()), encoding
312
313 def refactor_file(self, filename, write=False, doctests_only=False):
314 """Refactors a file."""
315 input, encoding = self._read_python_source(filename)
316 if input is None:
317 # Reading the file failed.
318 return
319 input += "\n" # Silence certain parse errors
Benjamin Peterson8951b612008-09-03 02:27:16 +0000320 if doctests_only:
321 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000322 output = self.refactor_docstring(input, filename)
323 if output != input:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000324 self.processed_file(output, filename, input, write, encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000325 else:
326 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000327 else:
328 tree = self.refactor_string(input, filename)
329 if tree and tree.was_changed:
330 # The [:-1] is to take off the \n we added earlier
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000331 self.processed_file(str(tree)[:-1], filename,
332 write=write, encoding=encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000333 else:
334 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000335
336 def refactor_string(self, data, name):
337 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000338
Martin v. Löwisef04c442008-03-19 05:04:44 +0000339 Args:
340 data: a string holding the code to be refactored.
341 name: a human-readable name for use in error/log messages.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000342
Martin v. Löwisef04c442008-03-19 05:04:44 +0000343 Returns:
344 An AST corresponding to the refactored input stream; None if
345 there were errors during the parse.
346 """
Benjamin Peterson3059b002009-07-20 16:42:03 +0000347 if _detect_future_print(data):
348 self.driver.grammar = pygram.python_grammar_no_print_statement
Martin v. Löwisef04c442008-03-19 05:04:44 +0000349 try:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000350 tree = self.driver.parse_string(data)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000351 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000352 self.log_error("Can't parse %s: %s: %s",
353 name, err.__class__.__name__, err)
354 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000355 finally:
356 self.driver.grammar = pygram.python_grammar
Benjamin Peterson8951b612008-09-03 02:27:16 +0000357 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000358 self.refactor_tree(tree, name)
359 return tree
360
Benjamin Peterson8951b612008-09-03 02:27:16 +0000361 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000362 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000363 if doctests_only:
364 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000365 output = self.refactor_docstring(input, "<stdin>")
366 if output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000367 self.processed_file(output, "<stdin>", input)
368 else:
369 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000370 else:
371 tree = self.refactor_string(input, "<stdin>")
372 if tree and tree.was_changed:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000373 self.processed_file(str(tree), "<stdin>", input)
374 else:
375 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000376
377 def refactor_tree(self, tree, name):
378 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000379
Martin v. Löwisef04c442008-03-19 05:04:44 +0000380 Args:
381 tree: a pytree.Node instance representing the root of the tree
382 to be refactored.
383 name: a human-readable name for this tree.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000384
Martin v. Löwisef04c442008-03-19 05:04:44 +0000385 Returns:
386 True if the tree was modified, False otherwise.
387 """
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000388 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000389 fixer.start_tree(tree, name)
390
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000391 self.traverse_by(self.pre_order_heads, tree.pre_order())
392 self.traverse_by(self.post_order_heads, tree.post_order())
Martin v. Löwisef04c442008-03-19 05:04:44 +0000393
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000394 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000395 fixer.finish_tree(tree, name)
396 return tree.was_changed
397
398 def traverse_by(self, fixers, traversal):
399 """Traverse an AST, applying a set of fixers to each node.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000400
Martin v. Löwisef04c442008-03-19 05:04:44 +0000401 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000402
Martin v. Löwisef04c442008-03-19 05:04:44 +0000403 Args:
404 fixers: a list of fixer instances.
405 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000406
Martin v. Löwisef04c442008-03-19 05:04:44 +0000407 Returns:
408 None
409 """
410 if not fixers:
411 return
412 for node in traversal:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000413 for fixer in fixers[node.type]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000414 results = fixer.match(node)
415 if results:
416 new = fixer.transform(node, results)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000417 if new is not None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000418 node.replace(new)
419 node = new
420
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000421 def processed_file(self, new_text, filename, old_text=None, write=False,
422 encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000423 """
424 Called when a file has been refactored, and there are changes.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000425 """
426 self.files.append(filename)
427 if old_text is None:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000428 old_text = self._read_python_source(filename)[0]
429 if old_text is None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000430 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000431 equal = old_text == new_text
432 self.print_output(old_text, new_text, filename, equal)
433 if equal:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000434 self.log_debug("No changes to %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000435 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000436 if write:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000437 self.write_file(new_text, filename, old_text, encoding)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000438 else:
439 self.log_debug("Not writing changes to %s", filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000440
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000441 def write_file(self, new_text, filename, old_text, encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000442 """Writes a string to a file.
443
444 It first shows a unified diff between the old text and the new text, and
445 then rewrites the file; the latter is only done if the write option is
446 set.
447 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000448 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000449 f = _open_with_encoding(filename, "w", encoding=encoding)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000450 except os.error as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000451 self.log_error("Can't create %s: %s", filename, err)
452 return
453 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000454 f.write(_to_system_newlines(new_text))
Benjamin Petersonba558182008-11-10 22:21:33 +0000455 except os.error as err:
456 self.log_error("Can't write %s: %s", filename, err)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000457 finally:
458 f.close()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000459 self.log_debug("Wrote changes to %s", filename)
460 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000461
462 PS1 = ">>> "
463 PS2 = "... "
464
465 def refactor_docstring(self, input, filename):
466 """Refactors a docstring, looking for doctests.
467
468 This returns a modified version of the input string. It looks
469 for doctests, which start with a ">>>" prompt, and may be
470 continued with "..." prompts, as long as the "..." is indented
471 the same as the ">>>".
472
473 (Unfortunately we can't use the doctest module's parser,
474 since, like most parsers, it is not geared towards preserving
475 the original source.)
476 """
477 result = []
478 block = None
479 block_lineno = None
480 indent = None
481 lineno = 0
482 for line in input.splitlines(True):
483 lineno += 1
484 if line.lstrip().startswith(self.PS1):
485 if block is not None:
486 result.extend(self.refactor_doctest(block, block_lineno,
487 indent, filename))
488 block_lineno = lineno
489 block = [line]
490 i = line.find(self.PS1)
491 indent = line[:i]
492 elif (indent is not None and
493 (line.startswith(indent + self.PS2) or
494 line == indent + self.PS2.rstrip() + "\n")):
495 block.append(line)
496 else:
497 if block is not None:
498 result.extend(self.refactor_doctest(block, block_lineno,
499 indent, filename))
500 block = None
501 indent = None
502 result.append(line)
503 if block is not None:
504 result.extend(self.refactor_doctest(block, block_lineno,
505 indent, filename))
506 return "".join(result)
507
508 def refactor_doctest(self, block, lineno, indent, filename):
509 """Refactors one doctest.
510
511 A doctest is given as a block of lines, the first of which starts
512 with ">>>" (possibly indented), while the remaining lines start
513 with "..." (identically indented).
514
515 """
516 try:
517 tree = self.parse_block(block, lineno, indent)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000518 except Exception as err:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000519 if self.log.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000520 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000521 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000522 self.log_error("Can't parse docstring in %s line %s: %s: %s",
523 filename, lineno, err.__class__.__name__, err)
524 return block
525 if self.refactor_tree(tree, filename):
526 new = str(tree).splitlines(True)
527 # Undo the adjustment of the line numbers in wrap_toks() below.
528 clipped, new = new[:lineno-1], new[lineno-1:]
529 assert clipped == ["\n"] * (lineno-1), clipped
530 if not new[-1].endswith("\n"):
531 new[-1] += "\n"
532 block = [indent + self.PS1 + new.pop(0)]
533 if new:
534 block += [indent + self.PS2 + line for line in new]
535 return block
536
537 def summarize(self):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000538 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000539 were = "were"
540 else:
541 were = "need to be"
542 if not self.files:
543 self.log_message("No files %s modified.", were)
544 else:
545 self.log_message("Files that %s modified:", were)
546 for file in self.files:
547 self.log_message(file)
548 if self.fixer_log:
549 self.log_message("Warnings/messages while refactoring:")
550 for message in self.fixer_log:
551 self.log_message(message)
552 if self.errors:
553 if len(self.errors) == 1:
554 self.log_message("There was 1 error:")
555 else:
556 self.log_message("There were %d errors:", len(self.errors))
557 for msg, args, kwds in self.errors:
558 self.log_message(msg, *args, **kwds)
559
560 def parse_block(self, block, lineno, indent):
561 """Parses a block into a tree.
562
563 This is necessary to get correct line number / offset information
564 in the parser diagnostics and embedded into the parse tree.
565 """
566 return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
567
568 def wrap_toks(self, block, lineno, indent):
569 """Wraps a tokenize stream to systematically modify start/end."""
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000570 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000571 for type, value, (line0, col0), (line1, col1), line_text in tokens:
572 line0 += lineno - 1
573 line1 += lineno - 1
574 # Don't bother updating the columns; this is too complicated
575 # since line_text would also have to be updated and it would
576 # still break for tokens spanning lines. Let the user guess
577 # that the column numbers for doctests are relative to the
578 # end of the prompt string (PS1 or PS2).
579 yield type, value, (line0, col0), (line1, col1), line_text
580
581
582 def gen_lines(self, block, indent):
583 """Generates lines as expected by tokenize from a list of lines.
584
585 This strips the first len(indent + self.PS1) characters off each line.
586 """
587 prefix1 = indent + self.PS1
588 prefix2 = indent + self.PS2
589 prefix = prefix1
590 for line in block:
591 if line.startswith(prefix):
592 yield line[len(prefix):]
593 elif line == prefix.rstrip() + "\n":
594 yield "\n"
595 else:
596 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
597 prefix = prefix2
598 while True:
599 yield ""
600
601
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000602class MultiprocessingUnsupported(Exception):
603 pass
604
605
606class MultiprocessRefactoringTool(RefactoringTool):
607
608 def __init__(self, *args, **kwargs):
609 super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
610 self.queue = None
611
612 def refactor(self, items, write=False, doctests_only=False,
613 num_processes=1):
614 if num_processes == 1:
615 return super(MultiprocessRefactoringTool, self).refactor(
616 items, write, doctests_only)
617 try:
618 import multiprocessing
619 except ImportError:
620 raise MultiprocessingUnsupported
621 if self.queue is not None:
622 raise RuntimeError("already doing multiple processes")
623 self.queue = multiprocessing.JoinableQueue()
624 processes = [multiprocessing.Process(target=self._child)
Benjamin Peterson87b87192009-07-03 13:18:18 +0000625 for i in range(num_processes)]
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000626 try:
627 for p in processes:
628 p.start()
629 super(MultiprocessRefactoringTool, self).refactor(items, write,
630 doctests_only)
631 finally:
632 self.queue.join()
Benjamin Peterson87b87192009-07-03 13:18:18 +0000633 for i in range(num_processes):
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000634 self.queue.put(None)
635 for p in processes:
636 if p.is_alive():
637 p.join()
638 self.queue = None
639
640 def _child(self):
641 task = self.queue.get()
642 while task is not None:
643 args, kwargs = task
644 try:
645 super(MultiprocessRefactoringTool, self).refactor_file(
646 *args, **kwargs)
647 finally:
648 self.queue.task_done()
649 task = self.queue.get()
650
651 def refactor_file(self, *args, **kwargs):
652 if self.queue is not None:
653 self.queue.put((args, kwargs))
654 else:
655 return super(MultiprocessRefactoringTool, self).refactor_file(
656 *args, **kwargs)