Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 97 additions & 12 deletions isort/literal.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@
LiteralSortTypeMismatch,
)
from isort.settings import DEFAULT_CONFIG, Config
from isort.wrap_modes import WrapModes


class ISortPrettyPrinter(PrettyPrinter):
"""an isort customized pretty printer for sorted literals"""

def __init__(self, config: Config):
super().__init__(width=config.line_length, compact=True)
def __init__(self, config: Config, prefix_length: int = 0):
self.config = config
self.available_width = (
config.wrap_length or config.line_length
) - prefix_length
super().__init__(width=self.available_width, compact=True)


type_mapping: dict[str, tuple[type, Callable[[Any, ISortPrettyPrinter], str]]] = {}
Expand All @@ -32,11 +37,14 @@ def assignments(code: str) -> str:
values[variable_name] = value

return "".join(
f"{variable_name} = {values[variable_name]}" for variable_name in sorted(values.keys())
f"{variable_name} = {values[variable_name]}"
for variable_name in sorted(values.keys())
)


def assignment(code: str, sort_type: str, extension: str, config: Config = DEFAULT_CONFIG) -> str:
def assignment(
code: str, sort_type: str, extension: str, config: Config = DEFAULT_CONFIG
) -> str:
"""Sorts the literal present within the provided code against the provided sort type,
returning the sorted representation of the source code.
"""
Expand All @@ -60,7 +68,7 @@ def assignment(code: str, sort_type: str, extension: str, config: Config = DEFAU
if type(value) is not expected_type:
raise LiteralSortTypeMismatch(type(value), expected_type)

printer = ISortPrettyPrinter(config)
printer = ISortPrettyPrinter(config, prefix_length=len(f"{variable_name} = "))
sorted_value_code = f"{variable_name} = {sort_function(value, printer)}"
if config.formatting_function:
sorted_value_code = config.formatting_function(
Expand All @@ -73,7 +81,9 @@ def assignment(code: str, sort_type: str, extension: str, config: Config = DEFAU

def register_type(
name: str, kind: type
) -> Callable[[Callable[[Any, ISortPrettyPrinter], str]], Callable[[Any, ISortPrettyPrinter], str]]:
) -> Callable[
[Callable[[Any, ISortPrettyPrinter], str]], Callable[[Any, ISortPrettyPrinter], str]
]:
"""Registers a new literal sort type."""

def wrap(
Expand All @@ -85,31 +95,106 @@ def wrap(
return wrap


def _use_vertical_hanging_indent(printer: ISortPrettyPrinter) -> bool:
return (
printer.config.multi_line_output == WrapModes.VERTICAL_HANGING_INDENT
and printer.config.use_parentheses
and printer.config.include_trailing_comma
)


def _format_items(
items: list[Any],
printer: ISortPrettyPrinter,
opener: str,
closer: str,
force_tuple_comma: bool = False,
) -> str:
rendered_items = [printer.pformat(item) for item in items]
single_line = f"{opener}{', '.join(rendered_items)}{closer}"
if force_tuple_comma and len(rendered_items) == 1:
single_line = f"{opener}{rendered_items[0]},{closer}"

if not rendered_items or not _use_vertical_hanging_indent(printer):
return single_line

if len(single_line) <= printer.available_width:
return single_line

indent = printer.config.indent
lines = [opener]
lines.extend(f"{indent}{item}," for item in rendered_items)
lines.append(closer)
return "\n".join(lines)


def _format_pairs(
pairs: list[tuple[Any, Any]],
printer: ISortPrettyPrinter,
opener: str,
closer: str,
) -> str:
rendered_pairs = [
f"{printer.pformat(key)}: {printer.pformat(value)}" for key, value in pairs
]
single_line = f"{opener}{', '.join(rendered_pairs)}{closer}"

if not rendered_pairs or not _use_vertical_hanging_indent(printer):
return single_line

if len(single_line) <= printer.available_width:
return single_line

indent = printer.config.indent
lines = [opener]
lines.extend(f"{indent}{pair}," for pair in rendered_pairs)
lines.append(closer)
return "\n".join(lines)


@register_type("dict", dict)
def _dict(value: dict[Any, Any], printer: ISortPrettyPrinter) -> str:
return printer.pformat(dict(sorted(value.items(), key=lambda item: item[1])))
sorted_items = sorted(value.items(), key=lambda item: item[1])
if _use_vertical_hanging_indent(printer):
return _format_pairs(sorted_items, printer, "{", "}")
return printer.pformat(dict(sorted_items))


@register_type("list", list)
def _list(value: list[Any], printer: ISortPrettyPrinter) -> str:
return printer.pformat(sorted(value))
sorted_items = sorted(value)
if _use_vertical_hanging_indent(printer):
return _format_items(sorted_items, printer, "[", "]")
return printer.pformat(sorted_items)


@register_type("unique-list", list)
def _unique_list(value: list[Any], printer: ISortPrettyPrinter) -> str:
return printer.pformat(sorted(set(value)))
sorted_items = sorted(set(value))
if _use_vertical_hanging_indent(printer):
return _format_items(sorted_items, printer, "[", "]")
return printer.pformat(sorted_items)


@register_type("set", set)
def _set(value: set[Any], printer: ISortPrettyPrinter) -> str:
return "{" + printer.pformat(tuple(sorted(value)))[1:-1] + "}"
sorted_items = sorted(value)
if _use_vertical_hanging_indent(printer):
return _format_items(sorted_items, printer, "{", "}")
return "{" + printer.pformat(tuple(sorted_items))[1:-1] + "}"


@register_type("tuple", tuple)
def _tuple(value: tuple[Any, ...], printer: ISortPrettyPrinter) -> str:
return printer.pformat(tuple(sorted(value)))
sorted_items = sorted(value)
if _use_vertical_hanging_indent(printer):
return _format_items(sorted_items, printer, "(", ")", force_tuple_comma=True)
return printer.pformat(tuple(sorted_items))


@register_type("unique-tuple", tuple)
def _unique_tuple(value: tuple[Any, ...], printer: ISortPrettyPrinter) -> str:
return printer.pformat(tuple(sorted(set(value))))
sorted_items = sorted(set(value))
if _use_vertical_hanging_indent(printer):
return _format_items(sorted_items, printer, "(", ")", force_tuple_comma=True)
return printer.pformat(tuple(sorted_items))
29 changes: 27 additions & 2 deletions tests/unit/test_literal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import isort.literal
from isort import exceptions
from isort.settings import Config


def test_value_mismatch():
Expand All @@ -15,14 +16,38 @@ def test_invalid_syntax():


def test_invalid_sort_type():
with pytest.raises(ValueError, match=r"Trying to sort using an undefined sort_type. Defined"):
with pytest.raises(
ValueError, match=r"Trying to sort using an undefined sort_type. Defined"
):
isort.literal.assignment("x = [1, 2, 3", "tuple-list-not-exist", "py")


def test_value_assignment_assignments():
assert isort.literal.assignment("b = 1\na = 2\n", "assignments", "py") == "a = 2\nb = 1\n"
assert (
isort.literal.assignment("b = 1\na = 2\n", "assignments", "py")
== "a = 2\nb = 1\n"
)


def test_assignments_invalid_section():
with pytest.raises(exceptions.AssignmentsFormatMismatch):
isort.literal.assignment("\n\nx = 1\nx++", "assignments", "py")


def test_tuple_sorting_uses_black_profile_wrapping():
assert (
isort.literal.assignment(
'data = ("therearesuperlong", "therearesuperlong", "therearesuperlong", '
'"therearesuperlong", "therearesuperlong")',
"tuple",
"py",
Config(profile="black"),
)
== """data = (
'therearesuperlong',
'therearesuperlong',
'therearesuperlong',
'therearesuperlong',
'therearesuperlong',
)"""
)
Loading