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 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
5 changes: 5 additions & 0 deletions README.md
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
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
43 changes: 43 additions & 0 deletions test_autoflake.py
Expand Up @@ -2008,6 +2008,49 @@ 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