def transform(self, node, results): if _literal_re.match(node.value): touch_import(None, u'six', node) new = node.clone() new.value = new.value[1:] new.prefix = '' node.replace(Call(Name(u'six.u', prefix=node.prefix), [new]))
def transform(self, node, results): if _literal_re.match(node.value): fixer_util.touch_import(None, "six", node) new = node.clone() new.value = new.value[1:] new.prefix = "" node.replace(Call(Name("six.u", prefix=node.prefix), [new]))
def _Call(self, name, args=None, prefix=None): """Help the next test""" children = [] if isinstance(args, list): for arg in args: children.append(arg) children.append(Comma()) children.pop() return Call(Name(name), children, prefix)
def transform(self, node, results): exc = results["exc"].clone() val = results["val"].clone() tb = results["tb"].clone() exc.prefix = u"" val.prefix = tb.prefix = u" " touch_import(None, u'six', node) return Call(Name(u"six.reraise"), [exc, Comma(), val, Comma(), tb], prefix=node.prefix)
def transform(self, node, results): if self.should_skip(node): return touch_import("six.moves", "input", node) name = results["name"] if name.value == "raw_input": name.replace(Name("input", prefix=name.prefix)) else: new_node = node.clone() new_node.prefix = "" return Call(Name("eval"), [new_node], prefix=node.prefix)
def transform(self, node, results): if self.should_skip(node): return touch_import(u'six.moves', u'input', node) name = results['name'] if name.value == 'raw_input': name.replace(Name('input', prefix=name.prefix)) else: new_node = node.clone() new_node.prefix = '' return Call(Name('eval'), [new_node], prefix=node.prefix)
def modify_attr(node: LN, capture: Capture, filename: Filename) -> Optional[LN]: node.replace( Call( Name("getattr"), args=[ capture["obj"].clone(), Comma(), Space(), String('"' + capture["attr"].value + '"'), ], ))
def translate_string(ln, cap, fn): # wrap string in a call to tr() args = cap.get('function_arguments') args[0].replace( Call( Name("tr"), args=[args[0].clone()] ), ) # drop a leading comment while not ln.prefix: prev = ln.prev_sibling if prev is None and ln.parent is None: break ln = prev or ln.parent ln.prefix = todo_re.sub("", ln.prefix)
def modify_dict_literal(node: LN, capture: Capture, filename: Filename) -> Optional[LN]: toks = iter(capture.get("body")) items = [] prefix = "" while True: try: tok = next(toks) if tok.type == TOKEN.DOUBLESTAR: body = next(toks).clone() body.prefix = prefix + tok.prefix + body.prefix items.append(body) else: colon = next(toks) value = next(toks).clone() value.prefix = colon.prefix + value.prefix if items and isinstance(items[-1], list): items[-1].append(TupleNode(tok, value)) else: items.append([TupleNode(tok, value)]) comma = next(toks) prefix = comma.prefix except StopIteration: break listitems = [] for item in items: if listitems: listitems.extend([Space(), Plus(), Space()]) if isinstance(item, list): listitems.append(ListNode(*item)) else: call = Node(SYMBOL.test, [*Attr(item, Name("items")), ArgList([])]) listitems.append(call) args = listitems if len(listitems) > 1: args = [Node(SYMBOL.arith_expr, args)] args.append(String(node.children[-1].prefix)) return Call(Name("dict"), args, prefix=node.prefix)
def transform(self, node, results): # First, find the sys import. We'll just hope it's global scope. if "sys_import" in results: if self.sys_import is None: self.sys_import = results["sys_import"] return func = results["func"].clone() func.prefix = "" register = pytree.Node(syms.power, Attr(Name("atexit"), Name("register"))) call = Call(register, [func], node.prefix) node.replace(call) if self.sys_import is None: # That's interesting. self.warning( node, "Can't find sys import; Please add an atexit " "import at the top of your file.", ) return # Now add an atexit import after the sys import. names = self.sys_import.children[1] if names.type == syms.dotted_as_names: names.append_child(Comma()) names.append_child(Name("atexit", " ")) else: containing_stmt = self.sys_import.parent position = containing_stmt.children.index(self.sys_import) stmt_container = containing_stmt.parent new_import = pytree.Node( syms.import_name, [Name("import"), Name("atexit", " ")] ) new = pytree.Node(syms.simple_stmt, [new_import]) containing_stmt.insert_child(position + 1, Newline()) containing_stmt.insert_child(position + 2, new)
def transform(self, node, results): if not has_metaclass(node): return # pragma: no cover fixup_parse_tree(node) # find metaclasses, keep the last one last_metaclass = None for suite, i, stmt in find_metas(node): last_metaclass = stmt stmt.remove() text_type = node.children[0].type # always Leaf(nnn, 'class') # figure out what kind of classdef we have if len(node.children) == 7: # Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite]) # 0 1 2 3 4 5 6 if node.children[3].type == syms.arglist: arglist = node.children[3] # Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite]) else: parent = node.children[3].clone() arglist = Node(syms.arglist, [parent]) node.set_child(3, arglist) elif len(node.children) == 6: # Node(classdef, ['class', 'name', '(', ')', ':', suite]) # 0 1 2 3 4 5 arglist = Node(syms.arglist, []) node.insert_child(3, arglist) elif len(node.children) == 4: # Node(classdef, ['class', 'name', ':', suite]) # 0 1 2 3 arglist = Node(syms.arglist, []) node.insert_child(2, Leaf(token.RPAR, u')')) node.insert_child(2, arglist) node.insert_child(2, Leaf(token.LPAR, u'(')) else: raise ValueError("Unexpected class definition") # pragma: no cover touch_import(None, u'six', node) metaclass = last_metaclass.children[0].children[2].clone() metaclass.prefix = u'' arguments = [metaclass] if arglist.children: bases = arglist.clone() bases.prefix = u' ' arguments.extend([Comma(), bases]) arglist.replace( Call(Name(u'six.with_metaclass', prefix=arglist.prefix), arguments)) fixup_indent(suite) # check for empty suite if not suite.children: # one-liner that was just __metaclass__ suite.remove() pass_leaf = Leaf(text_type, u'pass') pass_leaf.prefix = last_metaclass.prefix node.append_child(pass_leaf) node.append_child(Leaf(token.NEWLINE, u'\n')) elif len(suite.children) > 1 and \ (suite.children[-2].type == token.INDENT and suite.children[-1].type == token.DEDENT): # there was only one line in the class body and it was __metaclass__ pass_leaf = Leaf(text_type, u'pass') suite.insert_child(-1, pass_leaf) suite.insert_child(-1, Leaf(token.NEWLINE, u'\n'))
def assertmethod_to_assert(node, capture, arguments): """ self.assertEqual(foo, bar, msg) --> assert foo == bar, msg self.assertTrue(foo, msg) --> assert foo, msg self.assertIsNotNone(foo, msg) --> assert foo is not None, msg .. etc """ function_name = capture["function_name"].value invert = function_name in INVERT_FUNCTIONS function_name = SYNONYMS.get(function_name, function_name) num_arguments = ARGUMENTS[function_name] if len(arguments) not in (num_arguments, num_arguments + 1): # Not sure what this is. Leave it alone. return None if len(arguments) == num_arguments: message = None else: message = arguments.pop() if message.type == syms.argument: # keyword argument (e.g. `msg=abc`) message = message.children[2].clone() if function_name == "assertIsInstance": arguments[0].prefix = "" assert_test_nodes = [ Call(keyword("isinstance"), [arguments[0], Comma(), arguments[1]]) ] if invert: assert_test_nodes.insert(0, keyword("not")) elif function_name == "assertAlmostEqual": arguments[1].prefix = "" # TODO: insert the `import pytest` at the top of the file if invert: op_token = Leaf(TOKEN.NOTEQUAL, "!=", prefix=" ") else: op_token = Leaf(TOKEN.EQEQUAL, "==", prefix=" ") assert_test_nodes = [ Node( syms.comparison, [ arguments[0], op_token, Node( syms.power, Attr(keyword("pytest"), keyword("approx", prefix="")) + [ ArgList([ arguments[1], Comma(), KeywordArg(keyword("abs"), Leaf(TOKEN.NUMBER, "1e-7")), ]) ], ), ], ) ] # Adds a 'import pytest' if there wasn't one already touch_import(None, "pytest", node) else: op_tokens = OPERATORS[function_name] if not isinstance(op_tokens, list): op_tokens = [op_tokens] op_tokens = [o.clone() for o in op_tokens] if invert: if not op_tokens: op_tokens.append(keyword("not")) elif op_tokens[0].type == TOKEN.NAME and op_tokens[0].value == "is": op_tokens[0] = Node( syms.comp_op, [keyword("is"), keyword("not")], prefix=" ") elif op_tokens[0].type == TOKEN.NAME and op_tokens[0].value == "in": op_tokens[0] = Node( syms.comp_op, [keyword("not"), keyword("in")], prefix=" ") elif op_tokens[0].type == TOKEN.EQEQUAL: op_tokens[0] = Leaf(TOKEN.NOTEQUAL, "!=", prefix=" ") if num_arguments == 2: # a != b, etc. assert_test_nodes = [arguments[0]] + op_tokens + [arguments[1]] elif function_name == "assertTrue": assert_test_nodes = op_tokens + [arguments[0]] # not a elif function_name == "assertIsNone": # a is not None assert_test_nodes = [arguments[0]] + op_tokens return Assert(assert_test_nodes, message.clone() if message else None, prefix=node.prefix)
def wrap_string(node, capture, fn): args = capture["args"] if args and args[0].type == TOKEN.STRING: literal = args[0] literal.replace(Call(Name("tr"), [literal.clone()]))
def transform(self, node, results): base = results['base'] base = [n.clone() for n in base] base[0].prefix = u"" node.replace(Call(Name(u"next", prefix=node.prefix), base))