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