git-annex-mirror-orchestrator/gamo/report.py
Michael Hanke 4e08306164
All checks were successful
Codespell / Check for spelling errors (push) Successful in 45s
Ruff / Code linting (push) Successful in 45s
Type annotations / check (push) Successful in 53s
Unit tests (Linux) / check (push) Successful in 2m45s
chore: reformat
2026-11-16 06:09:36 +01:00

151 lines
5.3 KiB
Python

"""
Read all mirror state records from the mirror directory and emit a
markdown table reporting, for every repository, the date of the last
modification of the source repository and the number of tagged versions.
The table is meant to be dropped into the README of a Forgejo
organization ``.profile`` repository as a replacement for the regular
repository listing. Only the JSON state records populated by
``gamo-update-refs`` are read; no network queries are performed, which
keeps the command fast even for mirrors with thousands of repositories.
"""
import argparse
import json
from dataclasses import dataclass
from pathlib import Path
import humanize
from datalad_core.repo import Worktree
from gamo.timestamps import parse_timestamp
HEADER = '| Repository | Last mirrored | Last modified | Versions | Keys | Missing |'
SEPARATOR = '| --- | --- | --- | --- | --- | --- |'
@dataclass
class Row:
name: str
web_url: str | None
last_modified: str | None
n_tags: int | None
total_n: int | None
total_size: int | None
total_unsized: bool
missing_n: int | None
missing_size: int | None
missing_unsized: bool
last_mirrored: str | None
def repo_url_and_name(target_url: str, fallback_name: str) -> tuple[str | None, str]:
"""
Derive the web URL and display name of a repository from its target git URL.
Both ``https://host/org/repo(.git)`` and scp-like ``user@host:org/repo(.git)``
URLs are supported; the web URL is always emitted in https form. The display
name is the last path segment of the repository. Returns ``(None,
fallback_name)`` when no web URL can be derived.
"""
if '://' in target_url:
scheme, rest = target_url.split('://', 1)
if scheme.lower() not in ('http', 'https'):
return None, fallback_name
host, _, path = rest.partition('/')
else:
host, sep, path = target_url.partition(':')
if not sep:
return None, fallback_name
# drop a leading user@ from scp-like URLs
host = host.rpartition('@')[2]
segments = [segment for segment in path.split('/') if segment]
if not host or not segments:
return None, fallback_name
segments[-1] = segments[-1].removesuffix('.git')
name = segments[-1]
if not name:
return None, fallback_name
return f'https://{host}/' + '/'.join(segments), name
def _row(row: Row) -> str:
repo = f'[{row.name}]({row.web_url})' if row.web_url else row.name
last_modified = row.last_modified[:10] if row.last_modified else '-'
last_mirrored = row.last_mirrored[:10] if row.last_mirrored else '-'
if row.n_tags is None:
tags = '-'
elif row.web_url is None:
tags = str(row.n_tags)
else:
tags = f'[{row.n_tags}]({row.web_url}/tags)'
total_size = (
f'{humanize.naturalsize(row.total_size) if row.total_size is not None else "?"}'
)
if row.total_unsized:
total_size = f'{total_size}+X'
total = f'{row.total_n}@{total_size}' if row.total_n else '-'
missing_size = f'{humanize.naturalsize(row.missing_size) if row.missing_size is not None else "?"}'
missing = f'{row.missing_n}@{missing_size}' if row.missing_n else '-'
if row.missing_unsized:
total_size = f'{total_size}+X'
return (
f'| {repo} | {last_mirrored} | {last_modified} | {tags} | {total} | {missing} |'
)
def _sort_key(row: Row) -> tuple:
# most recently mirrored first, never-mirrored last,
# ties broken by name ascending
if row.last_mirrored:
return (0, -parse_timestamp(row.last_mirrored).timestamp(), row.name)
return (1, 0.0, row.name)
def main() -> None:
parser = argparse.ArgumentParser(
description=(
'Emit a markdown table reporting, for every mirror record, the '
'last source modification date and the number of tags.'
),
)
parser.add_argument('--mirror', type=Path, default='mirror')
args = parser.parse_args()
wt = Worktree.from_path(Path.cwd())
rows = []
for path in sorted((wt.path / args.mirror).glob('*.json')):
with path.open('r', encoding='utf-8') as file:
record = json.load(file)
target = record.get('target')
if isinstance(target, dict):
target_url = target.get('url', '')
elif isinstance(target, str):
target_url = target
else:
target_url = ''
state = record.get('state') or {}
fallback_name = str(record.get('id') or path.stem)
web_url, name = repo_url_and_name(target_url, fallback_name)
rows.append(
Row(
name=name,
web_url=web_url,
last_modified=state.get('source_last_modified'),
n_tags=state.get('n_tags'),
total_n=state.get('keys_total_n'),
total_size=state.get('keys_total_bytesize'),
total_unsized=state.get('keys_total_unsized_present', False),
missing_n=state.get('keys_missing_n'),
missing_size=state.get('keys_missing_bytesize'),
missing_unsized=state.get('keys_missing_unsized_present', False),
last_mirrored=state.get('last_success'),
),
)
rows.sort(key=_sort_key)
lines = [HEADER, SEPARATOR]
lines.extend(_row(row) for row in rows)
print('\n'.join(lines)) # noqa: T201