blob: 3a5aafffc6df07462dac0829ccfc2eb51c6938e5 [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
Benjamin Peterson93e8aa62019-07-24 16:38:50 -070017import pkgutil
Martin v. Löwisef04c442008-03-19 05:04:44 +000018import 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
Christian Heimes81ee3ef2008-05-04 22:42:01 +000022from itertools import chain
Martin v. Löwisef04c442008-03-19 05:04:44 +000023
24# Local imports
Benjamin Peterson3059b002009-07-20 16:42:03 +000025from .pgen2 import driver, tokenize, token
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000026from .fixer_util import find_root
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +000027from . import pytree, pygram
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000028from . import btm_matcher as bm
Martin v. Löwisef04c442008-03-19 05:04:44 +000029
Martin v. Löwisef04c442008-03-19 05:04:44 +000030
Benjamin Peterson8951b612008-09-03 02:27:16 +000031def get_all_fix_names(fixer_pkg, remove_prefix=True):
32 """Return a sorted list of all available fix names in the given package."""
33 pkg = __import__(fixer_pkg, [], [], ["*"])
Martin v. Löwisef04c442008-03-19 05:04:44 +000034 fix_names = []
Benjamin Peterson93e8aa62019-07-24 16:38:50 -070035 for finder, name, ispkg in pkgutil.iter_modules(pkg.__path__):
36 if name.startswith("fix_"):
Benjamin Peterson8951b612008-09-03 02:27:16 +000037 if remove_prefix:
38 name = name[4:]
Benjamin Peterson93e8aa62019-07-24 16:38:50 -070039 fix_names.append(name)
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,
Batuhan Taşkaya61b14152020-01-13 01:13:31 +0300158 "exec_function": False,
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800159 "write_unchanged_files" : False}
Benjamin Peterson8951b612008-09-03 02:27:16 +0000160
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000161 CLASS_PREFIX = "Fix" # The prefix for fixer classes
162 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
163
164 def __init__(self, fixer_names, options=None, explicit=None):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000165 """Initializer.
166
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000167 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000168 fixer_names: a list of fixers to import
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300169 options: a dict with configuration.
Benjamin Peterson8951b612008-09-03 02:27:16 +0000170 explicit: a list of fixers to run even if they are explicit.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000171 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000172 self.fixers = fixer_names
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000173 self.explicit = explicit or []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000174 self.options = self._default_options.copy()
175 if options is not None:
176 self.options.update(options)
Batuhan Taşkaya61b14152020-01-13 01:13:31 +0300177 self.grammar = pygram.python_grammar.copy()
178
179 if self.options['print_function']:
180 del self.grammar.keywords["print"]
181 elif self.options['exec_function']:
182 del self.grammar.keywords["exec"]
183
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800184 # When this is True, the refactor*() methods will call write_file() for
185 # files processed even if they were not changed during refactoring. If
186 # and only if the refactor method's write parameter was True.
187 self.write_unchanged_files = self.options.get("write_unchanged_files")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000188 self.errors = []
189 self.logger = logging.getLogger("RefactoringTool")
190 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000191 self.wrote = False
Benjamin Peterson20211002009-11-25 18:34:42 +0000192 self.driver = driver.Driver(self.grammar,
Martin v. Löwisef04c442008-03-19 05:04:44 +0000193 convert=pytree.convert,
194 logger=self.logger)
195 self.pre_order, self.post_order = self.get_fixers()
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000196
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000197
Martin v. Löwisef04c442008-03-19 05:04:44 +0000198 self.files = [] # List of files that were or should be modified
199
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000200 self.BM = bm.BottomMatcher()
201 self.bmi_pre_order = [] # Bottom Matcher incompatible fixers
202 self.bmi_post_order = []
203
204 for fixer in chain(self.post_order, self.pre_order):
205 if fixer.BM_compatible:
206 self.BM.add_fixer(fixer)
207 # remove fixers that will be handled by the bottom-up
208 # matcher
209 elif fixer in self.pre_order:
210 self.bmi_pre_order.append(fixer)
211 elif fixer in self.post_order:
212 self.bmi_post_order.append(fixer)
213
214 self.bmi_pre_order_heads = _get_headnode_dict(self.bmi_pre_order)
215 self.bmi_post_order_heads = _get_headnode_dict(self.bmi_post_order)
216
217
218
Martin v. Löwisef04c442008-03-19 05:04:44 +0000219 def get_fixers(self):
220 """Inspects the options to load the requested patterns and handlers.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000221
Martin v. Löwisef04c442008-03-19 05:04:44 +0000222 Returns:
223 (pre_order, post_order), where pre_order is the list of fixers that
224 want a pre-order AST traversal, and post_order is the list that want
225 post-order traversal.
226 """
227 pre_order_fixers = []
228 post_order_fixers = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000229 for fix_mod_path in self.fixers:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000230 mod = __import__(fix_mod_path, {}, {}, ["*"])
Benjamin Peterson8951b612008-09-03 02:27:16 +0000231 fix_name = fix_mod_path.rsplit(".", 1)[-1]
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000232 if fix_name.startswith(self.FILE_PREFIX):
233 fix_name = fix_name[len(self.FILE_PREFIX):]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000234 parts = fix_name.split("_")
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000235 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000236 try:
237 fix_class = getattr(mod, class_name)
238 except AttributeError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300239 raise FixerError("Can't find %s.%s" % (fix_name, class_name)) from None
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000240 fixer = fix_class(self.options, self.fixer_log)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000241 if fixer.explicit and self.explicit is not True and \
242 fix_mod_path not in self.explicit:
Berker Peksag3a81f9b2015-05-13 13:39:51 +0300243 self.log_message("Skipping optional fixer: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000244 continue
245
Benjamin Peterson8951b612008-09-03 02:27:16 +0000246 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000247 if fixer.order == "pre":
248 pre_order_fixers.append(fixer)
249 elif fixer.order == "post":
250 post_order_fixers.append(fixer)
251 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000252 raise FixerError("Illegal fixer order: %r" % fixer.order)
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000253
Benjamin Peterson8951b612008-09-03 02:27:16 +0000254 key_func = operator.attrgetter("run_order")
255 pre_order_fixers.sort(key=key_func)
256 post_order_fixers.sort(key=key_func)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000257 return (pre_order_fixers, post_order_fixers)
258
259 def log_error(self, msg, *args, **kwds):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000260 """Called when an error occurs."""
261 raise
Martin v. Löwisef04c442008-03-19 05:04:44 +0000262
263 def log_message(self, msg, *args):
264 """Hook to log a message."""
265 if args:
266 msg = msg % args
267 self.logger.info(msg)
268
Benjamin Peterson8951b612008-09-03 02:27:16 +0000269 def log_debug(self, msg, *args):
270 if args:
271 msg = msg % args
272 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000273
Benjamin Peterson3059b002009-07-20 16:42:03 +0000274 def print_output(self, old_text, new_text, filename, equal):
275 """Called with the old version, new version, and filename of a
276 refactored file."""
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000277 pass
278
Benjamin Peterson8951b612008-09-03 02:27:16 +0000279 def refactor(self, items, write=False, doctests_only=False):
280 """Refactor a list of files and directories."""
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000281
Benjamin Peterson8951b612008-09-03 02:27:16 +0000282 for dir_or_file in items:
283 if os.path.isdir(dir_or_file):
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000284 self.refactor_dir(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000285 else:
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000286 self.refactor_file(dir_or_file, write, doctests_only)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000287
288 def refactor_dir(self, dir_name, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000289 """Descends down a directory and refactor every Python file found.
290
291 Python files are assumed to have a .py extension.
292
293 Files and subdirectories starting with '.' are skipped.
294 """
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000295 py_ext = os.extsep + "py"
Benjamin Peterson8951b612008-09-03 02:27:16 +0000296 for dirpath, dirnames, filenames in os.walk(dir_name):
297 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000298 dirnames.sort()
299 filenames.sort()
300 for name in filenames:
Martin v. Löwise2bb4eb2010-12-03 23:11:07 +0000301 if (not name.startswith(".") and
302 os.path.splitext(name)[1] == py_ext):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000303 fullname = os.path.join(dirpath, name)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000304 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000305 # Modify dirnames in-place to remove subdirs with leading dots
306 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
307
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000308 def _read_python_source(self, filename):
309 """
310 Do our best to decode a Python source file correctly.
311 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000312 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000313 f = open(filename, "rb")
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200314 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000315 self.log_error("Can't open %s: %s", filename, err)
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000316 return None, None
Martin v. Löwisef04c442008-03-19 05:04:44 +0000317 try:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000318 encoding = tokenize.detect_encoding(f.readline)[0]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000319 finally:
320 f.close()
Aaron Angc127a862018-04-17 14:34:14 -0700321 with io.open(filename, "r", encoding=encoding, newline='') as f:
Victor Stinner272d8882017-06-16 08:59:01 +0200322 return f.read(), encoding
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000323
324 def refactor_file(self, filename, write=False, doctests_only=False):
325 """Refactors a file."""
326 input, encoding = self._read_python_source(filename)
327 if input is None:
328 # Reading the file failed.
329 return
330 input += "\n" # Silence certain parse errors
Benjamin Peterson8951b612008-09-03 02:27:16 +0000331 if doctests_only:
332 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000333 output = self.refactor_docstring(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800334 if self.write_unchanged_files or output != input:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000335 self.processed_file(output, filename, input, write, encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000336 else:
337 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000338 else:
339 tree = self.refactor_string(input, filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800340 if self.write_unchanged_files or (tree and tree.was_changed):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000341 # The [:-1] is to take off the \n we added earlier
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000342 self.processed_file(str(tree)[:-1], filename,
343 write=write, encoding=encoding)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000344 else:
345 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000346
347 def refactor_string(self, data, name):
348 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000349
Martin v. Löwisef04c442008-03-19 05:04:44 +0000350 Args:
351 data: a string holding the code to be refactored.
352 name: a human-readable name for use in error/log messages.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000353
Martin v. Löwisef04c442008-03-19 05:04:44 +0000354 Returns:
355 An AST corresponding to the refactored input stream; None if
356 there were errors during the parse.
357 """
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000358 features = _detect_future_features(data)
359 if "print_function" in features:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000360 self.driver.grammar = pygram.python_grammar_no_print_statement
Martin v. Löwisef04c442008-03-19 05:04:44 +0000361 try:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000362 tree = self.driver.parse_string(data)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000363 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000364 self.log_error("Can't parse %s: %s: %s",
365 name, err.__class__.__name__, err)
366 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000367 finally:
Benjamin Peterson20211002009-11-25 18:34:42 +0000368 self.driver.grammar = self.grammar
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000369 tree.future_features = features
Benjamin Peterson8951b612008-09-03 02:27:16 +0000370 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000371 self.refactor_tree(tree, name)
372 return tree
373
Benjamin Peterson8951b612008-09-03 02:27:16 +0000374 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000375 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000376 if doctests_only:
377 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000378 output = self.refactor_docstring(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800379 if self.write_unchanged_files or output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000380 self.processed_file(output, "<stdin>", input)
381 else:
382 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000383 else:
384 tree = self.refactor_string(input, "<stdin>")
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800385 if self.write_unchanged_files or (tree and tree.was_changed):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000386 self.processed_file(str(tree), "<stdin>", input)
387 else:
388 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000389
390 def refactor_tree(self, tree, name):
391 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000392
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000393 For compatible patterns the bottom matcher module is
394 used. Otherwise the tree is traversed node-to-node for
395 matches.
396
Martin v. Löwisef04c442008-03-19 05:04:44 +0000397 Args:
398 tree: a pytree.Node instance representing the root of the tree
399 to be refactored.
400 name: a human-readable name for this tree.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000401
Martin v. Löwisef04c442008-03-19 05:04:44 +0000402 Returns:
403 True if the tree was modified, False otherwise.
404 """
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000405
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000406 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000407 fixer.start_tree(tree, name)
408
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000409 #use traditional matching for the incompatible fixers
410 self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
411 self.traverse_by(self.bmi_post_order_heads, tree.post_order())
412
413 # obtain a set of candidate nodes
414 match_set = self.BM.run(tree.leaves())
415
416 while any(match_set.values()):
417 for fixer in self.BM.fixers:
418 if fixer in match_set and match_set[fixer]:
419 #sort by depth; apply fixers from bottom(of the AST) to top
420 match_set[fixer].sort(key=pytree.Base.depth, reverse=True)
421
422 if fixer.keep_line_order:
423 #some fixers(eg fix_imports) must be applied
424 #with the original file's line order
425 match_set[fixer].sort(key=pytree.Base.get_lineno)
426
427 for node in list(match_set[fixer]):
428 if node in match_set[fixer]:
429 match_set[fixer].remove(node)
430
431 try:
432 find_root(node)
Benjamin Peterson1654d742012-09-25 11:48:50 -0400433 except ValueError:
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +0000434 # this node has been cut off from a
435 # previous transformation ; skip
436 continue
437
438 if node.fixers_applied and fixer in node.fixers_applied:
439 # do not apply the same fixer again
440 continue
441
442 results = fixer.match(node)
443
444 if results:
445 new = fixer.transform(node, results)
446 if new is not None:
447 node.replace(new)
448 #new.fixers_applied.append(fixer)
449 for node in new.post_order():
450 # do not apply the fixer again to
451 # this or any subnode
452 if not node.fixers_applied:
453 node.fixers_applied = []
454 node.fixers_applied.append(fixer)
455
456 # update the original match set for
457 # the added code
458 new_matches = self.BM.run(new.leaves())
459 for fxr in new_matches:
460 if not fxr in match_set:
461 match_set[fxr]=[]
462
463 match_set[fxr].extend(new_matches[fxr])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000464
Benjamin Peterson8bcddca2009-01-03 16:53:14 +0000465 for fixer in chain(self.pre_order, self.post_order):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000466 fixer.finish_tree(tree, name)
467 return tree.was_changed
468
469 def traverse_by(self, fixers, traversal):
470 """Traverse an AST, applying a set of fixers to each node.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000471
Martin v. Löwisef04c442008-03-19 05:04:44 +0000472 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000473
Martin v. Löwisef04c442008-03-19 05:04:44 +0000474 Args:
475 fixers: a list of fixer instances.
476 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000477
Martin v. Löwisef04c442008-03-19 05:04:44 +0000478 Returns:
479 None
480 """
481 if not fixers:
482 return
483 for node in traversal:
Benjamin Peterson3059b002009-07-20 16:42:03 +0000484 for fixer in fixers[node.type]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000485 results = fixer.match(node)
486 if results:
487 new = fixer.transform(node, results)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000488 if new is not None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000489 node.replace(new)
490 node = new
491
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000492 def processed_file(self, new_text, filename, old_text=None, write=False,
493 encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000494 """
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800495 Called when a file has been refactored and there may be changes.
Martin v. Löwisef04c442008-03-19 05:04:44 +0000496 """
497 self.files.append(filename)
498 if old_text is None:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000499 old_text = self._read_python_source(filename)[0]
500 if old_text is None:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000501 return
Benjamin Peterson3059b002009-07-20 16:42:03 +0000502 equal = old_text == new_text
503 self.print_output(old_text, new_text, filename, equal)
504 if equal:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000505 self.log_debug("No changes to %s", filename)
Gregory P. Smith58f23ff2012-02-12 15:50:21 -0800506 if not self.write_unchanged_files:
507 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000508 if write:
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000509 self.write_file(new_text, filename, old_text, encoding)
Benjamin Petersond61de7f2008-09-27 22:17:35 +0000510 else:
511 self.log_debug("Not writing changes to %s", filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000512
Benjamin Petersond481e3d2009-05-09 19:42:23 +0000513 def write_file(self, new_text, filename, old_text, encoding=None):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000514 """Writes a string to a file.
515
516 It first shows a unified diff between the old text and the new text, and
517 then rewrites the file; the latter is only done if the write option is
518 set.
519 """
Martin v. Löwisef04c442008-03-19 05:04:44 +0000520 try:
Jason R. Coombscafaf042018-07-13 11:26:03 -0400521 fp = io.open(filename, "w", encoding=encoding, newline='')
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200522 except OSError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000523 self.log_error("Can't create %s: %s", filename, err)
524 return
Victor Stinner272d8882017-06-16 08:59:01 +0200525
526 with fp:
527 try:
528 fp.write(new_text)
529 except OSError as err:
530 self.log_error("Can't write %s: %s", filename, err)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000531 self.log_debug("Wrote changes to %s", filename)
532 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000533
534 PS1 = ">>> "
535 PS2 = "... "
536
537 def refactor_docstring(self, input, filename):
538 """Refactors a docstring, looking for doctests.
539
540 This returns a modified version of the input string. It looks
541 for doctests, which start with a ">>>" prompt, and may be
542 continued with "..." prompts, as long as the "..." is indented
543 the same as the ">>>".
544
545 (Unfortunately we can't use the doctest module's parser,
546 since, like most parsers, it is not geared towards preserving
547 the original source.)
548 """
549 result = []
550 block = None
551 block_lineno = None
552 indent = None
553 lineno = 0
Ezio Melottid8b509b2011-09-28 17:37:55 +0300554 for line in input.splitlines(keepends=True):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000555 lineno += 1
556 if line.lstrip().startswith(self.PS1):
557 if block is not None:
558 result.extend(self.refactor_doctest(block, block_lineno,
559 indent, filename))
560 block_lineno = lineno
561 block = [line]
562 i = line.find(self.PS1)
563 indent = line[:i]
564 elif (indent is not None and
565 (line.startswith(indent + self.PS2) or
566 line == indent + self.PS2.rstrip() + "\n")):
567 block.append(line)
568 else:
569 if block is not None:
570 result.extend(self.refactor_doctest(block, block_lineno,
571 indent, filename))
572 block = None
573 indent = None
574 result.append(line)
575 if block is not None:
576 result.extend(self.refactor_doctest(block, block_lineno,
577 indent, filename))
578 return "".join(result)
579
580 def refactor_doctest(self, block, lineno, indent, filename):
581 """Refactors one doctest.
582
583 A doctest is given as a block of lines, the first of which starts
584 with ">>>" (possibly indented), while the remaining lines start
585 with "..." (identically indented).
586
587 """
588 try:
589 tree = self.parse_block(block, lineno, indent)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000590 except Exception as err:
Benjamin Peterson4eb5fa52010-08-08 19:01:25 +0000591 if self.logger.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000592 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000593 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000594 self.log_error("Can't parse docstring in %s line %s: %s: %s",
595 filename, lineno, err.__class__.__name__, err)
596 return block
597 if self.refactor_tree(tree, filename):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300598 new = str(tree).splitlines(keepends=True)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000599 # Undo the adjustment of the line numbers in wrap_toks() below.
600 clipped, new = new[:lineno-1], new[lineno-1:]
601 assert clipped == ["\n"] * (lineno-1), clipped
602 if not new[-1].endswith("\n"):
603 new[-1] += "\n"
604 block = [indent + self.PS1 + new.pop(0)]
605 if new:
606 block += [indent + self.PS2 + line for line in new]
607 return block
608
609 def summarize(self):
Benjamin Peterson8951b612008-09-03 02:27:16 +0000610 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000611 were = "were"
612 else:
613 were = "need to be"
614 if not self.files:
615 self.log_message("No files %s modified.", were)
616 else:
617 self.log_message("Files that %s modified:", were)
618 for file in self.files:
619 self.log_message(file)
620 if self.fixer_log:
621 self.log_message("Warnings/messages while refactoring:")
622 for message in self.fixer_log:
623 self.log_message(message)
624 if self.errors:
625 if len(self.errors) == 1:
626 self.log_message("There was 1 error:")
627 else:
628 self.log_message("There were %d errors:", len(self.errors))
629 for msg, args, kwds in self.errors:
630 self.log_message(msg, *args, **kwds)
631
632 def parse_block(self, block, lineno, indent):
633 """Parses a block into a tree.
634
635 This is necessary to get correct line number / offset information
636 in the parser diagnostics and embedded into the parse tree.
637 """
Benjamin Peterson2243e5e2010-05-22 18:59:24 +0000638 tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
639 tree.future_features = frozenset()
640 return tree
Martin v. Löwisef04c442008-03-19 05:04:44 +0000641
642 def wrap_toks(self, block, lineno, indent):
643 """Wraps a tokenize stream to systematically modify start/end."""
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000644 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000645 for type, value, (line0, col0), (line1, col1), line_text in tokens:
646 line0 += lineno - 1
647 line1 += lineno - 1
648 # Don't bother updating the columns; this is too complicated
649 # since line_text would also have to be updated and it would
650 # still break for tokens spanning lines. Let the user guess
651 # that the column numbers for doctests are relative to the
652 # end of the prompt string (PS1 or PS2).
653 yield type, value, (line0, col0), (line1, col1), line_text
654
655
656 def gen_lines(self, block, indent):
657 """Generates lines as expected by tokenize from a list of lines.
658
659 This strips the first len(indent + self.PS1) characters off each line.
660 """
661 prefix1 = indent + self.PS1
662 prefix2 = indent + self.PS2
663 prefix = prefix1
664 for line in block:
665 if line.startswith(prefix):
666 yield line[len(prefix):]
667 elif line == prefix.rstrip() + "\n":
668 yield "\n"
669 else:
670 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
671 prefix = prefix2
672 while True:
673 yield ""
674
675
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000676class MultiprocessingUnsupported(Exception):
677 pass
678
679
680class MultiprocessRefactoringTool(RefactoringTool):
681
682 def __init__(self, *args, **kwargs):
683 super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
684 self.queue = None
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000685 self.output_lock = None
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000686
687 def refactor(self, items, write=False, doctests_only=False,
688 num_processes=1):
689 if num_processes == 1:
690 return super(MultiprocessRefactoringTool, self).refactor(
691 items, write, doctests_only)
692 try:
693 import multiprocessing
Brett Cannoncd171c82013-07-04 17:43:24 -0400694 except ImportError:
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000695 raise MultiprocessingUnsupported
696 if self.queue is not None:
697 raise RuntimeError("already doing multiple processes")
698 self.queue = multiprocessing.JoinableQueue()
Benjamin Peterson8d26b0b2010-05-07 19:10:11 +0000699 self.output_lock = multiprocessing.Lock()
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000700 processes = [multiprocessing.Process(target=self._child)
Benjamin Peterson87b87192009-07-03 13:18:18 +0000701 for i in range(num_processes)]
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000702 try:
703 for p in processes:
704 p.start()
705 super(MultiprocessRefactoringTool, self).refactor(items, write,
706 doctests_only)
707 finally:
708 self.queue.join()
Benjamin Peterson87b87192009-07-03 13:18:18 +0000709 for i in range(num_processes):
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000710 self.queue.put(None)
711 for p in processes:
712 if p.is_alive():
713 p.join()
714 self.queue = None
715
716 def _child(self):
717 task = self.queue.get()
718 while task is not None:
719 args, kwargs = task
720 try:
721 super(MultiprocessRefactoringTool, self).refactor_file(
722 *args, **kwargs)
723 finally:
724 self.queue.task_done()
725 task = self.queue.get()
726
727 def refactor_file(self, *args, **kwargs):
728 if self.queue is not None:
729 self.queue.put((args, kwargs))
730 else:
731 return super(MultiprocessRefactoringTool, self).refactor_file(
732 *args, **kwargs)