diff --git a/README.md b/README.md index c3fc86b..2efb949 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/autoflake.py b/autoflake.py index 13e3136..8f5dbf3 100755 --- a/autoflake.py +++ b/autoflake.py @@ -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.""" @@ -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 diff --git a/test_autoflake.py b/test_autoflake.py index 9971639..203d5e9 100755 --- a/test_autoflake.py +++ b/test_autoflake.py @@ -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( """\