Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../usr/lib64/python2..../lib2to3
File: refactor.py
# Copyright 2006 Google, Inc. All Rights Reserved.
[0] Fix | Delete
# Licensed to PSF under a Contributor Agreement.
[1] Fix | Delete
[2] Fix | Delete
"""Refactoring framework.
[3] Fix | Delete
[4] Fix | Delete
Used as a main program, this can refactor any number of files and/or
[5] Fix | Delete
recursively descend down directories. Imported as a module, this
[6] Fix | Delete
provides infrastructure to write your own refactoring tool.
[7] Fix | Delete
"""
[8] Fix | Delete
[9] Fix | Delete
from __future__ import with_statement
[10] Fix | Delete
[11] Fix | Delete
__author__ = "Guido van Rossum <guido@python.org>"
[12] Fix | Delete
[13] Fix | Delete
[14] Fix | Delete
# Python imports
[15] Fix | Delete
import os
[16] Fix | Delete
import pkgutil
[17] Fix | Delete
import sys
[18] Fix | Delete
import logging
[19] Fix | Delete
import operator
[20] Fix | Delete
import collections
[21] Fix | Delete
import StringIO
[22] Fix | Delete
from itertools import chain
[23] Fix | Delete
[24] Fix | Delete
# Local imports
[25] Fix | Delete
from .pgen2 import driver, tokenize, token
[26] Fix | Delete
from .fixer_util import find_root
[27] Fix | Delete
from . import pytree, pygram
[28] Fix | Delete
from . import btm_utils as bu
[29] Fix | Delete
from . import btm_matcher as bm
[30] Fix | Delete
[31] Fix | Delete
[32] Fix | Delete
def get_all_fix_names(fixer_pkg, remove_prefix=True):
[33] Fix | Delete
"""Return a sorted list of all available fix names in the given package."""
[34] Fix | Delete
pkg = __import__(fixer_pkg, [], [], ["*"])
[35] Fix | Delete
fix_names = []
[36] Fix | Delete
for finder, name, ispkg in pkgutil.iter_modules(pkg.__path__):
[37] Fix | Delete
if name.startswith("fix_"):
[38] Fix | Delete
if remove_prefix:
[39] Fix | Delete
name = name[4:]
[40] Fix | Delete
fix_names.append(name)
[41] Fix | Delete
return fix_names
[42] Fix | Delete
[43] Fix | Delete
[44] Fix | Delete
class _EveryNode(Exception):
[45] Fix | Delete
pass
[46] Fix | Delete
[47] Fix | Delete
[48] Fix | Delete
def _get_head_types(pat):
[49] Fix | Delete
""" Accepts a pytree Pattern Node and returns a set
[50] Fix | Delete
of the pattern types which will match first. """
[51] Fix | Delete
[52] Fix | Delete
if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
[53] Fix | Delete
# NodePatters must either have no type and no content
[54] Fix | Delete
# or a type and content -- so they don't get any farther
[55] Fix | Delete
# Always return leafs
[56] Fix | Delete
if pat.type is None:
[57] Fix | Delete
raise _EveryNode
[58] Fix | Delete
return set([pat.type])
[59] Fix | Delete
[60] Fix | Delete
if isinstance(pat, pytree.NegatedPattern):
[61] Fix | Delete
if pat.content:
[62] Fix | Delete
return _get_head_types(pat.content)
[63] Fix | Delete
raise _EveryNode # Negated Patterns don't have a type
[64] Fix | Delete
[65] Fix | Delete
if isinstance(pat, pytree.WildcardPattern):
[66] Fix | Delete
# Recurse on each node in content
[67] Fix | Delete
r = set()
[68] Fix | Delete
for p in pat.content:
[69] Fix | Delete
for x in p:
[70] Fix | Delete
r.update(_get_head_types(x))
[71] Fix | Delete
return r
[72] Fix | Delete
[73] Fix | Delete
raise Exception("Oh no! I don't understand pattern %s" %(pat))
[74] Fix | Delete
[75] Fix | Delete
[76] Fix | Delete
def _get_headnode_dict(fixer_list):
[77] Fix | Delete
""" Accepts a list of fixers and returns a dictionary
[78] Fix | Delete
of head node type --> fixer list. """
[79] Fix | Delete
head_nodes = collections.defaultdict(list)
[80] Fix | Delete
every = []
[81] Fix | Delete
for fixer in fixer_list:
[82] Fix | Delete
if fixer.pattern:
[83] Fix | Delete
try:
[84] Fix | Delete
heads = _get_head_types(fixer.pattern)
[85] Fix | Delete
except _EveryNode:
[86] Fix | Delete
every.append(fixer)
[87] Fix | Delete
else:
[88] Fix | Delete
for node_type in heads:
[89] Fix | Delete
head_nodes[node_type].append(fixer)
[90] Fix | Delete
else:
[91] Fix | Delete
if fixer._accept_type is not None:
[92] Fix | Delete
head_nodes[fixer._accept_type].append(fixer)
[93] Fix | Delete
else:
[94] Fix | Delete
every.append(fixer)
[95] Fix | Delete
for node_type in chain(pygram.python_grammar.symbol2number.itervalues(),
[96] Fix | Delete
pygram.python_grammar.tokens):
[97] Fix | Delete
head_nodes[node_type].extend(every)
[98] Fix | Delete
return dict(head_nodes)
[99] Fix | Delete
[100] Fix | Delete
[101] Fix | Delete
def get_fixers_from_package(pkg_name):
[102] Fix | Delete
"""
[103] Fix | Delete
Return the fully qualified names for fixers in the package pkg_name.
[104] Fix | Delete
"""
[105] Fix | Delete
return [pkg_name + "." + fix_name
[106] Fix | Delete
for fix_name in get_all_fix_names(pkg_name, False)]
[107] Fix | Delete
[108] Fix | Delete
def _identity(obj):
[109] Fix | Delete
return obj
[110] Fix | Delete
[111] Fix | Delete
if sys.version_info < (3, 0):
[112] Fix | Delete
import codecs
[113] Fix | Delete
_open_with_encoding = codecs.open
[114] Fix | Delete
# codecs.open doesn't translate newlines sadly.
[115] Fix | Delete
def _from_system_newlines(input):
[116] Fix | Delete
return input.replace(u"\r\n", u"\n")
[117] Fix | Delete
def _to_system_newlines(input):
[118] Fix | Delete
if os.linesep != "\n":
[119] Fix | Delete
return input.replace(u"\n", os.linesep)
[120] Fix | Delete
else:
[121] Fix | Delete
return input
[122] Fix | Delete
else:
[123] Fix | Delete
_open_with_encoding = open
[124] Fix | Delete
_from_system_newlines = _identity
[125] Fix | Delete
_to_system_newlines = _identity
[126] Fix | Delete
[127] Fix | Delete
[128] Fix | Delete
def _detect_future_features(source):
[129] Fix | Delete
have_docstring = False
[130] Fix | Delete
gen = tokenize.generate_tokens(StringIO.StringIO(source).readline)
[131] Fix | Delete
def advance():
[132] Fix | Delete
tok = gen.next()
[133] Fix | Delete
return tok[0], tok[1]
[134] Fix | Delete
ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT))
[135] Fix | Delete
features = set()
[136] Fix | Delete
try:
[137] Fix | Delete
while True:
[138] Fix | Delete
tp, value = advance()
[139] Fix | Delete
if tp in ignore:
[140] Fix | Delete
continue
[141] Fix | Delete
elif tp == token.STRING:
[142] Fix | Delete
if have_docstring:
[143] Fix | Delete
break
[144] Fix | Delete
have_docstring = True
[145] Fix | Delete
elif tp == token.NAME and value == u"from":
[146] Fix | Delete
tp, value = advance()
[147] Fix | Delete
if tp != token.NAME or value != u"__future__":
[148] Fix | Delete
break
[149] Fix | Delete
tp, value = advance()
[150] Fix | Delete
if tp != token.NAME or value != u"import":
[151] Fix | Delete
break
[152] Fix | Delete
tp, value = advance()
[153] Fix | Delete
if tp == token.OP and value == u"(":
[154] Fix | Delete
tp, value = advance()
[155] Fix | Delete
while tp == token.NAME:
[156] Fix | Delete
features.add(value)
[157] Fix | Delete
tp, value = advance()
[158] Fix | Delete
if tp != token.OP or value != u",":
[159] Fix | Delete
break
[160] Fix | Delete
tp, value = advance()
[161] Fix | Delete
else:
[162] Fix | Delete
break
[163] Fix | Delete
except StopIteration:
[164] Fix | Delete
pass
[165] Fix | Delete
return frozenset(features)
[166] Fix | Delete
[167] Fix | Delete
[168] Fix | Delete
class FixerError(Exception):
[169] Fix | Delete
"""A fixer could not be loaded."""
[170] Fix | Delete
[171] Fix | Delete
[172] Fix | Delete
class RefactoringTool(object):
[173] Fix | Delete
[174] Fix | Delete
_default_options = {"print_function" : False,
[175] Fix | Delete
"write_unchanged_files" : False}
[176] Fix | Delete
[177] Fix | Delete
CLASS_PREFIX = "Fix" # The prefix for fixer classes
[178] Fix | Delete
FILE_PREFIX = "fix_" # The prefix for modules with a fixer within
[179] Fix | Delete
[180] Fix | Delete
def __init__(self, fixer_names, options=None, explicit=None):
[181] Fix | Delete
"""Initializer.
[182] Fix | Delete
[183] Fix | Delete
Args:
[184] Fix | Delete
fixer_names: a list of fixers to import
[185] Fix | Delete
options: a dict with configuration.
[186] Fix | Delete
explicit: a list of fixers to run even if they are explicit.
[187] Fix | Delete
"""
[188] Fix | Delete
self.fixers = fixer_names
[189] Fix | Delete
self.explicit = explicit or []
[190] Fix | Delete
self.options = self._default_options.copy()
[191] Fix | Delete
if options is not None:
[192] Fix | Delete
self.options.update(options)
[193] Fix | Delete
if self.options["print_function"]:
[194] Fix | Delete
self.grammar = pygram.python_grammar_no_print_statement
[195] Fix | Delete
else:
[196] Fix | Delete
self.grammar = pygram.python_grammar
[197] Fix | Delete
# When this is True, the refactor*() methods will call write_file() for
[198] Fix | Delete
# files processed even if they were not changed during refactoring. If
[199] Fix | Delete
# and only if the refactor method's write parameter was True.
[200] Fix | Delete
self.write_unchanged_files = self.options.get("write_unchanged_files")
[201] Fix | Delete
self.errors = []
[202] Fix | Delete
self.logger = logging.getLogger("RefactoringTool")
[203] Fix | Delete
self.fixer_log = []
[204] Fix | Delete
self.wrote = False
[205] Fix | Delete
self.driver = driver.Driver(self.grammar,
[206] Fix | Delete
convert=pytree.convert,
[207] Fix | Delete
logger=self.logger)
[208] Fix | Delete
self.pre_order, self.post_order = self.get_fixers()
[209] Fix | Delete
[210] Fix | Delete
[211] Fix | Delete
self.files = [] # List of files that were or should be modified
[212] Fix | Delete
[213] Fix | Delete
self.BM = bm.BottomMatcher()
[214] Fix | Delete
self.bmi_pre_order = [] # Bottom Matcher incompatible fixers
[215] Fix | Delete
self.bmi_post_order = []
[216] Fix | Delete
[217] Fix | Delete
for fixer in chain(self.post_order, self.pre_order):
[218] Fix | Delete
if fixer.BM_compatible:
[219] Fix | Delete
self.BM.add_fixer(fixer)
[220] Fix | Delete
# remove fixers that will be handled by the bottom-up
[221] Fix | Delete
# matcher
[222] Fix | Delete
elif fixer in self.pre_order:
[223] Fix | Delete
self.bmi_pre_order.append(fixer)
[224] Fix | Delete
elif fixer in self.post_order:
[225] Fix | Delete
self.bmi_post_order.append(fixer)
[226] Fix | Delete
[227] Fix | Delete
self.bmi_pre_order_heads = _get_headnode_dict(self.bmi_pre_order)
[228] Fix | Delete
self.bmi_post_order_heads = _get_headnode_dict(self.bmi_post_order)
[229] Fix | Delete
[230] Fix | Delete
[231] Fix | Delete
[232] Fix | Delete
def get_fixers(self):
[233] Fix | Delete
"""Inspects the options to load the requested patterns and handlers.
[234] Fix | Delete
[235] Fix | Delete
Returns:
[236] Fix | Delete
(pre_order, post_order), where pre_order is the list of fixers that
[237] Fix | Delete
want a pre-order AST traversal, and post_order is the list that want
[238] Fix | Delete
post-order traversal.
[239] Fix | Delete
"""
[240] Fix | Delete
pre_order_fixers = []
[241] Fix | Delete
post_order_fixers = []
[242] Fix | Delete
for fix_mod_path in self.fixers:
[243] Fix | Delete
mod = __import__(fix_mod_path, {}, {}, ["*"])
[244] Fix | Delete
fix_name = fix_mod_path.rsplit(".", 1)[-1]
[245] Fix | Delete
if fix_name.startswith(self.FILE_PREFIX):
[246] Fix | Delete
fix_name = fix_name[len(self.FILE_PREFIX):]
[247] Fix | Delete
parts = fix_name.split("_")
[248] Fix | Delete
class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
[249] Fix | Delete
try:
[250] Fix | Delete
fix_class = getattr(mod, class_name)
[251] Fix | Delete
except AttributeError:
[252] Fix | Delete
raise FixerError("Can't find %s.%s" % (fix_name, class_name))
[253] Fix | Delete
fixer = fix_class(self.options, self.fixer_log)
[254] Fix | Delete
if fixer.explicit and self.explicit is not True and \
[255] Fix | Delete
fix_mod_path not in self.explicit:
[256] Fix | Delete
self.log_message("Skipping optional fixer: %s", fix_name)
[257] Fix | Delete
continue
[258] Fix | Delete
[259] Fix | Delete
self.log_debug("Adding transformation: %s", fix_name)
[260] Fix | Delete
if fixer.order == "pre":
[261] Fix | Delete
pre_order_fixers.append(fixer)
[262] Fix | Delete
elif fixer.order == "post":
[263] Fix | Delete
post_order_fixers.append(fixer)
[264] Fix | Delete
else:
[265] Fix | Delete
raise FixerError("Illegal fixer order: %r" % fixer.order)
[266] Fix | Delete
[267] Fix | Delete
key_func = operator.attrgetter("run_order")
[268] Fix | Delete
pre_order_fixers.sort(key=key_func)
[269] Fix | Delete
post_order_fixers.sort(key=key_func)
[270] Fix | Delete
return (pre_order_fixers, post_order_fixers)
[271] Fix | Delete
[272] Fix | Delete
def log_error(self, msg, *args, **kwds):
[273] Fix | Delete
"""Called when an error occurs."""
[274] Fix | Delete
raise
[275] Fix | Delete
[276] Fix | Delete
def log_message(self, msg, *args):
[277] Fix | Delete
"""Hook to log a message."""
[278] Fix | Delete
if args:
[279] Fix | Delete
msg = msg % args
[280] Fix | Delete
self.logger.info(msg)
[281] Fix | Delete
[282] Fix | Delete
def log_debug(self, msg, *args):
[283] Fix | Delete
if args:
[284] Fix | Delete
msg = msg % args
[285] Fix | Delete
self.logger.debug(msg)
[286] Fix | Delete
[287] Fix | Delete
def print_output(self, old_text, new_text, filename, equal):
[288] Fix | Delete
"""Called with the old version, new version, and filename of a
[289] Fix | Delete
refactored file."""
[290] Fix | Delete
pass
[291] Fix | Delete
[292] Fix | Delete
def refactor(self, items, write=False, doctests_only=False):
[293] Fix | Delete
"""Refactor a list of files and directories."""
[294] Fix | Delete
[295] Fix | Delete
for dir_or_file in items:
[296] Fix | Delete
if os.path.isdir(dir_or_file):
[297] Fix | Delete
self.refactor_dir(dir_or_file, write, doctests_only)
[298] Fix | Delete
else:
[299] Fix | Delete
self.refactor_file(dir_or_file, write, doctests_only)
[300] Fix | Delete
[301] Fix | Delete
def refactor_dir(self, dir_name, write=False, doctests_only=False):
[302] Fix | Delete
"""Descends down a directory and refactor every Python file found.
[303] Fix | Delete
[304] Fix | Delete
Python files are assumed to have a .py extension.
[305] Fix | Delete
[306] Fix | Delete
Files and subdirectories starting with '.' are skipped.
[307] Fix | Delete
"""
[308] Fix | Delete
py_ext = os.extsep + "py"
[309] Fix | Delete
for dirpath, dirnames, filenames in os.walk(dir_name):
[310] Fix | Delete
self.log_debug("Descending into %s", dirpath)
[311] Fix | Delete
dirnames.sort()
[312] Fix | Delete
filenames.sort()
[313] Fix | Delete
for name in filenames:
[314] Fix | Delete
if (not name.startswith(".") and
[315] Fix | Delete
os.path.splitext(name)[1] == py_ext):
[316] Fix | Delete
fullname = os.path.join(dirpath, name)
[317] Fix | Delete
self.refactor_file(fullname, write, doctests_only)
[318] Fix | Delete
# Modify dirnames in-place to remove subdirs with leading dots
[319] Fix | Delete
dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
[320] Fix | Delete
[321] Fix | Delete
def _read_python_source(self, filename):
[322] Fix | Delete
"""
[323] Fix | Delete
Do our best to decode a Python source file correctly.
[324] Fix | Delete
"""
[325] Fix | Delete
try:
[326] Fix | Delete
f = open(filename, "rb")
[327] Fix | Delete
except IOError as err:
[328] Fix | Delete
self.log_error("Can't open %s: %s", filename, err)
[329] Fix | Delete
return None, None
[330] Fix | Delete
try:
[331] Fix | Delete
encoding = tokenize.detect_encoding(f.readline)[0]
[332] Fix | Delete
finally:
[333] Fix | Delete
f.close()
[334] Fix | Delete
with _open_with_encoding(filename, "r", encoding=encoding) as f:
[335] Fix | Delete
return _from_system_newlines(f.read()), encoding
[336] Fix | Delete
[337] Fix | Delete
def refactor_file(self, filename, write=False, doctests_only=False):
[338] Fix | Delete
"""Refactors a file."""
[339] Fix | Delete
input, encoding = self._read_python_source(filename)
[340] Fix | Delete
if input is None:
[341] Fix | Delete
# Reading the file failed.
[342] Fix | Delete
return
[343] Fix | Delete
input += u"\n" # Silence certain parse errors
[344] Fix | Delete
if doctests_only:
[345] Fix | Delete
self.log_debug("Refactoring doctests in %s", filename)
[346] Fix | Delete
output = self.refactor_docstring(input, filename)
[347] Fix | Delete
if self.write_unchanged_files or output != input:
[348] Fix | Delete
self.processed_file(output, filename, input, write, encoding)
[349] Fix | Delete
else:
[350] Fix | Delete
self.log_debug("No doctest changes in %s", filename)
[351] Fix | Delete
else:
[352] Fix | Delete
tree = self.refactor_string(input, filename)
[353] Fix | Delete
if self.write_unchanged_files or (tree and tree.was_changed):
[354] Fix | Delete
# The [:-1] is to take off the \n we added earlier
[355] Fix | Delete
self.processed_file(unicode(tree)[:-1], filename,
[356] Fix | Delete
write=write, encoding=encoding)
[357] Fix | Delete
else:
[358] Fix | Delete
self.log_debug("No changes in %s", filename)
[359] Fix | Delete
[360] Fix | Delete
def refactor_string(self, data, name):
[361] Fix | Delete
"""Refactor a given input string.
[362] Fix | Delete
[363] Fix | Delete
Args:
[364] Fix | Delete
data: a string holding the code to be refactored.
[365] Fix | Delete
name: a human-readable name for use in error/log messages.
[366] Fix | Delete
[367] Fix | Delete
Returns:
[368] Fix | Delete
An AST corresponding to the refactored input stream; None if
[369] Fix | Delete
there were errors during the parse.
[370] Fix | Delete
"""
[371] Fix | Delete
features = _detect_future_features(data)
[372] Fix | Delete
if "print_function" in features:
[373] Fix | Delete
self.driver.grammar = pygram.python_grammar_no_print_statement
[374] Fix | Delete
try:
[375] Fix | Delete
tree = self.driver.parse_string(data)
[376] Fix | Delete
except Exception as err:
[377] Fix | Delete
self.log_error("Can't parse %s: %s: %s",
[378] Fix | Delete
name, err.__class__.__name__, err)
[379] Fix | Delete
return
[380] Fix | Delete
finally:
[381] Fix | Delete
self.driver.grammar = self.grammar
[382] Fix | Delete
tree.future_features = features
[383] Fix | Delete
self.log_debug("Refactoring %s", name)
[384] Fix | Delete
self.refactor_tree(tree, name)
[385] Fix | Delete
return tree
[386] Fix | Delete
[387] Fix | Delete
def refactor_stdin(self, doctests_only=False):
[388] Fix | Delete
input = sys.stdin.read()
[389] Fix | Delete
if doctests_only:
[390] Fix | Delete
self.log_debug("Refactoring doctests in stdin")
[391] Fix | Delete
output = self.refactor_docstring(input, "<stdin>")
[392] Fix | Delete
if self.write_unchanged_files or output != input:
[393] Fix | Delete
self.processed_file(output, "<stdin>", input)
[394] Fix | Delete
else:
[395] Fix | Delete
self.log_debug("No doctest changes in stdin")
[396] Fix | Delete
else:
[397] Fix | Delete
tree = self.refactor_string(input, "<stdin>")
[398] Fix | Delete
if self.write_unchanged_files or (tree and tree.was_changed):
[399] Fix | Delete
self.processed_file(unicode(tree), "<stdin>", input)
[400] Fix | Delete
else:
[401] Fix | Delete
self.log_debug("No changes in stdin")
[402] Fix | Delete
[403] Fix | Delete
def refactor_tree(self, tree, name):
[404] Fix | Delete
"""Refactors a parse tree (modifying the tree in place).
[405] Fix | Delete
[406] Fix | Delete
For compatible patterns the bottom matcher module is
[407] Fix | Delete
used. Otherwise the tree is traversed node-to-node for
[408] Fix | Delete
matches.
[409] Fix | Delete
[410] Fix | Delete
Args:
[411] Fix | Delete
tree: a pytree.Node instance representing the root of the tree
[412] Fix | Delete
to be refactored.
[413] Fix | Delete
name: a human-readable name for this tree.
[414] Fix | Delete
[415] Fix | Delete
Returns:
[416] Fix | Delete
True if the tree was modified, False otherwise.
[417] Fix | Delete
"""
[418] Fix | Delete
[419] Fix | Delete
for fixer in chain(self.pre_order, self.post_order):
[420] Fix | Delete
fixer.start_tree(tree, name)
[421] Fix | Delete
[422] Fix | Delete
#use traditional matching for the incompatible fixers
[423] Fix | Delete
self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
[424] Fix | Delete
self.traverse_by(self.bmi_post_order_heads, tree.post_order())
[425] Fix | Delete
[426] Fix | Delete
# obtain a set of candidate nodes
[427] Fix | Delete
match_set = self.BM.run(tree.leaves())
[428] Fix | Delete
[429] Fix | Delete
while any(match_set.values()):
[430] Fix | Delete
for fixer in self.BM.fixers:
[431] Fix | Delete
if fixer in match_set and match_set[fixer]:
[432] Fix | Delete
#sort by depth; apply fixers from bottom(of the AST) to top
[433] Fix | Delete
match_set[fixer].sort(key=pytree.Base.depth, reverse=True)
[434] Fix | Delete
[435] Fix | Delete
if fixer.keep_line_order:
[436] Fix | Delete
#some fixers(eg fix_imports) must be applied
[437] Fix | Delete
#with the original file's line order
[438] Fix | Delete
match_set[fixer].sort(key=pytree.Base.get_lineno)
[439] Fix | Delete
[440] Fix | Delete
for node in list(match_set[fixer]):
[441] Fix | Delete
if node in match_set[fixer]:
[442] Fix | Delete
match_set[fixer].remove(node)
[443] Fix | Delete
[444] Fix | Delete
try:
[445] Fix | Delete
find_root(node)
[446] Fix | Delete
except ValueError:
[447] Fix | Delete
# this node has been cut off from a
[448] Fix | Delete
# previous transformation ; skip
[449] Fix | Delete
continue
[450] Fix | Delete
[451] Fix | Delete
if node.fixers_applied and fixer in node.fixers_applied:
[452] Fix | Delete
# do not apply the same fixer again
[453] Fix | Delete
continue
[454] Fix | Delete
[455] Fix | Delete
results = fixer.match(node)
[456] Fix | Delete
[457] Fix | Delete
if results:
[458] Fix | Delete
new = fixer.transform(node, results)
[459] Fix | Delete
if new is not None:
[460] Fix | Delete
node.replace(new)
[461] Fix | Delete
#new.fixers_applied.append(fixer)
[462] Fix | Delete
for node in new.post_order():
[463] Fix | Delete
# do not apply the fixer again to
[464] Fix | Delete
# this or any subnode
[465] Fix | Delete
if not node.fixers_applied:
[466] Fix | Delete
node.fixers_applied = []
[467] Fix | Delete
node.fixers_applied.append(fixer)
[468] Fix | Delete
[469] Fix | Delete
# update the original match set for
[470] Fix | Delete
# the added code
[471] Fix | Delete
new_matches = self.BM.run(new.leaves())
[472] Fix | Delete
for fxr in new_matches:
[473] Fix | Delete
if not fxr in match_set:
[474] Fix | Delete
match_set[fxr]=[]
[475] Fix | Delete
[476] Fix | Delete
match_set[fxr].extend(new_matches[fxr])
[477] Fix | Delete
[478] Fix | Delete
for fixer in chain(self.pre_order, self.post_order):
[479] Fix | Delete
fixer.finish_tree(tree, name)
[480] Fix | Delete
return tree.was_changed
[481] Fix | Delete
[482] Fix | Delete
def traverse_by(self, fixers, traversal):
[483] Fix | Delete
"""Traverse an AST, applying a set of fixers to each node.
[484] Fix | Delete
[485] Fix | Delete
This is a helper method for refactor_tree().
[486] Fix | Delete
[487] Fix | Delete
Args:
[488] Fix | Delete
fixers: a list of fixer instances.
[489] Fix | Delete
traversal: a generator that yields AST nodes.
[490] Fix | Delete
[491] Fix | Delete
Returns:
[492] Fix | Delete
None
[493] Fix | Delete
"""
[494] Fix | Delete
if not fixers:
[495] Fix | Delete
return
[496] Fix | Delete
for node in traversal:
[497] Fix | Delete
for fixer in fixers[node.type]:
[498] Fix | Delete
results = fixer.match(node)
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function