babregen 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.
babregen/__init__.py ADDED
@@ -0,0 +1,103 @@
1
+ # SPDX-FileCopyrightText: 2026 bartzbeielstein
2
+ # SPDX-License-Identifier: AGPL-3.0-or-later
3
+
4
+ """babregen: Regenerative Software tooling (stdlib only).
5
+
6
+ Chad Fowler's *Regenerative Software* treats code as disposable and the system's
7
+ knowledge as the asset. This package reads that knowledge from the tracked
8
+ ``regen/`` tree of a repository and checks it against the source tree. It uses the
9
+ standard library only and never imports the modules it describes.
10
+
11
+ The command line is ``babregen [--root DIR] <command>`` (see `babregen.cli.main`);
12
+ the functions below are the programmatic interface. The judge of a candidate module
13
+ lives in `babregen.judge`, the driver that regenerates a unit with a local model in
14
+ `babregen.drivers`, and the mutation analysis that measures mutation score in
15
+ `babregen.mutation`; none is imported here.
16
+ """
17
+
18
+ from importlib.metadata import PackageNotFoundError, version
19
+
20
+ from babregen.checks import (
21
+ Finding,
22
+ check_architecture,
23
+ check_decisions,
24
+ check_unit,
25
+ run_checks,
26
+ )
27
+ from babregen.compact import compaction_report
28
+ from babregen.context import build_context, public_contract
29
+ from babregen.measures import (
30
+ UnitMeasures,
31
+ measure_units,
32
+ measures_table,
33
+ unit_measures,
34
+ )
35
+ from babregen.reports import (
36
+ DeletionResult,
37
+ deletion_test,
38
+ )
39
+ from babregen.sample import make_sample_repo
40
+ from babregen.scan import find_importers
41
+ from babregen.spec import (
42
+ Alternative,
43
+ Architecture,
44
+ Consumer,
45
+ Decision,
46
+ IntentItem,
47
+ RegenSpec,
48
+ SpecError,
49
+ Unit,
50
+ find_repo_root,
51
+ load_spec,
52
+ resolve_unit,
53
+ )
54
+ from babregen.write import (
55
+ Written,
56
+ add_consumer,
57
+ add_intent,
58
+ new_decision,
59
+ scaffold_unit,
60
+ write_unit,
61
+ )
62
+
63
+ try:
64
+ __version__ = version("babregen")
65
+ except PackageNotFoundError: # pragma: no cover - running from an unbuilt tree
66
+ __version__ = "0+unknown"
67
+
68
+ __all__ = [
69
+ "Alternative",
70
+ "Architecture",
71
+ "Consumer",
72
+ "Decision",
73
+ "DeletionResult",
74
+ "Finding",
75
+ "IntentItem",
76
+ "RegenSpec",
77
+ "SpecError",
78
+ "Unit",
79
+ "UnitMeasures",
80
+ "Written",
81
+ "__version__",
82
+ "add_consumer",
83
+ "add_intent",
84
+ "build_context",
85
+ "check_architecture",
86
+ "check_decisions",
87
+ "check_unit",
88
+ "compaction_report",
89
+ "deletion_test",
90
+ "find_importers",
91
+ "find_repo_root",
92
+ "load_spec",
93
+ "make_sample_repo",
94
+ "measure_units",
95
+ "measures_table",
96
+ "new_decision",
97
+ "public_contract",
98
+ "resolve_unit",
99
+ "run_checks",
100
+ "scaffold_unit",
101
+ "unit_measures",
102
+ "write_unit",
103
+ ]
babregen/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ # SPDX-FileCopyrightText: 2026 bartzbeielstein
2
+ # SPDX-License-Identifier: AGPL-3.0-or-later
3
+
4
+ """Entry point of ``python -m babregen``."""
5
+
6
+ from babregen.cli import main
7
+
8
+ if __name__ == "__main__":
9
+ raise SystemExit(main())
@@ -0,0 +1,95 @@
1
+ # SPDX-FileCopyrightText: 2026 bartzbeielstein
2
+ # SPDX-License-Identifier: AGPL-3.0-or-later
3
+
4
+ """Run pytest in the target environment and record its scoring results."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ import pytest
14
+
15
+ SUMMARY = "babregen: failing evaluations"
16
+ """The line that opens the list of failing evaluations the runner prints at the end."""
17
+
18
+ _CRASH_LINES = 10
19
+ _CRASH_WIDTH = 240
20
+
21
+
22
+ def _place(path: object) -> str:
23
+ """`path` relative to the worktree if it lies in it, else as it is.
24
+
25
+ The line is cut after this, so its length must not depend on where the worktree is.
26
+ """
27
+ here = Path.cwd().resolve()
28
+ try:
29
+ return str(Path(str(path)).resolve().relative_to(here))
30
+ except ValueError:
31
+ return str(path)
32
+
33
+
34
+ def _crash(report: pytest.TestReport | pytest.CollectReport) -> list[str]:
35
+ """Where and why `report` failed: at most 10 lines of at most 240 characters."""
36
+ crash = getattr(report.longrepr, "reprcrash", None)
37
+ if crash is not None:
38
+ text = f"{_place(crash.path)}:{crash.lineno}: {crash.message}"
39
+ lines = text.splitlines()
40
+ else:
41
+ full = report.longreprtext.splitlines()
42
+ lines = [line for line in full if line.startswith("E ")] or full[-1:]
43
+ return [line[:_CRASH_WIDTH] for line in lines[:_CRASH_LINES]]
44
+
45
+
46
+ class _Scores:
47
+ def __init__(self) -> None:
48
+ self.counts = {"passed": 0, "failed": 0, "error": 0}
49
+ self.failing: list[tuple[str, str, list[str]]] = []
50
+
51
+ def pytest_configure(self, config: pytest.Config) -> None:
52
+ self.config = config
53
+
54
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
55
+ status = self.config.hook.pytest_report_teststatus(
56
+ report=report, config=self.config
57
+ )
58
+ if status is not None:
59
+ category, _, _ = status
60
+ self._count(category, report)
61
+
62
+ def pytest_collectreport(self, report: pytest.CollectReport) -> None:
63
+ if report.failed:
64
+ self._count("error", report)
65
+
66
+ def _count(
67
+ self, category: str, report: pytest.TestReport | pytest.CollectReport
68
+ ) -> None:
69
+ if category in self.counts and getattr(report, "count_towards_summary", True):
70
+ self.counts[category] += 1
71
+ if category != "passed":
72
+ word = "FAILED" if category == "failed" else "ERROR"
73
+ self.failing.append((word, report.nodeid, _crash(report)))
74
+
75
+
76
+ def _main() -> int:
77
+ report = Path(sys.argv.pop(1))
78
+ # Match the import resolution of `python -m pytest` in the worktree.
79
+ sys.path[0] = str(Path.cwd())
80
+ import pytest
81
+
82
+ scores = _Scores()
83
+ status = pytest.main(plugins=[scores])
84
+ report.write_text(" ".join(map(str, scores.counts.values())), encoding="ascii")
85
+ if scores.failing:
86
+ print(SUMMARY)
87
+ for word, nodeid, crash in scores.failing:
88
+ print(f"{word} {nodeid}")
89
+ for line in crash:
90
+ print(f" {line}")
91
+ return status
92
+
93
+
94
+ if __name__ == "__main__":
95
+ raise SystemExit(_main())
babregen/_tools.py ADDED
@@ -0,0 +1,111 @@
1
+ # SPDX-FileCopyrightText: 2026 bartzbeielstein
2
+ # SPDX-License-Identifier: AGPL-3.0-or-later
3
+
4
+ """Checks for the external tools and options the commands depend on (standard library only).
5
+
6
+ The commands call ``git`` and ``lsof``, or talk to a local model server. They fail early
7
+ and clearly when one of these is missing: `ExternalToolError` for a missing executable
8
+ or an unreachable endpoint, `ConfigurationError` for an option that is refused. The
9
+ command line maps both to exit code 2.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ import shutil
16
+
17
+ __all__ = [
18
+ "DEFAULT_TIMEOUT",
19
+ "ConfigurationError",
20
+ "ExternalToolError",
21
+ "require_executable",
22
+ "require_timeout",
23
+ ]
24
+
25
+ DEFAULT_TIMEOUT = 120.0
26
+ """Seconds one pytest run may take by default: the default of every ``--timeout`` of the
27
+ command line (``mutate``, ``score``) and of ``local --score-timeout``. The library
28
+ functions that run pytest have no default."""
29
+
30
+
31
+ class ExternalToolError(RuntimeError):
32
+ """A required executable is not installed or an endpoint is not reachable.
33
+
34
+ Examples:
35
+ ```{python}
36
+ from babregen._tools import ExternalToolError, require_executable
37
+
38
+ try:
39
+ require_executable("no-such-tool-xyz", "install it first")
40
+ except ExternalToolError as exc:
41
+ print(exc)
42
+ ```
43
+ """
44
+
45
+
46
+ class ConfigurationError(ValueError):
47
+ """A driver option is refused, for example a file outside the repository.
48
+
49
+ Examples:
50
+ ```{python}
51
+ from babregen._tools import ConfigurationError
52
+
53
+ print(issubclass(ConfigurationError, ValueError))
54
+ ```
55
+ """
56
+
57
+
58
+ def require_executable(name: str, hint: str = "") -> str:
59
+ """Find an executable on ``PATH`` or fail with a clear message.
60
+
61
+ Args:
62
+ name: Executable name, for example ``"claude"``.
63
+ hint: How to get it, appended to the error message. Defaults to ``""``.
64
+
65
+ Returns:
66
+ str: The absolute path of the executable.
67
+
68
+ Raises:
69
+ ExternalToolError: If the executable is not on ``PATH``.
70
+
71
+ Examples:
72
+ ```{python}
73
+ from babregen._tools import require_executable
74
+
75
+ print(require_executable("sh").endswith("sh"))
76
+ ```
77
+ """
78
+ found = shutil.which(name)
79
+ if found is None:
80
+ suffix = f" ({hint})" if hint else ""
81
+ raise ExternalToolError(f"'{name}' was not found on PATH{suffix}")
82
+ return found
83
+
84
+
85
+ def require_timeout(value: float, option: str) -> float:
86
+ """Refuse a time limit that is not positive and finite.
87
+
88
+ Args:
89
+ value: The limit in seconds.
90
+ option: The option that carries it, named in the message.
91
+
92
+ Returns:
93
+ float: `value`, unchanged.
94
+
95
+ Raises:
96
+ ConfigurationError: If `value` is zero, negative, infinite or not a number.
97
+
98
+ Examples:
99
+ ```{python}
100
+ from babregen._tools import ConfigurationError, require_timeout
101
+
102
+ print(require_timeout(5, "--timeout"))
103
+ try:
104
+ require_timeout(float("nan"), "--timeout")
105
+ except ConfigurationError as exc:
106
+ print(exc)
107
+ ```
108
+ """
109
+ if not (math.isfinite(value) and value > 0):
110
+ raise ConfigurationError(f"{option} must be positive and finite, got {value}")
111
+ return value