blob: 7841b99a5cd4c1ee7dcc48b405a1c8edb4340739 [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
Victor Stinner272d8882017-06-16 08:59:01 +020015import io
Martin v. Löwisef04c442008-03-19 05:04:44 +000016import os
17import sys
Martin v. Löwisef04c442008-03-19 05:04:44 +000018import logging
Benjamin Peterson8951b612008-09-03 02:27:16 +000019import operator
Benjamin Peterson3059b002009-07-20 16:42:03 +000020import collections
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
Martin v. Löwisef04c442008-03-19 05:04:44 +0000110
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000111def _detect_future_features(source):
Benjamin Peterson3059b002009-07-20 16:42:03 +0000112 have_docstring = False
113 gen = tokenize.generate_tokens(io.StringIO(source).readline)
114 def advance():
115 tok = next(gen)
116 return tok[0], tok[1]
Serhiy Storchakadb9b65d2014-12-13 21:50:49 +0200117 ignore = frozenset({token.NEWLINE, tokenize.NL, token.COMMENT})
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000118 features = set()
Benjamin Peterson3059b002009-07-20 16:42:03 +0000119 try:
120 while True:
121 tp, value = advance()
122 if tp in ignore:
123 continue
124 elif tp == token.STRING:
125 if have_docstring:
126 break
127 have_docstring = True
Benjamin Peterson20211002009-11-25 18:34:42 +0000128 elif tp == token.NAME and value == "from":
129 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000130 if tp != token.NAME or value != "__future__":
Benjamin Peterson3059b002009-07-20 16:42:03 +0000131 break
Benjamin Peterson20211002009-11-25 18:34:42 +0000132 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000133 if tp != token.NAME or value != "import":
Benjamin Peterson20211002009-11-25 18:34:42 +0000134 break
135 tp, value = advance()
136 if tp == token.OP and value == "(":
137 tp, value = advance()
138 while tp == token.NAME:
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000139 features.add(value)
Benjamin Peterson20211002009-11-25 18:34:42 +0000140 tp, value = advance()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000141 if tp != token.OP or value != ",":
Benjamin Peterson20211002009-11-25 18:34:42 +0000142 break
143 tp, value = advance()
Benjamin Peterson3059b002009-07-20 16:42:03 +0000144 else:
145 break
146 except StopIteration:
147 pass
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000148 return frozenset(features)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000149
150
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000151class FixerError(Exception):
152 """A fixer could not be loaded."""
153
154
Martin v. Löwisef04c442008-03-19 05:04:44 +0000155class RefactoringTool(object):
156
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800157 _default_options = {"print_function" : False,
158 "write_unchanged_files" : False}
Benjamin Peterson8951b612008-09-03 02:27:16 +0000159
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000160 CLASS_PREFIX = "Fix" # The prefix for fixer classes
161 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
162
163 def __init__(self, fixer_names, options=None, explicit=None):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000164 """Initializer.
165
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000166 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000167 fixer_names: a list of fixers to import
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300168 options: a dict with configuration.
Benjamin Peterson8951b612008-09-03 02:27:16 +0000169 explicit: a list of fixers to run even if they are explicit.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000170 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000171 self.fixers = fixer_names
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000172 self.explicit = explicit or []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000173 self.options = self._default_options.copy()
174 if options is not None:
175 self.options.update(options)
Benjamin Peterson20211002009-11-25 18:34:42 +0000176 if self.options["print_function"]:
177 self.grammar = pygram.python_grammar_no_print_statement
178 else:
179 self.grammar = pygram.python_grammar
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800180 # When this is True, the refactor*() methods will call write_file() for
181 # files processed even if they were not changed during refactoring. If
182 # and only if the refactor method's write parameter was True.
183 self.write_unchanged_files = self.options.get("write_unchanged_files")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000184 self.errors = []
185 self.logger = logging.getLogger("RefactoringTool")
186 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000187 self.wrote = False
Benjamin Peterson20211002009-11-25 18:34:42 +0000188 self.driver = driver.Driver(self.grammar,
Martin v. Löwisef04c442008-03-19 05:04:44 +0000189 convert=pytree.convert,
190 logger=self.logger)
191 self.pre_order, self.post_order = self.get_fixers()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000192
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000193
Martin v. Löwisef04c442008-03-19 05:04:44 +0000194 self.files = [] # List of files that were or should be modified
195
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000196 self.BM = bm.BottomMatcher()
197 self.bmi_pre_order = [] # Bottom Matcher incompatible fixers
198 self.bmi_post_order = []
199
200 for fixer in chain(self.post_order, self.pre_order):
201 if fixer.BM_compatible:
202 self.BM.add_fixer(fixer)
203 # remove fixers that will be handled by the bottom-up
204 # matcher
205 elif fixer in self.pre_order:
206 self.bmi_pre_order.append(fixer)
207 elif fixer in self.post_order:
208 self.bmi_post_order.append(fixer)
209
210 self.bmi_pre_order_heads = _get_headnode_dict(self.bmi_pre_order)
211 self.bmi_post_order_heads = _get_headnode_dict(self.bmi_post_order)
212
213
214
Martin v. Löwisef04c442008-03-19 05:04:44 +0000215 def get_fixers(self):
216 """Inspects the options to load the requested patterns and handlers.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000217
Martin v. Löwisef04c442008-03-19 05:04:44 +0000218 Returns:
219 (pre_order, post_order), where pre_order is the list of fixers that
220 want a pre-order AST traversal, and post_order is the list that want
221 post-order traversal.
222 """
223 pre_order_fixers = []
224 post_order_fixers = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000225 for fix_mod_path in self.fixers:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000226 mod = __import__(fix_mod_path, {}, {}, ["*"])
Benjamin Peterson8951b612008-09-03 02:27:16 +0000227 fix_name = fix_mod_path.rsplit(".", 1)[-1]
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000228 if fix_name.startswith(self.FILE_PREFIX):
229 fix_name = fix_name[len(self.FILE_PREFIX):]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000230 parts = fix_name.split("_")
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000231 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000232 try:
233 fix_class = getattr(mod, class_name)
234 except AttributeError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300235 raise FixerError("Can't find %s.%s" % (fix_name, class_name)) from None
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000236 fixer = fix_class(self.options, self.fixer_log)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000237 if fixer.explicit and self.explicit is not True and \
238 fix_mod_path not in self.explicit:
Berker Peksag3a81f9b2015-05-13 13:39:51 +0300239 self.log_message("Skipping optional fixer: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000240 continue
241
Benjamin Peterson8951b612008-09-03 02:27:16 +0000242 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000243 if fixer.order == "pre":
244 pre_order_fixers.append(fixer)
245 elif fixer.order == "post":
246 post_order_fixers.append(fixer)
247 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000248 raise FixerError("Illegal fixer order: %r" % fixer.order)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000249
Benjamin Peterson8951b612008-09-03 02:27:16 +0000250 key_func = operator.attrgetter("run_order")
251 pre_order_fixers.sort(key=key_func)
252 post_order_fixers.sort(key=key_func)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000253 return (pre_order_fixers, post_order_fixers)
254
255 def log_error(self, msg, *args, **kwds):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000256 """Called when an error occurs."""
257 raise
Martin v. Löwisef04c442008-03-19 05:04:44 +0000258
259 def log_message(self, msg, *args):
260 """Hook to log a message."""
261 if args:
262 msg = msg % args
263 self.logger.info(msg)
264
Benjamin Peterson8951b612008-09-03 02:27:16 +0000265 def log_debug(self, msg, *args):
266 if args:
267 msg = msg % args
268 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000269
Benjamin Peterson3059b002009-07-20 16:42:03 +0000270 def print_output(self, old_text, new_text, filename, equal):
271 """Called with the old version, new version, and filename of a
272 refactored file."""
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000273 pass
274
Benjamin Peterson8951b612008-09-03 02:27:16 +0000275 def refactor(self, items, write=False, doctests_only=False):
276 """Refactor a list of files and directories."""
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000277
Benjamin Peterson8951b612008-09-03 02:27:16 +0000278 for dir_or_file in items:
279 if os.path.isdir(dir_or_file):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000280 self.refactor_dir(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000281 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000282 self.refactor_file(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000283
284 def refactor_dir(self, dir_name, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000285 """Descends down a directory and refactor every Python file found.
286
287 Python files are assumed to have a .py extension.
288
289 Files and subdirectories starting with '.' are skipped.
290 """
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000291 py_ext = os.extsep + "py"
Benjamin Peterson8951b612008-09-03 02:27:16 +0000292 for dirpath, dirnames, filenames in os.walk(dir_name):
293 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000294 dirnames.sort()
295 filenames.sort()
296 for name in filenames:
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000297 if (not name.startswith(".") and
298 os.path.splitext(name)[1] == py_ext):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000299 fullname = os.path.join(dirpath, name)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000300 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000301 # Modify dirnames in-place to remove subdirs with leading dots
302 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
303
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000304 def _read_python_source(self, filename):
305 """
306 Do our best to decode a Python source file correctly.
307 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000308 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000309 f = open(filename, "rb")
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200310 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000311 self.log_error("Can't open %s: %s", filename, err)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000312 return None, None
Martin v. Löwisef04c442008-03-19 05:04:44 +0000313 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000314 encoding = tokenize.detect_encoding(f.readline)[0]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000315 finally:
316 f.close()
Aaron Angc127a862018-04-17 14:34:14 -0700317 with io.open(filename, "r", encoding=encoding, newline='') as f:
Victor Stinner272d8882017-06-16 08:59:01 +0200318 return f.read(), encoding
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000319
320 def refactor_file(self, filename, write=False, doctests_only=False):
321 """Refactors a file."""
322 input, encoding = self._read_python_source(filename)
323 if input is None:
324 # Reading the file failed.
325 return
326 input += "\n" # Silence certain parse errors
Benjamin Peterson8951b612008-09-03 02:27:16 +0000327 if doctests_only:
328 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000329 output = self.refactor_docstring(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800330 if self.write_unchanged_files or output != input:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000331 self.processed_file(output, filename, input, write, encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000332 else:
333 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000334 else:
335 tree = self.refactor_string(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800336 if self.write_unchanged_files or (tree and tree.was_changed):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000337 # The [:-1] is to take off the \n we added earlier
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000338 self.processed_file(str(tree)[:-1], filename,
339 write=write, encoding=encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000340 else:
341 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000342
343 def refactor_string(self, data, name):
344 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000345
Martin v. Löwisef04c442008-03-19 05:04:44 +0000346 Args:
347 data: a string holding the code to be refactored.
348 name: a human-readable name for use in error/log messages.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000349
Martin v. Löwisef04c442008-03-19 05:04:44 +0000350 Returns:
351 An AST corresponding to the refactored input stream; None if
352 there were errors during the parse.
353 """
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000354 features = _detect_future_features(data)
355 if "print_function" in features:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000356 self.driver.grammar = pygram.python_grammar_no_print_statement
Martin v. Löwisef04c442008-03-19 05:04:44 +0000357 try:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000358 tree = self.driver.parse_string(data)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000359 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000360 self.log_error("Can't parse %s: %s: %s",
361 name, err.__class__.__name__, err)
362 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000363 finally:
Benjamin Peterson20211002009-11-25 18:34:42 +0000364 self.driver.grammar = self.grammar
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000365 tree.future_features = features
Benjamin Peterson8951b612008-09-03 02:27:16 +0000366 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000367 self.refactor_tree(tree, name)
368 return tree
369
Benjamin Peterson8951b612008-09-03 02:27:16 +0000370 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000371 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000372 if doctests_only:
373 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000374 output = self.refactor_docstring(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800375 if self.write_unchanged_files or output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000376 self.processed_file(output, "<stdin>", input)
377 else:
378 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000379 else:
380 tree = self.refactor_string(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800381 if self.write_unchanged_files or (tree and tree.was_changed):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000382 self.processed_file(str(tree), "<stdin>", input)
383 else:
384 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000385
386 def refactor_tree(self, tree, name):
387 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000388
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000389 For compatible patterns the bottom matcher module is
390 used. Otherwise the tree is traversed node-to-node for
391 matches.
392
Martin v. Löwisef04c442008-03-19 05:04:44 +0000393 Args:
394 tree: a pytree.Node instance representing the root of the tree
395 to be refactored.
396 name: a human-readable name for this tree.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000397
Martin v. Löwisef04c442008-03-19 05:04:44 +0000398 Returns:
399 True if the tree was modified, False otherwise.
400 """
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000401
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000402 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000403 fixer.start_tree(tree, name)
404
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000405 #use traditional matching for the incompatible fixers
406 self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
407 self.traverse_by(self.bmi_post_order_heads, tree.post_order())
408
409 # obtain a set of candidate nodes
410 match_set = self.BM.run(tree.leaves())
411
412 while any(match_set.values()):
413 for fixer in self.BM.fixers:
414 if fixer in match_set and match_set[fixer]:
415 #sort by depth; apply fixers from bottom(of the AST) to top
416 match_set[fixer].sort(key=pytree.Base.depth, reverse=True)
417
418 if fixer.keep_line_order:
419 #some fixers(eg fix_imports) must be applied
420 #with the original file's line order
421 match_set[fixer].sort(key=pytree.Base.get_lineno)
422
423 for node in list(match_set[fixer]):
424 if node in match_set[fixer]:
425 match_set[fixer].remove(node)
426
427 try:
428 find_root(node)
Benjamin Peterson1654d742012-09-25 11:48:50 -0400429 except ValueError:
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000430 # this node has been cut off from a
431 # previous transformation ; skip
432 continue
433
434 if node.fixers_applied and fixer in node.fixers_applied:
435 # do not apply the same fixer again
436 continue
437
438 results = fixer.match(node)
439
440 if results:
441 new = fixer.transform(node, results)
442 if new is not None:
443 node.replace(new)
444 #new.fixers_applied.append(fixer)
445 for node in new.post_order():
446 # do not apply the fixer again to
447 # this or any subnode
448 if not node.fixers_applied:
449 node.fixers_applied = []
450 node.fixers_applied.append(fixer)
451
452 # update the original match set for
453 # the added code
454 new_matches = self.BM.run(new.leaves())
455 for fxr in new_matches:
456 if not fxr in match_set:
457 match_set[fxr]=[]
458
459 match_set[fxr].extend(new_matches[fxr])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000460
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000461 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000462 fixer.finish_tree(tree, name)
463 return tree.was_changed
464
465 def traverse_by(self, fixers, traversal):
466 """Traverse an AST, applying a set of fixers to each node.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000467
Martin v. Löwisef04c442008-03-19 05:04:44 +0000468 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000469
Martin v. Löwisef04c442008-03-19 05:04:44 +0000470 Args:
471 fixers: a list of fixer instances.
472 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000473
Martin v. Löwisef04c442008-03-19 05:04:44 +0000474 Returns:
475 None
476 """
477 if not fixers:
478 return
479 for node in traversal:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000480 for fixer in fixers[node.type]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000481 results = fixer.match(node)
482 if results:
483 new = fixer.transform(node, results)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000484 if new is not None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000485 node.replace(new)
486 node = new
487
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000488 def processed_file(self, new_text, filename, old_text=None, write=False,
489 encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000490 """
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800491 Called when a file has been refactored and there may be changes.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000492 """
493 self.files.append(filename)
494 if old_text is None:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000495 old_text = self._read_python_source(filename)[0]
496 if old_text is None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000497 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000498 equal = old_text == new_text
499 self.print_output(old_text, new_text, filename, equal)
500 if equal:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000501 self.log_debug("No changes to %s", filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800502 if not self.write_unchanged_files:
503 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000504 if write:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000505 self.write_file(new_text, filename, old_text, encoding)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000506 else:
507 self.log_debug("Not writing changes to %s", filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000508
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000509 def write_file(self, new_text, filename, old_text, encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000510 """Writes a string to a file.
511
512 It first shows a unified diff between the old text and the new text, and
513 then rewrites the file; the latter is only done if the write option is
514 set.
515 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000516 try:
Jason R. Coombscafaf042018-07-13 11:26:03 -0400517 fp = io.open(filename, "w", encoding=encoding, newline='')
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200518 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000519 self.log_error("Can't create %s: %s", filename, err)
520 return
Victor Stinner272d8882017-06-16 08:59:01 +0200521
522 with fp:
523 try:
524 fp.write(new_text)
525 except OSError as err:
526 self.log_error("Can't write %s: %s", filename, err)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000527 self.log_debug("Wrote changes to %s", filename)
528 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000529
530 PS1 = ">>> "
531 PS2 = "... "
532
533 def refactor_docstring(self, input, filename):
534 """Refactors a docstring, looking for doctests.
535
536 This returns a modified version of the input string. It looks
537 for doctests, which start with a ">>>" prompt, and may be
538 continued with "..." prompts, as long as the "..." is indented
539 the same as the ">>>".
540
541 (Unfortunately we can't use the doctest module's parser,
542 since, like most parsers, it is not geared towards preserving
543 the original source.)
544 """
545 result = []
546 block = None
547 block_lineno = None
548 indent = None
549 lineno = 0
Ezio Melottid8b509b2011-09-28 17:37:55 +0300550 for line in input.splitlines(keepends=True):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000551 lineno += 1
552 if line.lstrip().startswith(self.PS1):
553 if block is not None:
554 result.extend(self.refactor_doctest(block, block_lineno,
555 indent, filename))
556 block_lineno = lineno
557 block = [line]
558 i = line.find(self.PS1)
559 indent = line[:i]
560 elif (indent is not None and
561 (line.startswith(indent + self.PS2) or
562 line == indent + self.PS2.rstrip() + "\n")):
563 block.append(line)
564 else:
565 if block is not None:
566 result.extend(self.refactor_doctest(block, block_lineno,
567 indent, filename))
568 block = None
569 indent = None
570 result.append(line)
571 if block is not None:
572 result.extend(self.refactor_doctest(block, block_lineno,
573 indent, filename))
574 return "".join(result)
575
576 def refactor_doctest(self, block, lineno, indent, filename):
577 """Refactors one doctest.
578
579 A doctest is given as a block of lines, the first of which starts
580 with ">>>" (possibly indented), while the remaining lines start
581 with "..." (identically indented).
582
583 """
584 try:
585 tree = self.parse_block(block, lineno, indent)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000586 except Exception as err:
Benjamin Peterson4eb5fa52010-08-08 19:01:25 +0000587 if self.logger.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000588 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000589 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000590 self.log_error("Can't parse docstring in %s line %s: %s: %s",
591 filename, lineno, err.__class__.__name__, err)
592 return block
593 if self.refactor_tree(tree, filename):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300594 new = str(tree).splitlines(keepends=True)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000595 # Undo the adjustment of the line numbers in wrap_toks() below.
596 clipped, new = new[:lineno-1], new[lineno-1:]
597 assert clipped == ["\n"] * (lineno-1), clipped
598 if not new[-1].endswith("\n"):
599 new[-1] += "\n"
600 block = [indent + self.PS1 + new.pop(0)]
601 if new:
602 block += [indent + self.PS2 + line for line in new]
603 return block
604
605 def summarize(self):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000606 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000607 were = "were"
608 else:
609 were = "need to be"
610 if not self.files:
611 self.log_message("No files %s modified.", were)
612 else:
613 self.log_message("Files that %s modified:", were)
614 for file in self.files:
615 self.log_message(file)
616 if self.fixer_log:
617 self.log_message("Warnings/messages while refactoring:")
618 for message in self.fixer_log:
619 self.log_message(message)
620 if self.errors:
621 if len(self.errors) == 1:
622 self.log_message("There was 1 error:")
623 else:
624 self.log_message("There were %d errors:", len(self.errors))
625 for msg, args, kwds in self.errors:
626 self.log_message(msg, *args, **kwds)
627
628 def parse_block(self, block, lineno, indent):
629 """Parses a block into a tree.
630
631 This is necessary to get correct line number / offset information
632 in the parser diagnostics and embedded into the parse tree.
633 """
Benjamin Peterson2243e5e2010-05-22 18:59:24 +0000634 tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
635 tree.future_features = frozenset()
636 return tree
Martin v. Löwisef04c442008-03-19 05:04:44 +0000637
638 def wrap_toks(self, block, lineno, indent):
639 """Wraps a tokenize stream to systematically modify start/end."""
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000640 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000641 for type, value, (line0, col0), (line1, col1), line_text in tokens:
642 line0 += lineno - 1
643 line1 += lineno - 1
644 # Don't bother updating the columns; this is too complicated
645 # since line_text would also have to be updated and it would
646 # still break for tokens spanning lines. Let the user guess
647 # that the column numbers for doctests are relative to the
648 # end of the prompt string (PS1 or PS2).
649 yield type, value, (line0, col0), (line1, col1), line_text
650
651
652 def gen_lines(self, block, indent):
653 """Generates lines as expected by tokenize from a list of lines.
654
655 This strips the first len(indent + self.PS1) characters off each line.
656 """
657 prefix1 = indent + self.PS1
658 prefix2 = indent + self.PS2
659 prefix = prefix1
660 for line in block:
661 if line.startswith(prefix):
662 yield line[len(prefix):]
663 elif line == prefix.rstrip() + "\n":
664 yield "\n"
665 else:
666 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
667 prefix = prefix2
668 while True:
669 yield ""
670
671
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000672class MultiprocessingUnsupported(Exception):
673 pass
674
675
676class MultiprocessRefactoringTool(RefactoringTool):
677
678 def __init__(self, *args, **kwargs):
679 super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
680 self.queue = None
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000681 self.output_lock = None
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000682
683 def refactor(self, items, write=False, doctests_only=False,
684 num_processes=1):
685 if num_processes == 1:
686 return super(MultiprocessRefactoringTool, self).refactor(
687 items, write, doctests_only)
688 try:
689 import multiprocessing
Brett Cannoncd171c82013-07-04 17:43:24 -0400690 except ImportError:
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000691 raise MultiprocessingUnsupported
692 if self.queue is not None:
693 raise RuntimeError("already doing multiple processes")
694 self.queue = multiprocessing.JoinableQueue()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000695 self.output_lock = multiprocessing.Lock()
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000696 processes = [multiprocessing.Process(target=self._child)
Benjamin Peterson87b87192009-07-03 13:18:18 +0000697 for i in range(num_processes)]
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000698 try:
699 for p in processes:
700 p.start()
701 super(MultiprocessRefactoringTool, self).refactor(items, write,
702 doctests_only)
703 finally:
704 self.queue.join()
Benjamin Peterson87b87192009-07-03 13:18:18 +0000705 for i in range(num_processes):
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000706 self.queue.put(None)
707 for p in processes:
708 if p.is_alive():
709 p.join()
710 self.queue = None
711
712 def _child(self):
713 task = self.queue.get()
714 while task is not None:
715 args, kwargs = task
716 try:
717 super(MultiprocessRefactoringTool, self).refactor_file(
718 *args, **kwargs)
719 finally:
720 self.queue.task_done()
721 task = self.queue.get()
722
723 def refactor_file(self, *args, **kwargs):
724 if self.queue is not None:
725 self.queue.put((args, kwargs))
726 else:
727 return super(MultiprocessRefactoringTool, self).refactor_file(
728 *args, **kwargs)