feat(vcs): read tags and code page counts
draft forgejo-look obsolete
feat(vcs): read tags and code page counts Code page gets a bar of counts (commits, branches, tags, topics or bookmarks). Ancestor counts are cached per node: they never change and counting walks the history. Tags come from tags.findglobaltags, not repo.tags(): one .hgtags line naming ffff… (the working directory id) makes repo.tags() raise for the whole repository. Git takes no tags (tags=None). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| Changeset | 27f860554daa6d38f588700f19ec1d8ec54df422 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | 20c1f57f409d |
| Children | 810bce82588c |
| Pushlog | by timo via ssh |
modified docs/design.md +1 −0
| @@ -506,6 +506,7 @@ Alle Zugriffe liegen in `forge/vcs/hg/`. Stabilität: **S** = öffentlich bzw. seit ≥ 5.6 unverändert, **M** = intern, aber seit Langem stabil, **I** = privat oder kürzlich geändert (Smoke-Test Pflicht). | ||
| 506 | 506 | | Initialisierung | `mercurial.initialization` (erster Import, seit 7.2 Pflicht) | I (neu in 7.2) | |
| 507 | 507 | | Repo öffnen | `mercurial.repo.factory.repository`, `hg.cachedlocalrepo`, `repo.unfiltered()`, `repo.filtered(b'served')` | I (`repo.factory` neu in 7.2; `hg.repository` entfällt in 7.3) | |
| 508 | 508 | | Lesen | `repo.revs` + `revsetlang.formatspec`, `repo[x]`, `changectx`/`filectx` (`data`, `flags`, `isbinary`, `copysource`, `phase`, `obsolete`, `extra`), `changelog.changelogrevision`, `cl.parentrevs`/`isancestorrev`/`headrevs` | S/M | |
| 509 | +| Tags | `tags.findglobaltags(ui, repo)` (nur `.hgtags`, ohne `tip` und lokale Tags; entfernte Tags zeigen auf die Null-ID, Ziele ungeprüft), `changelog.rev` mit `error.LookupError`/`error.WdirUnsupported` für unbekannte Ziele. Nicht `repo.tags()`: eine `.hgtags`-Zeile mit `ffff…` lässt es für das ganze Repo scheitern (`tests/vcs/test_browse_stats.py`) | M | | |
| 509 | 510 | | Diff | `patch.diffhunks`, `patch.diff(copy=…)`, `patch.diffstatdata`, `mdiff.diffopts`; `cmdutil.exportfile` mit `patch.diffallopts(git=True)` für `.patch` | M | |
| 510 | 511 | | Graph/Annotate | `graphmod.dagwalker`, `fctx.annotate` | M (Umzug nach `utils/dag_util` in 7.2) | |
| 511 | 512 | | Topics | `ctx.extra()[b'topic']` roh; Branchmap-Schlüssel `branch//topic` (`hgext3rd.topic.common.parsefqbn`) | M | |
modified forge/vcs/dispatch.py +20 −0
| @@ -122,6 +122,26 @@ def branches(repo) -> list: | ||
| 122 | 122 | return mod.branches(target) |
| 123 | 123 | |
| 124 | 124 | |
| 125 | +def tags(repo) -> list: | |
| 126 | + """Tags, newest target first; the git backend accepts none.""" | |
| 127 | + if _git(repo): | |
| 128 | + return [] | |
| 129 | + from forge.vcs.hg.browse import tags as hg_tags | |
| 130 | + | |
| 131 | + return hg_tags(repo.path) | |
| 132 | + | |
| 133 | + | |
| 134 | +def stats(repo): | |
| 135 | + """``CodeStats`` for the bar above the file list.""" | |
| 136 | + if _git(repo): | |
| 137 | + from forge.vcs.git import browse as git_browse | |
| 138 | + | |
| 139 | + return git_browse.stats(repo) | |
| 140 | + from forge.vcs.hg import browse as hg_browse | |
| 141 | + | |
| 142 | + return hg_browse.stats(repo.path, repo.default_branch) | |
| 143 | + | |
| 144 | + | |
| 125 | 145 | def parse_patch(repo, base_node: str, text: bytes | str): |
| 126 | 146 | """Check a submitted patch strictly against ``base_node`` (patches.md 0): the |
| 127 | 147 | review store's ``check_patch``, for callers without a store at hand. |
modified forge/vcs/git/browse.py +29 −1
| @@ -13,6 +13,7 @@ from dulwich.walk import Walker | ||
| 13 | 13 | from forge.vcs.store import ( |
| 14 | 14 | BranchInfo, |
| 15 | 15 | ChangeInfo, |
| 16 | + CodeStats, | |
| 16 | 17 | Diff, |
| 17 | 18 | FileContent, |
| 18 | 19 | NotFound, |
| @@ -20,7 +21,7 @@ from forge.vcs.store import ( | ||
| 20 | 21 | ) |
| 21 | 22 | |
| 22 | 23 | from .core import open_repo |
| 23 | -from .review import _Pushlog, change_info, diff_trees | |
| 24 | +from .review import _Pushlog, change_info, diff_trees, topics | |
| 24 | 25 | from .stacks import branch_heads |
| 25 | 26 | |
| 26 | 27 | HEX = "0123456789abcdef" |
| @@ -224,3 +225,30 @@ def branches(repo_row) -> list[BranchInf | ||
| 224 | 225 | return [BranchInfo(name=default, head=r.info(r.heads[default]))] |
| 225 | 226 | finally: |
| 226 | 227 | r.close() |
| 228 | + | |
| 229 | + | |
| 230 | +# Ancestors of a commit never change; counting walks the history (see hg browse). | |
| 231 | +_ANCESTORS: dict[tuple[str, str], int] = {} | |
| 232 | +_ANCESTORS_MAX = 512 | |
| 233 | + | |
| 234 | + | |
| 235 | +def stats(repo_row) -> CodeStats: | |
| 236 | + """Counts for the code page: commits of the default branch, the one published | |
| 237 | + branch, bookmarks with a draft stack. Tags are not accepted (None).""" | |
| 238 | + r = _Repo(repo_row) | |
| 239 | + try: | |
| 240 | + default = repo_row.default_branch | |
| 241 | + if default not in r.heads: | |
| 242 | + commits = branches = 0 | |
| 243 | + else: | |
| 244 | + branches = 1 | |
| 245 | + key = (str(repo_row.path), r.heads[default]) | |
| 246 | + if key not in _ANCESTORS: | |
| 247 | + if len(_ANCESTORS) >= _ANCESTORS_MAX: | |
| 248 | + _ANCESTORS.clear() | |
| 249 | + walker = Walker(r.repo.object_store, [r.heads[default].encode()]) | |
| 250 | + _ANCESTORS[key] = sum(1 for _ in walker) | |
| 251 | + commits = _ANCESTORS[key] | |
| 252 | + finally: | |
| 253 | + r.close() | |
| 254 | + return CodeStats(commits=commits, branches=branches, topics=len(topics(repo_row))) | |
modified forge/vcs/hg/browse.py +79 −7
| @@ -13,17 +13,20 @@ from datetime import datetime, timedelta | ||
| 13 | 13 | from pathlib import Path |
| 14 | 14 | |
| 15 | 15 | from mercurial import error, mdiff, patch, scmutil |
| 16 | +from mercurial import tags as tagsmod | |
| 16 | 17 | from mercurial.node import hex |
| 17 | 18 | |
| 18 | 19 | from forge.vcs.store import ( |
| 19 | 20 | BranchInfo, |
| 20 | 21 | ChangeInfo, |
| 22 | + CodeStats, | |
| 21 | 23 | Diff, |
| 22 | 24 | DiffLine, |
| 23 | 25 | FileContent, |
| 24 | 26 | FileDiff, |
| 25 | 27 | Hunk, |
| 26 | 28 | NotFound, |
| 29 | + TagInfo, | |
| 27 | 30 | TopicInfo, |
| 28 | 31 | TreeEntry, |
| 29 | 32 | ) |
| @@ -294,19 +297,24 @@ def export(path: Path, nodes: list[str]) | ||
| 294 | 297 | return out.getvalue() |
| 295 | 298 | |
| 296 | 299 | |
| 300 | +def _topic_revs(repo) -> dict[tuple[str, str], list[int]]: | |
| 301 | + """(topic, branch) -> draft revisions, as 'hg topics' counts them.""" | |
| 302 | + names: dict[tuple[str, str], list[int]] = {} | |
| 303 | + for rev in repo.revs(b"not public() and not obsolete()"): | |
| 304 | + ctx = repo[rev] | |
| 305 | + name = _s(ctx.extra().get(b"topic", b"")) | |
| 306 | + if name: | |
| 307 | + names.setdefault((name, _s(ctx.branch())), []).append(rev) | |
| 308 | + return names | |
| 309 | + | |
| 310 | + | |
| 297 | 311 | def topics(path: Path) -> list[TopicInfo]: |
| 298 | 312 | """Draft topics with their heads (from the branchmap, like 'hg topics').""" |
| 299 | 313 | with open_repo(path) as repo: |
| 300 | 314 | if len(repo) == 0: |
| 301 | 315 | return [] |
| 302 | 316 | result = [] |
| 303 | - names: dict[tuple[str, str], list[int]] = {} | |
| 304 | - for rev in repo.revs(b"not public() and not obsolete()"): | |
| 305 | - ctx = repo[rev] | |
| 306 | - name = _s(ctx.extra().get(b"topic", b"")) | |
| 307 | - if name: | |
| 308 | - names.setdefault((name, _s(ctx.branch())), []).append(rev) | |
| 309 | - for (name, branch), revs in sorted(names.items()): | |
| 317 | + for (name, branch), revs in sorted(_topic_revs(repo).items()): | |
| 310 | 318 | heads = repo.revs(b"heads(%ld)", revs) |
| 311 | 319 | result.append( |
| 312 | 320 | TopicInfo( |
| @@ -318,6 +326,70 @@ def topics(path: Path) -> list[TopicInfo | ||
| 318 | 326 | return result |
| 319 | 327 | |
| 320 | 328 | |
| 329 | +def _global_tags(repo) -> list[tuple[bytes, bytes]]: | |
| 330 | + """(name, node) of the tags from .hgtags whose target is visible here. | |
| 331 | + | |
| 332 | + Not ``repo.tags()``: it adds ``tip`` and local tags (``.hg/localtags``, never | |
| 333 | + pushed), and one line of ``.hgtags`` naming the working directory id | |
| 334 | + (``ffff…``) makes it raise for the whole repository. Removed tags point at | |
| 335 | + the null id; targets the changelog does not know or hides are left out. | |
| 336 | + """ | |
| 337 | + found = [] | |
| 338 | + changelog = repo.changelog | |
| 339 | + for name, (node, _history) in tagsmod.findglobaltags(repo.ui, repo).items(): | |
| 340 | + if node == repo.nullid: | |
| 341 | + continue | |
| 342 | + try: | |
| 343 | + changelog.rev(node) | |
| 344 | + except (error.LookupError, error.WdirUnsupported): | |
| 345 | + continue | |
| 346 | + found.append((name, node)) | |
| 347 | + return found | |
| 348 | + | |
| 349 | + | |
| 350 | +def tags(path: Path) -> list[TagInfo]: | |
| 351 | + """Tags of the repository, newest target first.""" | |
| 352 | + with open_repo(path) as repo: | |
| 353 | + if len(repo) == 0: | |
| 354 | + return [] | |
| 355 | + found = [(repo[node], name) for name, node in _global_tags(repo)] | |
| 356 | + found.sort(key=lambda pair: (-pair[0].rev(), pair[1])) | |
| 357 | + return [TagInfo(name=_s(name), target=change_info(ctx)) for ctx, name in found] | |
| 358 | + | |
| 359 | + | |
| 360 | +# The number of ancestors of a node never changes, and counting walks the | |
| 361 | +# whole history: remembered per process, bounded. | |
| 362 | +_ANCESTORS: dict[tuple[str, bytes], int] = {} | |
| 363 | +_ANCESTORS_MAX = 512 | |
| 364 | + | |
| 365 | + | |
| 366 | +def _ancestor_count(repo, path: Path, ctx) -> int: | |
| 367 | + key = (str(path), ctx.node()) | |
| 368 | + if key not in _ANCESTORS: | |
| 369 | + if len(_ANCESTORS) >= _ANCESTORS_MAX: | |
| 370 | + _ANCESTORS.clear() | |
| 371 | + _ANCESTORS[key] = len(repo.revs(b"::%d", ctx.rev())) | |
| 372 | + return _ANCESTORS[key] | |
| 373 | + | |
| 374 | + | |
| 375 | +def stats(path: Path, default_branch: str) -> CodeStats: | |
| 376 | + """Counts for the code page: commits reachable from the default head (the | |
| 377 | + one ``default_head`` shows), named branches, draft topics, tags.""" | |
| 378 | + with open_repo(path) as repo: | |
| 379 | + if len(repo) == 0: | |
| 380 | + return CodeStats(commits=0, branches=0, topics=0, tags=0) | |
| 381 | + bname = b"literal:" + default_branch.encode() | |
| 382 | + head = (repo.revs(b"max(public() and branch(%s))", bname) | |
| 383 | + or repo.revs(b"max(branch(%s))", bname)) | |
| 384 | + ctx = repo[head.first()] if head else repo[b"tip"] | |
| 385 | + return CodeStats( | |
| 386 | + commits=_ancestor_count(repo, path, ctx), | |
| 387 | + branches=len({repo[r].branch() for r in repo.revs(b"head()")}), | |
| 388 | + topics=len(_topic_revs(repo)), | |
| 389 | + tags=len(_global_tags(repo)), | |
| 390 | + ) | |
| 391 | + | |
| 392 | + | |
| 321 | 393 | def branches(path: Path) -> list[BranchInfo]: |
| 322 | 394 | """Named branches with their tip (public tip if there is one). |
| 323 | 395 | |
modified forge/vcs/store.py +16 −0
| @@ -192,6 +192,22 @@ class BranchInfo: | ||
| 192 | 192 | closed: bool = False |
| 193 | 193 | |
| 194 | 194 | |
| 195 | +@dataclass(frozen=True) | |
| 196 | +class TagInfo: | |
| 197 | + name: str | |
| 198 | + target: ChangeInfo | |
| 199 | + | |
| 200 | + | |
| 201 | +@dataclass(frozen=True) | |
| 202 | +class CodeStats: | |
| 203 | + """Counts for the bar above the file list. ``tags`` is None where the VCS | |
| 204 | + backend takes none (git: only refs/heads are accepted).""" | |
| 205 | + commits: int | |
| 206 | + branches: int | |
| 207 | + topics: int | |
| 208 | + tags: int | None = None | |
| 209 | + | |
| 210 | + | |
| 195 | 211 | # --- submitted patches (docs/discussions/patches.md 0) ---------------------------- |
| 196 | 212 | |
| 197 | 213 | |
added tests/vcs/test_browse_stats.py +84 −0
| @@ -0,0 +1,84 @@ | ||
| 1 | +"""Tags and the counts of the code page, read from real repositories. | |
| 2 | + | |
| 3 | +The tag list rests on an hg internal (design 10.7): ``tags.findglobaltags`` | |
| 4 | +returns the tags of ``.hgtags`` only, with the null id for removed ones and | |
| 5 | +without checking that the target exists. | |
| 6 | +""" | |
| 7 | + | |
| 8 | +from __future__ import annotations | |
| 9 | + | |
| 10 | +import os | |
| 11 | +import subprocess | |
| 12 | +from pathlib import Path | |
| 13 | + | |
| 14 | +import pytest | |
| 15 | + | |
| 16 | +from forge.vcs.hg import browse | |
| 17 | +from tests.conftest import hg_client | |
| 18 | + | |
| 19 | +pytestmark = pytest.mark.hg | |
| 20 | + | |
| 21 | +ENV = {**os.environ, "HGRCPATH": "", "HGPLAIN": "1", "HGUSER": "test"} | |
| 22 | +EXT = ("--config", "extensions.topic=", "--config", "extensions.evolve=") | |
| 23 | + | |
| 24 | + | |
| 25 | +def hg(path: Path, *args) -> str: | |
| 26 | + prefix, env = hg_client(ENV) | |
| 27 | + return subprocess.run([*prefix, *EXT, *args], cwd=path, env=env, check=True, | |
| 28 | + capture_output=True, text=True).stdout | |
| 29 | + | |
| 30 | + | |
| 31 | +@pytest.fixture | |
| 32 | +def repo(tmp_path) -> Path: | |
| 33 | + path = tmp_path / "repo" | |
| 34 | + path.mkdir() | |
| 35 | + hg(path, "init") | |
| 36 | + (path / "a").write_text("a\n") | |
| 37 | + hg(path, "commit", "-Am", "one") | |
| 38 | + hg(path, "tag", "v1") # second changeset: .hgtags | |
| 39 | + hg(path, "tag", "--local", "mine") | |
| 40 | + hg(path, "phase", "--public", "-r", ".") | |
| 41 | + return path | |
| 42 | + | |
| 43 | + | |
| 44 | +def unknown_targets(path: Path) -> None: | |
| 45 | + """Tag changesets this repository does not have. ``ffff…`` is the working | |
| 46 | + directory id, on which the changelog raises something other than a | |
| 47 | + LookupError: hg's own tag commands fail in such a repository.""" | |
| 48 | + with open(path / ".hgtags", "a") as fh: | |
| 49 | + fh.write("1" * 40 + " ghost\n" + "f" * 40 + " wdir\n") | |
| 50 | + hg(path, "commit", "-m", "tag changesets that are not here") | |
| 51 | + | |
| 52 | + | |
| 53 | +def test_tags_are_those_of_hgtags_with_a_known_target(repo): | |
| 54 | + unknown_targets(repo) | |
| 55 | + found = browse.tags(repo) | |
| 56 | + assert [t.name for t in found] == ["v1"] | |
| 57 | + assert found[0].target.summary == "one" | |
| 58 | + assert browse.stats(repo, "default").tags == 1 | |
| 59 | + | |
| 60 | + | |
| 61 | +def test_tags_newest_target_first_and_removed_ones_gone(repo): | |
| 62 | + hg(repo, "tag", "-r", "1", "v2") | |
| 63 | + hg(repo, "tag", "-r", "0", "old") | |
| 64 | + assert [t.name for t in browse.tags(repo)] == ["v2", "old", "v1"] | |
| 65 | + hg(repo, "tag", "--remove", "old") | |
| 66 | + assert [t.name for t in browse.tags(repo)] == ["v2", "v1"] | |
| 67 | + | |
| 68 | + | |
| 69 | +def test_stats_count_the_default_head_not_the_drafts(repo): | |
| 70 | + hg(repo, "topic", "feature") | |
| 71 | + (repo / "a").write_text("b\n") | |
| 72 | + hg(repo, "commit", "-m", "draft on a topic") | |
| 73 | + stats = browse.stats(repo, "default") | |
| 74 | + # "one" and the tag commit; the topic draft is not on the public head | |
| 75 | + assert (stats.commits, stats.branches, stats.topics, stats.tags) == (2, 1, 1, 1) | |
| 76 | + | |
| 77 | + | |
| 78 | +def test_stats_of_an_empty_repository(tmp_path): | |
| 79 | + path = tmp_path / "empty" | |
| 80 | + path.mkdir() | |
| 81 | + hg(path, "init") | |
| 82 | + stats = browse.stats(path, "default") | |
| 83 | + assert (stats.commits, stats.branches, stats.topics, stats.tags) == (0, 0, 0, 0) | |
| 84 | + assert browse.tags(path) == [] | |