Developer tools dump stack traces, exit codes, and jargon. Figuring out *what to do next* often means searching the same Stack Overflow answers again.
| 1 | """Rule registry with automatic discovery.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | from why_failed.models import Rule |
| 6 | |
| 7 | _RULES: list[Rule] | None = None |
| 8 | |
| 9 | |
| 10 | def _load_rules() -> list[Rule]: |
| 11 | """Import all rule modules and collect RULES lists.""" |
| 12 | # Local imports keep startup light and avoid circular imports. |
| 13 | from why_failed.rules import ( |
| 14 | docker, |
| 15 | git, |
| 16 | linux, |
| 17 | mongodb, |
| 18 | node, |
| 19 | npm, |
| 20 | python, |
| 21 | redis, |
| 22 | typescript, |
| 23 | ) |
| 24 | |
| 25 | modules = (git, npm, node, python, docker, typescript, mongodb, redis, linux) |
| 26 | collected: list[Rule] = [] |
| 27 | for module in modules: |
| 28 | rules = getattr(module, "RULES", []) |
| 29 | collected.extend(rules) |
| 30 | return collected |
| 31 | |
| 32 | |
| 33 | def get_all_rules() -> list[Rule]: |
| 34 | """Return every registered rule (cached after first load).""" |
| 35 | global _RULES |
| 36 | if _RULES is None: |
| 37 | _RULES = _load_rules() |
| 38 | return list(_RULES) |
| 39 | |
| 40 | |
| 41 | def get_rules_for_tool(tool: str) -> list[Rule]: |
| 42 | """Return rules for a specific tool name.""" |
| 43 | tool_lower = tool.lower() |
| 44 | return [r for r in get_all_rules() if r.tool.lower() == tool_lower] |
| 45 | |
| 46 | |
| 47 | def reset_registry() -> None: |
| 48 | """Clear the cached rule list (useful in tests).""" |
| 49 | global _RULES |
| 50 | _RULES = None |
| 51 | |
| 52 | |
| 53 | def rules_by_tool() -> dict[str, list[Rule]]: |
| 54 | """Group rules by tool, sorted by tool name then rule id.""" |
| 55 | grouped: dict[str, list[Rule]] = {} |
| 56 | for rule in get_all_rules(): |
| 57 | grouped.setdefault(rule.tool, []).append(rule) |
| 58 | for tool in grouped: |
| 59 | grouped[tool].sort(key=lambda r: r.id) |
| 60 | return dict(sorted(grouped.items())) |