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