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

Add support of ignore comment on the top of the file #291

Merged
merged 2 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ options:
-s, --stdout print changed text to stdout. defaults to true when formatting stdin, or to false otherwise
```

To ignore the file, you can also add a comment to the top of the file:
```python
# autoflake: skip_file
import os
```

## Configuration

Expand Down
8 changes: 8 additions & 0 deletions autoflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@

MAX_PYTHON_FILE_DETECTION_BYTES = 1024

IGNORE_COMMENT_REGEX = re.compile(
r"\s*#\s{1,}autoflake:\s{1,}\bskip_file\b",
re.MULTILINE,
)


def standard_paths() -> Iterable[str]:
"""Yield paths to standard modules."""
Expand Down Expand Up @@ -904,6 +909,9 @@ def fix_code(
if not source:
return source

if IGNORE_COMMENT_REGEX.search(source):
return source

# pyflakes does not handle "nonlocal" correctly.
if "nonlocal" in source:
remove_unused_variables = False
Expand Down
41 changes: 41 additions & 0 deletions test_autoflake.py
Original file line number Diff line number Diff line change
Expand Up @@ -2008,6 +2008,47 @@ class SystemTests(unittest.TestCase):

"""System tests."""

def test_skip_file(self) -> None:
skipped_file_file_text = """
# autoflake: skip_file
import re
import os
import my_own_module
x = 1
"""
with temporary_file(skipped_file_file_text) as filename:
output_file = io.StringIO()
autoflake._main(
argv=["my_fake_program", filename, "--stdout"],
standard_out=output_file,
standard_error=None,
)
self.assertEqual(
skipped_file_file_text,
output_file.getvalue(),
)

def test_skip_file_with_shebang_respect(self) -> None:
skipped_file_file_text = """
#!/usr/bin/env python3
# autoflake: skip_file
import re
import os
import my_own_module
x = 1
"""
with temporary_file(skipped_file_file_text) as filename:
output_file = io.StringIO()
autoflake._main(
argv=["my_fake_program", filename, "--stdout"],
standard_out=output_file,
standard_error=None,
)
self.assertEqual(
skipped_file_file_text,
output_file.getvalue(),
)

def test_diff(self) -> None:
with temporary_file(
"""\
Expand Down