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