blob: b60b9def4d07c484fa9bc64b38c220498c6d5ee3 [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
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +000011from __future__ import with_statement
12
Martin v. Löwisef04c442008-03-19 05:04:44 +000013__author__ = "Guido van Rossum <guido@python.org>"
14
15
16# Python imports
17import os
18import sys
Martin v. Löwisef04c442008-03-19 05:04:44 +000019import logging
Benjamin Peterson8951b612008-09-03 02:27:16 +000020import operator
Benjamin Peterson3059b002009-07-20 16:42:03 +000021import collections
22import io
Christian Heimes81ee3ef2008-05-04 22:42:01 +000023from itertools import chain
Martin v. Löwisef04c442008-03-19 05:04:44 +000024
25# Local imports
Benjamin Peterson3059b002009-07-20 16:42:03 +000026from .pgen2 import driver, tokenize, token
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000027from .fixer_util import find_root
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000028from . import pytree, pygram
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000029from . import btm_matcher as bm
Martin v. Löwisef04c442008-03-19 05:04:44 +000030
Martin v. Löwisef04c442008-03-19 05:04:44 +000031
Benjamin Peterson8951b612008-09-03 02:27:16 +000032def get_all_fix_names(fixer_pkg, remove_prefix=True):
33 """Return a sorted list of all available fix names in the given package."""
34 pkg = __import__(fixer_pkg, [], [], ["*"])
35 fixer_dir = os.path.dirname(pkg.__file__)
Martin v. Löwisef04c442008-03-19 05:04:44 +000036 fix_names = []
Benjamin Peterson206e3072008-10-19 14:07:49 +000037 for name in sorted(os.listdir(fixer_dir)):
Martin v. Löwisef04c442008-03-19 05:04:44 +000038 if name.startswith("fix_") and name.endswith(".py"):
Benjamin Peterson8951b612008-09-03 02:27:16 +000039 if remove_prefix:
40 name = name[4:]
41 fix_names.append(name[:-3])
Martin v. Löwisef04c442008-03-19 05:04:44 +000042 return fix_names
43
Benjamin Peterson3059b002009-07-20 16:42:03 +000044
45class _EveryNode(Exception):
46 pass
47
48
49def _get_head_types(pat):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000050 """ Accepts a pytree Pattern Node and returns a set
51 of the pattern types which will match first. """
52
53 if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
54 # NodePatters must either have no type and no content
55 # or a type and content -- so they don't get any farther
56 # Always return leafs
Benjamin Peterson3059b002009-07-20 16:42:03 +000057 if pat.type is None:
58 raise _EveryNode
Serhiy Storchakadb9b65d2014-12-13 21:50:49 +020059 return {pat.type}
Christian Heimes81ee3ef2008-05-04 22:42:01 +000060
61 if isinstance(pat, pytree.NegatedPattern):
62 if pat.content:
Benjamin Peterson3059b002009-07-20 16:42:03 +000063 return _get_head_types(pat.content)
64 raise _EveryNode # Negated Patterns don't have a type
Christian Heimes81ee3ef2008-05-04 22:42:01 +000065
66 if isinstance(pat, pytree.WildcardPattern):
67 # Recurse on each node in content
68 r = set()
69 for p in pat.content:
70 for x in p:
Benjamin Peterson3059b002009-07-20 16:42:03 +000071 r.update(_get_head_types(x))
Christian Heimes81ee3ef2008-05-04 22:42:01 +000072 return r
73
74 raise Exception("Oh no! I don't understand pattern %s" %(pat))
75
Benjamin Peterson3059b002009-07-20 16:42:03 +000076
77def _get_headnode_dict(fixer_list):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000078 """ Accepts a list of fixers and returns a dictionary
79 of head node type --> fixer list. """
Benjamin Peterson3059b002009-07-20 16:42:03 +000080 head_nodes = collections.defaultdict(list)
81 every = []
Christian Heimes81ee3ef2008-05-04 22:42:01 +000082 for fixer in fixer_list:
Benjamin Peterson3059b002009-07-20 16:42:03 +000083 if fixer.pattern:
84 try:
85 heads = _get_head_types(fixer.pattern)
86 except _EveryNode:
87 every.append(fixer)
88 else:
89 for node_type in heads:
90 head_nodes[node_type].append(fixer)
91 else:
92 if fixer._accept_type is not None:
93 head_nodes[fixer._accept_type].append(fixer)
94 else:
95 every.append(fixer)
96 for node_type in chain(pygram.python_grammar.symbol2number.values(),
97 pygram.python_grammar.tokens):
98 head_nodes[node_type].extend(every)
99 return dict(head_nodes)
100
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000101
Benjamin Peterson8951b612008-09-03 02:27:16 +0000102def get_fixers_from_package(pkg_name):
103 """
104 Return the fully qualified names for fixers in the package pkg_name.
105 """
106 return [pkg_name + "." + fix_name
107 for fix_name in get_all_fix_names(pkg_name, False)]
108
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000109def _identity(obj):
110 return obj
111
112if sys.version_info < (3, 0):
113 import codecs
114 _open_with_encoding = codecs.open
115 # codecs.open doesn't translate newlines sadly.
116 def _from_system_newlines(input):
117 return input.replace("\r\n", "\n")
118 def _to_system_newlines(input):
119 if os.linesep != "\n":
120 return input.replace("\n", os.linesep)
121 else:
122 return input
123else:
124 _open_with_encoding = open
125 _from_system_newlines = _identity
126 _to_system_newlines = _identity
127
Martin v. Löwisef04c442008-03-19 05:04:44 +0000128
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000129def _detect_future_features(source):
Benjamin Peterson3059b002009-07-20 16:42:03 +0000130 have_docstring = False
131 gen = tokenize.generate_tokens(io.StringIO(source).readline)
132 def advance():
133 tok = next(gen)
134 return tok[0], tok[1]
Serhiy Storchakadb9b65d2014-12-13 21:50:49 +0200135 ignore = frozenset({token.NEWLINE, tokenize.NL, token.COMMENT})
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000136 features = set()
Benjamin Peterson3059b002009-07-20 16:42:03 +0000137 try:
138 while True:
139 tp, value = advance()
140 if tp in ignore:
141 continue
142 elif tp == token.STRING:
143 if have_docstring:
144 break
145 have_docstring = True
Benjamin Peterson20211002009-11-25 18:34:42 +0000146 elif tp == token.NAME and value == "from":
147 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000148 if tp != token.NAME or value != "__future__":
Benjamin Peterson3059b002009-07-20 16:42:03 +0000149 break
Benjamin Peterson20211002009-11-25 18:34:42 +0000150 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000151 if tp != token.NAME or value != "import":
Benjamin Peterson20211002009-11-25 18:34:42 +0000152 break
153 tp, value = advance()
154 if tp == token.OP and value == "(":
155 tp, value = advance()
156 while tp == token.NAME:
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000157 features.add(value)
Benjamin Peterson20211002009-11-25 18:34:42 +0000158 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000159 if tp != token.OP or value != ",":
Benjamin Peterson20211002009-11-25 18:34:42 +0000160 break
161 tp, value = advance()
Benjamin Peterson3059b002009-07-20 16:42:03 +0000162 else:
163 break
164 except StopIteration:
165 pass
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000166 return frozenset(features)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000167
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
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800175 _default_options = {"print_function" : False,
176 "write_unchanged_files" : False}
Benjamin Peterson8951b612008-09-03 02:27:16 +0000177
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000178 CLASS_PREFIX = "Fix" # The prefix for fixer classes
179 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
180
181 def __init__(self, fixer_names, options=None, explicit=None):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000182 """Initializer.
183
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000184 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000185 fixer_names: a list of fixers to import
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300186 options: a dict with configuration.
Benjamin Peterson8951b612008-09-03 02:27:16 +0000187 explicit: a list of fixers to run even if they are explicit.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000188 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000189 self.fixers = fixer_names
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000190 self.explicit = explicit or []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000191 self.options = self._default_options.copy()
192 if options is not None:
193 self.options.update(options)
Benjamin Peterson20211002009-11-25 18:34:42 +0000194 if self.options["print_function"]:
195 self.grammar = pygram.python_grammar_no_print_statement
196 else:
197 self.grammar = pygram.python_grammar
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800198 # When this is True, the refactor*() methods will call write_file() for
199 # files processed even if they were not changed during refactoring. If
200 # and only if the refactor method's write parameter was True.
201 self.write_unchanged_files = self.options.get("write_unchanged_files")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000202 self.errors = []
203 self.logger = logging.getLogger("RefactoringTool")
204 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000205 self.wrote = False
Benjamin Peterson20211002009-11-25 18:34:42 +0000206 self.driver = driver.Driver(self.grammar,
Martin v. Löwisef04c442008-03-19 05:04:44 +0000207 convert=pytree.convert,
208 logger=self.logger)
209 self.pre_order, self.post_order = self.get_fixers()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000210
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000211
Martin v. Löwisef04c442008-03-19 05:04:44 +0000212 self.files = [] # List of files that were or should be modified
213
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000214 self.BM = bm.BottomMatcher()
215 self.bmi_pre_order = [] # Bottom Matcher incompatible fixers
216 self.bmi_post_order = []
217
218 for fixer in chain(self.post_order, self.pre_order):
219 if fixer.BM_compatible:
220 self.BM.add_fixer(fixer)
221 # remove fixers that will be handled by the bottom-up
222 # matcher
223 elif fixer in self.pre_order:
224 self.bmi_pre_order.append(fixer)
225 elif fixer in self.post_order:
226 self.bmi_post_order.append(fixer)
227
228 self.bmi_pre_order_heads = _get_headnode_dict(self.bmi_pre_order)
229 self.bmi_post_order_heads = _get_headnode_dict(self.bmi_post_order)
230
231
232
Martin v. Löwisef04c442008-03-19 05:04:44 +0000233 def get_fixers(self):
234 """Inspects the options to load the requested patterns and handlers.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000235
Martin v. Löwisef04c442008-03-19 05:04:44 +0000236 Returns:
237 (pre_order, post_order), where pre_order is the list of fixers that
238 want a pre-order AST traversal, and post_order is the list that want
239 post-order traversal.
240 """
241 pre_order_fixers = []
242 post_order_fixers = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000243 for fix_mod_path in self.fixers:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000244 mod = __import__(fix_mod_path, {}, {}, ["*"])
Benjamin Peterson8951b612008-09-03 02:27:16 +0000245 fix_name = fix_mod_path.rsplit(".", 1)[-1]
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000246 if fix_name.startswith(self.FILE_PREFIX):
247 fix_name = fix_name[len(self.FILE_PREFIX):]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000248 parts = fix_name.split("_")
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000249 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000250 try:
251 fix_class = getattr(mod, class_name)
252 except AttributeError:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000253 raise FixerError("Can't find %s.%s" % (fix_name, class_name))
254 fixer = fix_class(self.options, self.fixer_log)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000255 if fixer.explicit and self.explicit is not True and \
256 fix_mod_path not in self.explicit:
Berker Peksag3a81f9b2015-05-13 13:39:51 +0300257 self.log_message("Skipping optional fixer: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000258 continue
259
Benjamin Peterson8951b612008-09-03 02:27:16 +0000260 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000261 if fixer.order == "pre":
262 pre_order_fixers.append(fixer)
263 elif fixer.order == "post":
264 post_order_fixers.append(fixer)
265 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000266 raise FixerError("Illegal fixer order: %r" % fixer.order)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000267
Benjamin Peterson8951b612008-09-03 02:27:16 +0000268 key_func = operator.attrgetter("run_order")
269 pre_order_fixers.sort(key=key_func)
270 post_order_fixers.sort(key=key_func)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000271 return (pre_order_fixers, post_order_fixers)
272
273 def log_error(self, msg, *args, **kwds):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000274 """Called when an error occurs."""
275 raise
Martin v. Löwisef04c442008-03-19 05:04:44 +0000276
277 def log_message(self, msg, *args):
278 """Hook to log a message."""
279 if args:
280 msg = msg % args
281 self.logger.info(msg)
282
Benjamin Peterson8951b612008-09-03 02:27:16 +0000283 def log_debug(self, msg, *args):
284 if args:
285 msg = msg % args
286 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000287
Benjamin Peterson3059b002009-07-20 16:42:03 +0000288 def print_output(self, old_text, new_text, filename, equal):
289 """Called with the old version, new version, and filename of a
290 refactored file."""
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000291 pass
292
Benjamin Peterson8951b612008-09-03 02:27:16 +0000293 def refactor(self, items, write=False, doctests_only=False):
294 """Refactor a list of files and directories."""
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000295
Benjamin Peterson8951b612008-09-03 02:27:16 +0000296 for dir_or_file in items:
297 if os.path.isdir(dir_or_file):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000298 self.refactor_dir(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000299 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000300 self.refactor_file(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000301
302 def refactor_dir(self, dir_name, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000303 """Descends down a directory and refactor every Python file found.
304
305 Python files are assumed to have a .py extension.
306
307 Files and subdirectories starting with '.' are skipped.
308 """
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000309 py_ext = os.extsep + "py"
Benjamin Peterson8951b612008-09-03 02:27:16 +0000310 for dirpath, dirnames, filenames in os.walk(dir_name):
311 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000312 dirnames.sort()
313 filenames.sort()
314 for name in filenames:
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000315 if (not name.startswith(".") and
316 os.path.splitext(name)[1] == py_ext):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000317 fullname = os.path.join(dirpath, name)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000318 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000319 # Modify dirnames in-place to remove subdirs with leading dots
320 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
321
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000322 def _read_python_source(self, filename):
323 """
324 Do our best to decode a Python source file correctly.
325 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000326 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000327 f = open(filename, "rb")
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200328 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000329 self.log_error("Can't open %s: %s", filename, err)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000330 return None, None
Martin v. Löwisef04c442008-03-19 05:04:44 +0000331 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000332 encoding = tokenize.detect_encoding(f.readline)[0]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000333 finally:
334 f.close()
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000335 with _open_with_encoding(filename, "r", encoding=encoding) as f:
336 return _from_system_newlines(f.read()), encoding
337
338 def refactor_file(self, filename, write=False, doctests_only=False):
339 """Refactors a file."""
340 input, encoding = self._read_python_source(filename)
341 if input is None:
342 # Reading the file failed.
343 return
344 input += "\n" # Silence certain parse errors
Benjamin Peterson8951b612008-09-03 02:27:16 +0000345 if doctests_only:
346 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000347 output = self.refactor_docstring(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800348 if self.write_unchanged_files or output != input:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000349 self.processed_file(output, filename, input, write, encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000350 else:
351 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000352 else:
353 tree = self.refactor_string(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800354 if self.write_unchanged_files or (tree and tree.was_changed):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000355 # The [:-1] is to take off the \n we added earlier
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000356 self.processed_file(str(tree)[:-1], filename,
357 write=write, encoding=encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000358 else:
359 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000360
361 def refactor_string(self, data, name):
362 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000363
Martin v. Löwisef04c442008-03-19 05:04:44 +0000364 Args:
365 data: a string holding the code to be refactored.
366 name: a human-readable name for use in error/log messages.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000367
Martin v. Löwisef04c442008-03-19 05:04:44 +0000368 Returns:
369 An AST corresponding to the refactored input stream; None if
370 there were errors during the parse.
371 """
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000372 features = _detect_future_features(data)
373 if "print_function" in features:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000374 self.driver.grammar = pygram.python_grammar_no_print_statement
Martin v. Löwisef04c442008-03-19 05:04:44 +0000375 try:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000376 tree = self.driver.parse_string(data)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000377 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000378 self.log_error("Can't parse %s: %s: %s",
379 name, err.__class__.__name__, err)
380 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000381 finally:
Benjamin Peterson20211002009-11-25 18:34:42 +0000382 self.driver.grammar = self.grammar
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000383 tree.future_features = features
Benjamin Peterson8951b612008-09-03 02:27:16 +0000384 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000385 self.refactor_tree(tree, name)
386 return tree
387
Benjamin Peterson8951b612008-09-03 02:27:16 +0000388 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000389 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000390 if doctests_only:
391 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000392 output = self.refactor_docstring(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800393 if self.write_unchanged_files or output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000394 self.processed_file(output, "<stdin>", input)
395 else:
396 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000397 else:
398 tree = self.refactor_string(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800399 if self.write_unchanged_files or (tree and tree.was_changed):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000400 self.processed_file(str(tree), "<stdin>", input)
401 else:
402 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000403
404 def refactor_tree(self, tree, name):
405 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000406
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000407 For compatible patterns the bottom matcher module is
408 used. Otherwise the tree is traversed node-to-node for
409 matches.
410
Martin v. Löwisef04c442008-03-19 05:04:44 +0000411 Args:
412 tree: a pytree.Node instance representing the root of the tree
413 to be refactored.
414 name: a human-readable name for this tree.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000415
Martin v. Löwisef04c442008-03-19 05:04:44 +0000416 Returns:
417 True if the tree was modified, False otherwise.
418 """
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000419
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000420 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000421 fixer.start_tree(tree, name)
422
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000423 #use traditional matching for the incompatible fixers
424 self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
425 self.traverse_by(self.bmi_post_order_heads, tree.post_order())
426
427 # obtain a set of candidate nodes
428 match_set = self.BM.run(tree.leaves())
429
430 while any(match_set.values()):
431 for fixer in self.BM.fixers:
432 if fixer in match_set and match_set[fixer]:
433 #sort by depth; apply fixers from bottom(of the AST) to top
434 match_set[fixer].sort(key=pytree.Base.depth, reverse=True)
435
436 if fixer.keep_line_order:
437 #some fixers(eg fix_imports) must be applied
438 #with the original file's line order
439 match_set[fixer].sort(key=pytree.Base.get_lineno)
440
441 for node in list(match_set[fixer]):
442 if node in match_set[fixer]:
443 match_set[fixer].remove(node)
444
445 try:
446 find_root(node)
Benjamin Peterson1654d742012-09-25 11:48:50 -0400447 except ValueError:
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000448 # this node has been cut off from a
449 # previous transformation ; skip
450 continue
451
452 if node.fixers_applied and fixer in node.fixers_applied:
453 # do not apply the same fixer again
454 continue
455
456 results = fixer.match(node)
457
458 if results:
459 new = fixer.transform(node, results)
460 if new is not None:
461 node.replace(new)
462 #new.fixers_applied.append(fixer)
463 for node in new.post_order():
464 # do not apply the fixer again to
465 # this or any subnode
466 if not node.fixers_applied:
467 node.fixers_applied = []
468 node.fixers_applied.append(fixer)
469
470 # update the original match set for
471 # the added code
472 new_matches = self.BM.run(new.leaves())
473 for fxr in new_matches:
474 if not fxr in match_set:
475 match_set[fxr]=[]
476
477 match_set[fxr].extend(new_matches[fxr])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000478
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000479 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000480 fixer.finish_tree(tree, name)
481 return tree.was_changed
482
483 def traverse_by(self, fixers, traversal):
484 """Traverse an AST, applying a set of fixers to each node.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000485
Martin v. Löwisef04c442008-03-19 05:04:44 +0000486 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000487
Martin v. Löwisef04c442008-03-19 05:04:44 +0000488 Args:
489 fixers: a list of fixer instances.
490 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000491
Martin v. Löwisef04c442008-03-19 05:04:44 +0000492 Returns:
493 None
494 """
495 if not fixers:
496 return
497 for node in traversal:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000498 for fixer in fixers[node.type]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000499 results = fixer.match(node)
500 if results:
501 new = fixer.transform(node, results)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000502 if new is not None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000503 node.replace(new)
504 node = new
505
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000506 def processed_file(self, new_text, filename, old_text=None, write=False,
507 encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000508 """
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800509 Called when a file has been refactored and there may be changes.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000510 """
511 self.files.append(filename)
512 if old_text is None:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000513 old_text = self._read_python_source(filename)[0]
514 if old_text is None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000515 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000516 equal = old_text == new_text
517 self.print_output(old_text, new_text, filename, equal)
518 if equal:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000519 self.log_debug("No changes to %s", filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800520 if not self.write_unchanged_files:
521 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000522 if write:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000523 self.write_file(new_text, filename, old_text, encoding)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000524 else:
525 self.log_debug("Not writing changes to %s", filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000526
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000527 def write_file(self, new_text, filename, old_text, encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000528 """Writes a string to a file.
529
530 It first shows a unified diff between the old text and the new text, and
531 then rewrites the file; the latter is only done if the write option is
532 set.
533 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000534 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000535 f = _open_with_encoding(filename, "w", encoding=encoding)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200536 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000537 self.log_error("Can't create %s: %s", filename, err)
538 return
539 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000540 f.write(_to_system_newlines(new_text))
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200541 except OSError as err:
Benjamin Petersonba558182008-11-10 22:21:33 +0000542 self.log_error("Can't write %s: %s", filename, err)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000543 finally:
544 f.close()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000545 self.log_debug("Wrote changes to %s", filename)
546 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000547
548 PS1 = ">>> "
549 PS2 = "... "
550
551 def refactor_docstring(self, input, filename):
552 """Refactors a docstring, looking for doctests.
553
554 This returns a modified version of the input string. It looks
555 for doctests, which start with a ">>>" prompt, and may be
556 continued with "..." prompts, as long as the "..." is indented
557 the same as the ">>>".
558
559 (Unfortunately we can't use the doctest module's parser,
560 since, like most parsers, it is not geared towards preserving
561 the original source.)
562 """
563 result = []
564 block = None
565 block_lineno = None
566 indent = None
567 lineno = 0
Ezio Melottid8b509b2011-09-28 17:37:55 +0300568 for line in input.splitlines(keepends=True):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000569 lineno += 1
570 if line.lstrip().startswith(self.PS1):
571 if block is not None:
572 result.extend(self.refactor_doctest(block, block_lineno,
573 indent, filename))
574 block_lineno = lineno
575 block = [line]
576 i = line.find(self.PS1)
577 indent = line[:i]
578 elif (indent is not None and
579 (line.startswith(indent + self.PS2) or
580 line == indent + self.PS2.rstrip() + "\n")):
581 block.append(line)
582 else:
583 if block is not None:
584 result.extend(self.refactor_doctest(block, block_lineno,
585 indent, filename))
586 block = None
587 indent = None
588 result.append(line)
589 if block is not None:
590 result.extend(self.refactor_doctest(block, block_lineno,
591 indent, filename))
592 return "".join(result)
593
594 def refactor_doctest(self, block, lineno, indent, filename):
595 """Refactors one doctest.
596
597 A doctest is given as a block of lines, the first of which starts
598 with ">>>" (possibly indented), while the remaining lines start
599 with "..." (identically indented).
600
601 """
602 try:
603 tree = self.parse_block(block, lineno, indent)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000604 except Exception as err:
Benjamin Peterson4eb5fa52010-08-08 19:01:25 +0000605 if self.logger.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000606 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000607 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000608 self.log_error("Can't parse docstring in %s line %s: %s: %s",
609 filename, lineno, err.__class__.__name__, err)
610 return block
611 if self.refactor_tree(tree, filename):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300612 new = str(tree).splitlines(keepends=True)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000613 # Undo the adjustment of the line numbers in wrap_toks() below.
614 clipped, new = new[:lineno-1], new[lineno-1:]
615 assert clipped == ["\n"] * (lineno-1), clipped
616 if not new[-1].endswith("\n"):
617 new[-1] += "\n"
618 block = [indent + self.PS1 + new.pop(0)]
619 if new:
620 block += [indent + self.PS2 + line for line in new]
621 return block
622
623 def summarize(self):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000624 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000625 were = "were"
626 else:
627 were = "need to be"
628 if not self.files:
629 self.log_message("No files %s modified.", were)
630 else:
631 self.log_message("Files that %s modified:", were)
632 for file in self.files:
633 self.log_message(file)
634 if self.fixer_log:
635 self.log_message("Warnings/messages while refactoring:")
636 for message in self.fixer_log:
637 self.log_message(message)
638 if self.errors:
639 if len(self.errors) == 1:
640 self.log_message("There was 1 error:")
641 else:
642 self.log_message("There were %d errors:", len(self.errors))
643 for msg, args, kwds in self.errors:
644 self.log_message(msg, *args, **kwds)
645
646 def parse_block(self, block, lineno, indent):
647 """Parses a block into a tree.
648
649 This is necessary to get correct line number / offset information
650 in the parser diagnostics and embedded into the parse tree.
651 """
Benjamin Peterson2243e5e2010-05-22 18:59:24 +0000652 tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
653 tree.future_features = frozenset()
654 return tree
Martin v. Löwisef04c442008-03-19 05:04:44 +0000655
656 def wrap_toks(self, block, lineno, indent):
657 """Wraps a tokenize stream to systematically modify start/end."""
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000658 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000659 for type, value, (line0, col0), (line1, col1), line_text in tokens:
660 line0 += lineno - 1
661 line1 += lineno - 1
662 # Don't bother updating the columns; this is too complicated
663 # since line_text would also have to be updated and it would
664 # still break for tokens spanning lines. Let the user guess
665 # that the column numbers for doctests are relative to the
666 # end of the prompt string (PS1 or PS2).
667 yield type, value, (line0, col0), (line1, col1), line_text
668
669
670 def gen_lines(self, block, indent):
671 """Generates lines as expected by tokenize from a list of lines.
672
673 This strips the first len(indent + self.PS1) characters off each line.
674 """
675 prefix1 = indent + self.PS1
676 prefix2 = indent + self.PS2
677 prefix = prefix1
678 for line in block:
679 if line.startswith(prefix):
680 yield line[len(prefix):]
681 elif line == prefix.rstrip() + "\n":
682 yield "\n"
683 else:
684 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
685 prefix = prefix2
686 while True:
687 yield ""
688
689
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000690class MultiprocessingUnsupported(Exception):
691 pass
692
693
694class MultiprocessRefactoringTool(RefactoringTool):
695
696 def __init__(self, *args, **kwargs):
697 super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
698 self.queue = None
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000699 self.output_lock = None
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000700
701 def refactor(self, items, write=False, doctests_only=False,
702 num_processes=1):
703 if num_processes == 1:
704 return super(MultiprocessRefactoringTool, self).refactor(
705 items, write, doctests_only)
706 try:
707 import multiprocessing
Brett Cannoncd171c82013-07-04 17:43:24 -0400708 except ImportError:
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000709 raise MultiprocessingUnsupported
710 if self.queue is not None:
711 raise RuntimeError("already doing multiple processes")
712 self.queue = multiprocessing.JoinableQueue()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000713 self.output_lock = multiprocessing.Lock()
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000714 processes = [multiprocessing.Process(target=self._child)
Benjamin Peterson87b87192009-07-03 13:18:18 +0000715 for i in range(num_processes)]
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000716 try:
717 for p in processes:
718 p.start()
719 super(MultiprocessRefactoringTool, self).refactor(items, write,
720 doctests_only)
721 finally:
722 self.queue.join()
Benjamin Peterson87b87192009-07-03 13:18:18 +0000723 for i in range(num_processes):
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000724 self.queue.put(None)
725 for p in processes:
726 if p.is_alive():
727 p.join()
728 self.queue = None
729
730 def _child(self):
731 task = self.queue.get()
732 while task is not None:
733 args, kwargs = task
734 try:
735 super(MultiprocessRefactoringTool, self).refactor_file(
736 *args, **kwargs)
737 finally:
738 self.queue.task_done()
739 task = self.queue.get()
740
741 def refactor_file(self, *args, **kwargs):
742 if self.queue is not None:
743 self.queue.put((args, kwargs))
744 else:
745 return super(MultiprocessRefactoringTool, self).refactor_file(
746 *args, **kwargs)