pyhyi 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyhyi/__init__.py +3 -0
- pyhyi/__main__.py +5 -0
- pyhyi/baseline.py +87 -0
- pyhyi/cli.py +145 -0
- pyhyi/config.py +115 -0
- pyhyi/context.py +109 -0
- pyhyi/engine.py +144 -0
- pyhyi/errors.py +13 -0
- pyhyi/findings.py +47 -0
- pyhyi/git.py +108 -0
- pyhyi/paths.py +57 -0
- pyhyi/registry.py +36 -0
- pyhyi/report.py +52 -0
- pyhyi/rules/__init__.py +104 -0
- pyhyi/rules/suppression.py +40 -0
- pyhyi/suppressions.py +58 -0
- pyhyi-0.0.1.dist-info/METADATA +165 -0
- pyhyi-0.0.1.dist-info/RECORD +21 -0
- pyhyi-0.0.1.dist-info/WHEEL +4 -0
- pyhyi-0.0.1.dist-info/entry_points.txt +2 -0
- pyhyi-0.0.1.dist-info/licenses/LICENSE +21 -0
pyhyi/__init__.py
ADDED
pyhyi/__main__.py
ADDED
pyhyi/baseline.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Baseline: known findings that do not fail the check.
|
|
2
|
+
|
|
3
|
+
Legacy repositories start with hundreds of findings. `pyhyi baseline` records
|
|
4
|
+
them; afterwards only new findings fail, and the baseline can be shrunk as
|
|
5
|
+
issues get fixed. Entries are matched by (rule, path, key) with counts, so
|
|
6
|
+
moving code around inside a file does not invalidate them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from collections.abc import Collection, Iterable
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from pyhyi.errors import PyhyiError
|
|
17
|
+
from pyhyi.findings import Finding
|
|
18
|
+
|
|
19
|
+
VERSION = 1
|
|
20
|
+
|
|
21
|
+
Fingerprint = tuple[str, str | None, str]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fingerprint(finding: Finding) -> Fingerprint:
|
|
25
|
+
key = finding.key if finding.key is not None else finding.message
|
|
26
|
+
return (finding.rule, finding.path, key)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load(path: Path) -> Counter[Fingerprint] | None:
|
|
30
|
+
"""Read a baseline file; None if it does not exist."""
|
|
31
|
+
if not path.is_file():
|
|
32
|
+
return None
|
|
33
|
+
try:
|
|
34
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
35
|
+
except (OSError, ValueError) as exc:
|
|
36
|
+
raise PyhyiError(f"cannot read baseline {path.name}: {exc}") from exc
|
|
37
|
+
if not isinstance(data, dict) or data.get("version") != VERSION:
|
|
38
|
+
raise PyhyiError(f"{path.name}: unsupported baseline format (expected version {VERSION})")
|
|
39
|
+
counter: Counter[Fingerprint] = Counter()
|
|
40
|
+
for entry in data.get("findings", []):
|
|
41
|
+
try:
|
|
42
|
+
fp = (str(entry["rule"]), entry["path"], str(entry["key"]))
|
|
43
|
+
count = int(entry.get("count", 1))
|
|
44
|
+
if count < 1:
|
|
45
|
+
raise ValueError("count must be positive")
|
|
46
|
+
except (KeyError, TypeError, ValueError, AttributeError) as exc:
|
|
47
|
+
raise PyhyiError(f"{path.name}: malformed entry {entry!r}") from exc
|
|
48
|
+
counter[fp] += count
|
|
49
|
+
return counter
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def dump(path: Path, findings: Iterable[Finding]) -> None:
|
|
53
|
+
counter = Counter(fingerprint(f) for f in findings)
|
|
54
|
+
entries = [
|
|
55
|
+
{"rule": rule, "path": file, "key": key, "count": count}
|
|
56
|
+
for (rule, file, key), count in sorted(
|
|
57
|
+
counter.items(), key=lambda item: (item[0][0], item[0][1] or "", item[0][2])
|
|
58
|
+
)
|
|
59
|
+
]
|
|
60
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
with path.open("w", encoding="utf-8", newline="\n") as fh:
|
|
62
|
+
json.dump({"version": VERSION, "findings": entries}, fh, ensure_ascii=False, indent=2)
|
|
63
|
+
fh.write("\n")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def apply(
|
|
67
|
+
findings: Iterable[Finding],
|
|
68
|
+
known: Counter[Fingerprint],
|
|
69
|
+
active_rules: Collection[str],
|
|
70
|
+
) -> tuple[list[Finding], list[Finding], int]:
|
|
71
|
+
"""Split findings into (new, baselined) and count stale baseline entries.
|
|
72
|
+
|
|
73
|
+
Only entries of rules that actually ran are counted as stale, so running a
|
|
74
|
+
subset of rules does not make the rest of the baseline look fixed.
|
|
75
|
+
"""
|
|
76
|
+
remaining = Counter(known)
|
|
77
|
+
new: list[Finding] = []
|
|
78
|
+
baselined: list[Finding] = []
|
|
79
|
+
for finding in findings:
|
|
80
|
+
fp = fingerprint(finding)
|
|
81
|
+
if remaining[fp] > 0:
|
|
82
|
+
remaining[fp] -= 1
|
|
83
|
+
baselined.append(finding)
|
|
84
|
+
else:
|
|
85
|
+
new.append(finding)
|
|
86
|
+
stale = sum(count for (rule, _, _), count in remaining.items() if rule in active_rules)
|
|
87
|
+
return new, baselined, stale
|
pyhyi/cli.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Command-line entry point.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 - no issues, 1 - issues found, 2 - usage, configuration or
|
|
4
|
+
internal error.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import contextlib
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Callable, Sequence
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from pyhyi import __version__, baseline, engine, git, report
|
|
16
|
+
from pyhyi.config import Config, load_config
|
|
17
|
+
from pyhyi.errors import PyhyiError
|
|
18
|
+
from pyhyi.registry import load_rules
|
|
19
|
+
|
|
20
|
+
EXIT_OK = 0
|
|
21
|
+
EXIT_ISSUES = 1
|
|
22
|
+
EXIT_ERROR = 2
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _id_list(value: str) -> tuple[str, ...]:
|
|
26
|
+
return tuple(part.strip() for part in value.split(",") if part.strip())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _add_path(parser: argparse.ArgumentParser) -> None:
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"path",
|
|
32
|
+
nargs="?",
|
|
33
|
+
default=".",
|
|
34
|
+
help="any path inside the repository (default: current directory)",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
39
|
+
parser = argparse.ArgumentParser(prog="pyhyi", description="Repository hygiene checker.")
|
|
40
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
41
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
42
|
+
|
|
43
|
+
check = sub.add_parser("check", help="check the repository and report issues")
|
|
44
|
+
_add_path(check)
|
|
45
|
+
check.add_argument("--format", choices=("text", "json"), default="text")
|
|
46
|
+
check.add_argument(
|
|
47
|
+
"--select", type=_id_list, metavar="IDS", help="comma-separated rules to run instead"
|
|
48
|
+
)
|
|
49
|
+
check.add_argument(
|
|
50
|
+
"--ignore", type=_id_list, default=(), metavar="IDS", help="comma-separated rules to skip"
|
|
51
|
+
)
|
|
52
|
+
check.add_argument("--no-baseline", action="store_true", help="report baselined issues as well")
|
|
53
|
+
|
|
54
|
+
base = sub.add_parser(
|
|
55
|
+
"baseline", help="record current issues so that only new ones fail the check"
|
|
56
|
+
)
|
|
57
|
+
_add_path(base)
|
|
58
|
+
|
|
59
|
+
sub.add_parser("rules", help="list available rules")
|
|
60
|
+
return parser
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _open_repo(path_arg: str) -> tuple[Path, Config]:
|
|
64
|
+
start = Path(path_arg).resolve()
|
|
65
|
+
if start.is_file():
|
|
66
|
+
start = start.parent
|
|
67
|
+
if not start.is_dir():
|
|
68
|
+
raise PyhyiError(f"path does not exist: {path_arg}")
|
|
69
|
+
root = git.find_root(start)
|
|
70
|
+
return root, load_config(root)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _print_errors(result: engine.Result) -> None:
|
|
74
|
+
for error in result.errors:
|
|
75
|
+
print(f"pyhyi: rule {error.rule} crashed:\n{error.traceback}", file=sys.stderr)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
79
|
+
root, config = _open_repo(args.path)
|
|
80
|
+
result = engine.run(
|
|
81
|
+
root,
|
|
82
|
+
config,
|
|
83
|
+
load_rules(),
|
|
84
|
+
select=args.select,
|
|
85
|
+
ignore=args.ignore,
|
|
86
|
+
use_baseline=not args.no_baseline,
|
|
87
|
+
)
|
|
88
|
+
render = report.render_json if args.format == "json" else report.render_text
|
|
89
|
+
sys.stdout.write(render(result))
|
|
90
|
+
_print_errors(result)
|
|
91
|
+
if result.errors:
|
|
92
|
+
return EXIT_ERROR
|
|
93
|
+
return EXIT_ISSUES if result.findings else EXIT_OK
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def cmd_baseline(args: argparse.Namespace) -> int:
|
|
97
|
+
root, config = _open_repo(args.path)
|
|
98
|
+
result = engine.run(root, config, load_rules(), use_baseline=False)
|
|
99
|
+
if result.errors:
|
|
100
|
+
_print_errors(result)
|
|
101
|
+
print("pyhyi: baseline not written because some rules crashed", file=sys.stderr)
|
|
102
|
+
return EXIT_ERROR
|
|
103
|
+
baseline.dump(root / config.baseline, result.findings)
|
|
104
|
+
issues = "1 issue" if len(result.findings) == 1 else f"{len(result.findings)} issues"
|
|
105
|
+
print(f"Recorded {issues} in {config.baseline}.")
|
|
106
|
+
return EXIT_OK
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_rules(args: argparse.Namespace) -> int:
|
|
110
|
+
registry = load_rules()
|
|
111
|
+
width = max(len(rule_id) for rule_id in registry)
|
|
112
|
+
for rule_id, cls in registry.items():
|
|
113
|
+
state = "" if cls.default_enabled else " (off by default)"
|
|
114
|
+
print(f"{rule_id:<{width}} {cls.summary}{state}")
|
|
115
|
+
return EXIT_OK
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
COMMANDS: dict[str, Callable[[argparse.Namespace], int]] = {
|
|
119
|
+
"check": cmd_check,
|
|
120
|
+
"baseline": cmd_baseline,
|
|
121
|
+
"rules": cmd_rules,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _tolerant_streams() -> None:
|
|
126
|
+
# Never crash on characters the console encoding cannot represent.
|
|
127
|
+
for stream in (sys.stdout, sys.stderr):
|
|
128
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
129
|
+
if reconfigure is not None:
|
|
130
|
+
with contextlib.suppress(ValueError, OSError):
|
|
131
|
+
reconfigure(errors="replace")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
135
|
+
_tolerant_streams()
|
|
136
|
+
parser = build_parser()
|
|
137
|
+
args = parser.parse_args(argv)
|
|
138
|
+
if args.command is None:
|
|
139
|
+
parser.print_help()
|
|
140
|
+
return EXIT_OK
|
|
141
|
+
try:
|
|
142
|
+
return COMMANDS[args.command](args)
|
|
143
|
+
except PyhyiError as exc:
|
|
144
|
+
print(f"pyhyi: error: {exc}", file=sys.stderr)
|
|
145
|
+
return EXIT_ERROR
|
pyhyi/config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Configuration: `pyhyi.toml`, `.pyhyi.toml` or `[tool.pyhyi]` in `pyproject.toml`.
|
|
2
|
+
|
|
3
|
+
The first file found in the repository root wins. Standalone files hold the
|
|
4
|
+
settings at the top level, so non-Python projects need no `pyproject.toml`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from pyhyi.errors import ConfigError
|
|
16
|
+
|
|
17
|
+
if sys.version_info >= (3, 11):
|
|
18
|
+
import tomllib
|
|
19
|
+
else: # pragma: no cover - exercised on Python 3.10 only
|
|
20
|
+
import tomli as tomllib
|
|
21
|
+
|
|
22
|
+
DEFAULT_BASELINE = ".pyhyi-baseline.json"
|
|
23
|
+
CONFIG_FILES = ("pyhyi.toml", ".pyhyi.toml", "pyproject.toml")
|
|
24
|
+
|
|
25
|
+
Where = Callable[[str], str]
|
|
26
|
+
|
|
27
|
+
_KEYS = frozenset({"select", "ignore", "exclude", "per-path-ignores", "baseline", "rules"})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Config:
|
|
32
|
+
source: Path | None = None
|
|
33
|
+
select: tuple[str, ...] | None = None
|
|
34
|
+
ignore: tuple[str, ...] = ()
|
|
35
|
+
exclude: tuple[str, ...] = ()
|
|
36
|
+
per_path_ignores: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
|
37
|
+
baseline: str = DEFAULT_BASELINE
|
|
38
|
+
rules: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
def where(self, key: str) -> str:
|
|
41
|
+
"""Human-readable location of a setting, for error messages."""
|
|
42
|
+
return f"{self.source.name}: {key}" if self.source else key
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_config(root: Path) -> Config:
|
|
46
|
+
for name in CONFIG_FILES:
|
|
47
|
+
path = root / name
|
|
48
|
+
if not path.is_file():
|
|
49
|
+
continue
|
|
50
|
+
data = _read_toml(path)
|
|
51
|
+
if name == "pyproject.toml":
|
|
52
|
+
tool = data.get("tool")
|
|
53
|
+
if not isinstance(tool, dict) or "pyhyi" not in tool:
|
|
54
|
+
continue
|
|
55
|
+
data = tool["pyhyi"]
|
|
56
|
+
return parse_config(data, source=path)
|
|
57
|
+
return Config()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _read_toml(path: Path) -> dict[str, Any]:
|
|
61
|
+
try:
|
|
62
|
+
with path.open("rb") as fh:
|
|
63
|
+
return tomllib.load(fh)
|
|
64
|
+
except tomllib.TOMLDecodeError as exc:
|
|
65
|
+
raise ConfigError(f"{path.name}: invalid TOML: {exc}") from exc
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_config(data: Any, source: Path | None = None) -> Config:
|
|
69
|
+
where = Config(source=source).where
|
|
70
|
+
if not isinstance(data, dict):
|
|
71
|
+
raise ConfigError(where("pyhyi settings must be a table"))
|
|
72
|
+
unknown = sorted(set(data) - _KEYS)
|
|
73
|
+
if unknown:
|
|
74
|
+
raise ConfigError(where(f"unknown key(s): {', '.join(unknown)}"))
|
|
75
|
+
return Config(
|
|
76
|
+
source=source,
|
|
77
|
+
select=_str_list(data, "select", where) if "select" in data else None,
|
|
78
|
+
ignore=_str_list(data, "ignore", where),
|
|
79
|
+
exclude=_str_list(data, "exclude", where),
|
|
80
|
+
per_path_ignores=_per_path(data.get("per-path-ignores", {}), where),
|
|
81
|
+
baseline=_baseline(data, where),
|
|
82
|
+
rules=_rules(data.get("rules", {}), where),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _str_list(data: dict[str, Any], key: str, where: Where) -> tuple[str, ...]:
|
|
87
|
+
value = data.get(key, [])
|
|
88
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
89
|
+
raise ConfigError(where(f"{key} must be a list of strings"))
|
|
90
|
+
return tuple(value)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _per_path(value: Any, where: Where) -> dict[str, tuple[str, ...]]:
|
|
94
|
+
if not isinstance(value, dict):
|
|
95
|
+
raise ConfigError(where("per-path-ignores must be a table of pattern = [rules]"))
|
|
96
|
+
return {
|
|
97
|
+
pattern: _str_list(value, pattern, lambda msg: where(f"per-path-ignores.{msg}"))
|
|
98
|
+
for pattern in value
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _baseline(data: dict[str, Any], where: Where) -> str:
|
|
103
|
+
value = data.get("baseline", DEFAULT_BASELINE)
|
|
104
|
+
if not isinstance(value, str) or not value.strip():
|
|
105
|
+
raise ConfigError(where("baseline must be a non-empty path string"))
|
|
106
|
+
return value
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _rules(value: Any, where: Where) -> dict[str, dict[str, Any]]:
|
|
110
|
+
if not isinstance(value, dict):
|
|
111
|
+
raise ConfigError(where("rules must be a table of rule-id tables"))
|
|
112
|
+
for rule_id, options in value.items():
|
|
113
|
+
if not isinstance(options, dict):
|
|
114
|
+
raise ConfigError(where(f"rules.{rule_id} must be a table of options"))
|
|
115
|
+
return {rule_id: dict(options) for rule_id, options in value.items()}
|
pyhyi/context.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Read-only view of the repository shared by all rules during one run."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from pathlib import Path, PurePosixPath
|
|
7
|
+
|
|
8
|
+
from pyhyi import git
|
|
9
|
+
from pyhyi.config import Config
|
|
10
|
+
from pyhyi.paths import PathMatcher
|
|
11
|
+
from pyhyi.suppressions import Suppression, scan
|
|
12
|
+
|
|
13
|
+
# Larger files are treated as non-text: rules almost never need them and
|
|
14
|
+
# reading generated multi-megabyte dumps would dominate run time.
|
|
15
|
+
MAX_TEXT_BYTES = 5_000_000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Context:
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
root: Path,
|
|
22
|
+
config: Config,
|
|
23
|
+
known_rules: frozenset[str] = frozenset(),
|
|
24
|
+
) -> None:
|
|
25
|
+
self.root = root
|
|
26
|
+
self.config = config
|
|
27
|
+
self.known_rules = known_rules
|
|
28
|
+
self.excluded = PathMatcher(config.exclude)
|
|
29
|
+
self.baseline_path = str(PurePosixPath(config.baseline))
|
|
30
|
+
self._text: dict[str, str | None] = {}
|
|
31
|
+
self._suppressions: dict[str, dict[int, Suppression]] = {}
|
|
32
|
+
|
|
33
|
+
# --- files -------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
@cached_property
|
|
36
|
+
def all_files(self) -> tuple[str, ...]:
|
|
37
|
+
"""Every file in the work tree that git knows about or would add."""
|
|
38
|
+
return tuple(git.list_files(self.root))
|
|
39
|
+
|
|
40
|
+
def is_excluded(self, path: str) -> bool:
|
|
41
|
+
"""Configured excludes, plus pyhyi's own baseline file."""
|
|
42
|
+
return path == self.baseline_path or self.excluded.match(path)
|
|
43
|
+
|
|
44
|
+
@cached_property
|
|
45
|
+
def files(self) -> tuple[str, ...]:
|
|
46
|
+
"""Files rules should scan: `all_files` minus excluded ones."""
|
|
47
|
+
return tuple(p for p in self.all_files if not self.is_excluded(p))
|
|
48
|
+
|
|
49
|
+
@cached_property
|
|
50
|
+
def _file_set(self) -> frozenset[str]:
|
|
51
|
+
return frozenset(self.all_files)
|
|
52
|
+
|
|
53
|
+
@cached_property
|
|
54
|
+
def _dir_set(self) -> frozenset[str]:
|
|
55
|
+
dirs: set[str] = set()
|
|
56
|
+
for path in self.all_files:
|
|
57
|
+
dirs.update(str(parent) for parent in PurePosixPath(path).parents)
|
|
58
|
+
dirs.discard(".")
|
|
59
|
+
return frozenset(dirs)
|
|
60
|
+
|
|
61
|
+
def exists(self, path: str) -> bool:
|
|
62
|
+
"""Whether a repository-relative path is a file or directory in the repo.
|
|
63
|
+
|
|
64
|
+
Excluded files still exist: `exclude` means "do not scan", not "absent".
|
|
65
|
+
"""
|
|
66
|
+
norm = str(PurePosixPath(path))
|
|
67
|
+
if norm == ".":
|
|
68
|
+
return True
|
|
69
|
+
return norm in self._file_set or norm in self._dir_set
|
|
70
|
+
|
|
71
|
+
def read_text(self, path: str) -> str | None:
|
|
72
|
+
"""File content as text, or None for binary, non-UTF-8 or huge files."""
|
|
73
|
+
if path not in self._text:
|
|
74
|
+
self._text[path] = self._load_text(path)
|
|
75
|
+
return self._text[path]
|
|
76
|
+
|
|
77
|
+
def lines(self, path: str) -> list[str]:
|
|
78
|
+
text = self.read_text(path)
|
|
79
|
+
return [] if text is None else text.splitlines()
|
|
80
|
+
|
|
81
|
+
def _load_text(self, path: str) -> str | None:
|
|
82
|
+
full = self.root / path
|
|
83
|
+
try:
|
|
84
|
+
if full.stat().st_size > MAX_TEXT_BYTES:
|
|
85
|
+
return None
|
|
86
|
+
data = full.read_bytes()
|
|
87
|
+
except OSError:
|
|
88
|
+
return None
|
|
89
|
+
if b"\0" in data[:8192]:
|
|
90
|
+
return None
|
|
91
|
+
try:
|
|
92
|
+
return data.decode("utf-8")
|
|
93
|
+
except UnicodeDecodeError:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
# --- suppressions ------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
def suppressions(self, path: str) -> dict[int, Suppression]:
|
|
99
|
+
if path not in self._suppressions:
|
|
100
|
+
text = self.read_text(path)
|
|
101
|
+
self._suppressions[path] = {} if text is None else scan(text)
|
|
102
|
+
return self._suppressions[path]
|
|
103
|
+
|
|
104
|
+
# --- history -----------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
@cached_property
|
|
107
|
+
def commits(self) -> tuple[git.Commit, ...]:
|
|
108
|
+
"""Commits reachable from HEAD, newest first."""
|
|
109
|
+
return tuple(git.log(self.root))
|
pyhyi/engine.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Runs selected rules over a repository and filters their findings.
|
|
2
|
+
|
|
3
|
+
Filtering order: `exclude` -> `per-path-ignores` -> inline suppressions ->
|
|
4
|
+
baseline. Excluded and per-path-ignored findings are dropped silently;
|
|
5
|
+
suppressed and baselined ones are counted in the summary.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import traceback
|
|
11
|
+
from collections.abc import Collection, Iterable, Mapping
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from pyhyi import baseline
|
|
17
|
+
from pyhyi.config import Config
|
|
18
|
+
from pyhyi.context import Context
|
|
19
|
+
from pyhyi.errors import ConfigError
|
|
20
|
+
from pyhyi.findings import Finding
|
|
21
|
+
from pyhyi.paths import PathMatcher
|
|
22
|
+
from pyhyi.rules import Rule, resolve_options
|
|
23
|
+
|
|
24
|
+
Registry = Mapping[str, type[Rule]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class RuleError:
|
|
29
|
+
"""A rule crashed. Other rules still run; the check exits with an error."""
|
|
30
|
+
|
|
31
|
+
rule: str
|
|
32
|
+
traceback: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Result:
|
|
37
|
+
findings: list[Finding] = field(default_factory=list)
|
|
38
|
+
suppressed: list[Finding] = field(default_factory=list)
|
|
39
|
+
baselined: list[Finding] = field(default_factory=list)
|
|
40
|
+
stale_baseline: int = 0
|
|
41
|
+
errors: list[RuleError] = field(default_factory=list)
|
|
42
|
+
rules: tuple[str, ...] = ()
|
|
43
|
+
|
|
44
|
+
def to_dict(self) -> dict[str, Any]:
|
|
45
|
+
return {
|
|
46
|
+
"findings": [f.to_dict() for f in self.findings],
|
|
47
|
+
"summary": {
|
|
48
|
+
"issues": len(self.findings),
|
|
49
|
+
"suppressed": len(self.suppressed),
|
|
50
|
+
"baselined": len(self.baselined),
|
|
51
|
+
"stale_baseline": self.stale_baseline,
|
|
52
|
+
"rules": list(self.rules),
|
|
53
|
+
},
|
|
54
|
+
"errors": [{"rule": e.rule, "traceback": e.traceback} for e in self.errors],
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _check_ids(ids: Iterable[str], registry: Registry, where: str) -> None:
|
|
59
|
+
unknown = sorted(set(ids) - set(registry))
|
|
60
|
+
if unknown:
|
|
61
|
+
raise ConfigError(f"{where}: unknown rule(s): {', '.join(unknown)}")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def validate_config(config: Config, registry: Registry) -> None:
|
|
65
|
+
"""Reject references to unknown rules and invalid rule options."""
|
|
66
|
+
_check_ids(config.select or (), registry, config.where("select"))
|
|
67
|
+
_check_ids(config.ignore, registry, config.where("ignore"))
|
|
68
|
+
for pattern, ids in config.per_path_ignores.items():
|
|
69
|
+
_check_ids(ids, registry, config.where(f"per-path-ignores.{pattern}"))
|
|
70
|
+
_check_ids(config.rules, registry, config.where("rules"))
|
|
71
|
+
for rule_id in config.rules:
|
|
72
|
+
resolve_options(registry[rule_id], config)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def select_rules(
|
|
76
|
+
registry: Registry,
|
|
77
|
+
config: Config,
|
|
78
|
+
*,
|
|
79
|
+
select: Collection[str] | None = None,
|
|
80
|
+
ignore: Collection[str] = (),
|
|
81
|
+
) -> list[type[Rule]]:
|
|
82
|
+
"""`select` (CLI) replaces the configured selection; `ignore` adds to it."""
|
|
83
|
+
if select is not None:
|
|
84
|
+
_check_ids(select, registry, "--select")
|
|
85
|
+
_check_ids(ignore, registry, "--ignore")
|
|
86
|
+
chosen = select if select is not None else config.select
|
|
87
|
+
if chosen is None:
|
|
88
|
+
ids = [rule_id for rule_id, cls in registry.items() if cls.default_enabled]
|
|
89
|
+
else:
|
|
90
|
+
ids = list(chosen)
|
|
91
|
+
skip = set(config.ignore) | set(ignore)
|
|
92
|
+
return [registry[rule_id] for rule_id in sorted(set(ids)) if rule_id not in skip]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def run(
|
|
96
|
+
root: Path,
|
|
97
|
+
config: Config,
|
|
98
|
+
registry: Registry,
|
|
99
|
+
*,
|
|
100
|
+
select: Collection[str] | None = None,
|
|
101
|
+
ignore: Collection[str] = (),
|
|
102
|
+
use_baseline: bool = True,
|
|
103
|
+
) -> Result:
|
|
104
|
+
validate_config(config, registry)
|
|
105
|
+
rules = select_rules(registry, config, select=select, ignore=ignore)
|
|
106
|
+
ctx = Context(root, config, known_rules=frozenset(registry))
|
|
107
|
+
per_path = [
|
|
108
|
+
(PathMatcher([pattern]), set(ids)) for pattern, ids in config.per_path_ignores.items()
|
|
109
|
+
]
|
|
110
|
+
result = Result(rules=tuple(cls.id for cls in rules))
|
|
111
|
+
|
|
112
|
+
for cls in rules:
|
|
113
|
+
rule = cls(resolve_options(cls, config))
|
|
114
|
+
try:
|
|
115
|
+
produced = list(rule.check(ctx))
|
|
116
|
+
except Exception:
|
|
117
|
+
result.errors.append(RuleError(cls.id, traceback.format_exc()))
|
|
118
|
+
continue
|
|
119
|
+
for finding in produced:
|
|
120
|
+
if finding.path is not None:
|
|
121
|
+
if ctx.is_excluded(finding.path):
|
|
122
|
+
continue
|
|
123
|
+
if any(finding.rule in ids and m.match(finding.path) for m, ids in per_path):
|
|
124
|
+
continue
|
|
125
|
+
if _suppressed(ctx, finding):
|
|
126
|
+
result.suppressed.append(finding)
|
|
127
|
+
continue
|
|
128
|
+
result.findings.append(finding)
|
|
129
|
+
|
|
130
|
+
result.findings.sort(key=Finding.sort_key)
|
|
131
|
+
if use_baseline:
|
|
132
|
+
known = baseline.load(root / config.baseline)
|
|
133
|
+
if known is not None:
|
|
134
|
+
result.findings, result.baselined, result.stale_baseline = baseline.apply(
|
|
135
|
+
result.findings, known, result.rules
|
|
136
|
+
)
|
|
137
|
+
return result
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _suppressed(ctx: Context, finding: Finding) -> bool:
|
|
141
|
+
if finding.path is None or finding.line is None:
|
|
142
|
+
return False
|
|
143
|
+
sup = ctx.suppressions(finding.path).get(finding.line)
|
|
144
|
+
return sup is not None and bool(sup.reason) and finding.rule in sup.rules
|
pyhyi/errors.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Errors shown to the user as-is (no traceback)."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class PyhyiError(Exception):
|
|
5
|
+
"""Base class for expected failures: bad config, not a git repo, and so on."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ConfigError(PyhyiError):
|
|
9
|
+
"""Invalid pyhyi configuration."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GitError(PyhyiError):
|
|
13
|
+
"""A git command failed or git is unavailable."""
|
pyhyi/findings.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The unit of output: one finding reported by one rule."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Severity(str, Enum):
|
|
11
|
+
ERROR = "error"
|
|
12
|
+
WARNING = "warning"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Finding:
|
|
17
|
+
"""One issue found in the repository.
|
|
18
|
+
|
|
19
|
+
`path` is a repository-relative POSIX path, or None for repository-level
|
|
20
|
+
findings (commits, layout as a whole). `line` is 1-based.
|
|
21
|
+
|
|
22
|
+
`key` identifies the finding within its rule and path for the baseline.
|
|
23
|
+
It must not depend on line numbers, so that unrelated edits do not
|
|
24
|
+
resurrect baselined findings. When omitted, `message` is used, which is why
|
|
25
|
+
messages must not contain line numbers either.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
rule: str
|
|
29
|
+
message: str
|
|
30
|
+
path: str | None = None
|
|
31
|
+
line: int | None = None
|
|
32
|
+
key: str | None = None
|
|
33
|
+
hint: str | None = None
|
|
34
|
+
severity: Severity = Severity.ERROR
|
|
35
|
+
|
|
36
|
+
def to_dict(self) -> dict[str, Any]:
|
|
37
|
+
return {
|
|
38
|
+
"rule": self.rule,
|
|
39
|
+
"severity": self.severity.value,
|
|
40
|
+
"path": self.path,
|
|
41
|
+
"line": self.line,
|
|
42
|
+
"message": self.message,
|
|
43
|
+
"hint": self.hint,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
def sort_key(self) -> tuple[str, int, str, str]:
|
|
47
|
+
return (self.path or "", self.line or 0, self.rule, self.message)
|