Skip to content

Commit

Permalink
Add support of ignore comment on the top of the file (#291)
Browse files Browse the repository at this point in the history
* Add support of ignore comment on the top of the file

* test_autoflake: add some empty lines to make test more realistic

---------

Co-authored-by: francisco souza <108725+fsouza@users.noreply.github.com>
  • Loading branch information
bp72 and fsouza committed Feb 19, 2024
1 parent 23cfe6f commit d90f8f4
Show file tree
Hide file tree
Showing 3 changed files with 56 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
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

0 comments on commit d90f8f4

Please sign in to comment.