Skip to content

Commit

Permalink
Merge pull request #183 from superDross/feat/ignore-fmt-skip
Browse files Browse the repository at this point in the history
Ignore fmt skip comments
  • Loading branch information
lyz-code committed Jan 25, 2022
2 parents 83e750b + a065cd1 commit d80f91c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/index.md
Expand Up @@ -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
Expand Down
16 changes: 12 additions & 4 deletions src/autoimport/model.py
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_services.py
Expand Up @@ -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
Expand Down

0 comments on commit d80f91c

Please sign in to comment.