Skip to content

Commit

Permalink
Merge branch 'master' into update-travis-conf
Browse files Browse the repository at this point in the history
  • Loading branch information
Hideo Hattori committed Jun 30, 2017
2 parents f92b41f + ce4c633 commit 3beca03
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
45 changes: 41 additions & 4 deletions autopep8.py
Expand Up @@ -1120,15 +1120,51 @@ def fix_w503(self, result):
return
if not _is_binary_operator(ts[0][0], one_string_token):
return
# find comment
comment_index = None
for i in range(5):
# NOTE: try to parse code in 5 times
if (line_index - i) < 0:
break
from_index = line_index - i - 1
to_index = line_index + 1
try:
ts = generate_tokens("".join(self.source[from_index:to_index]))
except Exception:
continue
newline_count = 0
newline_index = []
for i, t in enumerate(ts):
if t[0] in (tokenize.NEWLINE, tokenize.NL):
newline_index.append(i)
newline_count += 1
if newline_count > 2:
tts = ts[newline_index[-3]:]
else:
tts = ts
old = None
for t in tts:
if tokenize.COMMENT == t[0]:
if old is None:
comment_index = 0
else:
comment_index = old[3][1]
break
old = t
break
i = target.index(one_string_token)
self.source[line_index] = '{0}{1}'.format(
target[:i], target[i + len(one_string_token):])
nl = find_newline(self.source[line_index - 1:line_index])
before_line = self.source[line_index - 1]
bl = before_line.index(nl)
self.source[line_index - 1] = '{0} {1}{2}'.format(
before_line[:bl], one_string_token,
before_line[bl:])
if comment_index:
self.source[line_index - 1] = '{0} {1} {2}'.format(
before_line[:comment_index], one_string_token,
before_line[comment_index + 1:])
else:
self.source[line_index - 1] = '{0} {1}{2}'.format(
before_line[:bl], one_string_token, before_line[bl:])


def get_index_offset_contents(result, source):
Expand Down Expand Up @@ -1499,7 +1535,8 @@ def _priority_key(pep8_result):
lowest_priority = [
# We need to shorten lines last since the logical fixer can get in a
# loop, which causes us to exit early.
'e501'
'e501',
'w503'
]
key = pep8_result['id'].lower()
try:
Expand Down
24 changes: 24 additions & 0 deletions test/test_autopep8.py
Expand Up @@ -4090,6 +4090,30 @@ def test_w503_and_or(self):
with autopep8_context(line, options=['-aaa']) as result:
self.assertEqual(fixed, result)

def test_w503_with_comment(self):
line = '(width == 0 # this is comment\n + height == 0)\n'
fixed = '(width == 0 + # this is comment\n height == 0)\n'
with autopep8_context(line, options=['-aaa']) as result:
self.assertEqual(fixed, result)

def test_w503_with_comment_double(self):
line = """\
(
1111 # C1
and 22222222 # C2
and 333333333333 # C3
)
"""
fixed = """\
(
1111 and # C1
22222222 and # C2
333333333333 # C3
)
"""
with autopep8_context(line, options=['-aaa']) as result:
self.assertEqual(fixed, result)

def test_w601(self):
line = 'a = {0: 1}\na.has_key(0)\n'
fixed = 'a = {0: 1}\n0 in a\n'
Expand Down

0 comments on commit 3beca03

Please sign in to comment.