1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
|
#!/usr/bin/env python
"""Test that autoflake performs correctly on arbitrary Python files.
This checks that autoflake never introduces incorrect syntax. This is
done by doing a syntax check after the autoflake run. The number of
Pyflakes warnings is also confirmed to always improve.
"""
from __future__ import annotations
import argparse
import os
import shlex
import subprocess
import sys
from typing import Sequence
import autoflake
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
AUTOFLAKE_BIN = "'{}' '{}'".format(
sys.executable,
os.path.join(ROOT_PATH, "autoflake.py"),
)
if sys.stdout.isatty():
YELLOW = "\x1b[33m"
END = "\x1b[0m"
else:
YELLOW = ""
END = ""
def colored(text: str, color: str) -> str:
"""Return color coded text."""
return color + text + END
def pyflakes_count(filename: str) -> int:
"""Return pyflakes error count."""
with autoflake.open_with_encoding(
filename,
encoding=autoflake.detect_encoding(filename),
) as f:
return len(list(autoflake.check(f.read())))
def readlines(filename: str) -> Sequence[str]:
"""Return contents of file as a list of lines."""
with autoflake.open_with_encoding(
filename,
encoding=autoflake.detect_encoding(filename),
) as f:
return f.readlines()
def diff(before: str, after: str) -> str:
"""Return diff of two files."""
import difflib
return "".join(
difflib.unified_diff(
readlines(before),
readlines(after),
before,
after,
),
)
def run(
filename: str,
command: str,
verbose: bool = False,
options: list[str] | None = None,
) -> bool:
"""Run autoflake on file at filename.
Return True on success.
"""
if not options:
options = []
import test_autoflake
with test_autoflake.temporary_directory() as temp_directory:
temp_filename = os.path.join(
temp_directory,
os.path.basename(filename),
)
import shutil
shutil.copyfile(filename, temp_filename)
if 0 != subprocess.call(
shlex.split(command) + ["--in-place", temp_filename] + options,
):
sys.stderr.write("autoflake crashed on " + filename + "\n")
return False
try:
file_diff = diff(filename, temp_filename)
if verbose:
sys.stderr.write(file_diff)
if check_syntax(filename):
try:
check_syntax(temp_filename, raise_error=True)
except (
SyntaxError,
TypeError,
UnicodeDecodeError,
ValueError,
) as exception:
sys.stderr.write(
"autoflake broke " + filename + "\n" + str(exception) + "\n",
)
return False
before_count = pyflakes_count(filename)
after_count = pyflakes_count(temp_filename)
if verbose:
print("(before, after):", (before_count, after_count))
if file_diff and after_count > before_count:
sys.stderr.write("autoflake made " + filename + " worse\n")
return False
except OSError as exception:
sys.stderr.write(str(exception) + "\n")
return True
def check_syntax(filename: str, raise_error: bool = False) -> bool:
"""Return True if syntax is okay."""
with autoflake.open_with_encoding(
filename,
encoding=autoflake.detect_encoding(filename),
) as input_file:
try:
compile(input_file.read(), "<string>", "exec", dont_inherit=True)
return True
except (SyntaxError, TypeError, UnicodeDecodeError, ValueError):
if raise_error:
raise
else:
return False
def process_args() -> argparse.Namespace:
"""Return processed arguments (options and positional arguments)."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--command",
default=AUTOFLAKE_BIN,
help="autoflake command (default: %(default)s)",
)
parser.add_argument(
"--expand-star-imports",
action="store_true",
help="expand wildcard star imports with undefined " "names",
)
parser.add_argument(
"--imports",
help='pass to the autoflake "--imports" option',
)
parser.add_argument(
"--remove-all-unused-imports",
action="store_true",
help='pass "--remove-all-unused-imports" option to ' "autoflake",
)
parser.add_argument(
"--remove-duplicate-keys",
action="store_true",
help='pass "--remove-duplicate-keys" option to ' "autoflake",
)
parser.add_argument(
"--remove-unused-variables",
action="store_true",
help='pass "--remove-unused-variables" option to ' "autoflake",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="print verbose messages",
)
parser.add_argument("files", nargs="*", help="files to test against")
return parser.parse_args()
def check(args: argparse.Namespace) -> bool:
"""Run recursively run autoflake on directory of files.
Return False if the fix results in broken syntax.
"""
if args.files:
dir_paths = args.files
else:
dir_paths = [path for path in sys.path if os.path.isdir(path)]
options = []
if args.expand_star_imports:
options.append("--expand-star-imports")
if args.imports:
options.append("--imports=" + args.imports)
if args.remove_all_unused_imports:
options.append("--remove-all-unused-imports")
if args.remove_duplicate_keys:
options.append("--remove-duplicate-keys")
if args.remove_unused_variables:
options.append("--remove-unused-variables")
filenames = dir_paths
completed_filenames = set()
while filenames:
try:
name = os.path.realpath(filenames.pop(0))
if not os.path.exists(name):
# Invalid symlink.
continue
if name in completed_filenames:
sys.stderr.write(
colored(
"---> Skipping previously tested " + name + "\n",
YELLOW,
),
)
continue
else:
completed_filenames.update(name)
if os.path.isdir(name):
for root, directories, children in os.walk(name):
filenames += [
os.path.join(root, f)
for f in children
if f.endswith(".py") and not f.startswith(".")
]
directories[:] = [d for d in directories if not d.startswith(".")]
else:
verbose_message = "---> Testing with " + name
sys.stderr.write(colored(verbose_message + "\n", YELLOW))
if not run(
os.path.join(name),
command=args.command,
verbose=args.verbose,
options=options,
):
return False
except (UnicodeDecodeError, UnicodeEncodeError) as exception:
# Ignore annoying codec problems on Python 2.
print(exception, file=sys.stderr)
continue
return True
def main() -> int:
"""Run main."""
return 0 if check(process_args()) else 1
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(1)
|