Skip to content

Properly indent new statements #12

@isidentical

Description

@isidentical

Problem

The indentation for the statements are not preserved, since ast.unparse() uses 4 spaces by default. We should infer the common indentation level (even in some blocks it might be different), and smartly use it for the ast.unparse;

Rule

import ast
import refactor
from refactor import Rule, Action

class MakeAsyncWith(Action):
    def build(self):
        new_node = self.branch()
        new_node.__class__ = ast.AsyncWith
        return new_node

class ReplaceToAsync(Rule):
    def match(self, node):
        assert isinstance(node, ast.With)
        return MakeAsyncWith(node)

if __name__ == "__main__":
    refactor.run(rules=[ReplaceToAsync])

Input

if something: # comment
  with something: # comment2
    a = 1 # comment3
    b = 2 # comment4
  # comment5
  c()

Diff

--- t1.py

+++ t1.py

@@ -1,6 +1,6 @@

 if something: # comment
-  with something: # comment2
-    a = 1 # comment3
-    b = 2 # comment4
+  async with something:
+      a = 1
+      b = 2 # comment4
   # comment5
   c()

Expected Difff

--- t1.py

+++ t1.py

@@ -1,6 +1,6 @@

 if something: # comment
-  with something: # comment2
-    a = 1 # comment3
-    b = 2 # comment4
+  async with something:
+    a = 1
+    b = 2 # comment4
   # comment5
   c()

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions