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