Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore fmt skip comments #183

Merged
merged 1 commit into from Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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