From 192cd6c4a06afa5cc9523f080a64f3286487e71e Mon Sep 17 00:00:00 2001 From: Maggie Moss Date: Mon, 5 Jan 2026 10:54:17 -0800 Subject: [PATCH 1/6] Add new option to preserve inline comments --- usort/config.py | 5 ++++ usort/tests/functional.py | 52 +++++++++++++++++++++++++++++++++++++++ usort/translate.py | 22 ++++++++++++++++- 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/usort/config.py b/usort/config.py index b42546a..430ffe7 100644 --- a/usort/config.py +++ b/usort/config.py @@ -65,6 +65,9 @@ class Config: # Whether to merge imports when sorting merge_imports: bool = True + # Whether to preserve inline comments on individual imports when sorting + preserve_inline_comments: bool = False + # gitignore-style filename patterns to exclude when sorting entire directories excludes: List[str] = field(default_factory=list) @@ -167,6 +170,8 @@ def update_from_config(self, toml_path: Path) -> None: self.magic_commas = bool(tbl["magic_commas"]) if "merge_imports" in tbl: self.merge_imports = bool(tbl["merge_imports"]) + if "preserve_inline_comments" in tbl: + self.preserve_inline_comments = bool(tbl["preserve_inline_comments"]) if "excludes" in tbl: self.excludes = tbl["excludes"] diff --git a/usort/tests/functional.py b/usort/tests/functional.py index 3b6557f..351aedc 100644 --- a/usort/tests/functional.py +++ b/usort/tests/functional.py @@ -1140,6 +1140,58 @@ def test_sorting_with_extra_blank_lines(self) -> None: """, ) + def test_preserve_inline_comments(self) -> None: + config = replace(DEFAULT_CONFIG, preserve_inline_comments=True) + self.assertUsortResult( + """ + from torch._C import _linalg # pyrefly: + from torch._C import ( + _LinAlgError as LinAlgError, # pyrefly: ignore # missing-module-attribute + ) + from torch._C import _add_docstr + """, + """ + from torch._C import ( + _add_docstr, + _linalg, # pyrefly: + _LinAlgError as LinAlgError, # pyrefly: ignore # missing-module-attribute + ) + """, + config, + ) + + def test_preserve_inline_comments_multiple_modules(self) -> None: + config = replace(DEFAULT_CONFIG, preserve_inline_comments=True) + self.assertUsortResult( + """ + from foo import bar # comment1 + from foo import baz # comment2 + from foo import alpha + """, + """ + from foo import ( + alpha, + bar, # comment1 + baz, # comment2 + ) + """, + config, + ) + + def test_preserve_inline_comments_disabled(self) -> None: + # Without preserve_inline_comments, comments become import-level + config = replace(DEFAULT_CONFIG, preserve_inline_comments=False) + self.assertUsortResult( + """ + from torch._C import _linalg # pyrefly: + from torch._C import _add_docstr + """, + """ + from torch._C import _add_docstr, _linalg # pyrefly: + """, + config, + ) + if __name__ == "__main__": unittest.main() diff --git a/usort/translate.py b/usort/translate.py index f07fbfd..6e4eeea 100644 --- a/usort/translate.py +++ b/usort/translate.py @@ -201,10 +201,22 @@ def import_from_node(node: cst.SimpleStatementLine, config: Config) -> SortableI if node.body[0].relative: stem = "." * len(node.body[0].relative) + stem - for name in node.body[0].names: + # For single-line imports with preserve_inline_comments, attach trailing + # comments to the specific item instead of the import level + is_single_line = not node.body[0].lpar + single_item_count = len(node.body[0].names) + + for idx, name in enumerate(node.body[0].names): items.append(item_from_node(name, stem, comments.initial)) comments.initial = [] + # If preserving inline comments and this is a single-line import with + # one item, move first_inline comments to the item's inline comments + if (config.preserve_inline_comments and is_single_line and + single_item_count == 1 and idx == 0 and comments.first_inline): + items[-1].comments.inline.extend(comments.first_inline) + comments.first_inline.clear() + else: raise TypeError @@ -240,6 +252,14 @@ def import_to_node( ) -> cst.BaseStatement: if config.magic_commas and imp.stem and imp.trailing_comma: return import_to_node_multi(imp, module) + + # If preserve_inline_comments is enabled and any item has inline comments, + # use multi-line format to preserve them + if config.preserve_inline_comments and imp.stem: + has_item_comments = any(item.comments.inline for item in imp.items) + if has_item_comments: + return import_to_node_multi(imp, module) + node = import_to_node_single(imp, module) content = indent + render_node(node, module).rstrip() # basic imports can't be reflowed, so only deal with from-imports From 3f728f9468eadf7f02c641585ddb8e4e44371aa4 Mon Sep 17 00:00:00 2001 From: Maggie Moss Date: Mon, 5 Jan 2026 10:56:33 -0800 Subject: [PATCH 2/6] Add docs --- docs/guide.rst | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/docs/guide.rst b/docs/guide.rst index c2bcd4f..636ecee 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -537,6 +537,57 @@ The following options are valid for the main ``tool.usort`` table: Whether to merge sequential imports from the same base module. See `Merging`_ for details on how this works. +.. attribute:: preserve_inline_comments + :type: bool + :value: false + + Whether to preserve the placement of inline comments with their associated + import items when sorting and merging imports. + + When set to ``false`` (the default), inline comments from single-line imports + are treated as import-level comments and will be placed at the end of the + merged import statement:: + + # Before + from foo import bar # comment1 + from foo import baz # comment2 + + # After (default behavior) + from foo import bar, baz # comment1 # comment2 + + When set to ``true``, inline comments are associated with their specific + import items and will remain attached to those items after sorting and + merging:: + + # Before + from foo import bar # comment1 + from foo import baz # comment2 + + # After (preserve_inline_comments = true) + from foo import ( + bar, # comment1 + baz, # comment2 + ) + + This is particularly useful when using inline comments for directives like + type checker annotations or linter suppressions that are specific to individual + imports:: + + # Before + from torch._C import _linalg # pyrefly: + from torch._C import _LinAlgError as LinAlgError # pyrefly: ignore + from torch._C import _add_docstr + + # After (preserve_inline_comments = true) + from torch._C import ( + _add_docstr, + _linalg, # pyrefly: + _LinAlgError as LinAlgError, # pyrefly: ignore + ) + + Note that this option only affects inline comments on single-line imports. + Comments on multi-line imports are always preserved with their associated items. + .. attribute:: excludes :type: List[str] From a562b5400bccce908573b54a0ce8050d0dd28332 Mon Sep 17 00:00:00 2001 From: Maggie Moss Date: Mon, 5 Jan 2026 11:09:16 -0800 Subject: [PATCH 3/6] Fix docs --- docs/guide.rst | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/guide.rst b/docs/guide.rst index 636ecee..e53549c 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -573,16 +573,23 @@ The following options are valid for the main ``tool.usort`` table: type checker annotations or linter suppressions that are specific to individual imports:: - # Before - from torch._C import _linalg # pyrefly: - from torch._C import _LinAlgError as LinAlgError # pyrefly: ignore - from torch._C import _add_docstr + # Original Code + from example._C import _linalg # pyrefly: ignore [missing-attribute] + from example._C import _LinAlgError as LinAlgError # pyrefly: ignore + from example._C import _add_docstr + + # Without preserving inline comments + from example._C import ( # pyrefly: ignore [missing-attribute] + _add_docstr, + _linealg, + _LineAlgError as LinAlgError, # pyrefly: ignore + ) # After (preserve_inline_comments = true) - from torch._C import ( + from example._C import ( _add_docstr, - _linalg, # pyrefly: - _LinAlgError as LinAlgError, # pyrefly: ignore + _linealg, # pyrefly: ignore [missing-attribute] + _LineAlgError as LineAlgError, # pyrefly: ignore ) Note that this option only affects inline comments on single-line imports. From 3994c60183610510441681f63b6351df7f037597 Mon Sep 17 00:00:00 2001 From: Maggie Moss Date: Mon, 5 Jan 2026 11:16:33 -0800 Subject: [PATCH 4/6] Fix format --- usort/api.py | 1 - usort/tests/cli.py | 50 +++++++++-------------------- usort/tests/config.py | 66 +++++++++++++-------------------------- usort/tests/functional.py | 12 +++---- usort/tests/sorting.py | 6 ++-- usort/tests/types.py | 6 ++-- usort/translate.py | 9 ++++-- usort/types.py | 12 +++---- 8 files changed, 56 insertions(+), 106 deletions(-) diff --git a/usort/api.py b/usort/api.py index 0b23edd..329395a 100644 --- a/usort/api.py +++ b/usort/api.py @@ -16,7 +16,6 @@ from .types import Result from .util import get_timings, timed, try_parse - __all__ = ["usort_bytes", "usort_string", "usort_path", "usort_stdin"] diff --git a/usort/tests/cli.py b/usort/tests/cli.py index a274f56..cc79601 100644 --- a/usort/tests/cli.py +++ b/usort/tests/cli.py @@ -50,14 +50,12 @@ def test_benchmark(self) -> None: self.assertRegex( result.output, - dedent( - r""" + dedent(r""" walking \.:\s+\d+ µs parsing sample\.py:\s+\d+ µs sorting sample\.py:\s+\d+ µs total:\s+\d+ µs - """ - ).strip(), + """).strip(), ) self.assertEqual(0, result.exit_code) @@ -72,32 +70,26 @@ def test_benchmark_multiple(self) -> None: self.assertRegex( result.output, - dedent( - r""" + dedent(r""" parsing foo\.py:\s+\d+ µs sorting foo\.py:\s+\d+ µs - """ - ).strip(), + """).strip(), ) self.assertRegex( result.output, - dedent( - r""" + dedent(r""" parsing sample\.py:\s+\d+ µs sorting sample\.py:\s+\d+ µs - """ - ).strip(), + """).strip(), ) self.assertRegex( result.output, - dedent( - r""" + dedent(r""" walking \.:\s+\d+ µs total:\s+\d+ µs - """ - ).strip(), + """).strip(), ) self.assertEqual(0, result.exit_code) @@ -178,9 +170,7 @@ def test_diff_with_change(self) -> None: +import os import sys -import os -""".replace( - "\r", "" - ), +""".replace("\r", ""), result.output, ) @@ -284,13 +274,11 @@ def test_format_with_change(self) -> None: def test_format_utf8(self) -> None: # the string is "µ" as in "µsort" - with sample_contents( - b"""\ + with sample_contents(b"""\ import b import a s = "\xc2\xb5" -""" - ) as dtmp: +""") as dtmp: runner = CliRunner() with chdir(dtmp): result = runner.invoke(main, ["diff", "."]) @@ -324,16 +312,12 @@ def test_format_utf8(self) -> None: def test_format_latin_1(self) -> None: # the string is "µ" as in "µsort" - with sample_contents( - b"""\ + with sample_contents(b"""\ # -*- coding: latin-1 -*- import b import a s = "\xb5" -""".replace( - b"\r", b"" - ) # git on windows might make \r\n - ) as dtmp: +""".replace(b"\r", b"")) as dtmp: # git on windows might make \r\n runner = CliRunner() # Diff output is unicode @@ -351,9 +335,7 @@ def test_format_latin_1(self) -> None: import b -import a s = "\u00b5" -""".replace( - "\r", "" - ), # git on windows again +""".replace("\r", ""), # git on windows again result.output, ) @@ -367,8 +349,6 @@ def test_format_latin_1(self) -> None: import a import b s = "\xb5" -""".replace( - b"\r", b"" - ), # git on windows again +""".replace(b"\r", b""), # git on windows again (Path(dtmp) / "sample.py").read_bytes(), ) diff --git a/usort/tests/config.py b/usort/tests/config.py index 9bbf241..6969bb6 100644 --- a/usort/tests/config.py +++ b/usort/tests/config.py @@ -17,24 +17,20 @@ def test_third_party(self) -> None: # Defaults should not know about this module. # This is a silly value for default_category but this makes it more # obvious when it's in use. - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort] default_category = "future" -""" - ) +""") conf = Config.find(Path(d)) self.assertNotIn("psutil", conf.known) self.assertEqual(CAT_FUTURE, conf.category("psutil.cpu_times")) # "legacy" naming - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort] default_category = "future" known_third_party = ["psutil", "cocoa"] -""" - ) +""") conf = Config.find(Path(d)) self.assertEqual(CAT_THIRD_PARTY, conf.known["cocoa"]) @@ -48,14 +44,12 @@ def test_third_party(self) -> None: self.assertEqual(CAT_THIRD_PARTY, conf.category("psutil.cpu_times")) # New naming - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort] default_category = "future" [tool.usort.known] third_party = ["psutil", "cocoa"] -""" - ) +""") new_conf = Config.find(Path(d)) self.assertEqual(conf, new_conf) @@ -88,37 +82,31 @@ def test_first_party_root_finding_disable(self) -> None: conf = Config.find(f) self.assertEqual(CAT_FIRST_PARTY, conf.known["b"]) - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort] first_party_detection = false -""" - ) +""") conf = Config.find(f) self.assertNotIn("b", conf.known) def test_new_category_names(self) -> None: with tempfile.TemporaryDirectory() as d: - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort] categories = ["future", "standard_library", "numpy", "third_party", "first_party"] [tool.usort.known] numpy = ["numpy", "pandas"] -""" - ) +""") conf = Config.find(Path(d) / "sample.py") self.assertEqual("numpy", conf.known["pandas"]) def test_new_category_names_invalid(self) -> None: with tempfile.TemporaryDirectory() as d: - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort.known] foo = ["numpy", "pandas"] -""" - ) +""") with self.assertRaisesRegex(ValueError, "Known set for foo"): Config.find(Path(d) / "sample.py") @@ -183,12 +171,10 @@ def test_config_magic_commas(self) -> None: self.assertFalse(conf.magic_commas) with self.subTest("enabled"): - (d_path / "foo" / "pyproject.toml").write_text( - """\ + (d_path / "foo" / "pyproject.toml").write_text("""\ [tool.usort] magic_commas = true -""" - ) +""") conf = Config.find(d_path / "foo" / "bar.py") self.assertTrue(conf.magic_commas) @@ -204,12 +190,10 @@ def test_config_merge_imports(self) -> None: self.assertTrue(conf.merge_imports) with self.subTest("disabled"): - (d_path / "foo" / "pyproject.toml").write_text( - """\ + (d_path / "foo" / "pyproject.toml").write_text("""\ [tool.usort] merge_imports = false -""" - ) +""") conf = Config.find(d_path / "foo" / "bar.py") self.assertFalse(conf.merge_imports) @@ -225,15 +209,13 @@ def test_config_excludes(self) -> None: self.assertEqual([], conf.excludes) with self.subTest("with black config"): - (d_path / "foo" / "pyproject.toml").write_text( - """\ + (d_path / "foo" / "pyproject.toml").write_text("""\ [tool.usort] excludes = [ "fixtures/", "*generated.py", ] -""" - ) +""") conf = Config.find(d_path / "foo" / "bar.py") expected = ["fixtures/", "*generated.py"] self.assertEqual(expected, conf.excludes) @@ -250,12 +232,10 @@ def test_black_line_length(self) -> None: self.assertEqual(Config.line_length, conf.line_length) with self.subTest("with black config"): - (d_path / "foo" / "pyproject.toml").write_text( - """\ + (d_path / "foo" / "pyproject.toml").write_text("""\ [tool.black] line-length = 120 -""" - ) +""") conf = Config.find(d_path / "foo" / "bar.py") self.assertEqual(120, conf.line_length) @@ -267,12 +247,10 @@ def test_config_parent_walk(self) -> None: (d_path / "a" / "__init__.py").write_text("") (d_path / "b").mkdir(parents=True) - (d_path / "b" / "pyproject.toml").write_text( - """\ + (d_path / "b" / "pyproject.toml").write_text("""\ [tool.usort.known] first_party = ["x"] -""" - ) +""") (d_path / "b" / "c").mkdir(parents=True) (d_path / "b" / "c" / "d").symlink_to(d_path / "a") diff --git a/usort/tests/functional.py b/usort/tests/functional.py index 351aedc..ccb5f3c 100644 --- a/usort/tests/functional.py +++ b/usort/tests/functional.py @@ -228,14 +228,12 @@ def test_dot_handling(self) -> None: def test_customized_sections(self) -> None: with tempfile.TemporaryDirectory() as d: - (Path(d) / "pyproject.toml").write_text( - """\ + (Path(d) / "pyproject.toml").write_text("""\ [tool.usort] categories = ["future", "standard_library", "numpy", "third_party", "first_party"] [tool.usort.known] numpy = ["numpy", "pandas"] -""" - ) +""") sample = Path(d) / "sample.py" conf = Config.find(sample) self.assertUsortResult( @@ -1038,15 +1036,13 @@ def test_excludes(self) -> None: sorted_content = b"import asyncio\nimport os\n" with tempfile.TemporaryDirectory() as td: tdp = Path(td).resolve() - (tdp / "pyproject.toml").write_text( - """\ + (tdp / "pyproject.toml").write_text("""\ [tool.usort] excludes = [ "fixtures/", "*generated.py", ] -""" - ) +""") (tdp / "foo" / "tests" / "fixtures").mkdir(parents=True) excluded_paths = ( diff --git a/usort/tests/sorting.py b/usort/tests/sorting.py index 182169a..2b2b7ea 100644 --- a/usort/tests/sorting.py +++ b/usort/tests/sorting.py @@ -14,14 +14,12 @@ class SplitTest(unittest.TestCase): def test_split_block(self) -> None: - mod = cst.parse_module( - b"""\ + mod = cst.parse_module(b"""\ from a import x from b import y from b import y from c import x -""" - ) +""") x = ImportSorter(module=mod, path=Path(), config=Config()) blocks = x.sortable_blocks(mod.children) # type: ignore self.assertEqual(2, len(blocks)) diff --git a/usort/tests/types.py b/usort/tests/types.py index 0b6a76f..048befc 100644 --- a/usort/tests/types.py +++ b/usort/tests/types.py @@ -266,8 +266,7 @@ def test_sortable_block_repr(self) -> None: ], ) - expected_repr = dedent( - """ + expected_repr = dedent(""" SortableBlock( start_idx = 0, end_idx = 2, @@ -294,6 +293,5 @@ def test_sortable_block_repr(self) -> None: ], imported_names = {}, ) - """ - ).strip() + """).strip() self.assertEqual(expected_repr, repr(imp)) diff --git a/usort/translate.py b/usort/translate.py index 6e4eeea..892e8f4 100644 --- a/usort/translate.py +++ b/usort/translate.py @@ -212,8 +212,13 @@ def import_from_node(node: cst.SimpleStatementLine, config: Config) -> SortableI # If preserving inline comments and this is a single-line import with # one item, move first_inline comments to the item's inline comments - if (config.preserve_inline_comments and is_single_line and - single_item_count == 1 and idx == 0 and comments.first_inline): + if ( + config.preserve_inline_comments + and is_single_line + and single_item_count == 1 + and idx == 0 + and comments.first_inline + ): items[-1].comments.inline.extend(comments.first_inline) comments.first_inline.clear() diff --git a/usort/types.py b/usort/types.py index c564a7e..bb47ff8 100644 --- a/usort/types.py +++ b/usort/types.py @@ -146,8 +146,7 @@ class SortableImport: def __repr__(self) -> str: items = indent(("\n".join(f"{item!r}," for item in self.items)), " ") return ( - dedent( - """ + dedent(""" SortableImport( # sort_key = {sort_key!r}, stem = {stem!r}, @@ -157,8 +156,7 @@ def __repr__(self) -> str: comments = {comments!r}, indent = {indent!r}, ) - """ - ) + """) .strip() .format( sort_key=self.sort_key, @@ -263,8 +261,7 @@ class SortableBlock: def __repr__(self) -> str: imports = indent("\n".join(f"{imp!r}," for imp in self.imports), " ") return ( - dedent( - """ + dedent(""" SortableBlock( start_idx = {start_idx!r}, end_idx = {end_idx!r}, @@ -273,8 +270,7 @@ def __repr__(self) -> str: ], imported_names = {imported_names!r}, ) - """ - ) + """) .strip() .format( start_idx=self.start_idx, From 07cdbd6440bd989b0d0d309d5cad32310863127d Mon Sep 17 00:00:00 2001 From: Maggie Moss Date: Mon, 5 Jan 2026 11:18:04 -0800 Subject: [PATCH 5/6] Revert "Fix docs" This reverts commit a562b5400bccce908573b54a0ce8050d0dd28332. --- docs/guide.rst | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/docs/guide.rst b/docs/guide.rst index e53549c..636ecee 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -573,23 +573,16 @@ The following options are valid for the main ``tool.usort`` table: type checker annotations or linter suppressions that are specific to individual imports:: - # Original Code - from example._C import _linalg # pyrefly: ignore [missing-attribute] - from example._C import _LinAlgError as LinAlgError # pyrefly: ignore - from example._C import _add_docstr - - # Without preserving inline comments - from example._C import ( # pyrefly: ignore [missing-attribute] - _add_docstr, - _linealg, - _LineAlgError as LinAlgError, # pyrefly: ignore - ) + # Before + from torch._C import _linalg # pyrefly: + from torch._C import _LinAlgError as LinAlgError # pyrefly: ignore + from torch._C import _add_docstr # After (preserve_inline_comments = true) - from example._C import ( + from torch._C import ( _add_docstr, - _linealg, # pyrefly: ignore [missing-attribute] - _LineAlgError as LineAlgError, # pyrefly: ignore + _linalg, # pyrefly: + _LinAlgError as LinAlgError, # pyrefly: ignore ) Note that this option only affects inline comments on single-line imports. From 13d7daddb2acac20e9d5b7f79ed5c809cf058f5e Mon Sep 17 00:00:00 2001 From: Maggie Moss Date: Mon, 5 Jan 2026 13:04:19 -0800 Subject: [PATCH 6/6] Fix formatting, again. --- usort/tests/cli.py | 50 ++++++++++++++++++++--------- usort/tests/config.py | 66 ++++++++++++++++++++++++++------------- usort/tests/functional.py | 12 ++++--- usort/tests/sorting.py | 6 ++-- usort/tests/types.py | 6 ++-- usort/types.py | 12 ++++--- 6 files changed, 103 insertions(+), 49 deletions(-) diff --git a/usort/tests/cli.py b/usort/tests/cli.py index cc79601..c99dd1f 100644 --- a/usort/tests/cli.py +++ b/usort/tests/cli.py @@ -50,12 +50,14 @@ def test_benchmark(self) -> None: self.assertRegex( result.output, - dedent(r""" + dedent( + r""" walking \.:\s+\d+ µs parsing sample\.py:\s+\d+ µs sorting sample\.py:\s+\d+ µs total:\s+\d+ µs - """).strip(), + """ + ).strip(), ) self.assertEqual(0, result.exit_code) @@ -70,26 +72,32 @@ def test_benchmark_multiple(self) -> None: self.assertRegex( result.output, - dedent(r""" + dedent( + r""" parsing foo\.py:\s+\d+ µs sorting foo\.py:\s+\d+ µs - """).strip(), + """ + ).strip(), ) self.assertRegex( result.output, - dedent(r""" + dedent( + r""" parsing sample\.py:\s+\d+ µs sorting sample\.py:\s+\d+ µs - """).strip(), + """ + ).strip(), ) self.assertRegex( result.output, - dedent(r""" + dedent( + r""" walking \.:\s+\d+ µs total:\s+\d+ µs - """).strip(), + """ + ).strip(), ) self.assertEqual(0, result.exit_code) @@ -170,7 +178,9 @@ def test_diff_with_change(self) -> None: +import os import sys -import os -""".replace("\r", ""), +""".replace( + "\r", "" + ), result.output, ) @@ -274,11 +284,13 @@ def test_format_with_change(self) -> None: def test_format_utf8(self) -> None: # the string is "µ" as in "µsort" - with sample_contents(b"""\ + with sample_contents( + b"""\ import b import a s = "\xc2\xb5" -""") as dtmp: +""" + ) as dtmp: runner = CliRunner() with chdir(dtmp): result = runner.invoke(main, ["diff", "."]) @@ -312,12 +324,16 @@ def test_format_utf8(self) -> None: def test_format_latin_1(self) -> None: # the string is "µ" as in "µsort" - with sample_contents(b"""\ + with sample_contents( + b"""\ # -*- coding: latin-1 -*- import b import a s = "\xb5" -""".replace(b"\r", b"")) as dtmp: # git on windows might make \r\n +""".replace( + b"\r", b"" + ) + ) as dtmp: # git on windows might make \r\n runner = CliRunner() # Diff output is unicode @@ -335,7 +351,9 @@ def test_format_latin_1(self) -> None: import b -import a s = "\u00b5" -""".replace("\r", ""), # git on windows again +""".replace( + "\r", "" + ), # git on windows again result.output, ) @@ -349,6 +367,8 @@ def test_format_latin_1(self) -> None: import a import b s = "\xb5" -""".replace(b"\r", b""), # git on windows again +""".replace( + b"\r", b"" + ), # git on windows again (Path(dtmp) / "sample.py").read_bytes(), ) diff --git a/usort/tests/config.py b/usort/tests/config.py index 6969bb6..9bbf241 100644 --- a/usort/tests/config.py +++ b/usort/tests/config.py @@ -17,20 +17,24 @@ def test_third_party(self) -> None: # Defaults should not know about this module. # This is a silly value for default_category but this makes it more # obvious when it's in use. - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort] default_category = "future" -""") +""" + ) conf = Config.find(Path(d)) self.assertNotIn("psutil", conf.known) self.assertEqual(CAT_FUTURE, conf.category("psutil.cpu_times")) # "legacy" naming - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort] default_category = "future" known_third_party = ["psutil", "cocoa"] -""") +""" + ) conf = Config.find(Path(d)) self.assertEqual(CAT_THIRD_PARTY, conf.known["cocoa"]) @@ -44,12 +48,14 @@ def test_third_party(self) -> None: self.assertEqual(CAT_THIRD_PARTY, conf.category("psutil.cpu_times")) # New naming - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort] default_category = "future" [tool.usort.known] third_party = ["psutil", "cocoa"] -""") +""" + ) new_conf = Config.find(Path(d)) self.assertEqual(conf, new_conf) @@ -82,31 +88,37 @@ def test_first_party_root_finding_disable(self) -> None: conf = Config.find(f) self.assertEqual(CAT_FIRST_PARTY, conf.known["b"]) - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort] first_party_detection = false -""") +""" + ) conf = Config.find(f) self.assertNotIn("b", conf.known) def test_new_category_names(self) -> None: with tempfile.TemporaryDirectory() as d: - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort] categories = ["future", "standard_library", "numpy", "third_party", "first_party"] [tool.usort.known] numpy = ["numpy", "pandas"] -""") +""" + ) conf = Config.find(Path(d) / "sample.py") self.assertEqual("numpy", conf.known["pandas"]) def test_new_category_names_invalid(self) -> None: with tempfile.TemporaryDirectory() as d: - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort.known] foo = ["numpy", "pandas"] -""") +""" + ) with self.assertRaisesRegex(ValueError, "Known set for foo"): Config.find(Path(d) / "sample.py") @@ -171,10 +183,12 @@ def test_config_magic_commas(self) -> None: self.assertFalse(conf.magic_commas) with self.subTest("enabled"): - (d_path / "foo" / "pyproject.toml").write_text("""\ + (d_path / "foo" / "pyproject.toml").write_text( + """\ [tool.usort] magic_commas = true -""") +""" + ) conf = Config.find(d_path / "foo" / "bar.py") self.assertTrue(conf.magic_commas) @@ -190,10 +204,12 @@ def test_config_merge_imports(self) -> None: self.assertTrue(conf.merge_imports) with self.subTest("disabled"): - (d_path / "foo" / "pyproject.toml").write_text("""\ + (d_path / "foo" / "pyproject.toml").write_text( + """\ [tool.usort] merge_imports = false -""") +""" + ) conf = Config.find(d_path / "foo" / "bar.py") self.assertFalse(conf.merge_imports) @@ -209,13 +225,15 @@ def test_config_excludes(self) -> None: self.assertEqual([], conf.excludes) with self.subTest("with black config"): - (d_path / "foo" / "pyproject.toml").write_text("""\ + (d_path / "foo" / "pyproject.toml").write_text( + """\ [tool.usort] excludes = [ "fixtures/", "*generated.py", ] -""") +""" + ) conf = Config.find(d_path / "foo" / "bar.py") expected = ["fixtures/", "*generated.py"] self.assertEqual(expected, conf.excludes) @@ -232,10 +250,12 @@ def test_black_line_length(self) -> None: self.assertEqual(Config.line_length, conf.line_length) with self.subTest("with black config"): - (d_path / "foo" / "pyproject.toml").write_text("""\ + (d_path / "foo" / "pyproject.toml").write_text( + """\ [tool.black] line-length = 120 -""") +""" + ) conf = Config.find(d_path / "foo" / "bar.py") self.assertEqual(120, conf.line_length) @@ -247,10 +267,12 @@ def test_config_parent_walk(self) -> None: (d_path / "a" / "__init__.py").write_text("") (d_path / "b").mkdir(parents=True) - (d_path / "b" / "pyproject.toml").write_text("""\ + (d_path / "b" / "pyproject.toml").write_text( + """\ [tool.usort.known] first_party = ["x"] -""") +""" + ) (d_path / "b" / "c").mkdir(parents=True) (d_path / "b" / "c" / "d").symlink_to(d_path / "a") diff --git a/usort/tests/functional.py b/usort/tests/functional.py index ccb5f3c..351aedc 100644 --- a/usort/tests/functional.py +++ b/usort/tests/functional.py @@ -228,12 +228,14 @@ def test_dot_handling(self) -> None: def test_customized_sections(self) -> None: with tempfile.TemporaryDirectory() as d: - (Path(d) / "pyproject.toml").write_text("""\ + (Path(d) / "pyproject.toml").write_text( + """\ [tool.usort] categories = ["future", "standard_library", "numpy", "third_party", "first_party"] [tool.usort.known] numpy = ["numpy", "pandas"] -""") +""" + ) sample = Path(d) / "sample.py" conf = Config.find(sample) self.assertUsortResult( @@ -1036,13 +1038,15 @@ def test_excludes(self) -> None: sorted_content = b"import asyncio\nimport os\n" with tempfile.TemporaryDirectory() as td: tdp = Path(td).resolve() - (tdp / "pyproject.toml").write_text("""\ + (tdp / "pyproject.toml").write_text( + """\ [tool.usort] excludes = [ "fixtures/", "*generated.py", ] -""") +""" + ) (tdp / "foo" / "tests" / "fixtures").mkdir(parents=True) excluded_paths = ( diff --git a/usort/tests/sorting.py b/usort/tests/sorting.py index 2b2b7ea..182169a 100644 --- a/usort/tests/sorting.py +++ b/usort/tests/sorting.py @@ -14,12 +14,14 @@ class SplitTest(unittest.TestCase): def test_split_block(self) -> None: - mod = cst.parse_module(b"""\ + mod = cst.parse_module( + b"""\ from a import x from b import y from b import y from c import x -""") +""" + ) x = ImportSorter(module=mod, path=Path(), config=Config()) blocks = x.sortable_blocks(mod.children) # type: ignore self.assertEqual(2, len(blocks)) diff --git a/usort/tests/types.py b/usort/tests/types.py index 048befc..0b6a76f 100644 --- a/usort/tests/types.py +++ b/usort/tests/types.py @@ -266,7 +266,8 @@ def test_sortable_block_repr(self) -> None: ], ) - expected_repr = dedent(""" + expected_repr = dedent( + """ SortableBlock( start_idx = 0, end_idx = 2, @@ -293,5 +294,6 @@ def test_sortable_block_repr(self) -> None: ], imported_names = {}, ) - """).strip() + """ + ).strip() self.assertEqual(expected_repr, repr(imp)) diff --git a/usort/types.py b/usort/types.py index bb47ff8..c564a7e 100644 --- a/usort/types.py +++ b/usort/types.py @@ -146,7 +146,8 @@ class SortableImport: def __repr__(self) -> str: items = indent(("\n".join(f"{item!r}," for item in self.items)), " ") return ( - dedent(""" + dedent( + """ SortableImport( # sort_key = {sort_key!r}, stem = {stem!r}, @@ -156,7 +157,8 @@ def __repr__(self) -> str: comments = {comments!r}, indent = {indent!r}, ) - """) + """ + ) .strip() .format( sort_key=self.sort_key, @@ -261,7 +263,8 @@ class SortableBlock: def __repr__(self) -> str: imports = indent("\n".join(f"{imp!r}," for imp in self.imports), " ") return ( - dedent(""" + dedent( + """ SortableBlock( start_idx = {start_idx!r}, end_idx = {end_idx!r}, @@ -270,7 +273,8 @@ def __repr__(self) -> str: ], imported_names = {imported_names!r}, ) - """) + """ + ) .strip() .format( start_idx=self.start_idx,