def replace(code, pattern, goal): """used by other refactorings""" finder = similarfinder.RawSimilarFinder(code) matches = list(finder.get_matches(pattern)) ast = patchedast.get_patched_ast(code) lines = codeanalyze.SourceLinesAdapter(code) template = similarfinder.CodeTemplate(goal) computer = _ChangeComputer(code, ast, lines, template, matches) result = computer.get_changed() if result is None: return code return result
def _replace_occurrences(self, content, extract_info): for match in extract_info.matches: replacement = similarfinder.CodeTemplate( extract_info.replacement_pattern) mapping = {} for name in replacement.get_names(): node = match.get_ast(name) if node: start, end = patchedast.node_region(match.get_ast(name)) mapping[name] = self.info.source[start:end] else: mapping[name] = name region = match.get_region() content.add_change(region[0], region[1], replacement.substitute(mapping))
def __init__(self, project, pattern, goal, args=None, imports=None, wildcards=None): """Construct a restructuring See class pydoc for more info about the arguments. """ self.project = project self.pattern = pattern self.goal = goal self.args = args if self.args is None: self.args = {} self.imports = imports if self.imports is None: self.imports = [] self.wildcards = wildcards self.template = similarfinder.CodeTemplate(self.goal)
def test_substituting_multiple_names(self): template = similarfinder.CodeTemplate('${a}, ${b}\n') self.assertEqual('1, 2\n', template.substitute({'a': '1', 'b': '2'}))
def test_simple_substitution(self): template = similarfinder.CodeTemplate('${a}\n') self.assertEqual('b\n', template.substitute({'a': 'b'}))
def test_ignoring_matches_in_strings(self): template = similarfinder.CodeTemplate("'${a}'\n") self.assertEqual({}.keys(), template.get_names())
def test_ignoring_matches_in_comments(self): template = similarfinder.CodeTemplate('#${a}\n') self.assertEqual({}.keys(), template.get_names())
def test_simple_templates(self): template = similarfinder.CodeTemplate('${a}\n') self.assertEqual(set(['a']), set(template.get_names()))
def test_substituting_multiple_names(self): template = similarfinder.CodeTemplate("${a}, ${b}\n") self.assertEqual("1, 2\n", template.substitute({"a": "1", "b": "2"}))
def test_simple_substitution(self): template = similarfinder.CodeTemplate("${a}\n") self.assertEqual("b\n", template.substitute({"a": "b"}))