1 #!/usr/bin/env python2.5
2 # Copyright 2006 Google, Inc. All Rights Reserved.
3 # Licensed to PSF under a Contributor Agreement.
5 """Refactoring framework.
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.
12 __author__ = "Guido van Rossum <guido@python.org>"
21 from collections import defaultdict
22 from itertools import chain
25 from .pgen2 import driver
26 from .pgen2 import tokenize
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__)
39 for name in sorted(os.listdir(fixer_dir)):
40 if name.startswith("fix_") and name.endswith(".py"):
43 fix_names.append(name[:-3])
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. """
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
54 return set([pat.type])
56 if isinstance(pat, pytree.NegatedPattern):
58 return get_head_types(pat.content)
59 return set([None]) # Negated Patterns don't have a type
61 if isinstance(pat, pytree.WildcardPattern):
62 # Recurse on each node in content
66 r.update(get_head_types(x))
69 raise Exception("Oh no! I don't understand pattern %s" %(pat))
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:
77 head_nodes[None].append(fixer)
79 for t in get_head_types(fixer.pattern):
80 head_nodes[t].append(fixer)
83 def get_fixers_from_package(pkg_name):
85 Return the fully qualified names for fixers in the package pkg_name.
87 return [pkg_name + "." + fix_name
88 for fix_name in get_all_fix_names(pkg_name, False)]
91 class FixerError(Exception):
92 """A fixer could not be loaded."""
95 class RefactoringTool(object):
97 _default_options = {"print_function": False}
99 CLASS_PREFIX = "Fix" # The prefix for fixer classes
100 FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
102 def __init__(self, fixer_names, options=None, explicit=None):
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.
110 self.fixers = fixer_names
111 self.explicit = explicit or []
112 self.options = self._default_options.copy()
113 if options is not None:
114 self.options.update(options)
116 self.logger = logging.getLogger("RefactoringTool")
119 if self.options["print_function"]:
120 del pygram.python_grammar.keywords["print"]
121 self.driver = driver.Driver(pygram.python_grammar,
122 convert=pytree.convert,
124 self.pre_order, self.post_order = self.get_fixers()
126 self.pre_order_heads = get_headnode_dict(self.pre_order)
127 self.post_order_heads = get_headnode_dict(self.post_order)
129 self.files = [] # List of files that were or should be modified
131 def get_fixers(self):
132 """Inspects the options to load the requested patterns and handlers.
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.
139 pre_order_fixers = []
140 post_order_fixers = []
141 for fix_mod_path in self.fixers:
142 mod = __import__(fix_mod_path, {}, {}, ["*"])
143 fix_name = fix_mod_path.rsplit(".", 1)[-1]
144 if fix_name.startswith(self.FILE_PREFIX):
145 fix_name = fix_name[len(self.FILE_PREFIX):]
146 parts = fix_name.split("_")
147 class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
149 fix_class = getattr(mod, class_name)
150 except AttributeError:
151 raise FixerError("Can't find %s.%s" % (fix_name, class_name))
152 fixer = fix_class(self.options, self.fixer_log)
153 if fixer.explicit and self.explicit is not True and \
154 fix_mod_path not in self.explicit:
155 self.log_message("Skipping implicit fixer: %s", fix_name)
158 self.log_debug("Adding transformation: %s", fix_name)
159 if fixer.order == "pre":
160 pre_order_fixers.append(fixer)
161 elif fixer.order == "post":
162 post_order_fixers.append(fixer)
164 raise FixerError("Illegal fixer order: %r" % fixer.order)
166 key_func = operator.attrgetter("run_order")
167 pre_order_fixers.sort(key=key_func)
168 post_order_fixers.sort(key=key_func)
169 return (pre_order_fixers, post_order_fixers)
171 def log_error(self, msg, *args, **kwds):
172 """Called when an error occurs."""
175 def log_message(self, msg, *args):
176 """Hook to log a message."""
179 self.logger.info(msg)
181 def log_debug(self, msg, *args):
184 self.logger.debug(msg)
186 def print_output(self, lines):
187 """Called with lines of output to give to the user."""
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):
194 self.refactor_dir(dir_or_file, write, doctests_only)
196 self.refactor_file(dir_or_file, write, doctests_only)
198 def refactor_dir(self, dir_name, write=False, doctests_only=False):
199 """Descends down a directory and refactor every Python file found.
201 Python files are assumed to have a .py extension.
203 Files and subdirectories starting with '.' are skipped.
205 for dirpath, dirnames, filenames in os.walk(dir_name):
206 self.log_debug("Descending into %s", dirpath)
209 for name in filenames:
210 if not name.startswith(".") and name.endswith("py"):
211 fullname = os.path.join(dirpath, name)
212 self.refactor_file(fullname, write, doctests_only)
213 # Modify dirnames in-place to remove subdirs with leading dots
214 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
216 def refactor_file(self, filename, write=False, doctests_only=False):
217 """Refactors a file."""
221 self.log_error("Can't open %s: %s", filename, err)
224 input = f.read() + "\n" # Silence certain parse errors
228 self.log_debug("Refactoring doctests in %s", filename)
229 output = self.refactor_docstring(input, filename)
231 self.processed_file(output, filename, input, write=write)
233 self.log_debug("No doctest changes in %s", filename)
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
238 self.processed_file(str(tree)[:-1], filename, write=write)
240 self.log_debug("No changes in %s", filename)
242 def refactor_string(self, data, name):
243 """Refactor a given input string.
246 data: a string holding the code to be refactored.
247 name: a human-readable name for use in error/log messages.
250 An AST corresponding to the refactored input stream; None if
251 there were errors during the parse.
254 tree = self.driver.parse_string(data)
255 except Exception, err:
256 self.log_error("Can't parse %s: %s: %s",
257 name, err.__class__.__name__, err)
259 self.log_debug("Refactoring %s", name)
260 self.refactor_tree(tree, name)
263 def refactor_stdin(self, doctests_only=False):
264 input = sys.stdin.read()
266 self.log_debug("Refactoring doctests in stdin")
267 output = self.refactor_docstring(input, "<stdin>")
269 self.processed_file(output, "<stdin>", input)
271 self.log_debug("No doctest changes in stdin")
273 tree = self.refactor_string(input, "<stdin>")
274 if tree and tree.was_changed:
275 self.processed_file(str(tree), "<stdin>", input)
277 self.log_debug("No changes in stdin")
279 def refactor_tree(self, tree, name):
280 """Refactors a parse tree (modifying the tree in place).
283 tree: a pytree.Node instance representing the root of the tree
285 name: a human-readable name for this tree.
288 True if the tree was modified, False otherwise.
290 for fixer in chain(self.pre_order, self.post_order):
291 fixer.start_tree(tree, name)
293 self.traverse_by(self.pre_order_heads, tree.pre_order())
294 self.traverse_by(self.post_order_heads, tree.post_order())
296 for fixer in chain(self.pre_order, self.post_order):
297 fixer.finish_tree(tree, name)
298 return tree.was_changed
300 def traverse_by(self, fixers, traversal):
301 """Traverse an AST, applying a set of fixers to each node.
303 This is a helper method for refactor_tree().
306 fixers: a list of fixer instances.
307 traversal: a generator that yields AST nodes.
314 for node in traversal:
315 for fixer in fixers[node.type] + fixers[None]:
316 results = fixer.match(node)
318 new = fixer.transform(node, results)
319 if new is not None and (new != node or
320 str(new) != str(node)):
324 def processed_file(self, new_text, filename, old_text=None, write=False):
326 Called when a file has been refactored, and there are changes.
328 self.files.append(filename)
331 f = open(filename, "r")
333 self.log_error("Can't read %s: %s", filename, err)
339 if old_text == new_text:
340 self.log_debug("No changes to %s", filename)
342 self.print_output(diff_texts(old_text, new_text, filename))
344 self.write_file(new_text, filename, old_text)
346 self.log_debug("Not writing changes to %s", filename)
348 def write_file(self, new_text, filename, old_text):
349 """Writes a string to a file.
351 It first shows a unified diff between the old text and the new text, and
352 then rewrites the file; the latter is only done if the write option is
356 f = open(filename, "w")
357 except os.error, err:
358 self.log_error("Can't create %s: %s", filename, err)
362 except os.error, err:
363 self.log_error("Can't write %s: %s", filename, err)
366 self.log_debug("Wrote changes to %s", filename)
372 def refactor_docstring(self, input, filename):
373 """Refactors a docstring, looking for doctests.
375 This returns a modified version of the input string. It looks
376 for doctests, which start with a ">>>" prompt, and may be
377 continued with "..." prompts, as long as the "..." is indented
378 the same as the ">>>".
380 (Unfortunately we can't use the doctest module's parser,
381 since, like most parsers, it is not geared towards preserving
382 the original source.)
389 for line in input.splitlines(True):
391 if line.lstrip().startswith(self.PS1):
392 if block is not None:
393 result.extend(self.refactor_doctest(block, block_lineno,
395 block_lineno = lineno
397 i = line.find(self.PS1)
399 elif (indent is not None and
400 (line.startswith(indent + self.PS2) or
401 line == indent + self.PS2.rstrip() + "\n")):
404 if block is not None:
405 result.extend(self.refactor_doctest(block, block_lineno,
410 if block is not None:
411 result.extend(self.refactor_doctest(block, block_lineno,
413 return "".join(result)
415 def refactor_doctest(self, block, lineno, indent, filename):
416 """Refactors one doctest.
418 A doctest is given as a block of lines, the first of which starts
419 with ">>>" (possibly indented), while the remaining lines start
420 with "..." (identically indented).
424 tree = self.parse_block(block, lineno, indent)
425 except Exception, err:
426 if self.log.isEnabledFor(logging.DEBUG):
428 self.log_debug("Source: %s", line.rstrip("\n"))
429 self.log_error("Can't parse docstring in %s line %s: %s: %s",
430 filename, lineno, err.__class__.__name__, err)
432 if self.refactor_tree(tree, filename):
433 new = str(tree).splitlines(True)
434 # Undo the adjustment of the line numbers in wrap_toks() below.
435 clipped, new = new[:lineno-1], new[lineno-1:]
436 assert clipped == ["\n"] * (lineno-1), clipped
437 if not new[-1].endswith("\n"):
439 block = [indent + self.PS1 + new.pop(0)]
441 block += [indent + self.PS2 + line for line in new]
450 self.log_message("No files %s modified.", were)
452 self.log_message("Files that %s modified:", were)
453 for file in self.files:
454 self.log_message(file)
456 self.log_message("Warnings/messages while refactoring:")
457 for message in self.fixer_log:
458 self.log_message(message)
460 if len(self.errors) == 1:
461 self.log_message("There was 1 error:")
463 self.log_message("There were %d errors:", len(self.errors))
464 for msg, args, kwds in self.errors:
465 self.log_message(msg, *args, **kwds)
467 def parse_block(self, block, lineno, indent):
468 """Parses a block into a tree.
470 This is necessary to get correct line number / offset information
471 in the parser diagnostics and embedded into the parse tree.
473 return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
475 def wrap_toks(self, block, lineno, indent):
476 """Wraps a tokenize stream to systematically modify start/end."""
477 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).next)
478 for type, value, (line0, col0), (line1, col1), line_text in tokens:
481 # Don't bother updating the columns; this is too complicated
482 # since line_text would also have to be updated and it would
483 # still break for tokens spanning lines. Let the user guess
484 # that the column numbers for doctests are relative to the
485 # end of the prompt string (PS1 or PS2).
486 yield type, value, (line0, col0), (line1, col1), line_text
489 def gen_lines(self, block, indent):
490 """Generates lines as expected by tokenize from a list of lines.
492 This strips the first len(indent + self.PS1) characters off each line.
494 prefix1 = indent + self.PS1
495 prefix2 = indent + self.PS2
498 if line.startswith(prefix):
499 yield line[len(prefix):]
500 elif line == prefix.rstrip() + "\n":
503 raise AssertionError("line=%r, prefix=%r" % (line, prefix))
509 def diff_texts(a, b, filename):
510 """Return a unified diff of two strings."""
513 return difflib.unified_diff(a, b, filename, filename,
514 "(original)", "(refactored)",