Skip to content

Commit

Permalink
fix handling of comments in from imports (psf#829)
Browse files Browse the repository at this point in the history
Fixes psf#671
  • Loading branch information
JelleZijlstra authored May 6, 2019
1 parent e6ddb68 commit 6b994fd
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 3 deletions.
13 changes: 10 additions & 3 deletions black.py
Original file line number Diff line number Diff line change
Expand Up @@ -2405,10 +2405,17 @@ def bracket_split_build_line(
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma when expected.
# Ensure a trailing comma for imports, but be careful not to add one after
# any comments.
if original.is_import:
if leaves[-1].type != token.COMMA:
leaves.append(Leaf(token.COMMA, ","))
for i in range(len(leaves) - 1, -1, -1):
if leaves[i].type == STANDALONE_COMMENT:
continue
elif leaves[i].type == token.COMMA:
break
else:
leaves.insert(i + 1, Leaf(token.COMMA, ","))
break
# Populate the line
for leaf in leaves:
result.append(leaf, preformatted=True)
Expand Down
51 changes: 51 additions & 0 deletions tests/data/comments7.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
Path,
# String,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)


from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
no_comma_here_yet
# and some comments,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)

# output

from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
Path,
# String,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)


from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
no_comma_here_yet,
# and some comments,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)
8 changes: 8 additions & 0 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,14 @@ def test_comments6(self) -> None:
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())

@patch("black.dump_to_file", dump_to_stderr)
def test_comments7(self) -> None:
source, expected = read_data("comments7")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())

@patch("black.dump_to_file", dump_to_stderr)
def test_cantfit(self) -> None:
source, expected = read_data("cantfit")
Expand Down

0 comments on commit 6b994fd

Please sign in to comment.