From 2faf95795563abf5a72a485e7eedc1fba9111541 Mon Sep 17 00:00:00 2001 From: Chris Lawrence Date: Wed, 1 Jul 2020 20:46:19 -0400 Subject: [PATCH] Fix ValueError when formatting if continuation lines are incorrectly indented when using autopep8 (#829) --- pyls/plugins/autopep8_format.py | 11 ++++++++++- test/plugins/test_autopep8_format.py | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/pyls/plugins/autopep8_format.py b/pyls/plugins/autopep8_format.py index 1e4e4e1a..ff29a112 100644 --- a/pyls/plugins/autopep8_format.py +++ b/pyls/plugins/autopep8_format.py @@ -1,6 +1,7 @@ # Copyright 2018 Palantir Technologies, Inc. import logging -from autopep8 import fix_code +import pycodestyle +from autopep8 import fix_code, continued_indentation as autopep8_c_i from pyls import hookimpl log = logging.getLogger(__name__) @@ -31,8 +32,16 @@ def _format(config, document, line_range=None): if line_range: options['line_range'] = list(line_range) + # Temporarily re-monkey-patch the continued_indentation checker - #771 + del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation] + pycodestyle.register_check(autopep8_c_i) + new_source = fix_code(document.source, options=options) + # Switch it back + del pycodestyle._checks['logical_line'][autopep8_c_i] + pycodestyle.register_check(pycodestyle.continued_indentation) + if new_source == document.source: return [] diff --git a/test/plugins/test_autopep8_format.py b/test/plugins/test_autopep8_format.py index 8138952d..d23a1c49 100644 --- a/test/plugins/test_autopep8_format.py +++ b/test/plugins/test_autopep8_format.py @@ -15,6 +15,25 @@ def func(): GOOD_DOC = """A = ['hello', 'world']\n""" +INDENTED_DOC = """def foo(): + print('asdf', + file=None + ) + +bar = { 'foo': foo +} +""" + +CORRECT_INDENTED_DOC = """def foo(): + print('asdf', + file=None + ) + + +bar = {'foo': foo + } +""" + def test_format(config, workspace): doc = Document(DOC_URI, workspace, DOC) @@ -42,3 +61,11 @@ def test_range_format(config, workspace): def test_no_change(config, workspace): doc = Document(DOC_URI, workspace, GOOD_DOC) assert not pyls_format_document(config, doc) + + +def test_hanging_indentation(config, workspace): + doc = Document(DOC_URI, workspace, INDENTED_DOC) + res = pyls_format_document(config, doc) + + assert len(res) == 1 + assert res[0]['newText'] == CORRECT_INDENTED_DOC