blob: c318045a9c2a2954339c774b9edd8a39727301ae [file] [log] [blame]
Martin v. Löwisef04c442008-03-19 05:04:44 +00001#!/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
7Used as a main program, this can refactor any number of files and/or
8recursively descend down directories. Imported as a module, this
9provides infrastructure to write your own refactoring tool.
10"""
11
12__author__ = "Guido van Rossum <guido@python.org>"
13
14
15# Python imports
16import os
17import sys
18import difflib
Martin v. Löwisef04c442008-03-19 05:04:44 +000019import logging
Benjamin Peterson8951b612008-09-03 02:27:16 +000020import operator
Christian Heimes81ee3ef2008-05-04 22:42:01 +000021from collections import defaultdict
22from itertools import chain
Martin v. Löwisef04c442008-03-19 05:04:44 +000023
24# Local imports
25from .pgen2 import driver
26from .pgen2 import tokenize
27
28from . import pytree
29from . import patcomp
30from . import fixes
31from . import pygram
32
Martin v. Löwisef04c442008-03-19 05:04:44 +000033
Benjamin Peterson8951b612008-09-03 02:27:16 +000034def 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öwisef04c442008-03-19 05:04:44 +000038 fix_names = []
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +000039 names = os.listdir(fixer_dir)
Martin v. Löwisef04c442008-03-19 05:04:44 +000040 names.sort()
41 for name in names:
42 if name.startswith("fix_") and name.endswith(".py"):
Benjamin Peterson8951b612008-09-03 02:27:16 +000043 if remove_prefix:
44 name = name[4:]
45 fix_names.append(name[:-3])
Martin v. Löwisef04c442008-03-19 05:04:44 +000046 return fix_names
47
Christian Heimes81ee3ef2008-05-04 22:42:01 +000048def 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
73def 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 Peterson8951b612008-09-03 02:27:16 +000085def 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öwisef04c442008-03-19 05:04:44 +000092
93class RefactoringTool(object):
94
Benjamin Peterson8951b612008-09-03 02:27:16 +000095 _default_options = {"print_function": False}
96
97 def __init__(self, fixer_names, options=None, explicit=[]):
Martin v. Löwisef04c442008-03-19 05:04:44 +000098 """Initializer.
99
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +0000100 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000101 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öwisef04c442008-03-19 05:04:44 +0000104 """
Benjamin Peterson8951b612008-09-03 02:27:16 +0000105 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öwisef04c442008-03-19 05:04:44 +0000110 self.errors = []
111 self.logger = logging.getLogger("RefactoringTool")
112 self.fixer_log = []
Benjamin Peterson8951b612008-09-03 02:27:16 +0000113 self.wrote = False
114 if self.options["print_function"]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000115 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 Heimes81ee3ef2008-05-04 22:42:01 +0000120
121 self.pre_order = get_headnode_dict(self.pre_order)
122 self.post_order = get_headnode_dict(self.post_order)
123
Martin v. Löwisef04c442008-03-19 05:04:44 +0000124 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öwisf733c602008-03-19 05:26:18 +0000128
Martin v. Löwisef04c442008-03-19 05:04:44 +0000129 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 Peterson8951b612008-09-03 02:27:16 +0000136 for fix_mod_path in self.fixers:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000137 try:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000138 mod = __import__(fix_mod_path, {}, {}, ["*"])
Martin v. Löwisef04c442008-03-19 05:04:44 +0000139 except ImportError:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000140 self.log_error("Can't load transformation module %s",
141 fix_mod_path)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000142 continue
Benjamin Peterson8951b612008-09-03 02:27:16 +0000143 fix_name = fix_mod_path.rsplit(".", 1)[-1]
144 if fix_name.startswith("fix_"):
145 fix_name = fix_name[4:]
Martin v. Löwisef04c442008-03-19 05:04:44 +0000146 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 Peterson8951b612008-09-03 02:27:16 +0000151 self.log_error("Can't find %s.%s",
Martin v. Löwisef04c442008-03-19 05:04:44 +0000152 fix_name, class_name)
153 continue
154 try:
155 fixer = fix_class(self.options, self.fixer_log)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000156 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000157 self.log_error("Can't instantiate fixes.fix_%s.%s()",
158 fix_name, class_name, exc_info=True)
159 continue
Benjamin Peterson8951b612008-09-03 02:27:16 +0000160 if fixer.explicit and self.explicit is not True and \
161 fix_mod_path not in self.explicit:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000162 self.log_message("Skipping implicit fixer: %s", fix_name)
163 continue
164
Benjamin Peterson8951b612008-09-03 02:27:16 +0000165 self.log_debug("Adding transformation: %s", fix_name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000166 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öwis3faa84f2008-03-22 00:07:09 +0000172
Benjamin Peterson8951b612008-09-03 02:27:16 +0000173 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öwisef04c442008-03-19 05:04:44 +0000176 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 Peterson8951b612008-09-03 02:27:16 +0000189 def log_debug(self, msg, *args):
190 if args:
191 msg = msg % args
192 self.logger.debug(msg)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000193
Benjamin Peterson8951b612008-09-03 02:27:16 +0000194 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öwisef04c442008-03-19 05:04:44 +0000203 """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 Peterson8951b612008-09-03 02:27:16 +0000209 for dirpath, dirnames, filenames in os.walk(dir_name):
210 self.log_debug("Descending into %s", dirpath)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000211 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 Peterson8951b612008-09-03 02:27:16 +0000216 self.refactor_file(fullname, write, doctests_only)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000217 # Modify dirnames in-place to remove subdirs with leading dots
218 dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
219
Benjamin Peterson8951b612008-09-03 02:27:16 +0000220 def refactor_file(self, filename, write=False, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000221 """Refactors a file."""
222 try:
223 f = open(filename)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000224 except IOError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000225 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 Peterson8951b612008-09-03 02:27:16 +0000231 if doctests_only:
232 self.log_debug("Refactoring doctests in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000233 output = self.refactor_docstring(input, filename)
234 if output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000235 self.processed_file(output, filename, input, write=write)
236 else:
237 self.log_debug("No doctest changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000238 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 Peterson8951b612008-09-03 02:27:16 +0000242 self.processed_file(str(tree)[:-1], filename, write=write)
243 else:
244 self.log_debug("No changes in %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000245
246 def refactor_string(self, data, name):
247 """Refactor a given input string.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000248
Martin v. Löwisef04c442008-03-19 05:04:44 +0000249 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öwisf733c602008-03-19 05:26:18 +0000252
Martin v. Löwisef04c442008-03-19 05:04:44 +0000253 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öwis8a5f8ca2008-03-19 05:33:36 +0000259 except Exception as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000260 self.log_error("Can't parse %s: %s: %s",
261 name, err.__class__.__name__, err)
262 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000263 self.log_debug("Refactoring %s", name)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000264 self.refactor_tree(tree, name)
265 return tree
266
Benjamin Peterson8951b612008-09-03 02:27:16 +0000267 def refactor_stdin(self, doctests_only=False):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000268 input = sys.stdin.read()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000269 if doctests_only:
270 self.log_debug("Refactoring doctests in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000271 output = self.refactor_docstring(input, "<stdin>")
272 if output != input:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000273 self.processed_file(output, "<stdin>", input)
274 else:
275 self.log_debug("No doctest changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000276 else:
277 tree = self.refactor_string(input, "<stdin>")
278 if tree and tree.was_changed:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000279 self.processed_file(str(tree), "<stdin>", input)
280 else:
281 self.log_debug("No changes in stdin")
Martin v. Löwisef04c442008-03-19 05:04:44 +0000282
283 def refactor_tree(self, tree, name):
284 """Refactors a parse tree (modifying the tree in place).
Martin v. Löwisf733c602008-03-19 05:26:18 +0000285
Martin v. Löwisef04c442008-03-19 05:04:44 +0000286 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öwisf733c602008-03-19 05:26:18 +0000290
Martin v. Löwisef04c442008-03-19 05:04:44 +0000291 Returns:
292 True if the tree was modified, False otherwise.
293 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000294 # 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öwisef04c442008-03-19 05:04:44 +0000299 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öwisf733c602008-03-19 05:26:18 +0000311
Martin v. Löwisef04c442008-03-19 05:04:44 +0000312 This is a helper method for refactor_tree().
Martin v. Löwisf733c602008-03-19 05:26:18 +0000313
Martin v. Löwisef04c442008-03-19 05:04:44 +0000314 Args:
315 fixers: a list of fixer instances.
316 traversal: a generator that yields AST nodes.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000317
Martin v. Löwisef04c442008-03-19 05:04:44 +0000318 Returns:
319 None
320 """
321 if not fixers:
322 return
323 for node in traversal:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000324 for fixer in fixers[node.type] + fixers[None]:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000325 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 Peterson8951b612008-09-03 02:27:16 +0000333 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öwisef04c442008-03-19 05:04:44 +0000336 """
337 self.files.append(filename)
338 if old_text is None:
339 try:
340 f = open(filename, "r")
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000341 except IOError as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000342 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 Peterson8951b612008-09-03 02:27:16 +0000349 self.log_debug("No changes to %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000350 return
351 diff_texts(old_text, new_text, filename)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000352 if not write:
353 self.log_debug("Not writing changes to %s", filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000354 return
Benjamin Peterson8951b612008-09-03 02:27:16 +0000355 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öwisef04c442008-03-19 05:04:44 +0000365 backup = filename + ".bak"
366 if os.path.lexists(backup):
367 try:
368 os.remove(backup)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000369 except os.error as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000370 self.log_message("Can't remove backup %s", backup)
371 try:
372 os.rename(filename, backup)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000373 except os.error as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000374 self.log_message("Can't rename %s to %s", filename, backup)
375 try:
376 f = open(filename, "w")
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000377 except os.error as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000378 self.log_error("Can't create %s: %s", filename, err)
379 return
380 try:
381 try:
382 f.write(new_text)
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000383 except os.error as err:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000384 self.log_error("Can't write %s: %s", filename, err)
385 finally:
386 f.close()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000387 self.log_debug("Wrote changes to %s", filename)
388 self.wrote = True
Martin v. Löwisef04c442008-03-19 05:04:44 +0000389
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öwis8a5f8ca2008-03-19 05:33:36 +0000446 except Exception as err:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000447 if self.log.isEnabledFor(logging.DEBUG):
Martin v. Löwisef04c442008-03-19 05:04:44 +0000448 for line in block:
Benjamin Peterson8951b612008-09-03 02:27:16 +0000449 self.log_debug("Source: %s", line.rstrip("\n"))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000450 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 Peterson8951b612008-09-03 02:27:16 +0000466 if self.wrote:
Martin v. Löwisef04c442008-03-19 05:04:44 +0000467 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öwis8a5f8ca2008-03-19 05:33:36 +0000498 tokens = tokenize.generate_tokens(self.gen_lines(block, indent).__next__)
Martin v. Löwisef04c442008-03-19 05:04:44 +0000499 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
530def 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öwis8a5f8ca2008-03-19 05:33:36 +0000537 print(line)