21
from collections import defaultdict
22
21
from itertools import chain
25
from .pgen2 import driver
26
from .pgen2 import tokenize
24
from .pgen2 import driver, tokenize, token
25
from . import pytree, pygram
34
28
def get_all_fix_names(fixer_pkg, remove_prefix=True):
51
50
# NodePatters must either have no type and no content
52
51
# or a type and content -- so they don't get any farther
53
52
# Always return leafs
54
55
return set([pat.type])
56
57
if isinstance(pat, pytree.NegatedPattern):
58
return get_head_types(pat.content)
59
return set([None]) # Negated Patterns don't have a type
59
return _get_head_types(pat.content)
60
raise _EveryNode # Negated Patterns don't have a type
61
62
if isinstance(pat, pytree.WildcardPattern):
62
63
# Recurse on each node in content
64
65
for p in pat.content:
66
r.update(get_head_types(x))
67
r.update(_get_head_types(x))
69
70
raise Exception("Oh no! I don't understand pattern %s" %(pat))
71
def get_headnode_dict(fixer_list):
73
def _get_headnode_dict(fixer_list):
72
74
""" Accepts a list of fixers and returns a dictionary
73
75
of head node type --> fixer list. """
74
head_nodes = defaultdict(list)
76
head_nodes = collections.defaultdict(list)
75
78
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)
81
heads = _get_head_types(fixer.pattern)
85
for node_type in heads:
86
head_nodes[node_type].append(fixer)
88
if fixer._accept_type is not None:
89
head_nodes[fixer._accept_type].append(fixer)
92
for node_type in chain(pygram.python_grammar.symbol2number.itervalues(),
93
pygram.python_grammar.tokens):
94
head_nodes[node_type].extend(every)
95
return dict(head_nodes)
83
98
def get_fixers_from_package(pkg_name):
87
102
return [pkg_name + "." + fix_name
88
103
for fix_name in get_all_fix_names(pkg_name, False)]
108
if sys.version_info < (3, 0):
110
_open_with_encoding = codecs.open
111
# codecs.open doesn't translate newlines sadly.
112
def _from_system_newlines(input):
113
return input.replace(u"\r\n", u"\n")
114
def _to_system_newlines(input):
115
if os.linesep != "\n":
116
return input.replace(u"\n", os.linesep)
120
_open_with_encoding = open
121
_from_system_newlines = _identity
122
_to_system_newlines = _identity
125
def _detect_future_print(source):
126
have_docstring = False
127
gen = tokenize.generate_tokens(StringIO.StringIO(source).readline)
130
return tok[0], tok[1]
131
ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT))
134
tp, value = advance()
137
elif tp == token.STRING:
140
have_docstring = True
141
elif tp == token.NAME and value == u"from":
142
tp, value = advance()
143
if tp != token.NAME and value != u"__future__":
145
tp, value = advance()
146
if tp != token.NAME and value != u"import":
148
tp, value = advance()
149
if tp == token.OP and value == u"(":
150
tp, value = advance()
151
while tp == token.NAME:
152
if value == u"print_function":
154
tp, value = advance()
155
if tp != token.OP and value != u",":
157
tp, value = advance()
160
except StopIteration:
91
165
class FixerError(Exception):
92
166
"""A fixer could not be loaded."""
112
186
self.options = self._default_options.copy()
113
187
if options is not None:
114
188
self.options.update(options)
189
if self.options["print_function"]:
190
self.grammar = pygram.python_grammar_no_print_statement
192
self.grammar = pygram.python_grammar
116
194
self.logger = logging.getLogger("RefactoringTool")
117
195
self.fixer_log = []
118
196
self.wrote = False
119
if self.options["print_function"]:
120
del pygram.python_grammar.keywords["print"]
121
self.driver = driver.Driver(pygram.python_grammar,
197
self.driver = driver.Driver(self.grammar,
122
198
convert=pytree.convert,
123
199
logger=self.logger)
124
200
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)
202
self.pre_order_heads = _get_headnode_dict(self.pre_order)
203
self.post_order_heads = _get_headnode_dict(self.post_order)
129
205
self.files = [] # List of files that were or should be modified
184
260
self.logger.debug(msg)
186
def print_output(self, lines):
187
"""Called with lines of output to give to the user."""
262
def print_output(self, old_text, new_text, filename, equal):
263
"""Called with the old version, new version, and filename of a
190
267
def refactor(self, items, write=False, doctests_only=False):
209
286
for name in filenames:
210
if not name.startswith(".") and name.endswith("py"):
287
if not name.startswith(".") and \
288
os.path.splitext(name)[1].endswith("py"):
211
289
fullname = os.path.join(dirpath, name)
212
290
self.refactor_file(fullname, write, doctests_only)
213
291
# Modify dirnames in-place to remove subdirs with leading dots
214
292
dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
294
def _read_python_source(self, filename):
296
Do our best to decode a Python source file correctly.
299
f = open(filename, "rb")
301
self.log_error("Can't open %s: %s", filename, err)
304
encoding = tokenize.detect_encoding(f.readline)[0]
307
with _open_with_encoding(filename, "r", encoding=encoding) as f:
308
return _from_system_newlines(f.read()), encoding
216
310
def refactor_file(self, filename, write=False, doctests_only=False):
217
311
"""Refactors a file."""
221
self.log_error("Can't open %s: %s", filename, err)
312
input, encoding = self._read_python_source(filename)
314
# Reading the file failed.
224
input = f.read() + "\n" # Silence certain parse errors
316
input += u"\n" # Silence certain parse errors
227
317
if doctests_only:
228
318
self.log_debug("Refactoring doctests in %s", filename)
229
319
output = self.refactor_docstring(input, filename)
230
320
if output != input:
231
self.processed_file(output, filename, input, write=write)
321
self.processed_file(output, filename, input, write, encoding)
233
323
self.log_debug("No doctest changes in %s", filename)
235
325
tree = self.refactor_string(input, filename)
236
326
if tree and tree.was_changed:
237
327
# The [:-1] is to take off the \n we added earlier
238
self.processed_file(str(tree)[:-1], filename, write=write)
328
self.processed_file(unicode(tree)[:-1], filename,
329
write=write, encoding=encoding)
240
331
self.log_debug("No changes in %s", filename)
250
341
An AST corresponding to the refactored input stream; None if
251
342
there were errors during the parse.
344
if _detect_future_print(data):
345
self.driver.grammar = pygram.python_grammar_no_print_statement
254
347
tree = self.driver.parse_string(data)
255
348
except Exception, err:
256
349
self.log_error("Can't parse %s: %s: %s",
257
350
name, err.__class__.__name__, err)
353
self.driver.grammar = self.grammar
259
354
self.log_debug("Refactoring %s", name)
260
355
self.refactor_tree(tree, name)
273
368
tree = self.refactor_string(input, "<stdin>")
274
369
if tree and tree.was_changed:
275
self.processed_file(str(tree), "<stdin>", input)
370
self.processed_file(unicode(tree), "<stdin>", input)
277
372
self.log_debug("No changes in stdin")
314
409
for node in traversal:
315
for fixer in fixers[node.type] + fixers[None]:
410
for fixer in fixers[node.type]:
316
411
results = fixer.match(node)
318
413
new = fixer.transform(node, results)
319
if new is not None and (new != node or
320
str(new) != str(node)):
321
415
node.replace(new)
324
def processed_file(self, new_text, filename, old_text=None, write=False):
418
def processed_file(self, new_text, filename, old_text=None, write=False,
326
421
Called when a file has been refactored, and there are changes.
328
423
self.files.append(filename)
329
424
if old_text is None:
331
f = open(filename, "r")
333
self.log_error("Can't read %s: %s", filename, err)
425
old_text = self._read_python_source(filename)[0]
339
if old_text == new_text:
428
equal = old_text == new_text
429
self.print_output(old_text, new_text, filename, equal)
340
431
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)
434
self.write_file(new_text, filename, old_text, encoding)
346
436
self.log_debug("Not writing changes to %s", filename)
348
def write_file(self, new_text, filename, old_text):
438
def write_file(self, new_text, filename, old_text, encoding=None):
349
439
"""Writes a string to a file.
351
441
It first shows a unified diff between the old text and the new text, and
356
f = open(filename, "w")
446
f = _open_with_encoding(filename, "w", encoding=encoding)
357
447
except os.error, err:
358
448
self.log_error("Can't create %s: %s", filename, err)
451
f.write(_to_system_newlines(new_text))
362
452
except os.error, err:
363
453
self.log_error("Can't write %s: %s", filename, err)
425
515
except Exception, err:
426
516
if self.log.isEnabledFor(logging.DEBUG):
427
517
for line in block:
428
self.log_debug("Source: %s", line.rstrip("\n"))
518
self.log_debug("Source: %s", line.rstrip(u"\n"))
429
519
self.log_error("Can't parse docstring in %s line %s: %s: %s",
430
520
filename, lineno, err.__class__.__name__, err)
432
522
if self.refactor_tree(tree, filename):
433
new = str(tree).splitlines(True)
523
new = unicode(tree).splitlines(True)
434
524
# Undo the adjustment of the line numbers in wrap_toks() below.
435
525
clipped, new = new[:lineno-1], new[lineno-1:]
436
assert clipped == ["\n"] * (lineno-1), clipped
437
if not new[-1].endswith("\n"):
526
assert clipped == [u"\n"] * (lineno-1), clipped
527
if not new[-1].endswith(u"\n"):
439
529
block = [indent + self.PS1 + new.pop(0)]
441
531
block += [indent + self.PS2 + line for line in new]
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)",
599
class MultiprocessingUnsupported(Exception):
603
class MultiprocessRefactoringTool(RefactoringTool):
605
def __init__(self, *args, **kwargs):
606
super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs)
609
def refactor(self, items, write=False, doctests_only=False,
611
if num_processes == 1:
612
return super(MultiprocessRefactoringTool, self).refactor(
613
items, write, doctests_only)
615
import multiprocessing
617
raise MultiprocessingUnsupported
618
if self.queue is not None:
619
raise RuntimeError("already doing multiple processes")
620
self.queue = multiprocessing.JoinableQueue()
621
processes = [multiprocessing.Process(target=self._child)
622
for i in xrange(num_processes)]
626
super(MultiprocessRefactoringTool, self).refactor(items, write,
630
for i in xrange(num_processes):
638
task = self.queue.get()
639
while task is not None:
642
super(MultiprocessRefactoringTool, self).refactor_file(
645
self.queue.task_done()
646
task = self.queue.get()
648
def refactor_file(self, *args, **kwargs):
649
if self.queue is not None:
650
self.queue.put((args, kwargs))
652
return super(MultiprocessRefactoringTool, self).refactor_file(