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