tminus 1.0.0__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.
Files changed (70) hide show
  1. tminus/__init__.py +3 -0
  2. tminus/cli/__init__.py +0 -0
  3. tminus/cli/main.py +177 -0
  4. tminus/engine/__init__.py +0 -0
  5. tminus/engine/app_packaging.py +160 -0
  6. tminus/engine/baseline.py +84 -0
  7. tminus/engine/context.py +53 -0
  8. tminus/engine/env_check.py +133 -0
  9. tminus/engine/frappe_refs.py +310 -0
  10. tminus/engine/guards.py +32 -0
  11. tminus/engine/jinja_refs.py +89 -0
  12. tminus/engine/js_refs.py +464 -0
  13. tminus/engine/loader.py +55 -0
  14. tminus/engine/matchers/__init__.py +22 -0
  15. tminus/engine/matchers/call.py +65 -0
  16. tminus/engine/matchers/doctype.py +50 -0
  17. tminus/engine/matchers/import_path.py +59 -0
  18. tminus/engine/matchers/query_syntax.py +249 -0
  19. tminus/engine/matchers/returns_none.py +86 -0
  20. tminus/engine/matchers/subclass.py +27 -0
  21. tminus/engine/models.py +217 -0
  22. tminus/engine/names.py +33 -0
  23. tminus/engine/paths.py +13 -0
  24. tminus/engine/pyparse.py +13 -0
  25. tminus/engine/ref_rules.py +50 -0
  26. tminus/engine/runner.py +78 -0
  27. tminus/engine/scanners/__init__.py +0 -0
  28. tminus/engine/scanners/hooks.py +413 -0
  29. tminus/engine/scanners/js_ast.py +16 -0
  30. tminus/engine/scanners/packaging.py +88 -0
  31. tminus/engine/scanners/print_format.py +105 -0
  32. tminus/engine/scanners/python_ast.py +29 -0
  33. tminus/engine/sql_refs.py +92 -0
  34. tminus/engine/suppress.py +15 -0
  35. tminus/engine/versions.py +127 -0
  36. tminus/report/__init__.py +0 -0
  37. tminus/report/files.py +51 -0
  38. tminus/report/pdf.py +146 -0
  39. tminus/report/render.py +407 -0
  40. tminus/rules/v16/target.yaml +18 -0
  41. tminus/rules/v16/v16-app-dependency-pins.yaml +102 -0
  42. tminus/rules/v16/v16-app-frappe-bound-missing.yaml +20 -0
  43. tminus/rules/v16/v16-app-frappe-bound.yaml +21 -0
  44. tminus/rules/v16/v16-app-node-engine.yaml +21 -0
  45. tminus/rules/v16/v16-app-requires-python.yaml +22 -0
  46. tminus/rules/v16/v16-db-commit-in-doc-events.yaml +26 -0
  47. tminus/rules/v16/v16-erpnext-get-item-tax-map-keyword-only.yaml +25 -0
  48. tminus/rules/v16/v16-erpnext-get-itemised-tax-takes-doc.yaml +26 -0
  49. tminus/rules/v16/v16-erpnext-removed-get-batch-incoming-rate.yaml +26 -0
  50. tminus/rules/v16/v16-erpnext-removed-or-renamed-fields.yaml +171 -0
  51. tminus/rules/v16/v16-erpnext-removed-tax-withholding-helpers.yaml +49 -0
  52. tminus/rules/v16/v16-erpnext-validate-party-frozen-disabled-company-arg.yaml +25 -0
  53. tminus/rules/v16/v16-first-row-without-order-by.yaml +25 -0
  54. tminus/rules/v16/v16-frappe-removed-fields.yaml +59 -0
  55. tminus/rules/v16/v16-get-all-sql-strings.yaml +23 -0
  56. tminus/rules/v16/v16-get-doc-extra-keywords.yaml +28 -0
  57. tminus/rules/v16/v16-has-permission-hook-returns-none.yaml +23 -0
  58. tminus/rules/v16/v16-has-permission-hook-unreadable.yaml +22 -0
  59. tminus/rules/v16/v16-hrms-removed-fields.yaml +42 -0
  60. tminus/rules/v16/v16-hrms-removed-get-max-benefits.yaml +26 -0
  61. tminus/rules/v16/v16-override-doctype-class-no-base.yaml +25 -0
  62. tminus/rules/v16/v16-override-doctype-class-unreadable.yaml +22 -0
  63. tminus/rules/v16/v16-removed-doctypes.yaml +54 -0
  64. tminus/rules/v16/v16-removed-hooks.yaml +24 -0
  65. tminus/rules/v16/v16-removed-python-stdlib.yaml +21 -0
  66. tminus-1.0.0.dist-info/METADATA +124 -0
  67. tminus-1.0.0.dist-info/RECORD +70 -0
  68. tminus-1.0.0.dist-info/WHEEL +4 -0
  69. tminus-1.0.0.dist-info/entry_points.txt +2 -0
  70. tminus-1.0.0.dist-info/licenses/LICENSE +21 -0
tminus/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """T-MINUS: count down to a clean Frappe/ERPNext upgrade."""
2
+
3
+ __version__ = "1.0.0"
tminus/cli/__init__.py ADDED
File without changes
tminus/cli/main.py ADDED
@@ -0,0 +1,177 @@
1
+ """Command line entry point: `tminus scan <path> --target v16`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from enum import StrEnum
7
+ from pathlib import Path
8
+
9
+ import typer
10
+
11
+ from tminus import __version__
12
+ from tminus.engine.baseline import BaselineError, apply_baseline, load_baseline, write_baseline
13
+ from tminus.engine.env_check import check_environment, format_rows, run_command
14
+ from tminus.engine.loader import RuleLoadError, UnknownTargetError, load_rules, load_target
15
+ from tminus.engine.models import SEVERITY_ORDER
16
+ from tminus.engine.runner import scan_path
17
+ from tminus.report.files import default_report_path, open_report, write_report
18
+ from tminus.report.pdf import render_pdf
19
+ from tminus.report.render import render_html, render_json, render_sarif, render_text
20
+
21
+ app = typer.Typer(help="Count down to a clean Frappe/ERPNext upgrade.", no_args_is_help=True)
22
+
23
+ EXIT_FINDINGS = 1 # findings at or above --fail-on
24
+ EXIT_USAGE = 2 # unknown target, missing path
25
+ EXIT_FAILED = 3 # scan could not run
26
+
27
+
28
+ class OutputFormat(StrEnum):
29
+ """Supported report formats."""
30
+
31
+ text = "text"
32
+ json = "json"
33
+ html = "html"
34
+ pdf = "pdf"
35
+ sarif = "sarif"
36
+
37
+
38
+ class FailOn(StrEnum):
39
+ """Lowest severity that makes the command fail."""
40
+
41
+ error = "error"
42
+ warning = "warning"
43
+ info = "info"
44
+ never = "never"
45
+
46
+
47
+ class ColorMode(StrEnum):
48
+ """When the text report uses ANSI terminal colors."""
49
+
50
+ auto = "auto"
51
+ always = "always"
52
+ never = "never"
53
+
54
+
55
+ def _version_callback(value: bool) -> None:
56
+ """Print the version and exit when --version is given."""
57
+ if value:
58
+ typer.echo(f"tminus {__version__}")
59
+ raise typer.Exit()
60
+
61
+
62
+ @app.callback()
63
+ def main(
64
+ version: bool = typer.Option(
65
+ False, "--version", callback=_version_callback, is_eager=True, help="Show version."
66
+ ),
67
+ ) -> None:
68
+ """Root command group (keeps `scan` as a subcommand)."""
69
+
70
+
71
+ @app.command()
72
+ def scan(
73
+ path: Path = typer.Argument(..., help="App folder or file to scan."),
74
+ target: str = typer.Option(..., "--target", help="Version to check against, e.g. v16."),
75
+ fmt: OutputFormat = typer.Option(OutputFormat.text, "--format", help="Report format."),
76
+ fail_on: FailOn = typer.Option(FailOn.error, "--fail-on", help="Lowest severity that fails."),
77
+ baseline: Path | None = typer.Option(
78
+ None, "--baseline", help="Hide findings already in this baseline (or JSON report)."
79
+ ),
80
+ save_baseline: Path | None = typer.Option(
81
+ None, "--write-baseline", help="Save the current findings as a baseline and exit 0."
82
+ ),
83
+ color: ColorMode = typer.Option(
84
+ ColorMode.auto, "--color", help="Color text output: auto, always or never."
85
+ ),
86
+ output: Path | None = typer.Option(
87
+ None, "--output", help="Write the report to this file instead of the default location."
88
+ ),
89
+ open_saved: bool = typer.Option(
90
+ True,
91
+ "--open/--no-open",
92
+ help="Open saved HTML and PDF reports (default: open).",
93
+ ),
94
+ ) -> None:
95
+ """T-30: static scan of code for breaking changes (read-only)."""
96
+ if baseline is not None and save_baseline is not None:
97
+ typer.echo("use either --baseline or --write-baseline, not both", err=True)
98
+ raise typer.Exit(EXIT_USAGE)
99
+ try:
100
+ rules = load_rules(target)
101
+ result = scan_path(path, rules)
102
+ except UnknownTargetError as exc:
103
+ typer.echo(str(exc), err=True)
104
+ raise typer.Exit(EXIT_USAGE) from exc
105
+ except FileNotFoundError as exc:
106
+ typer.echo(f"path not found: {exc}", err=True)
107
+ raise typer.Exit(EXIT_USAGE) from exc
108
+ except RuleLoadError as exc: # a broken rule file is a tool bug, not a usage error
109
+ typer.echo(f"invalid rule: {exc}", err=True)
110
+ raise typer.Exit(EXIT_FAILED) from exc
111
+
112
+ if save_baseline is not None:
113
+ count = write_baseline(result, path, save_baseline, target)
114
+ typer.echo(f"Wrote a baseline of {count} findings to {save_baseline}")
115
+ return
116
+ if baseline is not None:
117
+ try:
118
+ result = apply_baseline(result, load_baseline(baseline, path), path)
119
+ except BaselineError as exc:
120
+ typer.echo(str(exc), err=True)
121
+ raise typer.Exit(EXIT_USAGE) from exc
122
+
123
+ use_color = fmt == OutputFormat.text and (
124
+ color == ColorMode.always or (color == ColorMode.auto and sys.stdout.isatty())
125
+ )
126
+ report: str | bytes
127
+ if fmt == OutputFormat.json:
128
+ report = render_json(result, target)
129
+ elif fmt == OutputFormat.html:
130
+ report = render_html(result, target, rules, app_name=path.name)
131
+ elif fmt == OutputFormat.pdf:
132
+ report = render_pdf(result, target, rules, app_name=path.name)
133
+ elif fmt == OutputFormat.sarif:
134
+ report = render_sarif(result, target, rules, path)
135
+ else:
136
+ report = render_text(result, target, rules, app_name=path.name, color=use_color)
137
+ saved_format = fmt in (OutputFormat.html, OutputFormat.pdf, OutputFormat.sarif)
138
+ destination = output or (default_report_path(path, target, fmt.value) if saved_format else None)
139
+ if destination is None:
140
+ typer.echo(report, color=use_color)
141
+ else:
142
+ try:
143
+ if output is None:
144
+ destination.parent.mkdir(parents=True, exist_ok=True)
145
+ saved = write_report(destination, report)
146
+ except OSError as exc:
147
+ typer.echo(f"cannot write report: {exc}", err=True)
148
+ raise typer.Exit(EXIT_FAILED) from exc
149
+ typer.echo(f"Report written to: {saved}")
150
+ if open_saved and fmt in (OutputFormat.html, OutputFormat.pdf):
151
+ try:
152
+ open_report(saved)
153
+ except OSError as exc:
154
+ typer.echo(f"could not open report: {exc}", err=True)
155
+
156
+ if fail_on is not FailOn.never:
157
+ threshold = SEVERITY_ORDER[fail_on.value]
158
+ if any(SEVERITY_ORDER[f.severity] >= threshold for f in result.findings):
159
+ raise typer.Exit(EXIT_FINDINGS)
160
+
161
+
162
+ @app.command()
163
+ def env(
164
+ path: Path = typer.Argument(Path("."), help="Bench folder (used to read its Python version)."),
165
+ target: str = typer.Option(..., "--target", help="Version to check against, e.g. v16."),
166
+ ) -> None:
167
+ """T-30: compare Python, Node, MariaDB and Redis on this machine with what the target needs."""
168
+ try:
169
+ info = load_target(target)
170
+ except UnknownTargetError as exc:
171
+ typer.echo(str(exc), err=True)
172
+ raise typer.Exit(EXIT_USAGE) from exc
173
+ except RuleLoadError as exc:
174
+ typer.echo(f"invalid target file: {exc}", err=True)
175
+ raise typer.Exit(EXIT_FAILED) from exc
176
+ rows = check_environment(info.requirements, run_command, path if path.is_dir() else None)
177
+ typer.echo(format_rows(rows, target))
File without changes
@@ -0,0 +1,160 @@
1
+ """Read an app's packaging files: Python range, frappe bound, dependencies, Node engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import json
7
+ import re
8
+ import tomllib
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from packaging.requirements import InvalidRequirement, Requirement
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Where:
17
+ """A value read from a packaging file, with the file and line it came from."""
18
+
19
+ value: str
20
+ file: Path
21
+ line: int
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Dependency:
26
+ """A dependency of the app: normalized name, version specifier text, and where it is."""
27
+
28
+ name: str
29
+ spec: str
30
+ where: Where
31
+
32
+
33
+ @dataclass
34
+ class AppPackaging:
35
+ """Everything the compatibility rules need to know about one app."""
36
+
37
+ name: str
38
+ root: Path
39
+ anchor: (
40
+ Path # file to point at when something is missing (pyproject.toml, setup.py or the root)
41
+ )
42
+ requires_python: Where | None = None
43
+ frappe_bound: Where | None = None
44
+ node_engine: Where | None = None
45
+ dependencies: list[Dependency] = field(default_factory=list)
46
+
47
+
48
+ def normalize(name: str) -> str:
49
+ """PEP 503 name normalization: lower case, runs of `-_.` become `-`."""
50
+ return re.sub(r"[-_.]+", "-", name).lower()
51
+
52
+
53
+ def _line_of(text: str, pattern: str) -> int:
54
+ """Line number (1-based) of the first match of a regex, or 1."""
55
+ match = re.search(pattern, text, re.MULTILINE)
56
+ return 1 + text.count("\n", 0, match.start()) if match else 1
57
+
58
+
59
+ def _dependency(requirement: str, file: Path, line: int) -> Dependency | None:
60
+ """Parse one requirement string; None for URLs, options and anything unreadable."""
61
+ try:
62
+ parsed = Requirement(requirement.strip())
63
+ except InvalidRequirement:
64
+ return None
65
+ if parsed.url: # direct references have no version range to compare
66
+ return None
67
+ return Dependency(normalize(parsed.name), str(parsed.specifier), Where(requirement, file, line))
68
+
69
+
70
+ def _from_pyproject(path: Path, app: AppPackaging) -> None:
71
+ """Fill the app facts from pyproject.toml."""
72
+ text = path.read_text(encoding="utf-8")
73
+ try:
74
+ data = tomllib.loads(text)
75
+ except tomllib.TOMLDecodeError:
76
+ return
77
+ project = data.get("project", {})
78
+ app.name = project.get("name", app.name)
79
+ if isinstance(project.get("requires-python"), str):
80
+ line = _line_of(text, r"^requires-python\s*=")
81
+ app.requires_python = Where(project["requires-python"], path, line)
82
+ bound = data.get("tool", {}).get("bench", {}).get("frappe-dependencies", {}).get("frappe")
83
+ if isinstance(bound, str):
84
+ app.frappe_bound = Where(bound, path, _line_of(text, r"^frappe\s*="))
85
+ for requirement in project.get("dependencies", []):
86
+ if isinstance(requirement, str):
87
+ line = _line_of(text, re.escape(f'"{requirement}"'))
88
+ if dep := _dependency(requirement, path, line):
89
+ app.dependencies.append(dep)
90
+
91
+
92
+ def _setup_keyword(tree: ast.Module, keyword: str) -> ast.expr | None:
93
+ """The value of a keyword argument of the setup(...) call."""
94
+ for node in ast.walk(tree):
95
+ if isinstance(node, ast.Call):
96
+ name = (
97
+ node.func.id if isinstance(node.func, ast.Name) else getattr(node.func, "attr", "")
98
+ )
99
+ if name == "setup":
100
+ for kw in node.keywords:
101
+ if kw.arg == keyword:
102
+ return kw.value
103
+ return None
104
+
105
+
106
+ def _from_setup_py(path: Path, app: AppPackaging) -> None:
107
+ """Fill the app facts from a legacy setup.py (literal values only)."""
108
+ try:
109
+ tree = ast.parse(path.read_text(encoding="utf-8"))
110
+ except (SyntaxError, UnicodeDecodeError):
111
+ return
112
+ required = _setup_keyword(tree, "python_requires")
113
+ if isinstance(required, ast.Constant) and isinstance(required.value, str):
114
+ app.requires_python = Where(required.value, path, required.lineno)
115
+ install = _setup_keyword(tree, "install_requires")
116
+ if isinstance(install, ast.List | ast.Tuple):
117
+ for item in install.elts:
118
+ is_str = isinstance(item, ast.Constant) and isinstance(item.value, str)
119
+ text = item.value if isinstance(item, ast.Constant) and is_str else None
120
+ if isinstance(text, str) and (dep := _dependency(text, path, item.lineno)):
121
+ app.dependencies.append(dep)
122
+
123
+
124
+ def _from_requirements(path: Path, app: AppPackaging) -> None:
125
+ """Fill dependencies from requirements.txt (one requirement per line)."""
126
+ for number, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
127
+ line = raw.split("#", 1)[0].strip()
128
+ if line and not line.startswith("-") and (dep := _dependency(line, path, number)):
129
+ app.dependencies.append(dep)
130
+
131
+
132
+ def _from_package_json(path: Path, app: AppPackaging) -> None:
133
+ """Fill the Node engine range from package.json."""
134
+ text = path.read_text(encoding="utf-8")
135
+ try:
136
+ engines = json.loads(text).get("engines", {})
137
+ except ValueError:
138
+ return
139
+ node = engines.get("node") if isinstance(engines, dict) else None
140
+ if isinstance(node, str):
141
+ app.node_engine = Where(node, path, _line_of(text, r'"node"\s*:'))
142
+
143
+
144
+ def read_app(root: Path) -> AppPackaging | None:
145
+ """Read the packaging files in an app's repository root; None if there are none."""
146
+ pyproject, setup_py = root / "pyproject.toml", root / "setup.py"
147
+ requirements, package_json = root / "requirements.txt", root / "package.json"
148
+ if not any(p.is_file() for p in (pyproject, setup_py, requirements)):
149
+ return None
150
+ anchor = pyproject if pyproject.is_file() else setup_py if setup_py.is_file() else root
151
+ app = AppPackaging(name=root.name, root=root, anchor=anchor)
152
+ if pyproject.is_file():
153
+ _from_pyproject(pyproject, app)
154
+ if setup_py.is_file():
155
+ _from_setup_py(setup_py, app)
156
+ if requirements.is_file() and not app.dependencies: # setup.py usually reads this file
157
+ _from_requirements(requirements, app)
158
+ if package_json.is_file():
159
+ _from_package_json(package_json, app)
160
+ return app
@@ -0,0 +1,84 @@
1
+ """Baselines: remember today's findings so that only new ones are reported."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections import Counter
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from tminus.engine.models import Finding, ScanResult
12
+
13
+ BASELINE_VERSION = 1
14
+ Fingerprint = tuple[
15
+ str, str, str, str
16
+ ] # (rule id, file relative to the scan root, snippet, detail)
17
+
18
+
19
+ class BaselineError(Exception):
20
+ """The baseline file cannot be read or has the wrong shape."""
21
+
22
+
23
+ def _relative(file: str, root: Path) -> str:
24
+ """The file path relative to the scanned folder, with forward slashes."""
25
+ base = root if root.is_dir() else root.parent
26
+ try:
27
+ return Path(os.path.relpath(file, base)).as_posix()
28
+ except ValueError: # a different drive on Windows
29
+ return Path(file).as_posix()
30
+
31
+
32
+ def fingerprint(finding: Finding, root: Path) -> Fingerprint:
33
+ """Identify a finding without its line number, so edits above it do not make it "new"."""
34
+ return (finding.rule_id, _relative(finding.file, root), finding.snippet.strip(), finding.detail)
35
+
36
+
37
+ def write_baseline(result: ScanResult, root: Path, path: Path, target: str) -> int:
38
+ """Save the current findings as a baseline file; returns how many findings it holds."""
39
+ counts = Counter(fingerprint(f, root) for f in result.findings)
40
+ entries = [
41
+ {"rule_id": rule, "file": file, "snippet": snippet, "detail": detail, "count": count}
42
+ for (rule, file, snippet, detail), count in sorted(counts.items())
43
+ ]
44
+ document = {"version": BASELINE_VERSION, "target": target, "entries": entries}
45
+ path.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8")
46
+ return len(result.findings)
47
+
48
+
49
+ def _from_entries(entries: list[dict[str, Any]]) -> Counter[Fingerprint]:
50
+ """Fingerprints from a baseline file's entries (each with a count)."""
51
+ counts: Counter[Fingerprint] = Counter()
52
+ for entry in entries:
53
+ key = (entry["rule_id"], entry["file"], entry["snippet"], entry.get("detail", ""))
54
+ counts[key] += int(entry.get("count", 1))
55
+ return counts
56
+
57
+
58
+ def load_baseline(path: Path, root: Path) -> Counter[Fingerprint]:
59
+ """Read a baseline file, or a full JSON report saved with `--format json`."""
60
+ try:
61
+ data = json.loads(path.read_text(encoding="utf-8"))
62
+ if "entries" in data:
63
+ return _from_entries(data["entries"])
64
+ if "result" in data: # a JSON report: use its findings
65
+ findings = [Finding.model_validate(f) for f in data["result"]["findings"]]
66
+ return Counter(fingerprint(f, root) for f in findings)
67
+ except (OSError, ValueError, KeyError, TypeError) as exc:
68
+ raise BaselineError(f"cannot read baseline {path}: {exc}") from exc
69
+ raise BaselineError(f"{path} is not a T-MINUS baseline or JSON report")
70
+
71
+
72
+ def apply_baseline(result: ScanResult, baseline: Counter[Fingerprint], root: Path) -> ScanResult:
73
+ """Hide the findings that are in the baseline (counted, so a second copy still shows)."""
74
+ remaining = Counter(baseline)
75
+ kept: list[Finding] = []
76
+ hidden = 0
77
+ for finding in result.findings:
78
+ key = fingerprint(finding, root)
79
+ if remaining[key] > 0:
80
+ remaining[key] -= 1
81
+ hidden += 1
82
+ else:
83
+ kept.append(finding)
84
+ return result.model_copy(update={"findings": kept, "baselined": hidden})
@@ -0,0 +1,53 @@
1
+ """Per-file facts computed once and shared by every matcher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import dataclass
7
+
8
+ from tminus.engine.frappe_refs import FieldRef, collect_refs
9
+ from tminus.engine.guards import guarded_ranges
10
+ from tminus.engine.names import build_alias_table, resolve
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class FileContext:
15
+ """The parsed file plus lookups that many rules need."""
16
+
17
+ tree: ast.AST
18
+ aliases: dict[str, str] # local name -> dotted import path
19
+ guarded: list[tuple[int, int]] # line ranges protected by try/except ImportError
20
+ from_imports: list[ast.ImportFrom]
21
+ calls: list[tuple[ast.Call, str | None]] # each call and the dotted path it calls
22
+ attr_paths: list[tuple[int, str]] # (line, dotted path) of resolvable attribute chains
23
+ field_refs: list[FieldRef] # (doctype, field name, line) where the doctype is known
24
+ doctype_refs: list[tuple[str, int]] # (doctype name, line) used as a DocType argument
25
+
26
+ @classmethod
27
+ def build(cls, tree: ast.AST) -> FileContext:
28
+ """Walk the tree once and collect everything the matchers will ask for."""
29
+ aliases = build_alias_table(tree)
30
+ from_imports: list[ast.ImportFrom] = []
31
+ calls: list[tuple[ast.Call, str | None]] = []
32
+ attr_paths: list[tuple[int, str]] = []
33
+ for node in ast.walk(tree):
34
+ if isinstance(node, ast.ImportFrom):
35
+ from_imports.append(node)
36
+ elif isinstance(node, ast.Call):
37
+ calls.append((node, resolve(node.func, aliases)))
38
+ elif isinstance(node, ast.Attribute):
39
+ path = resolve(node, aliases)
40
+ if path is not None:
41
+ attr_paths.append((node.lineno, path))
42
+
43
+ field_refs, doctype_refs = collect_refs(tree, aliases, calls)
44
+ return cls(
45
+ tree,
46
+ aliases,
47
+ guarded_ranges(tree),
48
+ from_imports,
49
+ calls,
50
+ attr_paths,
51
+ field_refs,
52
+ doctype_refs,
53
+ )
@@ -0,0 +1,133 @@
1
+ """Compare the versions installed on this machine with what a target version needs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Literal
11
+
12
+ from packaging.version import InvalidVersion, Version
13
+
14
+ from tminus.engine.models import RequirementSpec
15
+
16
+ Runner = Callable[[list[str]], str | None] # runs a command, returns its output or None
17
+ Status = Literal["ok", "upgrade", "missing"]
18
+
19
+ _VERSION = r"(\d+\.\d+(?:\.\d+)?)"
20
+ _PATTERNS: dict[str, list[str]] = {
21
+ "python": [rf"Python\s+{_VERSION}"],
22
+ "node": [rf"v?{_VERSION}"],
23
+ "redis": [rf"v={_VERSION}"],
24
+ "mariadb": [rf"{_VERSION}-MariaDB", rf"Distrib\s+{_VERSION}"],
25
+ }
26
+ _COMMANDS: dict[str, list[list[str]]] = {
27
+ "python": [["python3", "--version"]],
28
+ "node": [["node", "--version"]],
29
+ "redis": [["redis-server", "--version"]],
30
+ "mariadb": [["mariadb", "--version"], ["mysql", "--version"]],
31
+ }
32
+ _PYVENV = re.compile(rf"^version(?:_info)?\s*=\s*{_VERSION}", re.MULTILINE)
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class EnvRow:
37
+ """One line of the environment report."""
38
+
39
+ name: str
40
+ found: str | None
41
+ where: str # how it was found (a command or the bench's pyvenv.cfg)
42
+ needs: str
43
+ status: Status
44
+ note: str = ""
45
+
46
+
47
+ def run_command(args: list[str]) -> str | None:
48
+ """Run a command; return its output, or None if it is missing, fails or hangs."""
49
+ try:
50
+ done = subprocess.run(args, capture_output=True, text=True, timeout=10, check=False)
51
+ except (OSError, subprocess.TimeoutExpired):
52
+ return None
53
+ return (done.stdout + done.stderr).strip() or None
54
+
55
+
56
+ def _first_version(text: str, patterns: list[str]) -> str | None:
57
+ """The first version number matched by any of the patterns."""
58
+ for pattern in patterns:
59
+ if match := re.search(pattern, text):
60
+ return match.group(1)
61
+ return None
62
+
63
+
64
+ def detect(name: str, run: Runner, bench: Path | None) -> tuple[str | None, str]:
65
+ """(version, how it was found) of one tool on this machine."""
66
+ if name == "python" and bench is not None: # the bench's own interpreter, without running it
67
+ cfg = bench / "env" / "pyvenv.cfg"
68
+ if cfg.is_file():
69
+ match = _PYVENV.search(cfg.read_text(encoding="utf-8"))
70
+ if match:
71
+ return match.group(1), f"{cfg}"
72
+ for command in _COMMANDS.get(name, []):
73
+ output = run(command)
74
+ if output and (version := _first_version(output, _PATTERNS[name])):
75
+ return version, " ".join(command)
76
+ return None, ""
77
+
78
+
79
+ def needs_text(spec: RequirementSpec) -> str:
80
+ """The requirement as short text: `>=3.14,<3.15`, `>=10.6 (11.8 recommended)`."""
81
+ text = f">={spec.minimum}" + (f",<{spec.below}" if spec.below else "")
82
+ return text + (f" ({spec.recommended} recommended)" if spec.recommended else "")
83
+
84
+
85
+ def _at_least(found: str, wanted: str) -> bool | None:
86
+ """True if `found` is the same as or newer than `wanted` (None if unreadable)."""
87
+ try:
88
+ return Version(found) >= Version(wanted)
89
+ except InvalidVersion:
90
+ return None
91
+
92
+
93
+ def judge(found: str | None, spec: RequirementSpec) -> tuple[Status, str]:
94
+ """Status and an optional note for one detected version."""
95
+ if found is None:
96
+ return "missing", "not found on this machine"
97
+ if _at_least(found, spec.minimum) is not True:
98
+ return "upgrade", f"older than {spec.minimum}"
99
+ if spec.below and _at_least(found, spec.below) is True:
100
+ return "upgrade", f"{spec.below} or newer is not supported"
101
+ if spec.recommended and _at_least(found, spec.recommended) is False:
102
+ return "ok", f"works, but {spec.recommended} is recommended"
103
+ return "ok", ""
104
+
105
+
106
+ def check_environment(
107
+ requirements: dict[str, RequirementSpec], run: Runner, bench: Path | None
108
+ ) -> list[EnvRow]:
109
+ """Detect each required tool on this machine and compare it with the target's needs."""
110
+ rows: list[EnvRow] = []
111
+ for name, spec in requirements.items():
112
+ found, where = detect(name, run, bench)
113
+ status, note = judge(found, spec)
114
+ rows.append(EnvRow(name, found, where, needs_text(spec), status, note))
115
+ return rows
116
+
117
+
118
+ _LABELS = {"ok": "ok", "upgrade": "UPGRADE NEEDED", "missing": "NOT FOUND"}
119
+
120
+
121
+ def format_rows(rows: list[EnvRow], target: str) -> str:
122
+ """Human-readable environment report."""
123
+ out = [f"T-MINUS environment -> {target}", ""]
124
+ for row in rows:
125
+ found = row.found or "-"
126
+ line = f" {row.name:<8} found {found:<9} needs {row.needs:<26} {_LABELS[row.status]}"
127
+ out.append(line + (f" ({row.note})" if row.note else ""))
128
+ out += [
129
+ "",
130
+ "These are the versions on this machine. A v16 bench needs the versions in the",
131
+ "'needs' column; build it as a NEW bench and keep this one as the rollback.",
132
+ ]
133
+ return "\n".join(out)