Skip to content

Commit

Permalink
Convert the E266 fixer to be a more usual one
Browse files Browse the repository at this point in the history
This still ends up fixing cases of E265 which overlap with E266
but doesn't go out of its way to do so if E265 is disabled. This
ought to be fine since pycodestyle doesn't seem to ever complain
about E266 on any lines affected by E265.
  • Loading branch information
PeterJCLaw committed Sep 16, 2022
1 parent 7c10dd3 commit f3ac0b9
Showing 1 changed file with 22 additions and 42 deletions.
64 changes: 22 additions & 42 deletions autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,28 @@ def fix_e265(self, result):

self.source[result['line'] - 1] = fixed

def fix_e266(self, result):
"""Fix too many block comment hashes."""

source = ''.join(self.source)
# TODO: don't recompute this every time!
ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))

if result['line'] in ignored_line_numbers:
return

# Leave stylistic outlined blocks alone.
target = self.source[result['line'] - 1]
if target.strip().endswith('#'):
return

indentation = _get_indentation(target)
fixed = indentation + '# ' + target.lstrip('# \t')

self.source[result['line'] - 1] = fixed

def fix_e271(self, result):
"""Fix extraneous whitespace around keywords."""
line_index = result['line'] - 1
Expand Down Expand Up @@ -1696,48 +1718,6 @@ def split_and_strip_non_empty_lines(text):
return [line.strip() for line in text.splitlines() if line.strip()]


def fix_e266(source, aggressive=False): # pylint: disable=unused-argument
"""Format block comments."""
if '#' not in source:
# Optimization.
return source

ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))

fixed_lines = []
sio = io.StringIO(source)
for (line_number, line) in enumerate(sio.readlines(), start=1):
if (
line.lstrip().startswith('#') and
line_number not in ignored_line_numbers and
not pycodestyle.noqa(line)
):
indentation = _get_indentation(line)
line = line.lstrip()

# Normalize beginning if not a shebang.
if len(line) > 1:
pos = next((index for index, c in enumerate(line)
if c != '#'))
if (
# Leave multiple spaces like '# ' alone.
(line[:pos].count('#') > 1 or line[1].isalnum() or
not line[1].isspace()) and
line[1] not in ':!' and
# Leave stylistic outlined blocks alone.
not line.rstrip().endswith('#')
):
line = '# ' + line.lstrip('# \t')

fixed_lines.append(indentation + line)
else:
fixed_lines.append(line)

return ''.join(fixed_lines)


def refactor(source, fixer_names, ignore=None, filename=''):
"""Return refactored code using lib2to3.
Expand Down

0 comments on commit f3ac0b9

Please sign in to comment.