Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 1 | # Copyright 2006 Google, Inc. All Rights Reserved. |
| 2 | # Licensed to PSF under a Contributor Agreement. |
| 3 | |
| 4 | """Refactoring framework. |
| 5 | |
| 6 | Used as a main program, this can refactor any number of files and/or |
| 7 | recursively descend down directories. Imported as a module, this |
| 8 | provides infrastructure to write your own refactoring tool. |
| 9 | """ |
| 10 | |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 11 | from __future__ import with_statement |
| 12 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 13 | __author__ = "Guido van Rossum <guido@python.org>" |
| 14 | |
| 15 | |
| 16 | # Python imports |
| 17 | import os |
| 18 | import sys |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 19 | import logging |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 20 | import operator |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 21 | import collections |
| 22 | import io |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 23 | from itertools import chain |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 24 | |
| 25 | # Local imports |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 26 | from .pgen2 import driver, tokenize, token |
Benjamin Peterson | 2c3ac6b | 2009-06-11 23:47:38 +0000 | [diff] [blame] | 27 | from . import pytree, pygram |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 28 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 29 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 30 | def 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öwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 34 | fix_names = [] |
Benjamin Peterson | 206e307 | 2008-10-19 14:07:49 +0000 | [diff] [blame] | 35 | for name in sorted(os.listdir(fixer_dir)): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 36 | if name.startswith("fix_") and name.endswith(".py"): |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 37 | if remove_prefix: |
| 38 | name = name[4:] |
| 39 | fix_names.append(name[:-3]) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 40 | return fix_names |
| 41 | |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 42 | |
| 43 | class _EveryNode(Exception): |
| 44 | pass |
| 45 | |
| 46 | |
| 47 | def _get_head_types(pat): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 48 | """ 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 Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 55 | if pat.type is None: |
| 56 | raise _EveryNode |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 57 | return set([pat.type]) |
| 58 | |
| 59 | if isinstance(pat, pytree.NegatedPattern): |
| 60 | if pat.content: |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 61 | return _get_head_types(pat.content) |
| 62 | raise _EveryNode # Negated Patterns don't have a type |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 63 | |
| 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 Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 69 | r.update(_get_head_types(x)) |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 70 | return r |
| 71 | |
| 72 | raise Exception("Oh no! I don't understand pattern %s" %(pat)) |
| 73 | |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 74 | |
| 75 | def _get_headnode_dict(fixer_list): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 76 | """ Accepts a list of fixers and returns a dictionary |
| 77 | of head node type --> fixer list. """ |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 78 | head_nodes = collections.defaultdict(list) |
| 79 | every = [] |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 80 | for fixer in fixer_list: |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 81 | 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 Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 99 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 100 | def 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 Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 107 | def _identity(obj): |
| 108 | return obj |
| 109 | |
| 110 | if sys.version_info < (3, 0): |
| 111 | import codecs |
| 112 | _open_with_encoding = codecs.open |
| 113 | # codecs.open doesn't translate newlines sadly. |
| 114 | def _from_system_newlines(input): |
| 115 | return input.replace("\r\n", "\n") |
| 116 | def _to_system_newlines(input): |
| 117 | if os.linesep != "\n": |
| 118 | return input.replace("\n", os.linesep) |
| 119 | else: |
| 120 | return input |
| 121 | else: |
| 122 | _open_with_encoding = open |
| 123 | _from_system_newlines = _identity |
| 124 | _to_system_newlines = _identity |
| 125 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 126 | |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 127 | def _detect_future_features(source): |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 128 | have_docstring = False |
| 129 | gen = tokenize.generate_tokens(io.StringIO(source).readline) |
| 130 | def advance(): |
| 131 | tok = next(gen) |
| 132 | return tok[0], tok[1] |
| 133 | ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 134 | features = set() |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 135 | try: |
| 136 | while True: |
| 137 | tp, value = advance() |
| 138 | if tp in ignore: |
| 139 | continue |
| 140 | elif tp == token.STRING: |
| 141 | if have_docstring: |
| 142 | break |
| 143 | have_docstring = True |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 144 | elif tp == token.NAME and value == "from": |
| 145 | tp, value = advance() |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 146 | if tp != token.NAME or value != "__future__": |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 147 | break |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 148 | tp, value = advance() |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 149 | if tp != token.NAME or value != "import": |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 150 | break |
| 151 | tp, value = advance() |
| 152 | if tp == token.OP and value == "(": |
| 153 | tp, value = advance() |
| 154 | while tp == token.NAME: |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 155 | features.add(value) |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 156 | tp, value = advance() |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 157 | if tp != token.OP or value != ",": |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 158 | break |
| 159 | tp, value = advance() |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 160 | else: |
| 161 | break |
| 162 | except StopIteration: |
| 163 | pass |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 164 | return frozenset(features) |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 165 | |
| 166 | |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 167 | class FixerError(Exception): |
| 168 | """A fixer could not be loaded.""" |
| 169 | |
| 170 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 171 | class RefactoringTool(object): |
| 172 | |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 173 | _default_options = {"print_function" : False} |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 174 | |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 175 | CLASS_PREFIX = "Fix" # The prefix for fixer classes |
| 176 | FILE_PREFIX = "fix_" # The prefix for modules with a fixer within |
| 177 | |
| 178 | def __init__(self, fixer_names, options=None, explicit=None): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 179 | """Initializer. |
| 180 | |
Benjamin Peterson | df6dc8f | 2008-06-15 02:57:40 +0000 | [diff] [blame] | 181 | Args: |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 182 | fixer_names: a list of fixers to import |
| 183 | options: an dict with configuration. |
| 184 | explicit: a list of fixers to run even if they are explicit. |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 185 | """ |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 186 | self.fixers = fixer_names |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 187 | self.explicit = explicit or [] |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 188 | self.options = self._default_options.copy() |
| 189 | if options is not None: |
| 190 | self.options.update(options) |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 191 | if self.options["print_function"]: |
| 192 | self.grammar = pygram.python_grammar_no_print_statement |
| 193 | else: |
| 194 | self.grammar = pygram.python_grammar |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 195 | self.errors = [] |
| 196 | self.logger = logging.getLogger("RefactoringTool") |
| 197 | self.fixer_log = [] |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 198 | self.wrote = False |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 199 | self.driver = driver.Driver(self.grammar, |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 200 | convert=pytree.convert, |
| 201 | logger=self.logger) |
| 202 | self.pre_order, self.post_order = self.get_fixers() |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 203 | |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 204 | self.pre_order_heads = _get_headnode_dict(self.pre_order) |
| 205 | self.post_order_heads = _get_headnode_dict(self.post_order) |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 206 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 207 | self.files = [] # List of files that were or should be modified |
| 208 | |
| 209 | def get_fixers(self): |
| 210 | """Inspects the options to load the requested patterns and handlers. |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 211 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 212 | Returns: |
| 213 | (pre_order, post_order), where pre_order is the list of fixers that |
| 214 | want a pre-order AST traversal, and post_order is the list that want |
| 215 | post-order traversal. |
| 216 | """ |
| 217 | pre_order_fixers = [] |
| 218 | post_order_fixers = [] |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 219 | for fix_mod_path in self.fixers: |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 220 | mod = __import__(fix_mod_path, {}, {}, ["*"]) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 221 | fix_name = fix_mod_path.rsplit(".", 1)[-1] |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 222 | if fix_name.startswith(self.FILE_PREFIX): |
| 223 | fix_name = fix_name[len(self.FILE_PREFIX):] |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 224 | parts = fix_name.split("_") |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 225 | class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts]) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 226 | try: |
| 227 | fix_class = getattr(mod, class_name) |
| 228 | except AttributeError: |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 229 | raise FixerError("Can't find %s.%s" % (fix_name, class_name)) |
| 230 | fixer = fix_class(self.options, self.fixer_log) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 231 | if fixer.explicit and self.explicit is not True and \ |
| 232 | fix_mod_path not in self.explicit: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 233 | self.log_message("Skipping implicit fixer: %s", fix_name) |
| 234 | continue |
| 235 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 236 | self.log_debug("Adding transformation: %s", fix_name) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 237 | if fixer.order == "pre": |
| 238 | pre_order_fixers.append(fixer) |
| 239 | elif fixer.order == "post": |
| 240 | post_order_fixers.append(fixer) |
| 241 | else: |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 242 | raise FixerError("Illegal fixer order: %r" % fixer.order) |
Martin v. Löwis | 3faa84f | 2008-03-22 00:07:09 +0000 | [diff] [blame] | 243 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 244 | key_func = operator.attrgetter("run_order") |
| 245 | pre_order_fixers.sort(key=key_func) |
| 246 | post_order_fixers.sort(key=key_func) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 247 | return (pre_order_fixers, post_order_fixers) |
| 248 | |
| 249 | def log_error(self, msg, *args, **kwds): |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 250 | """Called when an error occurs.""" |
| 251 | raise |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 252 | |
| 253 | def log_message(self, msg, *args): |
| 254 | """Hook to log a message.""" |
| 255 | if args: |
| 256 | msg = msg % args |
| 257 | self.logger.info(msg) |
| 258 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 259 | def log_debug(self, msg, *args): |
| 260 | if args: |
| 261 | msg = msg % args |
| 262 | self.logger.debug(msg) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 263 | |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 264 | def print_output(self, old_text, new_text, filename, equal): |
| 265 | """Called with the old version, new version, and filename of a |
| 266 | refactored file.""" |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 267 | pass |
| 268 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 269 | def refactor(self, items, write=False, doctests_only=False): |
| 270 | """Refactor a list of files and directories.""" |
| 271 | for dir_or_file in items: |
| 272 | if os.path.isdir(dir_or_file): |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 273 | self.refactor_dir(dir_or_file, write, doctests_only) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 274 | else: |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 275 | self.refactor_file(dir_or_file, write, doctests_only) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 276 | |
| 277 | def refactor_dir(self, dir_name, write=False, doctests_only=False): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 278 | """Descends down a directory and refactor every Python file found. |
| 279 | |
| 280 | Python files are assumed to have a .py extension. |
| 281 | |
| 282 | Files and subdirectories starting with '.' are skipped. |
| 283 | """ |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 284 | for dirpath, dirnames, filenames in os.walk(dir_name): |
| 285 | self.log_debug("Descending into %s", dirpath) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 286 | dirnames.sort() |
| 287 | filenames.sort() |
| 288 | for name in filenames: |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 289 | if not name.startswith(".") and \ |
| 290 | os.path.splitext(name)[1].endswith("py"): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 291 | fullname = os.path.join(dirpath, name) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 292 | self.refactor_file(fullname, write, doctests_only) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 293 | # Modify dirnames in-place to remove subdirs with leading dots |
| 294 | dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")] |
| 295 | |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 296 | def _read_python_source(self, filename): |
| 297 | """ |
| 298 | Do our best to decode a Python source file correctly. |
| 299 | """ |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 300 | try: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 301 | f = open(filename, "rb") |
Martin v. Löwis | 8a5f8ca | 2008-03-19 05:33:36 +0000 | [diff] [blame] | 302 | except IOError as err: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 303 | self.log_error("Can't open %s: %s", filename, err) |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 304 | return None, None |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 305 | try: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 306 | encoding = tokenize.detect_encoding(f.readline)[0] |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 307 | finally: |
| 308 | f.close() |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 309 | with _open_with_encoding(filename, "r", encoding=encoding) as f: |
| 310 | return _from_system_newlines(f.read()), encoding |
| 311 | |
| 312 | def refactor_file(self, filename, write=False, doctests_only=False): |
| 313 | """Refactors a file.""" |
| 314 | input, encoding = self._read_python_source(filename) |
| 315 | if input is None: |
| 316 | # Reading the file failed. |
| 317 | return |
| 318 | input += "\n" # Silence certain parse errors |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 319 | if doctests_only: |
| 320 | self.log_debug("Refactoring doctests in %s", filename) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 321 | output = self.refactor_docstring(input, filename) |
| 322 | if output != input: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 323 | self.processed_file(output, filename, input, write, encoding) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 324 | else: |
| 325 | self.log_debug("No doctest changes in %s", filename) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 326 | else: |
| 327 | tree = self.refactor_string(input, filename) |
| 328 | if tree and tree.was_changed: |
| 329 | # The [:-1] is to take off the \n we added earlier |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 330 | self.processed_file(str(tree)[:-1], filename, |
| 331 | write=write, encoding=encoding) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 332 | else: |
| 333 | self.log_debug("No changes in %s", filename) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 334 | |
| 335 | def refactor_string(self, data, name): |
| 336 | """Refactor a given input string. |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 337 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 338 | Args: |
| 339 | data: a string holding the code to be refactored. |
| 340 | name: a human-readable name for use in error/log messages. |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 341 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 342 | Returns: |
| 343 | An AST corresponding to the refactored input stream; None if |
| 344 | there were errors during the parse. |
| 345 | """ |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 346 | features = _detect_future_features(data) |
| 347 | if "print_function" in features: |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 348 | self.driver.grammar = pygram.python_grammar_no_print_statement |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 349 | try: |
Benjamin Peterson | 206e307 | 2008-10-19 14:07:49 +0000 | [diff] [blame] | 350 | tree = self.driver.parse_string(data) |
Martin v. Löwis | 8a5f8ca | 2008-03-19 05:33:36 +0000 | [diff] [blame] | 351 | except Exception as err: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 352 | self.log_error("Can't parse %s: %s: %s", |
| 353 | name, err.__class__.__name__, err) |
| 354 | return |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 355 | finally: |
Benjamin Peterson | 2021100 | 2009-11-25 18:34:42 +0000 | [diff] [blame] | 356 | self.driver.grammar = self.grammar |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 357 | tree.future_features = features |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 358 | self.log_debug("Refactoring %s", name) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 359 | self.refactor_tree(tree, name) |
| 360 | return tree |
| 361 | |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 362 | def refactor_stdin(self, doctests_only=False): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 363 | input = sys.stdin.read() |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 364 | if doctests_only: |
| 365 | self.log_debug("Refactoring doctests in stdin") |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 366 | output = self.refactor_docstring(input, "<stdin>") |
| 367 | if output != input: |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 368 | self.processed_file(output, "<stdin>", input) |
| 369 | else: |
| 370 | self.log_debug("No doctest changes in stdin") |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 371 | else: |
| 372 | tree = self.refactor_string(input, "<stdin>") |
| 373 | if tree and tree.was_changed: |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 374 | self.processed_file(str(tree), "<stdin>", input) |
| 375 | else: |
| 376 | self.log_debug("No changes in stdin") |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 377 | |
| 378 | def refactor_tree(self, tree, name): |
| 379 | """Refactors a parse tree (modifying the tree in place). |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 380 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 381 | Args: |
| 382 | tree: a pytree.Node instance representing the root of the tree |
| 383 | to be refactored. |
| 384 | name: a human-readable name for this tree. |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 385 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 386 | Returns: |
| 387 | True if the tree was modified, False otherwise. |
| 388 | """ |
Benjamin Peterson | 8bcddca | 2009-01-03 16:53:14 +0000 | [diff] [blame] | 389 | for fixer in chain(self.pre_order, self.post_order): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 390 | fixer.start_tree(tree, name) |
| 391 | |
Benjamin Peterson | 0b24b3d | 2008-12-16 03:57:54 +0000 | [diff] [blame] | 392 | self.traverse_by(self.pre_order_heads, tree.pre_order()) |
| 393 | self.traverse_by(self.post_order_heads, tree.post_order()) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 394 | |
Benjamin Peterson | 8bcddca | 2009-01-03 16:53:14 +0000 | [diff] [blame] | 395 | for fixer in chain(self.pre_order, self.post_order): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 396 | fixer.finish_tree(tree, name) |
| 397 | return tree.was_changed |
| 398 | |
| 399 | def traverse_by(self, fixers, traversal): |
| 400 | """Traverse an AST, applying a set of fixers to each node. |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 401 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 402 | This is a helper method for refactor_tree(). |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 403 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 404 | Args: |
| 405 | fixers: a list of fixer instances. |
| 406 | traversal: a generator that yields AST nodes. |
Martin v. Löwis | f733c60 | 2008-03-19 05:26:18 +0000 | [diff] [blame] | 407 | |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 408 | Returns: |
| 409 | None |
| 410 | """ |
| 411 | if not fixers: |
| 412 | return |
| 413 | for node in traversal: |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 414 | for fixer in fixers[node.type]: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 415 | results = fixer.match(node) |
| 416 | if results: |
| 417 | new = fixer.transform(node, results) |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 418 | if new is not None: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 419 | node.replace(new) |
| 420 | node = new |
| 421 | |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 422 | def processed_file(self, new_text, filename, old_text=None, write=False, |
| 423 | encoding=None): |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 424 | """ |
| 425 | Called when a file has been refactored, and there are changes. |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 426 | """ |
| 427 | self.files.append(filename) |
| 428 | if old_text is None: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 429 | old_text = self._read_python_source(filename)[0] |
| 430 | if old_text is None: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 431 | return |
Benjamin Peterson | 3059b00 | 2009-07-20 16:42:03 +0000 | [diff] [blame] | 432 | equal = old_text == new_text |
| 433 | self.print_output(old_text, new_text, filename, equal) |
| 434 | if equal: |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 435 | self.log_debug("No changes to %s", filename) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 436 | return |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 437 | if write: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 438 | self.write_file(new_text, filename, old_text, encoding) |
Benjamin Peterson | d61de7f | 2008-09-27 22:17:35 +0000 | [diff] [blame] | 439 | else: |
| 440 | self.log_debug("Not writing changes to %s", filename) |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 441 | |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 442 | def write_file(self, new_text, filename, old_text, encoding=None): |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 443 | """Writes a string to a file. |
| 444 | |
| 445 | It first shows a unified diff between the old text and the new text, and |
| 446 | then rewrites the file; the latter is only done if the write option is |
| 447 | set. |
| 448 | """ |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 449 | try: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 450 | f = _open_with_encoding(filename, "w", encoding=encoding) |
Martin v. Löwis | 8a5f8ca | 2008-03-19 05:33:36 +0000 | [diff] [blame] | 451 | except os.error as err: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 452 | self.log_error("Can't create %s: %s", filename, err) |
| 453 | return |
| 454 | try: |
Benjamin Peterson | d481e3d | 2009-05-09 19:42:23 +0000 | [diff] [blame] | 455 | f.write(_to_system_newlines(new_text)) |
Benjamin Peterson | ba55818 | 2008-11-10 22:21:33 +0000 | [diff] [blame] | 456 | except os.error as err: |
| 457 | self.log_error("Can't write %s: %s", filename, err) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 458 | finally: |
| 459 | f.close() |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 460 | self.log_debug("Wrote changes to %s", filename) |
| 461 | self.wrote = True |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 462 | |
| 463 | PS1 = ">>> " |
| 464 | PS2 = "... " |
| 465 | |
| 466 | def refactor_docstring(self, input, filename): |
| 467 | """Refactors a docstring, looking for doctests. |
| 468 | |
| 469 | This returns a modified version of the input string. It looks |
| 470 | for doctests, which start with a ">>>" prompt, and may be |
| 471 | continued with "..." prompts, as long as the "..." is indented |
| 472 | the same as the ">>>". |
| 473 | |
| 474 | (Unfortunately we can't use the doctest module's parser, |
| 475 | since, like most parsers, it is not geared towards preserving |
| 476 | the original source.) |
| 477 | """ |
| 478 | result = [] |
| 479 | block = None |
| 480 | block_lineno = None |
| 481 | indent = None |
| 482 | lineno = 0 |
| 483 | for line in input.splitlines(True): |
| 484 | lineno += 1 |
| 485 | if line.lstrip().startswith(self.PS1): |
| 486 | if block is not None: |
| 487 | result.extend(self.refactor_doctest(block, block_lineno, |
| 488 | indent, filename)) |
| 489 | block_lineno = lineno |
| 490 | block = [line] |
| 491 | i = line.find(self.PS1) |
| 492 | indent = line[:i] |
| 493 | elif (indent is not None and |
| 494 | (line.startswith(indent + self.PS2) or |
| 495 | line == indent + self.PS2.rstrip() + "\n")): |
| 496 | block.append(line) |
| 497 | else: |
| 498 | if block is not None: |
| 499 | result.extend(self.refactor_doctest(block, block_lineno, |
| 500 | indent, filename)) |
| 501 | block = None |
| 502 | indent = None |
| 503 | result.append(line) |
| 504 | if block is not None: |
| 505 | result.extend(self.refactor_doctest(block, block_lineno, |
| 506 | indent, filename)) |
| 507 | return "".join(result) |
| 508 | |
| 509 | def refactor_doctest(self, block, lineno, indent, filename): |
| 510 | """Refactors one doctest. |
| 511 | |
| 512 | A doctest is given as a block of lines, the first of which starts |
| 513 | with ">>>" (possibly indented), while the remaining lines start |
| 514 | with "..." (identically indented). |
| 515 | |
| 516 | """ |
| 517 | try: |
| 518 | tree = self.parse_block(block, lineno, indent) |
Martin v. Löwis | 8a5f8ca | 2008-03-19 05:33:36 +0000 | [diff] [blame] | 519 | except Exception as err: |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 520 | if self.log.isEnabledFor(logging.DEBUG): |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 521 | for line in block: |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 522 | self.log_debug("Source: %s", line.rstrip("\n")) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 523 | self.log_error("Can't parse docstring in %s line %s: %s: %s", |
| 524 | filename, lineno, err.__class__.__name__, err) |
| 525 | return block |
| 526 | if self.refactor_tree(tree, filename): |
| 527 | new = str(tree).splitlines(True) |
| 528 | # Undo the adjustment of the line numbers in wrap_toks() below. |
| 529 | clipped, new = new[:lineno-1], new[lineno-1:] |
| 530 | assert clipped == ["\n"] * (lineno-1), clipped |
| 531 | if not new[-1].endswith("\n"): |
| 532 | new[-1] += "\n" |
| 533 | block = [indent + self.PS1 + new.pop(0)] |
| 534 | if new: |
| 535 | block += [indent + self.PS2 + line for line in new] |
| 536 | return block |
| 537 | |
| 538 | def summarize(self): |
Benjamin Peterson | 8951b61 | 2008-09-03 02:27:16 +0000 | [diff] [blame] | 539 | if self.wrote: |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 540 | were = "were" |
| 541 | else: |
| 542 | were = "need to be" |
| 543 | if not self.files: |
| 544 | self.log_message("No files %s modified.", were) |
| 545 | else: |
| 546 | self.log_message("Files that %s modified:", were) |
| 547 | for file in self.files: |
| 548 | self.log_message(file) |
| 549 | if self.fixer_log: |
| 550 | self.log_message("Warnings/messages while refactoring:") |
| 551 | for message in self.fixer_log: |
| 552 | self.log_message(message) |
| 553 | if self.errors: |
| 554 | if len(self.errors) == 1: |
| 555 | self.log_message("There was 1 error:") |
| 556 | else: |
| 557 | self.log_message("There were %d errors:", len(self.errors)) |
| 558 | for msg, args, kwds in self.errors: |
| 559 | self.log_message(msg, *args, **kwds) |
| 560 | |
| 561 | def parse_block(self, block, lineno, indent): |
| 562 | """Parses a block into a tree. |
| 563 | |
| 564 | This is necessary to get correct line number / offset information |
| 565 | in the parser diagnostics and embedded into the parse tree. |
| 566 | """ |
| 567 | return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) |
| 568 | |
| 569 | def wrap_toks(self, block, lineno, indent): |
| 570 | """Wraps a tokenize stream to systematically modify start/end.""" |
Martin v. Löwis | 8a5f8ca | 2008-03-19 05:33:36 +0000 | [diff] [blame] | 571 | tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__) |
Martin v. Löwis | ef04c44 | 2008-03-19 05:04:44 +0000 | [diff] [blame] | 572 | for type, value, (line0, col0), (line1, col1), line_text in tokens: |
| 573 | line0 += lineno - 1 |
| 574 | line1 += lineno - 1 |
| 575 | # Don't bother updating the columns; this is too complicated |
| 576 | # since line_text would also have to be updated and it would |
| 577 | # still break for tokens spanning lines. Let the user guess |
| 578 | # that the column numbers for doctests are relative to the |
| 579 | # end of the prompt string (PS1 or PS2). |
| 580 | yield type, value, (line0, col0), (line1, col1), line_text |
| 581 | |
| 582 | |
| 583 | def gen_lines(self, block, indent): |
| 584 | """Generates lines as expected by tokenize from a list of lines. |
| 585 | |
| 586 | This strips the first len(indent + self.PS1) characters off each line. |
| 587 | """ |
| 588 | prefix1 = indent + self.PS1 |
| 589 | prefix2 = indent + self.PS2 |
| 590 | prefix = prefix1 |
| 591 | for line in block: |
| 592 | if line.startswith(prefix): |
| 593 | yield line[len(prefix):] |
| 594 | elif line == prefix.rstrip() + "\n": |
| 595 | yield "\n" |
| 596 | else: |
| 597 | raise AssertionError("line=%r, prefix=%r" % (line, prefix)) |
| 598 | prefix = prefix2 |
| 599 | while True: |
| 600 | yield "" |
| 601 | |
| 602 | |
Benjamin Peterson | 608d8bc | 2009-05-05 23:23:31 +0000 | [diff] [blame] | 603 | class MultiprocessingUnsupported(Exception): |
| 604 | pass |
| 605 | |
| 606 | |
| 607 | class MultiprocessRefactoringTool(RefactoringTool): |
| 608 | |
| 609 | def __init__(self, *args, **kwargs): |
| 610 | super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs) |
| 611 | self.queue = None |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 612 | self.output_lock = None |
Benjamin Peterson | 608d8bc | 2009-05-05 23:23:31 +0000 | [diff] [blame] | 613 | |
| 614 | def refactor(self, items, write=False, doctests_only=False, |
| 615 | num_processes=1): |
| 616 | if num_processes == 1: |
| 617 | return super(MultiprocessRefactoringTool, self).refactor( |
| 618 | items, write, doctests_only) |
| 619 | try: |
| 620 | import multiprocessing |
| 621 | except ImportError: |
| 622 | raise MultiprocessingUnsupported |
| 623 | if self.queue is not None: |
| 624 | raise RuntimeError("already doing multiple processes") |
| 625 | self.queue = multiprocessing.JoinableQueue() |
Benjamin Peterson | 8d26b0b | 2010-05-07 19:10:11 +0000 | [diff] [blame^] | 626 | self.output_lock = multiprocessing.Lock() |
Benjamin Peterson | 608d8bc | 2009-05-05 23:23:31 +0000 | [diff] [blame] | 627 | processes = [multiprocessing.Process(target=self._child) |
Benjamin Peterson | 87b8719 | 2009-07-03 13:18:18 +0000 | [diff] [blame] | 628 | for i in range(num_processes)] |
Benjamin Peterson | 608d8bc | 2009-05-05 23:23:31 +0000 | [diff] [blame] | 629 | try: |
| 630 | for p in processes: |
| 631 | p.start() |
| 632 | super(MultiprocessRefactoringTool, self).refactor(items, write, |
| 633 | doctests_only) |
| 634 | finally: |
| 635 | self.queue.join() |
Benjamin Peterson | 87b8719 | 2009-07-03 13:18:18 +0000 | [diff] [blame] | 636 | for i in range(num_processes): |
Benjamin Peterson | 608d8bc | 2009-05-05 23:23:31 +0000 | [diff] [blame] | 637 | self.queue.put(None) |
| 638 | for p in processes: |
| 639 | if p.is_alive(): |
| 640 | p.join() |
| 641 | self.queue = None |
| 642 | |
| 643 | def _child(self): |
| 644 | task = self.queue.get() |
| 645 | while task is not None: |
| 646 | args, kwargs = task |
| 647 | try: |
| 648 | super(MultiprocessRefactoringTool, self).refactor_file( |
| 649 | *args, **kwargs) |
| 650 | finally: |
| 651 | self.queue.task_done() |
| 652 | task = self.queue.get() |
| 653 | |
| 654 | def refactor_file(self, *args, **kwargs): |
| 655 | if self.queue is not None: |
| 656 | self.queue.put((args, kwargs)) |
| 657 | else: |
| 658 | return super(MultiprocessRefactoringTool, self).refactor_file( |
| 659 | *args, **kwargs) |