Coverage for src/governed_harness/intake/project_kind.py: 92%
98 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""New or existing project, decided deterministically (#56).
3A project is **new** when its Git repository has no commit yet, or when it has no source file
4beyond scaffolding. Scaffolding is what a generator or a person writes before any behaviour:
5test files, configuration and documentation, source files that define nothing (only imports,
6an empty ``__init__.py``) and an entry point (``main``, ``index``, ``app``, ``Program``,
7``__main__``) of at most ``SCAFFOLD_LINES`` non-blank lines. Otherwise it is **existing**. The
8decision drives which questions INTENT asks (``intake.projectSetup``) and whether the
9architecture call advises options (new) or surveys what is there (existing)."""
11from __future__ import annotations
13import re
14import subprocess # nosec B404 - git with a fixed argv, no shell
15from dataclasses import dataclass, field
16from pathlib import Path
17from typing import Any
19from governed_harness.checks.model import is_test_path
20from governed_harness.checks.principles import is_source
21from governed_harness.runtime.workspace import DEFAULT_EXCLUDES
23SCAFFOLD_LINES = 15
24"""An entry point with at most this many non-blank lines counts as scaffolding."""
25_MAX_FILES = 20_000
26_ENOUGH = 20
27"""Counting stops here: ``source_files`` is exact below it and a lower bound at it."""
30@dataclass(frozen=True)
31class ProjectKind:
32 kind: str
33 """``new`` or ``existing``."""
34 reason: str
35 commits: int | None
36 """Commits on ``HEAD`` (``None`` when the workspace is not a Git repository)."""
37 source_files: int
38 """Source files beyond scaffolding, counted up to 20 (a large repository is not read
39 whole)."""
40 scaffolding: tuple[str, ...] = field(default_factory=tuple)
42 @property
43 def new(self) -> bool:
44 return self.kind == "new"
46 def as_dict(self) -> dict[str, Any]:
47 return {
48 "kind": self.kind,
49 "reason": self.reason,
50 "commits": self.commits,
51 "sourceFiles": self.source_files,
52 "scaffolding": list(self.scaffolding[:20]),
53 }
56def _commits(workspace: Path) -> int | None:
57 if not (workspace / ".git").exists():
58 return None
59 try:
60 result = subprocess.run( # nosec B603 B607 - fixed git argv, no shell
61 ["git", "rev-list", "--count", "HEAD"],
62 cwd=workspace,
63 capture_output=True,
64 text=True,
65 check=False,
66 timeout=30,
67 )
68 except (OSError, subprocess.SubprocessError):
69 return None
70 if result.returncode != 0:
71 return 0
72 try:
73 return int(result.stdout.strip() or 0)
74 except ValueError:
75 return 0
78_DEFINITION = re.compile(
79 r"\b(?:def|class|function|func|fn|fun|struct|interface|enum|trait|impl|record|module)\b"
80 r"|=>"
81)
82_ENTRY_POINTS = frozenset({"main", "index", "app", "program", "__main__", "application"})
85def _is_scaffolding(path: Path) -> bool:
86 try:
87 text = path.read_bytes()[:200_000].decode("utf-8", "replace")
88 except OSError:
89 return True
90 lines = [line for line in text.splitlines() if line.strip()]
91 if not _DEFINITION.search(text):
92 return True
93 return path.stem.lower() in _ENTRY_POINTS and len(lines) <= SCAFFOLD_LINES
96@dataclass
97class _Census:
98 """The source files beyond scaffolding counted so far, and the scaffolding seen."""
100 substantive: int = 0
101 scaffolding: list[str] = field(default_factory=list)
103 @property
104 def done(self) -> bool:
105 return self.substantive >= _ENOUGH
107 def add(self, entry: Path, relative: str) -> None:
108 if not is_source(relative) or is_test_path(relative):
109 return
110 if _is_scaffolding(entry):
111 self.scaffolding.append(relative)
112 else:
113 self.substantive += 1
116def _entries(directory: Path) -> list[Path]:
117 """The entries of a directory by name, without the default excludes and symbolic links
118 (none when the directory cannot be read)."""
119 try:
120 entries = sorted(directory.iterdir(), key=lambda item: item.name)
121 except OSError:
122 return []
123 return [
124 entry for entry in entries if entry.name not in DEFAULT_EXCLUDES and not entry.is_symlink()
125 ]
128def _census(root: Path) -> _Census:
129 census = _Census()
130 stack = [root]
131 seen = 0
132 # One source file beyond scaffolding settles it: a large repository is not read whole.
133 while stack and seen < _MAX_FILES and not census.done:
134 for entry in _entries(stack.pop()):
135 if entry.is_dir():
136 stack.append(entry)
137 continue
138 seen += 1
139 census.add(entry, entry.relative_to(root).as_posix())
140 if census.done: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true
141 break
142 return census
145def detect_project_kind(workspace: Path) -> ProjectKind:
146 root = workspace.resolve()
147 commits = _commits(root)
148 census = _census(root)
149 substantive = census.substantive
150 scaffolding = tuple(census.scaffolding)
151 if commits == 0:
152 return ProjectKind(
153 "new", "the Git repository has no commit", commits, substantive, scaffolding
154 )
155 if substantive == 0:
156 return ProjectKind(
157 "new", "no source file beyond scaffolding", commits, substantive, scaffolding
158 )
159 return ProjectKind(
160 "existing",
161 ("source files" if substantive >= _ENOUGH else f"{substantive} source file(s)")
162 + " beyond scaffolding"
163 + (f" and {commits} commit(s)" if commits else ""),
164 commits,
165 substantive,
166 scaffolding,
167 )
170__all__ = ["SCAFFOLD_LINES", "ProjectKind", "detect_project_kind"]