diff --git a/docs/index.md b/docs/index.md index 1badc4b..a871636 100644 --- a/docs/index.md +++ b/docs/index.md @@ -135,7 +135,7 @@ While we fix it you can write the import statement wherever you are in the file and the next time you run `autoimport` it will get moved to the top. If you don't want a specific line to go to the top, add the `# noqa: autoimport` -at the end. For example: +or `# fmt: skip` at the end. For example: ```python a = 1 diff --git a/src/autoimport/model.py b/src/autoimport/model.py index 05ddbeb..cf79fd0 100644 --- a/src/autoimport/model.py +++ b/src/autoimport/model.py @@ -204,6 +204,16 @@ def _join_code(self) -> str: return source_code + @staticmethod + def _should_ignore_line(line: str) -> bool: + """Determine whether a line should be ignored by autoimport or not.""" + return any( + [ + re.match(r".*?# ?fmt:.*?skip.*", line), + re.match(r".*?# ?noqa:.*?autoimport.*", line), + ] + ) + def _move_imports_to_top(self) -> None: """Fix python source code to move import statements to the top of the file. @@ -228,8 +238,7 @@ def _move_imports_to_top(self) -> None: and not multiline_string and re.match(r"^\s*(?:from .*)?import .[^\'\"]*$", line) ) or multiline_import: - # Ignore the lines containing # noqa: autoimport - if re.match(r".*?# ?noqa:.*?autoimport.*", line): + if self._should_ignore_line(line): continue # process lines using separation markers @@ -418,8 +427,7 @@ def _remove_unused_imports(self, import_name: str) -> None: object_name = import_name.split(".")[-1] for line in self.imports: - # Ignore the lines containing # noqa: autoimport - if re.match(r".*?# ?noqa:.*?autoimport.*", line): + if self._should_ignore_line(line): continue # If it's the only line, remove it diff --git a/tests/unit/test_services.py b/tests/unit/test_services.py index bb558a7..995f8e3 100644 --- a/tests/unit/test_services.py +++ b/tests/unit/test_services.py @@ -503,6 +503,21 @@ def test_fix_doesnt_fail_on_noqa_lines_on_unused_import() -> None: assert result == source +def test_fix_respects_fmt_skip_lines() -> None: + """Ignore lines that have # fmt: skip.""" + source = dedent( + """ + def why(): + import pdb;pdb.set_trace() # fmt: skip + return 'dunno' + """ + ).replace("\n", "", 1) + + result = fix_code(source) + + assert result == source + + def test_fix_respects_noqa_in_from_import_lines_in_multiple_lines() -> None: """ Given: Multiple from X import Y lines, some with multiline format with noqa