Repository: asottile/pyupgrade

Issue:
py2 / py3 branch rewrite breaks indentation
```python
import six

if six.PY2:  # pragma: no cover (py2)
    def wsgi_to_text(s):
        # Use latin-1, the encoding of ip addresses isn't important (they'll
        # always be either ascii, or invalidated by the ipaddress module)
        return s.decode('LATIN-1')

    def text_to_wsgi(s):
        return s.encode('US-ASCII')
else:  # pragma: no cover (py3)
    def wsgi_to_text(s):
        return s

    def text_to_wsgi(s):
        return s

def f():
    pass
```

currently rewritten to

```python
import six

def wsgi_to_text(s):
    return s

    def text_to_wsgi(s):
    return s


def f():
    pass
```

Discussion:

Patch:
diff --git a/pyupgrade.py b/pyupgrade.py
index cb91999..f6e8e94 100644
--- a/pyupgrade.py
+++ b/pyupgrade.py
@@ -1771,7 +1771,7 @@ class Block(NamedTuple):
         diff = self._minimum_indent(tokens) - self._initial_indent(tokens)
         for i in range(self.block, self.end):
             if (
-                    tokens[i - 1].name in ('NL', 'NEWLINE') and
+                    tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and
                     tokens[i].name in ('INDENT', UNIMPORTANT_WS)
             ):
                 tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:])


Test patch:
diff --git a/tests/versioned_branches_test.py b/tests/versioned_branches_test.py
index b0512f1..2f93791 100644
--- a/tests/versioned_branches_test.py
+++ b/tests/versioned_branches_test.py
@@ -264,6 +264,25 @@ def test_fix_py2_block_noop(s):
 
             id='six.PY2, comment after',
         ),
+        pytest.param(
+            'if six.PY2:\n'
+            '    def f():\n'
+            '        print("py2")\n'
+            '    def g():\n'
+            '        print("py2")\n'
+            'else:\n'
+            '    def f():\n'
+            '        print("py3")\n'
+            '    def g():\n'
+            '        print("py3")\n',
+
+            'def f():\n'
+            '    print("py3")\n'
+            'def g():\n'
+            '    print("py3")\n',
+
+            id='six.PY2 multiple functions',
+        ),
         pytest.param(
             'if True:\n'
             '    if six.PY3:\n'