Skip to content

Commit

Permalink
Add support of ignore comment on the top of the file
Browse files Browse the repository at this point in the history
  • Loading branch information
bp72 committed Feb 17, 2024
1 parent 23cfe6f commit ba134f9
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
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
5 changes: 5 additions & 0 deletions autoflake.py
Expand Up @@ -63,6 +63,8 @@

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 +906,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
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

0 comments on commit ba134f9

Please sign in to comment.