blob: c5a1aa2d0cc423c1789d08d65e6917e0cdf1f460 [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
Christian Heimes81ee3ef2008-05-04 22:42:01 +000021from itertools import chain
Martin v. Löwisef04c442008-03-19 05:04:44 +000022
23# Local imports
Benjamin Peterson3059b002009-07-20 16:42:03 +000024from .pgen2 import driver, tokenize, token
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000025from .fixer_util import find_root
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000026from . import pytree, pygram
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000027from . import btm_matcher as bm
Martin v. Löwisef04c442008-03-19 05:04:44 +000028
Martin v. Löwisef04c442008-03-19 05:04:44 +000029
Benjamin Peterson8951b612008-09-03 02:27:16 +000030def get_all_fix_names(fixer_pkg, remove_prefix=True):
31 """Return a sorted list of all available fix names in the given package."""
32 pkg = __import__(fixer_pkg, [], [], ["*"])
33 fixer_dir = os.path.dirname(pkg.__file__)
Martin v. Löwisef04c442008-03-19 05:04:44 +000034 fix_names = []
Benjamin Peterson206e3072008-10-19 14:07:49 +000035 for name in sorted(os.listdir(fixer_dir)):
Martin v. Löwisef04c442008-03-19 05:04:44 +000036 if name.startswith("fix_") and name.endswith(".py"):
Benjamin Peterson8951b612008-09-03 02:27:16 +000037 if remove_prefix:
38 name = name[4:]
39 fix_names.append(name[:-3])
Martin v. Löwisef04c442008-03-19 05:04:44 +000040 return fix_names
41
Benjamin Peterson3059b002009-07-20 16:42:03 +000042
43class _EveryNode(Exception):
44 pass
45
46
47def _get_head_types(pat):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000048 """ Accepts a pytree Pattern Node and returns a set
49 of the pattern types which will match first. """
50
51 if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
52 # NodePatters must either have no type and no content
53 # or a type and content -- so they don't get any farther
54 # Always return leafs
Benjamin Peterson3059b002009-07-20 16:42:03 +000055 if pat.type is None:
56 raise _EveryNode
Serhiy Storchakadb9b65d2014-12-13 21:50:49 +020057 return {pat.type}
Christian Heimes81ee3ef2008-05-04 22:42:01 +000058
59 if isinstance(pat, pytree.NegatedPattern):
60 if pat.content:
Benjamin Peterson3059b002009-07-20 16:42:03 +000061 return _get_head_types(pat.content)
62 raise _EveryNode # Negated Patterns don't have a type
Christian Heimes81ee3ef2008-05-04 22:42:01 +000063
64 if isinstance(pat, pytree.WildcardPattern):
65 # Recurse on each node in content
66 r = set()
67 for p in pat.content:
68 for x in p:
Benjamin Peterson3059b002009-07-20 16:42:03 +000069 r.update(_get_head_types(x))
Christian Heimes81ee3ef2008-05-04 22:42:01 +000070 return r
71
72 raise Exception("Oh no! I don't understand pattern %s" %(pat))
73
Benjamin Peterson3059b002009-07-20 16:42:03 +000074
75def _get_headnode_dict(fixer_list):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000076 """ Accepts a list of fixers and returns a dictionary
77 of head node type --> fixer list. """
Benjamin Peterson3059b002009-07-20 16:42:03 +000078 head_nodes = collections.defaultdict(list)
79 every = []
Christian Heimes81ee3ef2008-05-04 22:42:01 +000080 for fixer in fixer_list:
Benjamin Peterson3059b002009-07-20 16:42:03 +000081 if fixer.pattern:
82 try:
83 heads = _get_head_types(fixer.pattern)
84 except _EveryNode:
85 every.append(fixer)
86 else:
87 for node_type in heads:
88 head_nodes[node_type].append(fixer)
89 else:
90 if fixer._accept_type is not None:
91 head_nodes[fixer._accept_type].append(fixer)
92 else:
93 every.append(fixer)
94 for node_type in chain(pygram.python_grammar.symbol2number.values(),
95 pygram.python_grammar.tokens):
96 head_nodes[node_type].extend(every)
97 return dict(head_nodes)
98
Christian Heimes81ee3ef2008-05-04 22:42:01 +000099
Benjamin Peterson8951b612008-09-03 02:27:16 +0000100def get_fixers_from_package(pkg_name):
101 """
102 Return the fully qualified names for fixers in the package pkg_name.
103 """
104 return [pkg_name + "." + fix_name
105 for fix_name in get_all_fix_names(pkg_name, False)]
106
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000107def _identity(obj):
108 return obj
109
110if sys.version_info < (3, 0):
111 import codecs
112 _open_with_encoding = codecs.open
113 # codecs.open doesn't translate newlines sadly.
114 def _from_system_newlines(input):
115 return input.replace("\r\n", "\n")
116 def _to_system_newlines(input):
117 if os.linesep != "\n":
118 return input.replace("\n", os.linesep)
119 else:
120 return input
121else:
122 _open_with_encoding = open
123 _from_system_newlines = _identity
124 _to_system_newlines = _identity
125
Martin v. Löwisef04c442008-03-19 05:04:44 +0000126
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000127def _detect_future_features(source):
Benjamin Peterson3059b002009-07-20 16:42:03 +0000128 have_docstring = False
129 gen = tokenize.generate_tokens(io.StringIO(source).readline)
130 def advance():
131 tok = next(gen)
132 return tok[0], tok[1]
Serhiy Storchakadb9b65d2014-12-13 21:50:49 +0200133 ignore = frozenset({token.NEWLINE, tokenize.NL, token.COMMENT})
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000134 features = set()
Benjamin Peterson3059b002009-07-20 16:42:03 +0000135 try:
136 while True:
137 tp, value = advance()
138 if tp in ignore:
139 continue
140 elif tp == token.STRING:
141 if have_docstring:
142 break
143 have_docstring = True
Benjamin Peterson20211002009-11-25 18:34:42 +0000144 elif tp == token.NAME and value == "from":
145 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000146 if tp != token.NAME or value != "__future__":
Benjamin Peterson3059b002009-07-20 16:42:03 +0000147 break
Benjamin Peterson20211002009-11-25 18:34:42 +0000148 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000149 if tp != token.NAME or value != "import":
Benjamin Peterson20211002009-11-25 18:34:42 +0000150 break
151 tp, value = advance()
152 if tp == token.OP and value == "(":
153 tp, value = advance()
154 while tp == token.NAME:
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000155 features.add(value)
Benjamin Peterson20211002009-11-25 18:34:42 +0000156 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000157 if tp != token.OP or value != ",":
Benjamin Peterson20211002009-11-25 18:34:42 +0000158 break
159 tp, value = advance()
Benjamin Peterson3059b002009-07-20 16:42:03 +0000160 else:
161 break
162 except StopIteration:
163 pass
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000164 return frozenset(features)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000165
166
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000167class FixerError(Exception):
168 """A fixer could not be loaded."""
169
170
Martin v. Löwisef04c442008-03-19 05:04:44 +0000171class RefactoringTool(object):
172
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800173 _default_options = {"print_function" : False,
174 "write_unchanged_files" : False}
Benjamin Peterson8951b612008-09-03 02:27:16 +0000175
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000176 CLASS_PREFIX = "Fix" # The prefix for fixer classes
177 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
178
179 def __init__(self, fixer_names, options=None, explicit=None):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000180 """Initializer.
181
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000182 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000183 fixer_names: a list of fixers to import
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300184 options: a dict with configuration.
Benjamin Peterson8951b612008-09-03 02:27:16 +0000185 explicit: a list of fixers to run even if they are explicit.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000186 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000187 self.fixers = fixer_names
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000188 self.explicit = explicit or []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000189 self.options = self._default_options.copy()
190 if options is not None:
191 self.options.update(options)
Benjamin Peterson20211002009-11-25 18:34:42 +0000192 if self.options["print_function"]:
193 self.grammar = pygram.python_grammar_no_print_statement
194 else:
195 self.grammar = pygram.python_grammar
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800196 # When this is True, the refactor*() methods will call write_file() for
197 # files processed even if they were not changed during refactoring. If
198 # and only if the refactor method's write parameter was True.
199 self.write_unchanged_files = self.options.get("write_unchanged_files")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000200 self.errors = []
201 self.logger = logging.getLogger("RefactoringTool")
202 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000203 self.wrote = False
Benjamin Peterson20211002009-11-25 18:34:42 +0000204 self.driver = driver.Driver(self.grammar,
Martin v. Löwisef04c442008-03-19 05:04:44 +0000205 convert=pytree.convert,
206 logger=self.logger)
207 self.pre_order, self.post_order = self.get_fixers()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000208
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000209
Martin v. Löwisef04c442008-03-19 05:04:44 +0000210 self.files = [] # List of files that were or should be modified
211
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000212 self.BM = bm.BottomMatcher()
213 self.bmi_pre_order = [] # Bottom Matcher incompatible fixers
214 self.bmi_post_order = []
215
216 for fixer in chain(self.post_order, self.pre_order):
217 if fixer.BM_compatible:
218 self.BM.add_fixer(fixer)
219 # remove fixers that will be handled by the bottom-up
220 # matcher
221 elif fixer in self.pre_order:
222 self.bmi_pre_order.append(fixer)
223 elif fixer in self.post_order:
224 self.bmi_post_order.append(fixer)
225
226 self.bmi_pre_order_heads = _get_headnode_dict(self.bmi_pre_order)
227 self.bmi_post_order_heads = _get_headnode_dict(self.bmi_post_order)
228
229
230
Martin v. Löwisef04c442008-03-19 05:04:44 +0000231 def get_fixers(self):
232 """Inspects the options to load the requested patterns and handlers.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000233
Martin v. Löwisef04c442008-03-19 05:04:44 +0000234 Returns:
235 (pre_order, post_order), where pre_order is the list of fixers that
236 want a pre-order AST traversal, and post_order is the list that want
237 post-order traversal.
238 """
239 pre_order_fixers = []
240 post_order_fixers = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000241 for fix_mod_path in self.fixers:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000242 mod = __import__(fix_mod_path, {}, {}, ["*"])
Benjamin Peterson8951b612008-09-03 02:27:16 +0000243 fix_name = fix_mod_path.rsplit(".", 1)[-1]
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000244 if fix_name.startswith(self.FILE_PREFIX):
245 fix_name = fix_name[len(self.FILE_PREFIX):]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000246 parts = fix_name.split("_")
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000247 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000248 try:
249 fix_class = getattr(mod, class_name)
250 except AttributeError:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000251 raise FixerError("Can't find %s.%s" % (fix_name, class_name))
252 fixer = fix_class(self.options, self.fixer_log)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000253 if fixer.explicit and self.explicit is not True and \
254 fix_mod_path not in self.explicit:
Berker Peksag3a81f9b2015-05-13 13:39:51 +0300255 self.log_message("Skipping optional fixer: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000256 continue
257
Benjamin Peterson8951b612008-09-03 02:27:16 +0000258 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000259 if fixer.order == "pre":
260 pre_order_fixers.append(fixer)
261 elif fixer.order == "post":
262 post_order_fixers.append(fixer)
263 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000264 raise FixerError("Illegal fixer order: %r" % fixer.order)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000265
Benjamin Peterson8951b612008-09-03 02:27:16 +0000266 key_func = operator.attrgetter("run_order")
267 pre_order_fixers.sort(key=key_func)
268 post_order_fixers.sort(key=key_func)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000269 return (pre_order_fixers, post_order_fixers)
270
271 def log_error(self, msg, *args, **kwds):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000272 """Called when an error occurs."""
273 raise
Martin v. Löwisef04c442008-03-19 05:04:44 +0000274
275 def log_message(self, msg, *args):
276 """Hook to log a message."""
277 if args:
278 msg = msg % args
279 self.logger.info(msg)
280
Benjamin Peterson8951b612008-09-03 02:27:16 +0000281 def log_debug(self, msg, *args):
282 if args:
283 msg = msg % args
284 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000285
Benjamin Peterson3059b002009-07-20 16:42:03 +0000286 def print_output(self, old_text, new_text, filename, equal):
287 """Called with the old version, new version, and filename of a
288 refactored file."""
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000289 pass
290
Benjamin Peterson8951b612008-09-03 02:27:16 +0000291 def refactor(self, items, write=False, doctests_only=False):
292 """Refactor a list of files and directories."""
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000293
Benjamin Peterson8951b612008-09-03 02:27:16 +0000294 for dir_or_file in items:
295 if os.path.isdir(dir_or_file):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000296 self.refactor_dir(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000297 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000298 self.refactor_file(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000299
300 def refactor_dir(self, dir_name, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000301 """Descends down a directory and refactor every Python file found.
302
303 Python files are assumed to have a .py extension.
304
305 Files and subdirectories starting with '.' are skipped.
306 """
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000307 py_ext = os.extsep + "py"
Benjamin Peterson8951b612008-09-03 02:27:16 +0000308 for dirpath, dirnames, filenames in os.walk(dir_name):
309 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000310 dirnames.sort()
311 filenames.sort()
312 for name in filenames:
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000313 if (not name.startswith(".") and
314 os.path.splitext(name)[1] == py_ext):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000315 fullname = os.path.join(dirpath, name)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000316 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000317 # Modify dirnames in-place to remove subdirs with leading dots
318 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
319
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000320 def _read_python_source(self, filename):
321 """
322 Do our best to decode a Python source file correctly.
323 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000324 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000325 f = open(filename, "rb")
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200326 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000327 self.log_error("Can't open %s: %s", filename, err)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000328 return None, None
Martin v. Löwisef04c442008-03-19 05:04:44 +0000329 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000330 encoding = tokenize.detect_encoding(f.readline)[0]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000331 finally:
332 f.close()
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000333 with _open_with_encoding(filename, "r", encoding=encoding) as f:
334 return _from_system_newlines(f.read()), encoding
335
336 def refactor_file(self, filename, write=False, doctests_only=False):
337 """Refactors a file."""
338 input, encoding = self._read_python_source(filename)
339 if input is None:
340 # Reading the file failed.
341 return
342 input += "\n" # Silence certain parse errors
Benjamin Peterson8951b612008-09-03 02:27:16 +0000343 if doctests_only:
344 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000345 output = self.refactor_docstring(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800346 if self.write_unchanged_files or output != input:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000347 self.processed_file(output, filename, input, write, encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000348 else:
349 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000350 else:
351 tree = self.refactor_string(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800352 if self.write_unchanged_files or (tree and tree.was_changed):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000353 # The [:-1] is to take off the \n we added earlier
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000354 self.processed_file(str(tree)[:-1], filename,
355 write=write, encoding=encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000356 else:
357 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000358
359 def refactor_string(self, data, name):
360 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000361
Martin v. Löwisef04c442008-03-19 05:04:44 +0000362 Args:
363 data: a string holding the code to be refactored.
364 name: a human-readable name for use in error/log messages.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000365
Martin v. Löwisef04c442008-03-19 05:04:44 +0000366 Returns:
367 An AST corresponding to the refactored input stream; None if
368 there were errors during the parse.
369 """
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000370 features = _detect_future_features(data)
371 if "print_function" in features:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000372 self.driver.grammar = pygram.python_grammar_no_print_statement
Martin v. Löwisef04c442008-03-19 05:04:44 +0000373 try:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000374 tree = self.driver.parse_string(data)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000375 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000376 self.log_error("Can't parse %s: %s: %s",
377 name, err.__class__.__name__, err)
378 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000379 finally:
Benjamin Peterson20211002009-11-25 18:34:42 +0000380 self.driver.grammar = self.grammar
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000381 tree.future_features = features
Benjamin Peterson8951b612008-09-03 02:27:16 +0000382 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000383 self.refactor_tree(tree, name)
384 return tree
385
Benjamin Peterson8951b612008-09-03 02:27:16 +0000386 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000387 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000388 if doctests_only:
389 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000390 output = self.refactor_docstring(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800391 if self.write_unchanged_files or output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000392 self.processed_file(output, "<stdin>", input)
393 else:
394 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000395 else:
396 tree = self.refactor_string(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800397 if self.write_unchanged_files or (tree and tree.was_changed):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000398 self.processed_file(str(tree), "<stdin>", input)
399 else:
400 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000401
402 def refactor_tree(self, tree, name):
403 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000404
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000405 For compatible patterns the bottom matcher module is
406 used. Otherwise the tree is traversed node-to-node for
407 matches.
408
Martin v. Löwisef04c442008-03-19 05:04:44 +0000409 Args:
410 tree: a pytree.Node instance representing the root of the tree
411 to be refactored.
412 name: a human-readable name for this tree.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000413
Martin v. Löwisef04c442008-03-19 05:04:44 +0000414 Returns:
415 True if the tree was modified, False otherwise.
416 """
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000417
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000418 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000419 fixer.start_tree(tree, name)
420
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000421 #use traditional matching for the incompatible fixers
422 self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
423 self.traverse_by(self.bmi_post_order_heads, tree.post_order())
424
425 # obtain a set of candidate nodes
426 match_set = self.BM.run(tree.leaves())
427
428 while any(match_set.values()):
429 for fixer in self.BM.fixers:
430 if fixer in match_set and match_set[fixer]:
431 #sort by depth; apply fixers from bottom(of the AST) to top
432 match_set[fixer].sort(key=pytree.Base.depth, reverse=True)
433
434 if fixer.keep_line_order:
435 #some fixers(eg fix_imports) must be applied
436 #with the original file's line order
437 match_set[fixer].sort(key=pytree.Base.get_lineno)
438
439 for node in list(match_set[fixer]):
440 if node in match_set[fixer]:
441 match_set[fixer].remove(node)
442
443 try:
444 find_root(node)
Benjamin Peterson1654d742012-09-25 11:48:50 -0400445 except ValueError:
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000446 # this node has been cut off from a
447 # previous transformation ; skip
448 continue
449
450 if node.fixers_applied and fixer in node.fixers_applied:
451 # do not apply the same fixer again
452 continue
453
454 results = fixer.match(node)
455
456 if results:
457 new = fixer.transform(node, results)
458 if new is not None:
459 node.replace(new)
460 #new.fixers_applied.append(fixer)
461 for node in new.post_order():
462 # do not apply the fixer again to
463 # this or any subnode
464 if not node.fixers_applied:
465 node.fixers_applied = []
466 node.fixers_applied.append(fixer)
467
468 # update the original match set for
469 # the added code
470 new_matches = self.BM.run(new.leaves())
471 for fxr in new_matches:
472 if not fxr in match_set:
473 match_set[fxr]=[]
474
475 match_set[fxr].extend(new_matches[fxr])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000476
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000477 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000478 fixer.finish_tree(tree, name)
479 return tree.was_changed
480
481 def traverse_by(self, fixers, traversal):
482 """Traverse an AST, applying a set of fixers to each node.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000483
Martin v. Löwisef04c442008-03-19 05:04:44 +0000484 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000485
Martin v. Löwisef04c442008-03-19 05:04:44 +0000486 Args:
487 fixers: a list of fixer instances.
488 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000489
Martin v. Löwisef04c442008-03-19 05:04:44 +0000490 Returns:
491 None
492 """
493 if not fixers:
494 return
495 for node in traversal:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000496 for fixer in fixers[node.type]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000497 results = fixer.match(node)
498 if results:
499 new = fixer.transform(node, results)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000500 if new is not None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000501 node.replace(new)
502 node = new
503
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000504 def processed_file(self, new_text, filename, old_text=None, write=False,
505 encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000506 """
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800507 Called when a file has been refactored and there may be changes.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000508 """
509 self.files.append(filename)
510 if old_text is None:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000511 old_text = self._read_python_source(filename)[0]
512 if old_text is None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000513 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000514 equal = old_text == new_text
515 self.print_output(old_text, new_text, filename, equal)
516 if equal:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000517 self.log_debug("No changes to %s", filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800518 if not self.write_unchanged_files:
519 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000520 if write:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000521 self.write_file(new_text, filename, old_text, encoding)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000522 else:
523 self.log_debug("Not writing changes to %s", filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000524
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000525 def write_file(self, new_text, filename, old_text, encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000526 """Writes a string to a file.
527
528 It first shows a unified diff between the old text and the new text, and
529 then rewrites the file; the latter is only done if the write option is
530 set.
531 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000532 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000533 f = _open_with_encoding(filename, "w", encoding=encoding)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200534 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000535 self.log_error("Can't create %s: %s", filename, err)
536 return
537 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000538 f.write(_to_system_newlines(new_text))
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200539 except OSError as err:
Benjamin Petersonba558182008-11-10 22:21:33 +0000540 self.log_error("Can't write %s: %s", filename, err)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000541 finally:
542 f.close()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000543 self.log_debug("Wrote changes to %s", filename)
544 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000545
546 PS1 = ">>> "
547 PS2 = "... "
548
549 def refactor_docstring(self, input, filename):
550 """Refactors a docstring, looking for doctests.
551
552 This returns a modified version of the input string. It looks
553 for doctests, which start with a ">>>" prompt, and may be
554 continued with "..." prompts, as long as the "..." is indented
555 the same as the ">>>".
556
557 (Unfortunately we can't use the doctest module's parser,
558 since, like most parsers, it is not geared towards preserving
559 the original source.)
560 """
561 result = []
562 block = None
563 block_lineno = None
564 indent = None
565 lineno = 0
Ezio Melottid8b509b2011-09-28 17:37:55 +0300566 for line in input.splitlines(keepends=True):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000567 lineno += 1
568 if line.lstrip().startswith(self.PS1):
569 if block is not None:
570 result.extend(self.refactor_doctest(block, block_lineno,
571 indent, filename))
572 block_lineno = lineno
573 block = [line]
574 i = line.find(self.PS1)
575 indent = line[:i]
576 elif (indent is not None and
577 (line.startswith(indent + self.PS2) or
578 line == indent + self.PS2.rstrip() + "\n")):
579 block.append(line)
580 else:
581 if block is not None:
582 result.extend(self.refactor_doctest(block, block_lineno,
583 indent, filename))
584 block = None
585 indent = None
586 result.append(line)
587 if block is not None:
588 result.extend(self.refactor_doctest(block, block_lineno,
589 indent, filename))
590 return "".join(result)
591
592 def refactor_doctest(self, block, lineno, indent, filename):
593 """Refactors one doctest.
594
595 A doctest is given as a block of lines, the first of which starts
596 with ">>>" (possibly indented), while the remaining lines start
597 with "..." (identically indented).
598
599 """
600 try:
601 tree = self.parse_block(block, lineno, indent)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000602 except Exception as err:
Benjamin Peterson4eb5fa52010-08-08 19:01:25 +0000603 if self.logger.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000604 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000605 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000606 self.log_error("Can't parse docstring in %s line %s: %s: %s",
607 filename, lineno, err.__class__.__name__, err)
608 return block
609 if self.refactor_tree(tree, filename):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300610 new = str(tree).splitlines(keepends=True)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000611 # Undo the adjustment of the line numbers in wrap_toks() below.
612 clipped, new = new[:lineno-1], new[lineno-1:]
613 assert clipped == ["\n"] * (lineno-1), clipped
614 if not new[-1].endswith("\n"):
615 new[-1] += "\n"
616 block = [indent + self.PS1 + new.pop(0)]
617 if new:
618 block += [indent + self.PS2 + line for line in new]
619 return block
620
621 def summarize(self):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000622 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000623 were = "were"
624 else:
625 were = "need to be"
626 if not self.files:
627 self.log_message("No files %s modified.", were)
628 else:
629 self.log_message("Files that %s modified:", were)
630 for file in self.files:
631 self.log_message(file)
632 if self.fixer_log:
633 self.log_message("Warnings/messages while refactoring:")
634 for message in self.fixer_log:
635 self.log_message(message)
636 if self.errors:
637 if len(self.errors) == 1:
638 self.log_message("There was 1 error:")
639 else:
640 self.log_message("There were %d errors:", len(self.errors))
641 for msg, args, kwds in self.errors:
642 self.log_message(msg, *args, **kwds)
643
644 def parse_block(self, block, lineno, indent):
645 """Parses a block into a tree.
646
647 This is necessary to get correct line number / offset information
648 in the parser diagnostics and embedded into the parse tree.
649 """
Benjamin Peterson2243e5e2010-05-22 18:59:24 +0000650 tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
651 tree.future_features = frozenset()
652 return tree
Martin v. Löwisef04c442008-03-19 05:04:44 +0000653
654 def wrap_toks(self, block, lineno, indent):
655 """Wraps a tokenize stream to systematically modify start/end."""
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000656 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000657 for type, value, (line0, col0), (line1, col1), line_text in tokens:
658 line0 += lineno - 1
659 line1 += lineno - 1
660 # Don't bother updating the columns; this is too complicated
661 # since line_text would also have to be updated and it would
662 # still break for tokens spanning lines. Let the user guess
663 # that the column numbers for doctests are relative to the
664 # end of the prompt string (PS1 or PS2).
665 yield type, value, (line0, col0), (line1, col1), line_text
666
667
668 def gen_lines(self, block, indent):
669 """Generates lines as expected by tokenize from a list of lines.
670
671 This strips the first len(indent + self.PS1) characters off each line.
672 """
673 prefix1 = indent + self.PS1
674 prefix2 = indent + self.PS2
675 prefix = prefix1
676 for line in block:
677 if line.startswith(prefix):
678 yield line[len(prefix):]
679 elif line == prefix.rstrip() + "\n":
680 yield "\n"
681 else:
682 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
683 prefix = prefix2
684 while True:
685 yield ""
686
687
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000688class MultiprocessingUnsupported(Exception):
689 pass
690
691
692class MultiprocessRefactoringTool(RefactoringTool):
693
694 def __init__(self, *args, **kwargs):
695 super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
696 self.queue = None
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000697 self.output_lock = None
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000698
699 def refactor(self, items, write=False, doctests_only=False,
700 num_processes=1):
701 if num_processes == 1:
702 return super(MultiprocessRefactoringTool, self).refactor(
703 items, write, doctests_only)
704 try:
705 import multiprocessing
Brett Cannoncd171c82013-07-04 17:43:24 -0400706 except ImportError:
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000707 raise MultiprocessingUnsupported
708 if self.queue is not None:
709 raise RuntimeError("already doing multiple processes")
710 self.queue = multiprocessing.JoinableQueue()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000711 self.output_lock = multiprocessing.Lock()
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000712 processes = [multiprocessing.Process(target=self._child)
Benjamin Peterson87b87192009-07-03 13:18:18 +0000713 for i in range(num_processes)]
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000714 try:
715 for p in processes:
716 p.start()
717 super(MultiprocessRefactoringTool, self).refactor(items, write,
718 doctests_only)
719 finally:
720 self.queue.join()
Benjamin Peterson87b87192009-07-03 13:18:18 +0000721 for i in range(num_processes):
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000722 self.queue.put(None)
723 for p in processes:
724 if p.is_alive():
725 p.join()
726 self.queue = None
727
728 def _child(self):
729 task = self.queue.get()
730 while task is not None:
731 args, kwargs = task
732 try:
733 super(MultiprocessRefactoringTool, self).refactor_file(
734 *args, **kwargs)
735 finally:
736 self.queue.task_done()
737 task = self.queue.get()
738
739 def refactor_file(self, *args, **kwargs):
740 if self.queue is not None:
741 self.queue.put((args, kwargs))
742 else:
743 return super(MultiprocessRefactoringTool, self).refactor_file(
744 *args, **kwargs)