| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
"""Removes unused imports and unused variables as reported by pyflakes.""" |
| 23 |
|
| 24 |
from __future__ import annotations |
| 25 |
|
| 26 |
import ast |
| 27 |
import collections |
| 28 |
import difflib |
| 29 |
import fnmatch |
| 30 |
import io |
| 31 |
import logging |
| 32 |
import os |
| 33 |
import pathlib |
| 34 |
import re |
| 35 |
import signal |
| 36 |
import string |
| 37 |
import sys |
| 38 |
import sysconfig |
| 39 |
import tokenize |
| 40 |
from collections.abc import Callable |
| 41 |
from collections.abc import Iterable |
| 42 |
from collections.abc import Mapping |
| 43 |
from collections.abc import MutableMapping |
| 44 |
from collections.abc import Sequence |
| 45 |
from typing import Any |
| 46 |
from typing import cast |
| 47 |
from typing import IO |
| 48 |
|
| 49 |
import pyflakes.api |
| 50 |
import pyflakes.messages |
| 51 |
import pyflakes.reporter |
| 52 |
|
| 53 |
__version__ = "2.4.0" |
| 54 |
|
| 55 |
|
| 56 |
_LOGGER = logging.getLogger("autoflake") |
| 57 |
_LOGGER.propagate = False |
| 58 |
|
| 59 |
ATOMS = frozenset([tokenize.NAME, tokenize.NUMBER, tokenize.STRING]) |
| 60 |
|
| 61 |
EXCEPT_REGEX = re.compile(r"^\s*except [\s,()\w]+ as \w+:$") |
| 62 |
PYTHON_SHEBANG_REGEX = re.compile(r"^#!.*\bpython[3]?\b\s*$") |
| 63 |
|
| 64 |
MAX_PYTHON_FILE_DETECTION_BYTES = 1024 |
| 65 |
|
| 66 |
IGNORE_COMMENT_REGEX = re.compile( |
| 67 |
r"\s*#\s{1,}autoflake:\s{1,}\bskip_file\b", |
| 68 |
re.MULTILINE, |
| 69 |
) |
| 70 |
|
| 71 |
|
| 72 |
def standard_paths() -> Iterable[str]: |
| 73 |
"""Yield paths to standard modules.""" |
| 74 |
paths = sysconfig.get_paths() |
| 75 |
path_names = ("stdlib", "platstdlib") |
| 76 |
for path_name in path_names: |
| 77 |
|
| 78 |
if path_name in paths: |
| 79 |
path = paths[path_name] |
| 80 |
if os.path.isdir(path): |
| 81 |
yield from os.listdir(path) |
| 82 |
|
| 83 |
|
| 84 |
dynload_path = os.path.join(path, "lib-dynload") |
| 85 |
if os.path.isdir(dynload_path): |
| 86 |
yield from os.listdir(dynload_path) |
| 87 |
|
| 88 |
|
| 89 |
def standard_package_names() -> Iterable[str]: |
| 90 |
"""Yield standard module names.""" |
| 91 |
for name in standard_paths(): |
| 92 |
if name.startswith("_") or "-" in name: |
| 93 |
continue |
| 94 |
|
| 95 |
if "." in name and not name.endswith(("so", "py", "pyc")): |
| 96 |
continue |
| 97 |
|
| 98 |
yield name.split(".")[0] |
| 99 |
|
| 100 |
|
| 101 |
IMPORTS_WITH_SIDE_EFFECTS = {"antigravity", "rlcompleter", "this"} |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
BINARY_IMPORTS = { |
| 111 |
"datetime", |
| 112 |
"grp", |
| 113 |
"io", |
| 114 |
"json", |
| 115 |
"math", |
| 116 |
"multiprocessing", |
| 117 |
"parser", |
| 118 |
"pwd", |
| 119 |
"string", |
| 120 |
"operator", |
| 121 |
"os", |
| 122 |
"sys", |
| 123 |
"time", |
| 124 |
} | set(sys.builtin_module_names) |
| 125 |
|
| 126 |
SAFE_IMPORTS = ( |
| 127 |
frozenset(standard_package_names()) - IMPORTS_WITH_SIDE_EFFECTS | BINARY_IMPORTS |
| 128 |
) |
| 129 |
|
| 130 |
|
| 131 |
def unused_import_line_numbers( |
| 132 |
messages: Iterable[pyflakes.messages.Message], |
| 133 |
) -> Iterable[int]: |
| 134 |
"""Yield line numbers of unused imports.""" |
| 135 |
for message in messages: |
| 136 |
if isinstance(message, pyflakes.messages.UnusedImport): |
| 137 |
yield message.lineno |
| 138 |
|
| 139 |
|
| 140 |
def unused_import_module_name( |
| 141 |
messages: Iterable[pyflakes.messages.Message], |
| 142 |
) -> Iterable[tuple[int, str]]: |
| 143 |
"""Yield line number and module name of unused imports.""" |
| 144 |
pattern = re.compile(r"\'(.+?)\'") |
| 145 |
for message in messages: |
| 146 |
if isinstance(message, pyflakes.messages.UnusedImport): |
| 147 |
module_name = pattern.search(str(message)) |
| 148 |
if module_name: |
| 149 |
module_name = module_name.group()[1:-1] |
| 150 |
yield (message.lineno, module_name) |
| 151 |
|
| 152 |
|
| 153 |
def star_import_used_line_numbers( |
| 154 |
messages: Iterable[pyflakes.messages.Message], |
| 155 |
) -> Iterable[int]: |
| 156 |
"""Yield line number of star import usage.""" |
| 157 |
for message in messages: |
| 158 |
if isinstance(message, pyflakes.messages.ImportStarUsed): |
| 159 |
yield message.lineno |
| 160 |
|
| 161 |
|
| 162 |
def star_import_usage_undefined_name( |
| 163 |
messages: Iterable[pyflakes.messages.Message], |
| 164 |
) -> Iterable[tuple[int, str, str]]: |
| 165 |
"""Yield line number, undefined name, and its possible origin module.""" |
| 166 |
for message in messages: |
| 167 |
if isinstance(message, pyflakes.messages.ImportStarUsage): |
| 168 |
undefined_name = message.message_args[0] |
| 169 |
module_name = message.message_args[1] |
| 170 |
yield (message.lineno, undefined_name, module_name) |
| 171 |
|
| 172 |
|
| 173 |
def unused_variable_line_numbers( |
| 174 |
messages: Iterable[pyflakes.messages.Message], |
| 175 |
) -> Iterable[int]: |
| 176 |
"""Yield line numbers of unused variables.""" |
| 177 |
for message in messages: |
| 178 |
if isinstance(message, pyflakes.messages.UnusedVariable): |
| 179 |
yield message.lineno |
| 180 |
|
| 181 |
|
| 182 |
def _split_lines(source: str) -> list[str]: |
| 183 |
"""Split source into physical lines, keeping line endings. |
| 184 |
|
| 185 |
Unlike ``io.StringIO(source).readlines()``, honor the same line |
| 186 |
terminators as the tokenizer (``\r\n``, ``\r``, and ``\n``), so |
| 187 |
that enumerating the result stays consistent with the line numbers |
| 188 |
that pyflakes reports. A bare ``\r`` counts as a line terminator, |
| 189 |
while other characters ``str.splitlines()`` splits on (such as form |
| 190 |
feeds) do not. |
| 191 |
""" |
| 192 |
return re.findall(r"[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+", source) |
| 193 |
|
| 194 |
|
| 195 |
def duplicate_key_line_numbers( |
| 196 |
messages: Iterable[pyflakes.messages.Message], |
| 197 |
source: str, |
| 198 |
) -> Iterable[int]: |
| 199 |
"""Yield line numbers of duplicate keys.""" |
| 200 |
messages = [ |
| 201 |
message |
| 202 |
for message in messages |
| 203 |
if isinstance(message, pyflakes.messages.MultiValueRepeatedKeyLiteral) |
| 204 |
] |
| 205 |
|
| 206 |
if messages: |
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
key_to_messages = create_key_to_messages_dict(messages) |
| 211 |
|
| 212 |
lines = _split_lines(source) |
| 213 |
|
| 214 |
for key, messages in key_to_messages.items(): |
| 215 |
good = True |
| 216 |
for message in messages: |
| 217 |
line = lines[message.lineno - 1] |
| 218 |
key = message.message_args[0] |
| 219 |
|
| 220 |
if not dict_entry_has_key(line, key): |
| 221 |
good = False |
| 222 |
|
| 223 |
if good: |
| 224 |
for message in messages: |
| 225 |
yield message.lineno |
| 226 |
|
| 227 |
|
| 228 |
def create_key_to_messages_dict( |
| 229 |
messages: Iterable[pyflakes.messages.MultiValueRepeatedKeyLiteral], |
| 230 |
) -> Mapping[Any, Iterable[pyflakes.messages.MultiValueRepeatedKeyLiteral]]: |
| 231 |
"""Return dict mapping the key to list of messages.""" |
| 232 |
dictionary: dict[ |
| 233 |
Any, |
| 234 |
list[pyflakes.messages.MultiValueRepeatedKeyLiteral], |
| 235 |
] = collections.defaultdict(list) |
| 236 |
for message in messages: |
| 237 |
dictionary[message.message_args[0]].append(message) |
| 238 |
return dictionary |
| 239 |
|
| 240 |
|
| 241 |
def check(source: str) -> Iterable[pyflakes.messages.Message]: |
| 242 |
"""Return messages from pyflakes.""" |
| 243 |
reporter = ListReporter() |
| 244 |
try: |
| 245 |
pyflakes.api.check(source, filename="<string>", reporter=reporter) |
| 246 |
except (AttributeError, RecursionError, UnicodeDecodeError): |
| 247 |
pass |
| 248 |
return reporter.messages |
| 249 |
|
| 250 |
|
| 251 |
class StubFile: |
| 252 |
"""Stub out file for pyflakes.""" |
| 253 |
|
| 254 |
def write(self, *_: Any) -> None: |
| 255 |
"""Stub out.""" |
| 256 |
|
| 257 |
|
| 258 |
class ListReporter(pyflakes.reporter.Reporter): |
| 259 |
"""Accumulate messages in messages list.""" |
| 260 |
|
| 261 |
def __init__(self) -> None: |
| 262 |
"""Initialize. |
| 263 |
|
| 264 |
Ignore errors from Reporter. |
| 265 |
""" |
| 266 |
ignore = StubFile() |
| 267 |
pyflakes.reporter.Reporter.__init__(self, ignore, ignore) |
| 268 |
self.messages: list[pyflakes.messages.Message] = [] |
| 269 |
|
| 270 |
def flake(self, message: pyflakes.messages.Message) -> None: |
| 271 |
"""Accumulate messages.""" |
| 272 |
self.messages.append(message) |
| 273 |
|
| 274 |
|
| 275 |
def extract_package_name(line: str) -> str | None: |
| 276 |
"""Return package name in import statement.""" |
| 277 |
assert "\\" not in line |
| 278 |
assert "(" not in line |
| 279 |
assert ")" not in line |
| 280 |
assert ";" not in line |
| 281 |
|
| 282 |
if line.lstrip().startswith(("import", "from")): |
| 283 |
parts = line.split() |
| 284 |
if len(parts) < 2: |
| 285 |
return None |
| 286 |
word = parts[1] |
| 287 |
else: |
| 288 |
|
| 289 |
return None |
| 290 |
|
| 291 |
package = word.split(".")[0] |
| 292 |
assert " " not in package |
| 293 |
|
| 294 |
return package |
| 295 |
|
| 296 |
|
| 297 |
def multiline_import(line: str, previous_line: str = "") -> bool: |
| 298 |
"""Return True if import is spans multiples lines.""" |
| 299 |
for symbol in "()": |
| 300 |
if symbol in line: |
| 301 |
return True |
| 302 |
|
| 303 |
return multiline_statement(line, previous_line) |
| 304 |
|
| 305 |
|
| 306 |
def multiline_statement(line: str, previous_line: str = "") -> bool: |
| 307 |
"""Return True if this is part of a multiline statement.""" |
| 308 |
for symbol in "\\:;": |
| 309 |
if symbol in line: |
| 310 |
return True |
| 311 |
|
| 312 |
sio = io.StringIO(line) |
| 313 |
try: |
| 314 |
list(tokenize.generate_tokens(sio.readline)) |
| 315 |
return previous_line.rstrip().endswith("\\") |
| 316 |
except (SyntaxError, tokenize.TokenError): |
| 317 |
return True |
| 318 |
|
| 319 |
|
| 320 |
class PendingFix: |
| 321 |
"""Allows a rewrite operation to span multiple lines. |
| 322 |
|
| 323 |
In the main rewrite loop, every time a helper function returns a |
| 324 |
``PendingFix`` object instead of a string, this object will be called |
| 325 |
with the following line. |
| 326 |
""" |
| 327 |
|
| 328 |
def __init__(self, line: str) -> None: |
| 329 |
"""Analyse and store the first line.""" |
| 330 |
self.accumulator = collections.deque([line]) |
| 331 |
|
| 332 |
def __call__(self, line: str) -> PendingFix | str: |
| 333 |
"""Process line considering the accumulator. |
| 334 |
|
| 335 |
Return self to keep processing the following lines or a string |
| 336 |
with the final result of all the lines processed at once. |
| 337 |
""" |
| 338 |
raise NotImplementedError("Abstract method needs to be overwritten") |
| 339 |
|
| 340 |
|
| 341 |
def _valid_char_in_line(char: str, line: str) -> bool: |
| 342 |
"""Return True if a char appears in the line and is not commented.""" |
| 343 |
comment_index = line.find("#") |
| 344 |
char_index = line.find(char) |
| 345 |
valid_char_in_line = char_index >= 0 and ( |
| 346 |
comment_index > char_index or comment_index < 0 |
| 347 |
) |
| 348 |
return valid_char_in_line |
| 349 |
|
| 350 |
|
| 351 |
def _top_module(module_name: str) -> str: |
| 352 |
"""Return the name of the top level module in the hierarchy.""" |
| 353 |
if module_name[0] == ".": |
| 354 |
return "%LOCAL_MODULE%" |
| 355 |
return module_name.split(".")[0] |
| 356 |
|
| 357 |
|
| 358 |
def _modules_to_remove( |
| 359 |
unused_modules: Iterable[str], |
| 360 |
safe_to_remove: Iterable[str] = SAFE_IMPORTS, |
| 361 |
) -> Iterable[str]: |
| 362 |
"""Discard unused modules that are not safe to remove from the list.""" |
| 363 |
return [x for x in unused_modules if _top_module(x) in safe_to_remove] |
| 364 |
|
| 365 |
|
| 366 |
def _segment_module(segment: str) -> str: |
| 367 |
"""Extract the module identifier inside the segment. |
| 368 |
|
| 369 |
It might be the case the segment does not have a module (e.g. is composed |
| 370 |
just by a parenthesis or line continuation and whitespace). In this |
| 371 |
scenario we just keep the segment... These characters are not valid in |
| 372 |
identifiers, so they will never be contained in the list of unused modules |
| 373 |
anyway. |
| 374 |
""" |
| 375 |
return segment.strip(string.whitespace + ",\\()") or segment |
| 376 |
|
| 377 |
|
| 378 |
class FilterMultilineImport(PendingFix): |
| 379 |
"""Remove unused imports from multiline import statements. |
| 380 |
|
| 381 |
This class handles both the cases: "from imports" and "direct imports". |
| 382 |
|
| 383 |
Some limitations exist (e.g. imports with comments, lines joined by ``;``, |
| 384 |
etc). In these cases, the statement is left unchanged to avoid problems. |
| 385 |
""" |
| 386 |
|
| 387 |
IMPORT_RE = re.compile(r"\bimport\b\s*") |
| 388 |
INDENTATION_RE = re.compile(r"^\s*") |
| 389 |
BASE_RE = re.compile(r"\bfrom\s+([^ ]+)") |
| 390 |
SEGMENT_RE = re.compile( |
| 391 |
r"([^,\s]+(?:[\s\\]+as[\s\\]+[^,\s]+)?[,\s\\)]*)", |
| 392 |
re.M, |
| 393 |
) |
| 394 |
|
| 395 |
IDENTIFIER_RE = re.compile(r"[^,\s]+") |
| 396 |
|
| 397 |
def __init__( |
| 398 |
self, |
| 399 |
line: str, |
| 400 |
unused_module: Iterable[str] = (), |
| 401 |
remove_all_unused_imports: bool = False, |
| 402 |
safe_to_remove: Iterable[str] = SAFE_IMPORTS, |
| 403 |
previous_line: str = "", |
| 404 |
): |
| 405 |
"""Receive the same parameters as ``filter_unused_import``.""" |
| 406 |
self.remove: Iterable[str] = unused_module |
| 407 |
self.parenthesized: bool = "(" in line |
| 408 |
self.from_, imports = self.IMPORT_RE.split(line, maxsplit=1) |
| 409 |
match = self.BASE_RE.search(self.from_) |
| 410 |
self.base = match.group(1) if match else None |
| 411 |
self.give_up: bool = False |
| 412 |
|
| 413 |
if not remove_all_unused_imports: |
| 414 |
if self.base and _top_module(self.base) not in safe_to_remove: |
| 415 |
self.give_up = True |
| 416 |
else: |
| 417 |
self.remove = _modules_to_remove(self.remove, safe_to_remove) |
| 418 |
|
| 419 |
if "\\" in previous_line: |
| 420 |
|
| 421 |
self.give_up = True |
| 422 |
|
| 423 |
self.analyze(line) |
| 424 |
|
| 425 |
PendingFix.__init__(self, imports) |
| 426 |
|
| 427 |
def is_over(self, line: str | None = None) -> bool: |
| 428 |
"""Return True if the multiline import statement is over.""" |
| 429 |
line = line or self.accumulator[-1] |
| 430 |
|
| 431 |
if self.parenthesized: |
| 432 |
return _valid_char_in_line(")", line) |
| 433 |
|
| 434 |
return not _valid_char_in_line("\\", line) |
| 435 |
|
| 436 |
def analyze(self, line: str) -> None: |
| 437 |
"""Decide if the statement will be fixed or left unchanged.""" |
| 438 |
if any(ch in line for ch in ";:#"): |
| 439 |
self.give_up = True |
| 440 |
|
| 441 |
def fix(self, accumulated: Iterable[str]) -> str: |
| 442 |
"""Given a collection of accumulated lines, fix the entire import.""" |
| 443 |
old_imports = "".join(accumulated) |
| 444 |
ending = get_line_ending(old_imports) |
| 445 |
|
| 446 |
|
| 447 |
segments = [x for x in self.SEGMENT_RE.findall(old_imports) if x] |
| 448 |
modules = [_segment_module(x) for x in segments] |
| 449 |
keep = _filter_imports(modules, self.base, self.remove) |
| 450 |
|
| 451 |
|
| 452 |
if len(keep) == len(segments): |
| 453 |
return self.from_ + "import " + "".join(accumulated) |
| 454 |
|
| 455 |
fixed = "" |
| 456 |
if keep: |
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
templates = list(zip(modules, segments)) |
| 462 |
templates = templates[: len(keep) - 1] + templates[-1:] |
| 463 |
|
| 464 |
|
| 465 |
fixed = "".join( |
| 466 |
template.replace(module, keep[i]) |
| 467 |
for i, (module, template) in enumerate(templates) |
| 468 |
) |
| 469 |
|
| 470 |
|
| 471 |
if self.parenthesized and any(ch not in fixed for ch in "()"): |
| 472 |
fixed = fixed.strip(string.whitespace + "()") + ending |
| 473 |
|
| 474 |
|
| 475 |
empty = len(fixed.strip(string.whitespace + "\\(),")) < 1 |
| 476 |
if empty: |
| 477 |
match = self.INDENTATION_RE.search(self.from_) |
| 478 |
assert match is not None |
| 479 |
indentation = match.group(0) |
| 480 |
return indentation + "pass" + ending |
| 481 |
|
| 482 |
return self.from_ + "import " + fixed |
| 483 |
|
| 484 |
def __call__(self, line: str | None = None) -> PendingFix | str: |
| 485 |
"""Accumulate all the lines in the import and then trigger the fix.""" |
| 486 |
if line: |
| 487 |
self.accumulator.append(line) |
| 488 |
self.analyze(line) |
| 489 |
if not self.is_over(line): |
| 490 |
return self |
| 491 |
if self.give_up: |
| 492 |
return self.from_ + "import " + "".join(self.accumulator) |
| 493 |
|
| 494 |
return self.fix(self.accumulator) |
| 495 |
|
| 496 |
|
| 497 |
def _filter_imports( |
| 498 |
imports: Iterable[str], |
| 499 |
parent: str | None = None, |
| 500 |
unused_module: Iterable[str] = (), |
| 501 |
) -> Sequence[str]: |
| 502 |
|
| 503 |
|
| 504 |
sep = "" if parent and parent[-1] == "." else "." |
| 505 |
|
| 506 |
def full_name(name: str) -> str: |
| 507 |
return name if parent is None else parent + sep + name |
| 508 |
|
| 509 |
return [x for x in imports if full_name(x) not in unused_module] |
| 510 |
|
| 511 |
|
| 512 |
def filter_from_import(line: str, unused_module: Iterable[str]) -> str: |
| 513 |
"""Parse and filter ``from something import a, b, c``. |
| 514 |
|
| 515 |
Return line without unused import modules, or `pass` if all of the |
| 516 |
module in import is unused. |
| 517 |
""" |
| 518 |
indentation, imports = re.split( |
| 519 |
pattern=r"\bimport\b", |
| 520 |
string=line, |
| 521 |
maxsplit=1, |
| 522 |
) |
| 523 |
match = re.search( |
| 524 |
pattern=r"\bfrom\s+([^ ]+)", |
| 525 |
string=indentation, |
| 526 |
) |
| 527 |
assert match is not None |
| 528 |
base_module = match.group(1) |
| 529 |
|
| 530 |
imports = re.split(pattern=r"\s*,\s*", string=imports.strip()) |
| 531 |
filtered_imports = _filter_imports(imports, base_module, unused_module) |
| 532 |
|
| 533 |
|
| 534 |
if not filtered_imports: |
| 535 |
return get_indentation(line) + "pass" + get_line_ending(line) |
| 536 |
|
| 537 |
indentation += "import " |
| 538 |
|
| 539 |
return indentation + ", ".join(filtered_imports) + get_line_ending(line) |
| 540 |
|
| 541 |
|
| 542 |
def break_up_import(line: str) -> str: |
| 543 |
"""Return line with imports on separate lines.""" |
| 544 |
assert "\\" not in line |
| 545 |
assert "(" not in line |
| 546 |
assert ")" not in line |
| 547 |
assert ";" not in line |
| 548 |
assert "#" not in line |
| 549 |
assert not line.lstrip().startswith("from") |
| 550 |
|
| 551 |
newline = get_line_ending(line) |
| 552 |
if not newline: |
| 553 |
return line |
| 554 |
|
| 555 |
indentation, imports = re.split( |
| 556 |
pattern=r"\bimport\b", |
| 557 |
string=line, |
| 558 |
maxsplit=1, |
| 559 |
) |
| 560 |
|
| 561 |
indentation += "import " |
| 562 |
assert newline |
| 563 |
|
| 564 |
return "".join( |
| 565 |
[indentation + i.strip() + newline for i in imports.split(",")], |
| 566 |
) |
| 567 |
|
| 568 |
|
| 569 |
def filter_code( |
| 570 |
source: str, |
| 571 |
additional_imports: Iterable[str] | None = None, |
| 572 |
expand_star_imports: bool = False, |
| 573 |
remove_all_unused_imports: bool = False, |
| 574 |
remove_duplicate_keys: bool = False, |
| 575 |
remove_unused_variables: bool = False, |
| 576 |
remove_rhs_for_unused_variables: bool = False, |
| 577 |
ignore_init_module_imports: bool = False, |
| 578 |
) -> Iterable[str]: |
| 579 |
"""Yield code with unused imports removed.""" |
| 580 |
imports = SAFE_IMPORTS |
| 581 |
if additional_imports: |
| 582 |
imports |= frozenset(additional_imports) |
| 583 |
del additional_imports |
| 584 |
|
| 585 |
messages = check(source) |
| 586 |
|
| 587 |
if ignore_init_module_imports: |
| 588 |
marked_import_line_numbers: frozenset[int] = frozenset() |
| 589 |
else: |
| 590 |
marked_import_line_numbers = frozenset( |
| 591 |
unused_import_line_numbers(messages), |
| 592 |
) |
| 593 |
marked_unused_module: dict[int, list[str]] = collections.defaultdict(list) |
| 594 |
for line_number, module_name in unused_import_module_name(messages): |
| 595 |
marked_unused_module[line_number].append(module_name) |
| 596 |
|
| 597 |
undefined_names: list[str] = [] |
| 598 |
if expand_star_imports and not ( |
| 599 |
|
| 600 |
re.search(r"\b__all__\b", source) or re.search(r"\bdel\b", source) |
| 601 |
): |
| 602 |
marked_star_import_line_numbers = frozenset( |
| 603 |
star_import_used_line_numbers(messages), |
| 604 |
) |
| 605 |
if len(marked_star_import_line_numbers) > 1: |
| 606 |
|
| 607 |
marked_star_import_line_numbers = frozenset() |
| 608 |
else: |
| 609 |
for line_number, undefined_name, _ in star_import_usage_undefined_name( |
| 610 |
messages, |
| 611 |
): |
| 612 |
undefined_names.append(undefined_name) |
| 613 |
if not undefined_names: |
| 614 |
marked_star_import_line_numbers = frozenset() |
| 615 |
else: |
| 616 |
marked_star_import_line_numbers = frozenset() |
| 617 |
|
| 618 |
if remove_unused_variables: |
| 619 |
marked_variable_line_numbers = frozenset( |
| 620 |
unused_variable_line_numbers(messages), |
| 621 |
) |
| 622 |
else: |
| 623 |
marked_variable_line_numbers = frozenset() |
| 624 |
|
| 625 |
if remove_duplicate_keys: |
| 626 |
marked_key_line_numbers: frozenset[int] = frozenset( |
| 627 |
duplicate_key_line_numbers(messages, source), |
| 628 |
) |
| 629 |
else: |
| 630 |
marked_key_line_numbers = frozenset() |
| 631 |
|
| 632 |
line_messages = get_messages_by_line(messages) |
| 633 |
|
| 634 |
previous_line = "" |
| 635 |
result: str | PendingFix = "" |
| 636 |
for line_number, line in enumerate(_split_lines(source), start=1): |
| 637 |
if isinstance(result, PendingFix): |
| 638 |
result = result(line) |
| 639 |
elif "#" in line: |
| 640 |
result = line |
| 641 |
elif line_number in marked_import_line_numbers: |
| 642 |
result = filter_unused_import( |
| 643 |
line, |
| 644 |
unused_module=marked_unused_module[line_number], |
| 645 |
remove_all_unused_imports=remove_all_unused_imports, |
| 646 |
imports=imports, |
| 647 |
previous_line=previous_line, |
| 648 |
) |
| 649 |
elif line_number in marked_variable_line_numbers: |
| 650 |
result = filter_unused_variable( |
| 651 |
line, |
| 652 |
drop_rhs=remove_rhs_for_unused_variables, |
| 653 |
) |
| 654 |
elif line_number in marked_key_line_numbers: |
| 655 |
result = filter_duplicate_key( |
| 656 |
line, |
| 657 |
line_messages[line_number], |
| 658 |
line_number, |
| 659 |
marked_key_line_numbers, |
| 660 |
source, |
| 661 |
) |
| 662 |
elif line_number in marked_star_import_line_numbers: |
| 663 |
result = filter_star_import(line, undefined_names) |
| 664 |
else: |
| 665 |
result = line |
| 666 |
|
| 667 |
if not isinstance(result, PendingFix): |
| 668 |
yield result |
| 669 |
|
| 670 |
previous_line = line |
| 671 |
|
| 672 |
|
| 673 |
def get_messages_by_line( |
| 674 |
messages: Iterable[pyflakes.messages.Message], |
| 675 |
) -> Mapping[int, pyflakes.messages.Message]: |
| 676 |
"""Return dictionary that maps line number to message.""" |
| 677 |
line_messages: dict[int, pyflakes.messages.Message] = {} |
| 678 |
for message in messages: |
| 679 |
line_messages[message.lineno] = message |
| 680 |
return line_messages |
| 681 |
|
| 682 |
|
| 683 |
def filter_star_import( |
| 684 |
line: str, |
| 685 |
marked_star_import_undefined_name: Iterable[str], |
| 686 |
) -> str: |
| 687 |
"""Return line with the star import expanded.""" |
| 688 |
undefined_name = sorted(set(marked_star_import_undefined_name)) |
| 689 |
return re.sub(r"\*", ", ".join(undefined_name), line) |
| 690 |
|
| 691 |
|
| 692 |
def filter_unused_import( |
| 693 |
line: str, |
| 694 |
unused_module: Iterable[str], |
| 695 |
remove_all_unused_imports: bool, |
| 696 |
imports: Iterable[str], |
| 697 |
previous_line: str = "", |
| 698 |
) -> PendingFix | str: |
| 699 |
"""Return line if used, otherwise return None.""" |
| 700 |
|
| 701 |
if line.lstrip().startswith(">"): |
| 702 |
return line |
| 703 |
|
| 704 |
if multiline_import(line, previous_line): |
| 705 |
if not FilterMultilineImport.IMPORT_RE.search(line): |
| 706 |
|
| 707 |
|
| 708 |
return line |
| 709 |
filt = FilterMultilineImport( |
| 710 |
line, |
| 711 |
unused_module, |
| 712 |
remove_all_unused_imports, |
| 713 |
imports, |
| 714 |
previous_line, |
| 715 |
) |
| 716 |
return filt() |
| 717 |
|
| 718 |
is_from_import = line.lstrip().startswith("from") |
| 719 |
|
| 720 |
if "," in line and not is_from_import: |
| 721 |
return break_up_import(line) |
| 722 |
|
| 723 |
package = extract_package_name(line) |
| 724 |
if not remove_all_unused_imports and package is not None and package not in imports: |
| 725 |
return line |
| 726 |
|
| 727 |
if "," in line: |
| 728 |
assert is_from_import |
| 729 |
return filter_from_import(line, unused_module) |
| 730 |
else: |
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
return get_indentation(line) + "pass" + get_line_ending(line) |
| 736 |
|
| 737 |
|
| 738 |
def filter_unused_variable( |
| 739 |
line: str, |
| 740 |
previous_line: str = "", |
| 741 |
drop_rhs: bool = False, |
| 742 |
) -> str: |
| 743 |
"""Return line if used, otherwise return None.""" |
| 744 |
if re.match(EXCEPT_REGEX, line): |
| 745 |
return re.sub(r" as \w+:$", ":", line, count=1) |
| 746 |
elif multiline_statement(line, previous_line): |
| 747 |
return line |
| 748 |
elif line.count("=") == 1: |
| 749 |
split_line = line.split("=") |
| 750 |
assert len(split_line) == 2 |
| 751 |
value = split_line[1].lstrip() |
| 752 |
if "," in split_line[0]: |
| 753 |
return line |
| 754 |
|
| 755 |
if is_literal_or_name(value): |
| 756 |
|
| 757 |
|
| 758 |
value = "pass" + get_line_ending(line) |
| 759 |
if drop_rhs: |
| 760 |
return get_indentation(line) + value |
| 761 |
|
| 762 |
if drop_rhs: |
| 763 |
return "" |
| 764 |
return get_indentation(line) + value |
| 765 |
else: |
| 766 |
return line |
| 767 |
|
| 768 |
|
| 769 |
def filter_duplicate_key( |
| 770 |
line: str, |
| 771 |
message: pyflakes.messages.Message, |
| 772 |
line_number: int, |
| 773 |
marked_line_numbers: Iterable[int], |
| 774 |
source: str, |
| 775 |
previous_line: str = "", |
| 776 |
) -> str: |
| 777 |
"""Return '' if first occurrence of the key otherwise return `line`.""" |
| 778 |
if marked_line_numbers and line_number == sorted(marked_line_numbers)[0]: |
| 779 |
return "" |
| 780 |
|
| 781 |
return line |
| 782 |
|
| 783 |
|
| 784 |
def dict_entry_has_key(line: str, key: Any) -> bool: |
| 785 |
"""Return True if `line` is a dict entry that uses `key`. |
| 786 |
|
| 787 |
Return False for multiline cases where the line should not be removed by |
| 788 |
itself. |
| 789 |
|
| 790 |
""" |
| 791 |
if "#" in line: |
| 792 |
return False |
| 793 |
|
| 794 |
result = re.match(r"\s*(.*)\s*:\s*(.*),\s*$", line) |
| 795 |
if not result: |
| 796 |
return False |
| 797 |
|
| 798 |
try: |
| 799 |
candidate_key = ast.literal_eval(result.group(1)) |
| 800 |
except (SyntaxError, ValueError): |
| 801 |
return False |
| 802 |
|
| 803 |
if multiline_statement(result.group(2)): |
| 804 |
return False |
| 805 |
|
| 806 |
return cast(bool, candidate_key == key) |
| 807 |
|
| 808 |
|
| 809 |
def is_literal_or_name(value: str) -> bool: |
| 810 |
"""Return True if value is a literal or a name.""" |
| 811 |
try: |
| 812 |
ast.literal_eval(value) |
| 813 |
return True |
| 814 |
except (SyntaxError, TypeError, ValueError): |
| 815 |
pass |
| 816 |
|
| 817 |
if value.strip() in ["dict()", "list()", "set()"]: |
| 818 |
return True |
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
return re.match(r"^\w+\s*$", value) is not None |
| 823 |
|
| 824 |
|
| 825 |
def useless_pass_line_numbers( |
| 826 |
source: str, |
| 827 |
ignore_pass_after_docstring: bool = False, |
| 828 |
) -> Iterable[int]: |
| 829 |
"""Yield line numbers of unneeded "pass" statements.""" |
| 830 |
sio = io.StringIO(source) |
| 831 |
previous_token_type = None |
| 832 |
last_pass_row = None |
| 833 |
last_pass_indentation = None |
| 834 |
previous_line = "" |
| 835 |
previous_non_empty_line = "" |
| 836 |
for token in tokenize.generate_tokens(sio.readline): |
| 837 |
token_type = token[0] |
| 838 |
start_row = token[2][0] |
| 839 |
line = token[4] |
| 840 |
|
| 841 |
is_pass = token_type == tokenize.NAME and line.strip() == "pass" |
| 842 |
|
| 843 |
|
| 844 |
if ( |
| 845 |
start_row - 1 == last_pass_row |
| 846 |
and get_indentation(line) == last_pass_indentation |
| 847 |
and token_type in ATOMS |
| 848 |
and not is_pass |
| 849 |
): |
| 850 |
yield start_row - 1 |
| 851 |
|
| 852 |
if is_pass: |
| 853 |
last_pass_row = start_row |
| 854 |
last_pass_indentation = get_indentation(line) |
| 855 |
|
| 856 |
is_trailing_pass = ( |
| 857 |
previous_token_type != tokenize.INDENT |
| 858 |
and not previous_line.rstrip().endswith("\\") |
| 859 |
) |
| 860 |
|
| 861 |
is_pass_after_docstring = previous_non_empty_line.rstrip().endswith( |
| 862 |
("'''", '"""'), |
| 863 |
) |
| 864 |
|
| 865 |
|
| 866 |
if is_trailing_pass: |
| 867 |
if is_pass_after_docstring and ignore_pass_after_docstring: |
| 868 |
continue |
| 869 |
else: |
| 870 |
yield start_row |
| 871 |
|
| 872 |
previous_token_type = token_type |
| 873 |
previous_line = line |
| 874 |
if line.strip(): |
| 875 |
previous_non_empty_line = line |
| 876 |
|
| 877 |
|
| 878 |
def filter_useless_pass( |
| 879 |
source: str, |
| 880 |
ignore_pass_statements: bool = False, |
| 881 |
ignore_pass_after_docstring: bool = False, |
| 882 |
) -> Iterable[str]: |
| 883 |
"""Yield code with useless "pass" lines removed.""" |
| 884 |
if ignore_pass_statements: |
| 885 |
marked_lines: frozenset[int] = frozenset() |
| 886 |
else: |
| 887 |
try: |
| 888 |
marked_lines = frozenset( |
| 889 |
useless_pass_line_numbers( |
| 890 |
source, |
| 891 |
ignore_pass_after_docstring, |
| 892 |
), |
| 893 |
) |
| 894 |
except (SyntaxError, tokenize.TokenError): |
| 895 |
marked_lines = frozenset() |
| 896 |
|
| 897 |
sio = io.StringIO(source) |
| 898 |
for line_number, line in enumerate(sio.readlines(), start=1): |
| 899 |
if line_number not in marked_lines: |
| 900 |
yield line |
| 901 |
|
| 902 |
|
| 903 |
def get_indentation(line: str) -> str: |
| 904 |
"""Return leading whitespace.""" |
| 905 |
if line.strip(): |
| 906 |
non_whitespace_index = len(line) - len(line.lstrip()) |
| 907 |
return line[:non_whitespace_index] |
| 908 |
else: |
| 909 |
return "" |
| 910 |
|
| 911 |
|
| 912 |
def get_line_ending(line: str) -> str: |
| 913 |
"""Return line ending.""" |
| 914 |
non_whitespace_index = len(line.rstrip()) - len(line) |
| 915 |
if not non_whitespace_index: |
| 916 |
return "" |
| 917 |
else: |
| 918 |
return line[non_whitespace_index:] |
| 919 |
|
| 920 |
|
| 921 |
def fix_code( |
| 922 |
source: str, |
| 923 |
additional_imports: Iterable[str] | None = None, |
| 924 |
expand_star_imports: bool = False, |
| 925 |
remove_all_unused_imports: bool = False, |
| 926 |
remove_duplicate_keys: bool = False, |
| 927 |
remove_unused_variables: bool = False, |
| 928 |
remove_rhs_for_unused_variables: bool = False, |
| 929 |
ignore_init_module_imports: bool = False, |
| 930 |
ignore_pass_statements: bool = False, |
| 931 |
ignore_pass_after_docstring: bool = False, |
| 932 |
) -> str: |
| 933 |
"""Return code with all filtering run on it.""" |
| 934 |
if not source: |
| 935 |
return source |
| 936 |
|
| 937 |
if IGNORE_COMMENT_REGEX.search(source): |
| 938 |
return source |
| 939 |
|
| 940 |
|
| 941 |
if "nonlocal" in source: |
| 942 |
remove_unused_variables = False |
| 943 |
|
| 944 |
filtered_source = None |
| 945 |
while True: |
| 946 |
filtered_source = "".join( |
| 947 |
filter_useless_pass( |
| 948 |
"".join( |
| 949 |
filter_code( |
| 950 |
source, |
| 951 |
additional_imports=additional_imports, |
| 952 |
expand_star_imports=expand_star_imports, |
| 953 |
remove_all_unused_imports=remove_all_unused_imports, |
| 954 |
remove_duplicate_keys=remove_duplicate_keys, |
| 955 |
remove_unused_variables=remove_unused_variables, |
| 956 |
remove_rhs_for_unused_variables=( |
| 957 |
remove_rhs_for_unused_variables |
| 958 |
), |
| 959 |
ignore_init_module_imports=ignore_init_module_imports, |
| 960 |
), |
| 961 |
), |
| 962 |
ignore_pass_statements=ignore_pass_statements, |
| 963 |
ignore_pass_after_docstring=ignore_pass_after_docstring, |
| 964 |
), |
| 965 |
) |
| 966 |
|
| 967 |
if filtered_source == source: |
| 968 |
break |
| 969 |
source = filtered_source |
| 970 |
|
| 971 |
return filtered_source |
| 972 |
|
| 973 |
|
| 974 |
def fix_file( |
| 975 |
filename: str, |
| 976 |
args: Mapping[str, Any], |
| 977 |
standard_out: IO[str] | None = None, |
| 978 |
) -> int: |
| 979 |
"""Run fix_code() on a file.""" |
| 980 |
if standard_out is None: |
| 981 |
standard_out = sys.stdout |
| 982 |
encoding = detect_encoding(filename) |
| 983 |
with open_with_encoding(filename, encoding=encoding) as input_file: |
| 984 |
return _fix_file( |
| 985 |
input_file, |
| 986 |
filename, |
| 987 |
args, |
| 988 |
args["write_to_stdout"], |
| 989 |
cast(IO[str], standard_out), |
| 990 |
encoding=encoding, |
| 991 |
) |
| 992 |
|
| 993 |
|
| 994 |
def _fix_file( |
| 995 |
input_file: IO[str], |
| 996 |
filename: str, |
| 997 |
args: Mapping[str, Any], |
| 998 |
write_to_stdout: bool, |
| 999 |
standard_out: IO[str], |
| 1000 |
encoding: str | None = None, |
| 1001 |
) -> int: |
| 1002 |
source = input_file.read() |
| 1003 |
original_source = source |
| 1004 |
|
| 1005 |
isInitFile = os.path.basename(filename) == "__init__.py" |
| 1006 |
|
| 1007 |
if args["ignore_init_module_imports"] and isInitFile: |
| 1008 |
ignore_init_module_imports = True |
| 1009 |
else: |
| 1010 |
ignore_init_module_imports = False |
| 1011 |
|
| 1012 |
filtered_source = fix_code( |
| 1013 |
source, |
| 1014 |
additional_imports=(args["imports"].split(",") if "imports" in args else None), |
| 1015 |
expand_star_imports=args["expand_star_imports"], |
| 1016 |
remove_all_unused_imports=args["remove_all_unused_imports"], |
| 1017 |
remove_duplicate_keys=args["remove_duplicate_keys"], |
| 1018 |
remove_unused_variables=args["remove_unused_variables"], |
| 1019 |
remove_rhs_for_unused_variables=(args["remove_rhs_for_unused_variables"]), |
| 1020 |
ignore_init_module_imports=ignore_init_module_imports, |
| 1021 |
ignore_pass_statements=args["ignore_pass_statements"], |
| 1022 |
ignore_pass_after_docstring=args["ignore_pass_after_docstring"], |
| 1023 |
) |
| 1024 |
|
| 1025 |
if original_source != filtered_source: |
| 1026 |
if args["check"]: |
| 1027 |
standard_out.write( |
| 1028 |
f"{filename}: Unused imports/variables detected{os.linesep}", |
| 1029 |
) |
| 1030 |
return 1 |
| 1031 |
if args["check_diff"]: |
| 1032 |
diff = get_diff_text( |
| 1033 |
io.StringIO(original_source).readlines(), |
| 1034 |
io.StringIO(filtered_source).readlines(), |
| 1035 |
filename, |
| 1036 |
) |
| 1037 |
standard_out.write("".join(diff)) |
| 1038 |
return 1 |
| 1039 |
if write_to_stdout: |
| 1040 |
standard_out.write(filtered_source) |
| 1041 |
elif args["in_place"]: |
| 1042 |
with open_with_encoding( |
| 1043 |
filename, |
| 1044 |
mode="w", |
| 1045 |
encoding=encoding, |
| 1046 |
) as output_file: |
| 1047 |
output_file.write(filtered_source) |
| 1048 |
_LOGGER.info("Fixed %s", filename) |
| 1049 |
else: |
| 1050 |
diff = get_diff_text( |
| 1051 |
io.StringIO(original_source).readlines(), |
| 1052 |
io.StringIO(filtered_source).readlines(), |
| 1053 |
filename, |
| 1054 |
) |
| 1055 |
standard_out.write("".join(diff)) |
| 1056 |
elif write_to_stdout: |
| 1057 |
standard_out.write(filtered_source) |
| 1058 |
else: |
| 1059 |
if (args["check"] or args["check_diff"]) and not args["quiet"]: |
| 1060 |
standard_out.write(f"{filename}: No issues detected!{os.linesep}") |
| 1061 |
else: |
| 1062 |
_LOGGER.debug("Clean %s: nothing to fix", filename) |
| 1063 |
|
| 1064 |
return 0 |
| 1065 |
|
| 1066 |
|
| 1067 |
def open_with_encoding( |
| 1068 |
filename: str, |
| 1069 |
encoding: str | None, |
| 1070 |
mode: str = "r", |
| 1071 |
limit_byte_check: int = -1, |
| 1072 |
) -> IO[str]: |
| 1073 |
"""Return opened file with a specific encoding.""" |
| 1074 |
if not encoding: |
| 1075 |
encoding = detect_encoding(filename, limit_byte_check=limit_byte_check) |
| 1076 |
|
| 1077 |
return open( |
| 1078 |
filename, |
| 1079 |
mode=mode, |
| 1080 |
encoding=encoding, |
| 1081 |
newline="", |
| 1082 |
) |
| 1083 |
|
| 1084 |
|
| 1085 |
def detect_encoding(filename: str, limit_byte_check: int = -1) -> str: |
| 1086 |
"""Return file encoding.""" |
| 1087 |
try: |
| 1088 |
with open(filename, "rb") as input_file: |
| 1089 |
encoding = _detect_encoding(input_file.readline) |
| 1090 |
|
| 1091 |
|
| 1092 |
with open_with_encoding(filename, encoding) as input_file: |
| 1093 |
input_file.read(limit_byte_check) |
| 1094 |
|
| 1095 |
return encoding |
| 1096 |
except (LookupError, SyntaxError, UnicodeDecodeError): |
| 1097 |
return "latin-1" |
| 1098 |
|
| 1099 |
|
| 1100 |
def _detect_encoding(readline: Callable[[], bytes]) -> str: |
| 1101 |
"""Return file encoding.""" |
| 1102 |
try: |
| 1103 |
encoding = tokenize.detect_encoding(readline)[0] |
| 1104 |
return encoding |
| 1105 |
except (LookupError, SyntaxError, UnicodeDecodeError): |
| 1106 |
return "latin-1" |
| 1107 |
|
| 1108 |
|
| 1109 |
def get_diff_text(old: Sequence[str], new: Sequence[str], filename: str) -> str: |
| 1110 |
"""Return text of unified diff between old and new.""" |
| 1111 |
newline = "\n" |
| 1112 |
diff = difflib.unified_diff( |
| 1113 |
old, |
| 1114 |
new, |
| 1115 |
"original/" + filename, |
| 1116 |
"fixed/" + filename, |
| 1117 |
lineterm=newline, |
| 1118 |
) |
| 1119 |
|
| 1120 |
text = "" |
| 1121 |
for line in diff: |
| 1122 |
text += line |
| 1123 |
|
| 1124 |
|
| 1125 |
if not line.endswith(newline): |
| 1126 |
text += newline + r"\ No newline at end of file" + newline |
| 1127 |
|
| 1128 |
return text |
| 1129 |
|
| 1130 |
|
| 1131 |
def _split_comma_separated(string: str) -> set[str]: |
| 1132 |
"""Return a set of strings.""" |
| 1133 |
return {text.strip() for text in string.split(",") if text.strip()} |
| 1134 |
|
| 1135 |
|
| 1136 |
def is_python_file(filename: str) -> bool: |
| 1137 |
"""Return True if filename is Python file.""" |
| 1138 |
if filename.endswith(".py"): |
| 1139 |
return True |
| 1140 |
|
| 1141 |
try: |
| 1142 |
with open_with_encoding( |
| 1143 |
filename, |
| 1144 |
None, |
| 1145 |
limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES, |
| 1146 |
) as f: |
| 1147 |
text = f.read(MAX_PYTHON_FILE_DETECTION_BYTES) |
| 1148 |
if not text: |
| 1149 |
return False |
| 1150 |
first_line = text.splitlines()[0] |
| 1151 |
except (OSError, IndexError): |
| 1152 |
return False |
| 1153 |
|
| 1154 |
if not PYTHON_SHEBANG_REGEX.match(first_line): |
| 1155 |
return False |
| 1156 |
|
| 1157 |
return True |
| 1158 |
|
| 1159 |
|
| 1160 |
def is_exclude_file(filename: str, exclude: Iterable[str]) -> bool: |
| 1161 |
"""Return True if file matches exclude pattern.""" |
| 1162 |
base_name = os.path.basename(filename) |
| 1163 |
|
| 1164 |
if base_name.startswith("."): |
| 1165 |
return True |
| 1166 |
|
| 1167 |
for pattern in exclude: |
| 1168 |
if fnmatch.fnmatch(base_name, pattern): |
| 1169 |
return True |
| 1170 |
if fnmatch.fnmatch(filename, pattern): |
| 1171 |
return True |
| 1172 |
return False |
| 1173 |
|
| 1174 |
|
| 1175 |
def match_file(filename: str, exclude: Iterable[str]) -> bool: |
| 1176 |
"""Return True if file is okay for modifying/recursing.""" |
| 1177 |
if is_exclude_file(filename, exclude): |
| 1178 |
_LOGGER.debug("Skipped %s: matched to exclude pattern", filename) |
| 1179 |
return False |
| 1180 |
|
| 1181 |
if not os.path.isdir(filename) and not is_python_file(filename): |
| 1182 |
return False |
| 1183 |
|
| 1184 |
return True |
| 1185 |
|
| 1186 |
|
| 1187 |
def find_files( |
| 1188 |
filenames: list[str], |
| 1189 |
recursive: bool, |
| 1190 |
exclude: Iterable[str], |
| 1191 |
) -> Iterable[str]: |
| 1192 |
"""Yield filenames.""" |
| 1193 |
while filenames: |
| 1194 |
name = filenames.pop(0) |
| 1195 |
if recursive and os.path.isdir(name): |
| 1196 |
for root, directories, children in os.walk(name): |
| 1197 |
filenames += [ |
| 1198 |
os.path.join(root, f) |
| 1199 |
for f in children |
| 1200 |
if match_file( |
| 1201 |
os.path.join(root, f), |
| 1202 |
exclude, |
| 1203 |
) |
| 1204 |
] |
| 1205 |
directories[:] = [ |
| 1206 |
d |
| 1207 |
for d in directories |
| 1208 |
if match_file( |
| 1209 |
os.path.join(root, d), |
| 1210 |
exclude, |
| 1211 |
) |
| 1212 |
] |
| 1213 |
else: |
| 1214 |
if not is_exclude_file(name, exclude): |
| 1215 |
yield name |
| 1216 |
else: |
| 1217 |
_LOGGER.debug("Skipped %s: matched to exclude pattern", name) |
| 1218 |
|
| 1219 |
|
| 1220 |
def process_pyproject_toml(toml_file_path: str) -> MutableMapping[str, Any] | None: |
| 1221 |
"""Extract config mapping from pyproject.toml file.""" |
| 1222 |
try: |
| 1223 |
import tomllib |
| 1224 |
except ModuleNotFoundError: |
| 1225 |
import tomli as tomllib |
| 1226 |
|
| 1227 |
with open(toml_file_path, "rb") as f: |
| 1228 |
return tomllib.load(f).get("tool", {}).get("autoflake", None) |
| 1229 |
|
| 1230 |
|
| 1231 |
def process_config_file(config_file_path: str) -> MutableMapping[str, Any] | None: |
| 1232 |
"""Extract config mapping from config file.""" |
| 1233 |
import configparser |
| 1234 |
|
| 1235 |
reader = configparser.ConfigParser() |
| 1236 |
reader.read(config_file_path, encoding="utf-8") |
| 1237 |
if not reader.has_section("autoflake"): |
| 1238 |
return None |
| 1239 |
|
| 1240 |
return reader["autoflake"] |
| 1241 |
|
| 1242 |
|
| 1243 |
def find_and_process_config(args: Mapping[str, Any]) -> MutableMapping[str, Any] | None: |
| 1244 |
|
| 1245 |
CONFIG_FILES: Mapping[str, Callable[[str], MutableMapping[str, Any] | None]] = { |
| 1246 |
"pyproject.toml": process_pyproject_toml, |
| 1247 |
"setup.cfg": process_config_file, |
| 1248 |
} |
| 1249 |
|
| 1250 |
|
| 1251 |
config_path = os.path.commonpath([os.path.abspath(file) for file in args["files"]]) |
| 1252 |
config: Mapping[str, Any] | None = None |
| 1253 |
while True: |
| 1254 |
for config_file, processor in CONFIG_FILES.items(): |
| 1255 |
config_file_path = os.path.join( |
| 1256 |
os.path.join(config_path, config_file), |
| 1257 |
) |
| 1258 |
if os.path.isfile(config_file_path): |
| 1259 |
config = processor(config_file_path) |
| 1260 |
if config is not None: |
| 1261 |
break |
| 1262 |
if config is not None: |
| 1263 |
break |
| 1264 |
config_path, tail = os.path.split(config_path) |
| 1265 |
if not tail: |
| 1266 |
break |
| 1267 |
return config |
| 1268 |
|
| 1269 |
|
| 1270 |
def merge_configuration_file( |
| 1271 |
flag_args: MutableMapping[str, Any], |
| 1272 |
) -> tuple[MutableMapping[str, Any], bool]: |
| 1273 |
"""Merge configuration from a file into args.""" |
| 1274 |
BOOL_TYPES = { |
| 1275 |
"1": True, |
| 1276 |
"yes": True, |
| 1277 |
"true": True, |
| 1278 |
"on": True, |
| 1279 |
"0": False, |
| 1280 |
"no": False, |
| 1281 |
"false": False, |
| 1282 |
"off": False, |
| 1283 |
} |
| 1284 |
|
| 1285 |
if "config_file" in flag_args: |
| 1286 |
config_file = pathlib.Path(flag_args["config_file"]).resolve() |
| 1287 |
process_method = process_config_file |
| 1288 |
if config_file.suffix == ".toml": |
| 1289 |
process_method = process_pyproject_toml |
| 1290 |
|
| 1291 |
config = process_method(str(config_file)) |
| 1292 |
|
| 1293 |
if not config: |
| 1294 |
_LOGGER.error( |
| 1295 |
"can't parse config file '%s'", |
| 1296 |
config_file, |
| 1297 |
) |
| 1298 |
return flag_args, False |
| 1299 |
else: |
| 1300 |
config = find_and_process_config(flag_args) |
| 1301 |
|
| 1302 |
BOOL_FLAGS = { |
| 1303 |
"check", |
| 1304 |
"check_diff", |
| 1305 |
"expand_star_imports", |
| 1306 |
"ignore_init_module_imports", |
| 1307 |
"ignore_pass_after_docstring", |
| 1308 |
"ignore_pass_statements", |
| 1309 |
"in_place", |
| 1310 |
"quiet", |
| 1311 |
"recursive", |
| 1312 |
"remove_all_unused_imports", |
| 1313 |
"remove_duplicate_keys", |
| 1314 |
"remove_rhs_for_unused_variables", |
| 1315 |
"remove_unused_variables", |
| 1316 |
"write_to_stdout", |
| 1317 |
} |
| 1318 |
|
| 1319 |
config_args: dict[str, Any] = {} |
| 1320 |
if config is not None: |
| 1321 |
for name, value in config.items(): |
| 1322 |
arg = name.replace("-", "_") |
| 1323 |
if arg in BOOL_FLAGS: |
| 1324 |
|
| 1325 |
if isinstance(value, str): |
| 1326 |
value = BOOL_TYPES.get(value.lower(), value) |
| 1327 |
if not isinstance(value, bool): |
| 1328 |
_LOGGER.error( |
| 1329 |
"'%s' in the config file should be a boolean", |
| 1330 |
name, |
| 1331 |
) |
| 1332 |
return flag_args, False |
| 1333 |
config_args[arg] = value |
| 1334 |
else: |
| 1335 |
if isinstance(value, list) and all( |
| 1336 |
isinstance(val, str) for val in value |
| 1337 |
): |
| 1338 |
value = ",".join(str(val) for val in value) |
| 1339 |
if not isinstance(value, str): |
| 1340 |
_LOGGER.error( |
| 1341 |
"'%s' in the config file should be a comma separated" |
| 1342 |
" string or list of strings", |
| 1343 |
name, |
| 1344 |
) |
| 1345 |
return flag_args, False |
| 1346 |
|
| 1347 |
config_args[arg] = value |
| 1348 |
|
| 1349 |
|
| 1350 |
merged_args = {} |
| 1351 |
mergeable_keys = {"imports", "exclude"} |
| 1352 |
for key in mergeable_keys: |
| 1353 |
values = ( |
| 1354 |
v for v in (config_args.get(key), flag_args.get(key)) if v is not None |
| 1355 |
) |
| 1356 |
value = ",".join(values) |
| 1357 |
if value != "": |
| 1358 |
merged_args[key] = value |
| 1359 |
|
| 1360 |
default_args = {arg: False for arg in BOOL_FLAGS} |
| 1361 |
return { |
| 1362 |
**default_args, |
| 1363 |
**config_args, |
| 1364 |
**flag_args, |
| 1365 |
**merged_args, |
| 1366 |
}, True |
| 1367 |
|
| 1368 |
|
| 1369 |
def _main( |
| 1370 |
argv: Sequence[str], |
| 1371 |
standard_out: IO[str] | None, |
| 1372 |
standard_error: IO[str] | None, |
| 1373 |
standard_input: IO[str] | None = None, |
| 1374 |
) -> int: |
| 1375 |
"""Return exit status. |
| 1376 |
|
| 1377 |
0 means no error. |
| 1378 |
""" |
| 1379 |
import argparse |
| 1380 |
|
| 1381 |
parser = argparse.ArgumentParser( |
| 1382 |
description=__doc__, |
| 1383 |
prog="autoflake", |
| 1384 |
argument_default=argparse.SUPPRESS, |
| 1385 |
) |
| 1386 |
check_group = parser.add_mutually_exclusive_group() |
| 1387 |
check_group.add_argument( |
| 1388 |
"-c", |
| 1389 |
"--check", |
| 1390 |
action="store_true", |
| 1391 |
help="return error code if changes are needed", |
| 1392 |
) |
| 1393 |
check_group.add_argument( |
| 1394 |
"-cd", |
| 1395 |
"--check-diff", |
| 1396 |
action="store_true", |
| 1397 |
help="return error code if changes are needed, also display file diffs", |
| 1398 |
) |
| 1399 |
|
| 1400 |
imports_group = parser.add_mutually_exclusive_group() |
| 1401 |
imports_group.add_argument( |
| 1402 |
"--imports", |
| 1403 |
help="by default, only unused standard library " |
| 1404 |
"imports are removed; specify a comma-separated " |
| 1405 |
"list of additional modules/packages", |
| 1406 |
) |
| 1407 |
imports_group.add_argument( |
| 1408 |
"--remove-all-unused-imports", |
| 1409 |
action="store_true", |
| 1410 |
help="remove all unused imports (not just those from the standard library)", |
| 1411 |
) |
| 1412 |
|
| 1413 |
parser.add_argument( |
| 1414 |
"-r", |
| 1415 |
"--recursive", |
| 1416 |
action="store_true", |
| 1417 |
help="drill down directories recursively", |
| 1418 |
) |
| 1419 |
parser.add_argument( |
| 1420 |
"-j", |
| 1421 |
"--jobs", |
| 1422 |
type=int, |
| 1423 |
metavar="n", |
| 1424 |
default=0, |
| 1425 |
help="number of parallel jobs; match CPU count if value is 0 (default: 0)", |
| 1426 |
) |
| 1427 |
parser.add_argument( |
| 1428 |
"--exclude", |
| 1429 |
metavar="globs", |
| 1430 |
help="exclude file/directory names that match these comma-separated globs", |
| 1431 |
) |
| 1432 |
parser.add_argument( |
| 1433 |
"--expand-star-imports", |
| 1434 |
action="store_true", |
| 1435 |
help="expand wildcard star imports with undefined " |
| 1436 |
"names; this only triggers if there is only " |
| 1437 |
"one star import in the file; this is skipped if " |
| 1438 |
"there are any uses of `__all__` or `del` in the " |
| 1439 |
"file", |
| 1440 |
) |
| 1441 |
parser.add_argument( |
| 1442 |
"--ignore-init-module-imports", |
| 1443 |
action="store_true", |
| 1444 |
help="exclude __init__.py when removing unused imports", |
| 1445 |
) |
| 1446 |
parser.add_argument( |
| 1447 |
"--remove-duplicate-keys", |
| 1448 |
action="store_true", |
| 1449 |
help="remove all duplicate keys in objects", |
| 1450 |
) |
| 1451 |
parser.add_argument( |
| 1452 |
"--remove-unused-variables", |
| 1453 |
action="store_true", |
| 1454 |
help="remove unused variables", |
| 1455 |
) |
| 1456 |
parser.add_argument( |
| 1457 |
"--remove-rhs-for-unused-variables", |
| 1458 |
action="store_true", |
| 1459 |
help="remove RHS of statements when removing unused variables (unsafe)", |
| 1460 |
) |
| 1461 |
parser.add_argument( |
| 1462 |
"--ignore-pass-statements", |
| 1463 |
action="store_true", |
| 1464 |
help="ignore all pass statements", |
| 1465 |
) |
| 1466 |
parser.add_argument( |
| 1467 |
"--ignore-pass-after-docstring", |
| 1468 |
action="store_true", |
| 1469 |
help='ignore pass statements after a newline ending on \'"""\'', |
| 1470 |
) |
| 1471 |
parser.add_argument( |
| 1472 |
"--version", |
| 1473 |
action="version", |
| 1474 |
version="%(prog)s " + __version__, |
| 1475 |
) |
| 1476 |
parser.add_argument( |
| 1477 |
"--quiet", |
| 1478 |
action="store_true", |
| 1479 |
help="Suppress output if there are no issues", |
| 1480 |
) |
| 1481 |
parser.add_argument( |
| 1482 |
"-v", |
| 1483 |
"--verbose", |
| 1484 |
action="count", |
| 1485 |
dest="verbosity", |
| 1486 |
default=0, |
| 1487 |
help="print more verbose logs (you can repeat `-v` to make it more verbose)", |
| 1488 |
) |
| 1489 |
parser.add_argument( |
| 1490 |
"--stdin-display-name", |
| 1491 |
dest="stdin_display_name", |
| 1492 |
default="stdin", |
| 1493 |
help="the name used when processing input from stdin", |
| 1494 |
) |
| 1495 |
|
| 1496 |
parser.add_argument( |
| 1497 |
"--config", |
| 1498 |
dest="config_file", |
| 1499 |
help=( |
| 1500 |
"Explicitly set the config file " |
| 1501 |
"instead of auto determining based on file location" |
| 1502 |
), |
| 1503 |
) |
| 1504 |
|
| 1505 |
parser.add_argument("files", nargs="+", help="files to format") |
| 1506 |
|
| 1507 |
output_group = parser.add_mutually_exclusive_group() |
| 1508 |
output_group.add_argument( |
| 1509 |
"-i", |
| 1510 |
"--in-place", |
| 1511 |
action="store_true", |
| 1512 |
help="make changes to files instead of printing diffs", |
| 1513 |
) |
| 1514 |
output_group.add_argument( |
| 1515 |
"-s", |
| 1516 |
"--stdout", |
| 1517 |
action="store_true", |
| 1518 |
dest="write_to_stdout", |
| 1519 |
help=( |
| 1520 |
"print changed text to stdout. defaults to true " |
| 1521 |
"when formatting stdin, or to false otherwise" |
| 1522 |
), |
| 1523 |
) |
| 1524 |
|
| 1525 |
args: MutableMapping[str, Any] = vars(parser.parse_args(argv[1:])) |
| 1526 |
|
| 1527 |
if standard_error is None: |
| 1528 |
_LOGGER.addHandler(logging.NullHandler()) |
| 1529 |
else: |
| 1530 |
_LOGGER.addHandler(logging.StreamHandler(standard_error)) |
| 1531 |
loglevels = [logging.WARNING, logging.INFO, logging.DEBUG] |
| 1532 |
try: |
| 1533 |
loglevel = loglevels[args["verbosity"]] |
| 1534 |
except IndexError: |
| 1535 |
loglevel = loglevels[-1] |
| 1536 |
_LOGGER.setLevel(loglevel) |
| 1537 |
|
| 1538 |
args, success = merge_configuration_file(args) |
| 1539 |
if not success: |
| 1540 |
return 1 |
| 1541 |
|
| 1542 |
if ( |
| 1543 |
args["remove_rhs_for_unused_variables"] |
| 1544 |
and not (args["remove_unused_variables"]) |
| 1545 |
): |
| 1546 |
_LOGGER.error( |
| 1547 |
"Using --remove-rhs-for-unused-variables only makes sense when " |
| 1548 |
"used with --remove-unused-variables", |
| 1549 |
) |
| 1550 |
return 1 |
| 1551 |
|
| 1552 |
if "exclude" in args: |
| 1553 |
args["exclude"] = _split_comma_separated(args["exclude"]) |
| 1554 |
else: |
| 1555 |
args["exclude"] = set() |
| 1556 |
|
| 1557 |
if args["jobs"] < 1: |
| 1558 |
worker_count = os.cpu_count() |
| 1559 |
if sys.platform == "win32": |
| 1560 |
|
| 1561 |
worker_count = min(worker_count, 60) |
| 1562 |
args["jobs"] = worker_count or 1 |
| 1563 |
|
| 1564 |
filenames = list(set(args["files"])) |
| 1565 |
|
| 1566 |
|
| 1567 |
|
| 1568 |
exit_status = 0 |
| 1569 |
files = list(find_files(filenames, args["recursive"], args["exclude"])) |
| 1570 |
if ( |
| 1571 |
args["jobs"] == 1 |
| 1572 |
or len(files) == 1 |
| 1573 |
or args["jobs"] == 1 |
| 1574 |
or "-" in files |
| 1575 |
or standard_out is not None |
| 1576 |
): |
| 1577 |
for name in files: |
| 1578 |
if name == "-" and standard_input is not None: |
| 1579 |
exit_status |= _fix_file( |
| 1580 |
standard_input, |
| 1581 |
args["stdin_display_name"], |
| 1582 |
args=args, |
| 1583 |
write_to_stdout=True, |
| 1584 |
standard_out=standard_out or sys.stdout, |
| 1585 |
) |
| 1586 |
else: |
| 1587 |
try: |
| 1588 |
exit_status |= fix_file( |
| 1589 |
name, |
| 1590 |
args=args, |
| 1591 |
standard_out=standard_out, |
| 1592 |
) |
| 1593 |
except OSError as exception: |
| 1594 |
_LOGGER.error(str(exception)) |
| 1595 |
exit_status |= 1 |
| 1596 |
else: |
| 1597 |
import multiprocessing |
| 1598 |
|
| 1599 |
with multiprocessing.Pool(args["jobs"]) as pool: |
| 1600 |
futs = [] |
| 1601 |
for name in files: |
| 1602 |
fut = pool.apply_async(fix_file, args=(name, args)) |
| 1603 |
futs.append(fut) |
| 1604 |
for fut in futs: |
| 1605 |
try: |
| 1606 |
exit_status |= fut.get() |
| 1607 |
except OSError as exception: |
| 1608 |
_LOGGER.error(str(exception)) |
| 1609 |
exit_status |= 1 |
| 1610 |
|
| 1611 |
return exit_status |
| 1612 |
|
| 1613 |
|
| 1614 |
def main() -> int: |
| 1615 |
"""Command-line entry point.""" |
| 1616 |
try: |
| 1617 |
|
| 1618 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) |
| 1619 |
except AttributeError: |
| 1620 |
|
| 1621 |
pass |
| 1622 |
|
| 1623 |
try: |
| 1624 |
return _main( |
| 1625 |
sys.argv, |
| 1626 |
standard_out=None, |
| 1627 |
standard_error=sys.stderr, |
| 1628 |
standard_input=sys.stdin, |
| 1629 |
) |
| 1630 |
except KeyboardInterrupt: |
| 1631 |
return 2 |
| 1632 |
|
| 1633 |
|
| 1634 |
if __name__ == "__main__": |
| 1635 |
sys.exit(main()) |