Commits

Álvaro Justen - Turicas  committed b178074

if-else indenting

  • Participants
  • Parent commits c3001fc

Comments (0)

Files changed (2)

File new_template.py

     else:
         return line
 
+def should_unindent(parsed_line):
+    unindentation_words = ('pass', 'else')
+    return parsed_line.split()[0].replace(':', '').strip() in unindentation_words
+
 
 def parse_python_code(python_code):
+    indentation_level = 0
     response = []
 
     in_string = False
     last_quote = ''
+    last_character = ''
     line = []
 
     for character in python_code:
         if character == '\n' and not in_string:
             parsed_line = parse_line(''.join(line[:-1]))
             if parsed_line:
-                response.append(parsed_line)
+                if should_unindent(parsed_line):
+                    indentation_level -= 1
+                if parsed_line.strip() != 'pass':
+                    response.append(indentation_level * '    ' + parsed_line)
             line = []
+        if last_character == ':' and not in_string and character == '\n':
+            indentation_level += 1
+        last_character = character
+
     if line:
         parsed_line = parse_line(''.join(line))
         if parsed_line:
-            response.append(parsed_line)
+            if should_unindent(parsed_line):
+                indentation_level -= 1
+            response.append(indentation_level * '    ' + parsed_line)
 
     return response
 

File test_new_template.py

         self.do_it()
 
 
+    def test_if_in_python_code_should_indent_next_lines(self):
+        self.input_ = '''{{if something:
+some_code
+other_code}}'''
+        self.expected_output = '''if something:
+    some_code
+    other_code'''
+        self.do_it()
+
+
+    def test_if_in_python_code_should_indent_next_lines(self):
+        self.input_ = '''{{if something:
+some_code
+other_code
+pass
+code_outside_if}}'''
+        self.expected_output = '''if something:
+    some_code
+    other_code
+code_outside_if'''
+        self.do_it()
+
+
+    def test_if_and_else_in_python_code_should_indent_only_block_lines(self):
+        self.input_ = '''{{if something:
+some_code
+other_code
+else:
+code_on_else
+other_code_on_else
+pass
+code_outside}}'''
+        self.expected_output = '''if something:
+    some_code
+    other_code
+else:
+    code_on_else
+    other_code_on_else
+code_outside'''
+        self.do_it()
+
+
 if __name__ == '__main__':
     if len(argv) == 1:
         import new_template