blob: 82a98d1ade47d99ac4fd135d325ab09fd4dfa435 [file] [log] [blame]
Martin v. Löwisef04c442008-03-19 05:04:44 +00001#!/usr/bin/env python2.5
2# Copyright 2006 Google, Inc. All Rights Reserved.
3# Licensed to PSF under a Contributor Agreement.
4
5"""Refactoring framework.
6
7Used as a main program, this can refactor any number of files and/or
8recursively descend down directories. Imported as a module, this
9provides infrastructure to write your own refactoring tool.
10"""
11
12__author__ = "Guido van Rossum <guido@python.org>"
13
14
15# Python imports
16import os
17import sys
18import difflib
Martin v. Löwisef04c442008-03-19 05:04:44 +000019import logging
Benjamin Peterson8951b612008-09-03 02:27:16 +000020import operator
Christian Heimes81ee3ef2008-05-04 22:42:01 +000021from collections import defaultdict
22from itertools import chain
Martin v. Löwisef04c442008-03-19 05:04:44 +000023
24# Local imports
Benjamin Petersond481e3d2009-05-09 19:42:23 +000025from .pgen2 import driver, tokenize
Martin v. Löwisef04c442008-03-19 05:04:44 +000026
27from . import pytree
28from . import patcomp
29from . import fixes
30from . import pygram
31
Martin v. Löwisef04c442008-03-19 05:04:44 +000032
Benjamin Peterson8951b612008-09-03 02:27:16 +000033def get_all_fix_names(fixer_pkg, remove_prefix=True):
34 """Return a sorted list of all available fix names in the given package."""
35 pkg = __import__(fixer_pkg, [], [], ["*"])
36 fixer_dir = os.path.dirname(pkg.__file__)
Martin v. Löwisef04c442008-03-19 05:04:44 +000037 fix_names = []
Benjamin Peterson206e3072008-10-19 14:07:49 +000038 for name in sorted(os.listdir(fixer_dir)):
Martin v. Löwisef04c442008-03-19 05:04:44 +000039 if name.startswith("fix_") and name.endswith(".py"):
Benjamin Peterson8951b612008-09-03 02:27:16 +000040 if remove_prefix:
41 name = name[4:]
42 fix_names.append(name[:-3])
Martin v. Löwisef04c442008-03-19 05:04:44 +000043 return fix_names
44
Christian Heimes81ee3ef2008-05-04 22:42:01 +000045def get_head_types(pat):
46 """ Accepts a pytree Pattern Node and returns a set
47 of the pattern types which will match first. """
48
49 if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
50 # NodePatters must either have no type and no content
51 # or a type and content -- so they don't get any farther
52 # Always return leafs
53 return set([pat.type])
54
55 if isinstance(pat, pytree.NegatedPattern):
56 if pat.content:
57 return get_head_types(pat.content)
58 return set([None]) # Negated Patterns don't have a type
59
60 if isinstance(pat, pytree.WildcardPattern):
61 # Recurse on each node in content
62 r = set()
63 for p in pat.content:
64 for x in p:
65 r.update(get_head_types(x))
66 return r
67
68 raise Exception("Oh no! I don't understand pattern %s" %(pat))
69
70def get_headnode_dict(fixer_list):
71 """ Accepts a list of fixers and returns a dictionary
72 of head node type --> fixer list. """
73 head_nodes = defaultdict(list)
74 for fixer in fixer_list:
75 if not fixer.pattern:
76 head_nodes[None].append(fixer)
77 continue
78 for t in get_head_types(fixer.pattern):
79 head_nodes[t].append(fixer)
80 return head_nodes
81
Benjamin Peterson8951b612008-09-03 02:27:16 +000082def get_fixers_from_package(pkg_name):
83 """
84 Return the fully qualified names for fixers in the package pkg_name.
85 """
86 return [pkg_name + "." + fix_name
87 for fix_name in get_all_fix_names(pkg_name, False)]
88
Benjamin Petersond481e3d2009-05-09 19:42:23 +000089def _identity(obj):
90 return obj
91
92if sys.version_info < (3, 0):
93 import codecs
94 _open_with_encoding = codecs.open
95 # codecs.open doesn't translate newlines sadly.
96 def _from_system_newlines(input):
97 return input.replace("\r\n", "\n")
98 def _to_system_newlines(input):
99 if os.linesep != "\n":
100 return input.replace("\n", os.linesep)
101 else:
102 return input
103else:
104 _open_with_encoding = open
105 _from_system_newlines = _identity
106 _to_system_newlines = _identity
107
Martin v. Löwisef04c442008-03-19 05:04:44 +0000108
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000109class FixerError(Exception):
110 """A fixer could not be loaded."""
111
112
Martin v. Löwisef04c442008-03-19 05:04:44 +0000113class RefactoringTool(object):
114
Benjamin Peterson8951b612008-09-03 02:27:16 +0000115 _default_options = {"print_function": False}
116
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000117 CLASS_PREFIX = "Fix" # The prefix for fixer classes
118 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
119
120 def __init__(self, fixer_names, options=None, explicit=None):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000121 """Initializer.
122
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000123 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000124 fixer_names: a list of fixers to import
125 options: an dict with configuration.
126 explicit: a list of fixers to run even if they are explicit.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000127 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000128 self.fixers = fixer_names
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000129 self.explicit = explicit or []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000130 self.options = self._default_options.copy()
131 if options is not None:
132 self.options.update(options)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000133 self.errors = []
134 self.logger = logging.getLogger("RefactoringTool")
135 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000136 self.wrote = False
137 if self.options["print_function"]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000138 del pygram.python_grammar.keywords["print"]
139 self.driver = driver.Driver(pygram.python_grammar,
140 convert=pytree.convert,
141 logger=self.logger)
142 self.pre_order, self.post_order = self.get_fixers()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000143
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000144 self.pre_order_heads = get_headnode_dict(self.pre_order)
145 self.post_order_heads = get_headnode_dict(self.post_order)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000146
Martin v. Löwisef04c442008-03-19 05:04:44 +0000147 self.files = [] # List of files that were or should be modified
148
149 def get_fixers(self):
150 """Inspects the options to load the requested patterns and handlers.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000151
Martin v. Löwisef04c442008-03-19 05:04:44 +0000152 Returns:
153 (pre_order, post_order), where pre_order is the list of fixers that
154 want a pre-order AST traversal, and post_order is the list that want
155 post-order traversal.
156 """
157 pre_order_fixers = []
158 post_order_fixers = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000159 for fix_mod_path in self.fixers:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000160 mod = __import__(fix_mod_path, {}, {}, ["*"])
Benjamin Peterson8951b612008-09-03 02:27:16 +0000161 fix_name = fix_mod_path.rsplit(".", 1)[-1]
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000162 if fix_name.startswith(self.FILE_PREFIX):
163 fix_name = fix_name[len(self.FILE_PREFIX):]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000164 parts = fix_name.split("_")
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000165 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000166 try:
167 fix_class = getattr(mod, class_name)
168 except AttributeError:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000169 raise FixerError("Can't find %s.%s" % (fix_name, class_name))
170 fixer = fix_class(self.options, self.fixer_log)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000171 if fixer.explicit and self.explicit is not True and \
172 fix_mod_path not in self.explicit:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000173 self.log_message("Skipping implicit fixer: %s", fix_name)
174 continue
175
Benjamin Peterson8951b612008-09-03 02:27:16 +0000176 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000177 if fixer.order == "pre":
178 pre_order_fixers.append(fixer)
179 elif fixer.order == "post":
180 post_order_fixers.append(fixer)
181 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000182 raise FixerError("Illegal fixer order: %r" % fixer.order)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000183
Benjamin Peterson8951b612008-09-03 02:27:16 +0000184 key_func = operator.attrgetter("run_order")
185 pre_order_fixers.sort(key=key_func)
186 post_order_fixers.sort(key=key_func)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000187 return (pre_order_fixers, post_order_fixers)
188
189 def log_error(self, msg, *args, **kwds):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000190 """Called when an error occurs."""
191 raise
Martin v. Löwisef04c442008-03-19 05:04:44 +0000192
193 def log_message(self, msg, *args):
194 """Hook to log a message."""
195 if args:
196 msg = msg % args
197 self.logger.info(msg)
198
Benjamin Peterson8951b612008-09-03 02:27:16 +0000199 def log_debug(self, msg, *args):
200 if args:
201 msg = msg % args
202 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000203
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000204 def print_output(self, lines):
205 """Called with lines of output to give to the user."""
206 pass
207
Benjamin Peterson8951b612008-09-03 02:27:16 +0000208 def refactor(self, items, write=False, doctests_only=False):
209 """Refactor a list of files and directories."""
210 for dir_or_file in items:
211 if os.path.isdir(dir_or_file):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000212 self.refactor_dir(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000213 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000214 self.refactor_file(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000215
216 def refactor_dir(self, dir_name, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000217 """Descends down a directory and refactor every Python file found.
218
219 Python files are assumed to have a .py extension.
220
221 Files and subdirectories starting with '.' are skipped.
222 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000223 for dirpath, dirnames, filenames in os.walk(dir_name):
224 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000225 dirnames.sort()
226 filenames.sort()
227 for name in filenames:
228 if not name.startswith(".") and name.endswith("py"):
229 fullname = os.path.join(dirpath, name)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000230 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000231 # Modify dirnames in-place to remove subdirs with leading dots
232 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
233
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000234 def _read_python_source(self, filename):
235 """
236 Do our best to decode a Python source file correctly.
237 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000238 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000239 f = open(filename, "rb")
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000240 except IOError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000241 self.log_error("Can't open %s: %s", filename, err)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000242 return None, None
Martin v. Löwisef04c442008-03-19 05:04:44 +0000243 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000244 encoding = tokenize.detect_encoding(f.readline)[0]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000245 finally:
246 f.close()
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000247 with _open_with_encoding(filename, "r", encoding=encoding) as f:
248 return _from_system_newlines(f.read()), encoding
249
250 def refactor_file(self, filename, write=False, doctests_only=False):
251 """Refactors a file."""
252 input, encoding = self._read_python_source(filename)
253 if input is None:
254 # Reading the file failed.
255 return
256 input += "\n" # Silence certain parse errors
Benjamin Peterson8951b612008-09-03 02:27:16 +0000257 if doctests_only:
258 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000259 output = self.refactor_docstring(input, filename)
260 if output != input:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000261 self.processed_file(output, filename, input, write, encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000262 else:
263 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000264 else:
265 tree = self.refactor_string(input, filename)
266 if tree and tree.was_changed:
267 # The [:-1] is to take off the \n we added earlier
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000268 self.processed_file(str(tree)[:-1], filename,
269 write=write, encoding=encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000270 else:
271 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000272
273 def refactor_string(self, data, name):
274 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000275
Martin v. Löwisef04c442008-03-19 05:04:44 +0000276 Args:
277 data: a string holding the code to be refactored.
278 name: a human-readable name for use in error/log messages.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000279
Martin v. Löwisef04c442008-03-19 05:04:44 +0000280 Returns:
281 An AST corresponding to the refactored input stream; None if
282 there were errors during the parse.
283 """
284 try:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000285 tree = self.driver.parse_string(data)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000286 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000287 self.log_error("Can't parse %s: %s: %s",
288 name, err.__class__.__name__, err)
289 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000290 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000291 self.refactor_tree(tree, name)
292 return tree
293
Benjamin Peterson8951b612008-09-03 02:27:16 +0000294 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000295 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000296 if doctests_only:
297 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000298 output = self.refactor_docstring(input, "<stdin>")
299 if output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000300 self.processed_file(output, "<stdin>", input)
301 else:
302 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000303 else:
304 tree = self.refactor_string(input, "<stdin>")
305 if tree and tree.was_changed:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000306 self.processed_file(str(tree), "<stdin>", input)
307 else:
308 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000309
310 def refactor_tree(self, tree, name):
311 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000312
Martin v. Löwisef04c442008-03-19 05:04:44 +0000313 Args:
314 tree: a pytree.Node instance representing the root of the tree
315 to be refactored.
316 name: a human-readable name for this tree.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000317
Martin v. Löwisef04c442008-03-19 05:04:44 +0000318 Returns:
319 True if the tree was modified, False otherwise.
320 """
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000321 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000322 fixer.start_tree(tree, name)
323
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +0000324 self.traverse_by(self.pre_order_heads, tree.pre_order())
325 self.traverse_by(self.post_order_heads, tree.post_order())
Martin v. Löwisef04c442008-03-19 05:04:44 +0000326
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000327 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000328 fixer.finish_tree(tree, name)
329 return tree.was_changed
330
331 def traverse_by(self, fixers, traversal):
332 """Traverse an AST, applying a set of fixers to each node.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000333
Martin v. Löwisef04c442008-03-19 05:04:44 +0000334 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000335
Martin v. Löwisef04c442008-03-19 05:04:44 +0000336 Args:
337 fixers: a list of fixer instances.
338 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000339
Martin v. Löwisef04c442008-03-19 05:04:44 +0000340 Returns:
341 None
342 """
343 if not fixers:
344 return
345 for node in traversal:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000346 for fixer in fixers[node.type] + fixers[None]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000347 results = fixer.match(node)
348 if results:
349 new = fixer.transform(node, results)
350 if new is not None and (new != node or
351 str(new) != str(node)):
352 node.replace(new)
353 node = new
354
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000355 def processed_file(self, new_text, filename, old_text=None, write=False,
356 encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000357 """
358 Called when a file has been refactored, and there are changes.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000359 """
360 self.files.append(filename)
361 if old_text is None:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000362 old_text = self._read_python_source(filename)[0]
363 if old_text is None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000364 return
Martin v. Löwisef04c442008-03-19 05:04:44 +0000365 if old_text == new_text:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000366 self.log_debug("No changes to %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000367 return
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000368 self.print_output(diff_texts(old_text, new_text, filename))
Benjamin Peterson8951b612008-09-03 02:27:16 +0000369 if write:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000370 self.write_file(new_text, filename, old_text, encoding)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000371 else:
372 self.log_debug("Not writing changes to %s", filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000373
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000374 def write_file(self, new_text, filename, old_text, encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000375 """Writes a string to a file.
376
377 It first shows a unified diff between the old text and the new text, and
378 then rewrites the file; the latter is only done if the write option is
379 set.
380 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000381 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000382 f = _open_with_encoding(filename, "w", encoding=encoding)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000383 except os.error as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000384 self.log_error("Can't create %s: %s", filename, err)
385 return
386 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000387 f.write(_to_system_newlines(new_text))
Benjamin Petersonba558182008-11-10 22:21:33 +0000388 except os.error as err:
389 self.log_error("Can't write %s: %s", filename, err)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000390 finally:
391 f.close()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000392 self.log_debug("Wrote changes to %s", filename)
393 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000394
395 PS1 = ">>> "
396 PS2 = "... "
397
398 def refactor_docstring(self, input, filename):
399 """Refactors a docstring, looking for doctests.
400
401 This returns a modified version of the input string. It looks
402 for doctests, which start with a ">>>" prompt, and may be
403 continued with "..." prompts, as long as the "..." is indented
404 the same as the ">>>".
405
406 (Unfortunately we can't use the doctest module's parser,
407 since, like most parsers, it is not geared towards preserving
408 the original source.)
409 """
410 result = []
411 block = None
412 block_lineno = None
413 indent = None
414 lineno = 0
415 for line in input.splitlines(True):
416 lineno += 1
417 if line.lstrip().startswith(self.PS1):
418 if block is not None:
419 result.extend(self.refactor_doctest(block, block_lineno,
420 indent, filename))
421 block_lineno = lineno
422 block = [line]
423 i = line.find(self.PS1)
424 indent = line[:i]
425 elif (indent is not None and
426 (line.startswith(indent + self.PS2) or
427 line == indent + self.PS2.rstrip() + "\n")):
428 block.append(line)
429 else:
430 if block is not None:
431 result.extend(self.refactor_doctest(block, block_lineno,
432 indent, filename))
433 block = None
434 indent = None
435 result.append(line)
436 if block is not None:
437 result.extend(self.refactor_doctest(block, block_lineno,
438 indent, filename))
439 return "".join(result)
440
441 def refactor_doctest(self, block, lineno, indent, filename):
442 """Refactors one doctest.
443
444 A doctest is given as a block of lines, the first of which starts
445 with ">>>" (possibly indented), while the remaining lines start
446 with "..." (identically indented).
447
448 """
449 try:
450 tree = self.parse_block(block, lineno, indent)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000451 except Exception as err:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000452 if self.log.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000453 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000454 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000455 self.log_error("Can't parse docstring in %s line %s: %s: %s",
456 filename, lineno, err.__class__.__name__, err)
457 return block
458 if self.refactor_tree(tree, filename):
459 new = str(tree).splitlines(True)
460 # Undo the adjustment of the line numbers in wrap_toks() below.
461 clipped, new = new[:lineno-1], new[lineno-1:]
462 assert clipped == ["\n"] * (lineno-1), clipped
463 if not new[-1].endswith("\n"):
464 new[-1] += "\n"
465 block = [indent + self.PS1 + new.pop(0)]
466 if new:
467 block += [indent + self.PS2 + line for line in new]
468 return block
469
470 def summarize(self):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000471 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000472 were = "were"
473 else:
474 were = "need to be"
475 if not self.files:
476 self.log_message("No files %s modified.", were)
477 else:
478 self.log_message("Files that %s modified:", were)
479 for file in self.files:
480 self.log_message(file)
481 if self.fixer_log:
482 self.log_message("Warnings/messages while refactoring:")
483 for message in self.fixer_log:
484 self.log_message(message)
485 if self.errors:
486 if len(self.errors) == 1:
487 self.log_message("There was 1 error:")
488 else:
489 self.log_message("There were %d errors:", len(self.errors))
490 for msg, args, kwds in self.errors:
491 self.log_message(msg, *args, **kwds)
492
493 def parse_block(self, block, lineno, indent):
494 """Parses a block into a tree.
495
496 This is necessary to get correct line number / offset information
497 in the parser diagnostics and embedded into the parse tree.
498 """
499 return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
500
501 def wrap_toks(self, block, lineno, indent):
502 """Wraps a tokenize stream to systematically modify start/end."""
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000503 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000504 for type, value, (line0, col0), (line1, col1), line_text in tokens:
505 line0 += lineno - 1
506 line1 += lineno - 1
507 # Don't bother updating the columns; this is too complicated
508 # since line_text would also have to be updated and it would
509 # still break for tokens spanning lines. Let the user guess
510 # that the column numbers for doctests are relative to the
511 # end of the prompt string (PS1 or PS2).
512 yield type, value, (line0, col0), (line1, col1), line_text
513
514
515 def gen_lines(self, block, indent):
516 """Generates lines as expected by tokenize from a list of lines.
517
518 This strips the first len(indent + self.PS1) characters off each line.
519 """
520 prefix1 = indent + self.PS1
521 prefix2 = indent + self.PS2
522 prefix = prefix1
523 for line in block:
524 if line.startswith(prefix):
525 yield line[len(prefix):]
526 elif line == prefix.rstrip() + "\n":
527 yield "\n"
528 else:
529 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
530 prefix = prefix2
531 while True:
532 yield ""
533
534
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000535class MultiprocessingUnsupported(Exception):
536 pass
537
538
539class MultiprocessRefactoringTool(RefactoringTool):
540
541 def __init__(self, *args, **kwargs):
542 super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
543 self.queue = None
544
545 def refactor(self, items, write=False, doctests_only=False,
546 num_processes=1):
547 if num_processes == 1:
548 return super(MultiprocessRefactoringTool, self).refactor(
549 items, write, doctests_only)
550 try:
551 import multiprocessing
552 except ImportError:
553 raise MultiprocessingUnsupported
554 if self.queue is not None:
555 raise RuntimeError("already doing multiple processes")
556 self.queue = multiprocessing.JoinableQueue()
557 processes = [multiprocessing.Process(target=self._child)
558 for i in xrange(num_processes)]
559 try:
560 for p in processes:
561 p.start()
562 super(MultiprocessRefactoringTool, self).refactor(items, write,
563 doctests_only)
564 finally:
565 self.queue.join()
566 for i in xrange(num_processes):
567 self.queue.put(None)
568 for p in processes:
569 if p.is_alive():
570 p.join()
571 self.queue = None
572
573 def _child(self):
574 task = self.queue.get()
575 while task is not None:
576 args, kwargs = task
577 try:
578 super(MultiprocessRefactoringTool, self).refactor_file(
579 *args, **kwargs)
580 finally:
581 self.queue.task_done()
582 task = self.queue.get()
583
584 def refactor_file(self, *args, **kwargs):
585 if self.queue is not None:
586 self.queue.put((args, kwargs))
587 else:
588 return super(MultiprocessRefactoringTool, self).refactor_file(
589 *args, **kwargs)
590
591
Martin v. Löwisef04c442008-03-19 05:04:44 +0000592def diff_texts(a, b, filename):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000593 """Return a unified diff of two strings."""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000594 a = a.splitlines()
595 b = b.splitlines()
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000596 return difflib.unified_diff(a, b, filename, filename,
597 "(original)", "(refactored)",
598 lineterm="")