50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Offline lint for this small Python project: syntax, whitespace, unused imports."""
|
|
|
|
import ast
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
FILES = [ROOT / "app/main.py", ROOT / "scripts/cache_experiment.py", ROOT / "scripts/lint.py", ROOT / "tests/level4.py"]
|
|
|
|
|
|
def check(path):
|
|
source = path.read_text()
|
|
issues = []
|
|
try:
|
|
tree = ast.parse(source, filename=str(path))
|
|
except SyntaxError as error:
|
|
return [f"{path}:{error.lineno}: {error.msg}"]
|
|
used = {node.id for node in ast.walk(tree) if isinstance(node, ast.Name)}
|
|
for node in ast.walk(tree):
|
|
if isinstance(node, ast.Import):
|
|
imports = [(item.asname or item.name.split(".")[0], node.lineno) for item in node.names]
|
|
elif isinstance(node, ast.ImportFrom):
|
|
imports = [(item.asname or item.name, node.lineno) for item in node.names]
|
|
else:
|
|
continue
|
|
for name, line in imports:
|
|
if name not in used:
|
|
issues.append(f"{path}:{line}: unused import {name}")
|
|
for number, line in enumerate(source.splitlines(), 1):
|
|
if line.rstrip() != line:
|
|
issues.append(f"{path}:{number}: trailing whitespace")
|
|
if "\t" in line:
|
|
issues.append(f"{path}:{number}: tab character")
|
|
return issues
|
|
|
|
|
|
def main():
|
|
issues = [issue for path in FILES for issue in check(path)]
|
|
if issues:
|
|
print("\n".join(issues))
|
|
return 1
|
|
print(f"PASS: lint ({len(FILES)} Python files)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|