Compare commits

...
7 Commits
Author SHA1 Message Date
grm-ci-bot a0b03f01ef release: v0.5.0
Publish Release / publish (push) Failing after 15s
Sync Wiki / sync-wiki (push) Successful in 1m43s
2026-06-22 00:00:01 +02:00
emil 3f5808d6be GRM-42: fix: rewrite changelog and re-tag releases at user-facing milestones 2026-06-21 21:58:29 +00:00
emil 60c94b2b93 GRM-42: fix: clean up infrastructure-only releases and fix release classification 2026-06-21 21:46:37 +00:00
emil 2ca56ed317 GRM-41: feat: enforce commit naming conventions and workflow discipline 2026-06-21 21:33:01 +00:00
grm-ci-bot fb76ac91ef release: v0.4.0
Publish Release / publish (push) Failing after 16s
Sync Wiki / sync-wiki (push) Successful in 1m58s
2026-06-21 23:25:29 +02:00
emil 0c54efbf6b GRM-40: fix: wiki links, add --strict integrity check for wiki sync (#34) 2026-06-21 21:14:17 +00:00
emil 945344f960 GRM-39: fix: use content_base64 for Gitea wiki API, add --verify flag (#33) 2026-06-21 21:03:00 +00:00
14 changed files with 692 additions and 147 deletions
+27
View File
@@ -94,6 +94,33 @@ jobs:
echo "No user-facing files changed — skipping release dry-run."
fi
validate-merge:
if: github.event_name == 'push'
runs-on: docker
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Validate commit message format
run: |
set -euo pipefail
MSG=$(git log -1 --pretty=%s)
echo "Commit message: $MSG"
# Allowed formats:
# GRM-N <type>: <description> (squash-merge)
# release: vX.Y.Z (release commits)
# GRM-N <type>: <description> (#M) (squash-merge with PR ref)
if echo "$MSG" | grep -qE '^GRM-[0-9]+ [a-z]+: .+'; then
echo "OK: GRM-N <conventional> format"
elif echo "$MSG" | grep -qE '^release: v[0-9]+\.[0-9]+\.[0-9]+'; then
echo "OK: release commit format"
else
echo "FAIL: commit message does not follow naming convention"
echo "Expected: GRM-N <type>: <description> or release: vX.Y.Z"
echo "Got: $MSG"
exit 1
fi
discover-runners:
needs: [detect-changes]
if: needs.detect-changes.outputs.ansible-changed == 'true'
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
PYTHONPATH: src
run: |
. .venv/bin/activate
python3 scripts/ci/sync_wiki.py --repo "${{ github.repository }}"
python3 scripts/ci/sync_wiki.py --repo "${{ github.repository }}" --strict
- name: Tag wiki on release
if: startsWith(github.ref, 'refs/tags/v')
env:
+8 -2
View File
@@ -103,13 +103,19 @@ REPO_TOKEN=<token> python3 scripts/ci/review_pr.py <pr_number> <owner/repo> \
```
Then add the `ready-to-merge` label. The auto-merge workflow will:
1. **Validate** PR title format and match against Vikunja task title
1. **Validate** PR title format (`GRM-N: <vikunja task title>`) and match against Vikunja task title
2. **Check** that at least one APPROVE review exists
3. Wait for all CI checks to pass
4. Squash-merge with title: `GRM-N <conventional commit message>` (space-separated)
4. Squash-merge with title: `GRM-N <conventional commit message>` (space-separated, no colon after GRM-N)
5. The post-merge workflow marks the Vikunja task as done
6. The release workflow automatically versions, tags, and publishes (see below)
> **IMPORTANT**: Never manually merge PRs via the API. Always use the auto-merge
> workflow by adding the `ready-to-merge` label. Manual merges bypass the
> `GRM-N <conventional>` format enforcement, producing incorrectly named commits.
> The CI `validate-merge` job checks every push to master and will fail if a
> commit message doesn't match `GRM-N <type>: <description>` or `release: vX.Y.Z`.
### CI Path Filtering
The CI workflow includes a `detect-changes` job that checks whether any files
+130 -99
View File
@@ -2,127 +2,158 @@
All notable changes to this project will be documented in this file.
## [0.3.2] - 2026-06-21
## [0.5.0] - 2026-06-21
### Features
- Add mandatory PR review step to workflow
- Add automated semver versioning, tagging, and releases with git-cliff
- Fix 12 critical workflow gaps in release pipeline
- Implement documentation-as-code with wiki sync and doc-coverage
- Smart CI and release skipping for workflow-only changes
- Enforce commit naming conventions and workflow discipline
### Bug Fixes
- Move release commit skip check into release.py
- Install git-cliff to user-writable dir and fix archlinux idempotence
- Use mktemp for git-cliff extraction to avoid file conflicts
- Use full path for git-cliff version check in install step
- Handle same-version update in release.py
- Skip commit when version file unchanged in release.py
- Release push permission and notify_failure label IDs
- Strip git-cliff header from CHANGELOG.md updates
- Enforce tests pass before tagging a release
- Bypass commit-msg hook for release commits
- Use correct Gitea 1.26 wiki API endpoints
- Set PYTHONPATH=. for release.py to find scripts.ci module (#32)
- Use content_base64 for Gitea wiki API, add --verify flag (#33)
- Wiki links, add --strict integrity check for wiki sync (#34)
- Clean up infrastructure-only releases and fix release classification
- Rewrite changelog and re-tag releases at user-facing milestones
### Other
### Refactor
- Smart CI and release skipping for workflow-only changes
- Split CI scripts, fix release PYTHONPATH, dynamic runner discovery
## [0.3.1] - 2026-06-21
## [0.4.0] - 2026-06-21
### Bug Fixes
### Rootless Docker Support
- Use correct Gitea 1.26 wiki API endpoints
- Full rootless Docker installation and configuration via Ansible
- `docker_rootless_setup` variable controls whether rootless Docker tasks run
- User setup tasks (subuid/subgid, lingering, dockerd-rootless)
- Proper gating of all Docker-dependent and `systemctl --user` tasks
### Runner Labels
- `--labels` option on `grm install` — specify runner labels (e.g., `--labels "ubuntu-latest:docker://node:20"`)
- Labels passed through to runner config YAML
### Security Fix (CWE-214)
- **Critical**: Registration tokens and admin tokens are no longer passed via `--extra-vars` on the command line
- Extra-vars are now written to a temporary JSON file with `0600` permissions and passed via `--extra-vars @tempfile`
- This prevents secrets from being visible in the process list (`ps aux`)
### Configuration via Environment Variables
- API URLs and repo configuration in `config.py` are now overridable via environment variables:
- `GRM_GITEA_API_URL`
- `GRM_VIKUNJA_API_URL`
- `GRM_REPO_OWNER`
- `GRM_REPO_NAME`
- `GRM_VIKUNJA_PROJECT_ID`
### Ansible Role Improvements
- Dead code cleanup (removed `config.yml`, legacy system-level service, duplicate task includes)
- `remove-runner.yml` now disables lingering and removes subuid/subgid entries for complete cleanup
- Arch Linux: `gnupg` package name fix, pacman cache handling
- Docker APT repository: deb822 format, proper GPG handling, arch mapping
- Idempotence fixes for user_setup and download tasks
## [0.3.0] - 2026-06-21
### Features
### New CLI Options
- Implement documentation-as-code with wiki sync and doc-coverage
- `--force` flag on `grm remove` — remove a runner even when the host is unreachable (skips Ansible playbook, only deregisters via API)
- `--url` option — override the Gitea URL for any command (useful for multiple Gitea instances)
- `--ask-become-pass` is now the default behavior (no need to pass it explicitly)
## [0.2.2] - 2026-06-21
### Status Detection Fixes
### Bug Fixes
- `grm list` now correctly retrieves runner status (was showing "unknown" for active runners)
- Docker mode status detection via `docker inspect`
- Host/user context added to status output
- Enforce tests pass before tagging a release
- Bypass commit-msg hook for release commits
### Output Improvements
## [0.2.1] - 2026-06-21
- Colorized output for better visual feedback (green/red/yellow)
- Translated operation reports for success and failure cases
- Dual logging: `click.echo()` for user-facing messages, `logging` for debug
- `GRM_LOG_LEVEL` environment variable for controlling verbosity
- Full i18n support (all user-facing strings translated)
### Bug Fixes
### Internal Refactoring
- Strip git-cliff header from CHANGELOG.md updates
- Validation moved from CLI layer to business layer
- Centralized API clients and HTTP status codes
- User-friendly Click errors with i18n
## [0.2.0] - 2026-06-21
### New CLI Commands
- `grm start <host>` — start a runner's systemd service
- `grm stop <host>` — stop a runner's systemd service
- `grm enable <host>` — enable a runner to start on boot
- `grm disable <host>` — disable a runner from starting on boot
- `grm status <host>` — check runner service status
- `grm remove <host>` — deregister and remove a runner
- `grm list-runners` — list all runners from the local registry
### Runner Registry
- Runners are tracked in `~/.config/grm/runners.toml` for simplified CLI usage
- No need to specify `--url`, `--user`, `--key` for every command — the registry remembers
### Multi-Instance Support
- systemd template units (`gitea-runner@.service`) for running multiple runners per host
- Per-instance config and data directories
### Ansible Role Improvements
- Parameterized all hardcoded configuration values as Ansible variables
- Idempotence fixes for repeated runs
- Runner config converted from TOML to YAML format
- Registration timeout to prevent indefinite hangs
- Docker container entrypoint override and working directory fix for `.runner` persistence
## [0.1.0] - 2026-06-21
### Initial Release
The first release of GRM, a lean CLI for managing Gitea Actions runners via SSH.
### CLI Commands
- `grm install <host>` — install and register a Gitea Runner on a remote host via SSH
- `grm token` — generate a registration token via the Gitea API
- `grm list` — list all registered runners
- `grm update <host>` — update a runner to the latest version
### Ansible Role
- Installs Gitea Runner binary in binary or Docker mode
- Registers runner with Gitea instance
- Configures systemd service
- Supports Arch Linux, Ubuntu, and Debian
### Features
- Fix 12 critical workflow gaps in release pipeline
### Bug Fixes
- Release push permission and notify_failure label IDs
## [Unreleased]
### Added
- **Automated semver versioning and releases**: `scripts/release.py` — CI script that uses git-cliff to calculate the next version from conventional commits, update version files, create a release commit, tag, and push.
- `cliff.toml` — git-cliff configuration for conventional commit parsing, semver bumping, and changelog generation.
- Release workflow (`.gitea/workflows/release.yml`) — triggers on push to master, runs `scripts/release.py` to automatically version and tag releases.
- `publish.py` now uses git-cliff to generate release notes for Gitea releases (falls back to generic message if git-cliff is not available).
- `pyproject.toml` now uses `dynamic = ["version"]` with setuptools `attr` to source version from `__init__.py` (single source of truth — release script only updates `__init__.py`).
- **Mandatory PR review step**: `scripts/review_pr.py` — CLI to post Gitea PR reviews (COMMENT, APPROVE, REQUEST_CHANGES) with inline comments via `--comments-json` or `--comments-stdin`.
- `GiteaClient.get_pr_files`, `GiteaClient.get_pr_commits`, `GiteaClient.create_review` — API methods for PR review workflow.
- `VikunjaClient.get_task` — fetch a single task by numeric ID.
- PR title format: `GRM-N: <vikunja task title>` (colon-separated, human-friendly).
- Merge commit format: `GRM-N <conventional commit message>` (space-separated, conventional).
- `auto_merge.py` now extracts the conventional commit message from PR commits and constructs the merge title as `GRM-N <conventional commit>`.
- `post_merge.py` `extract_conventional_msg` now handles both legacy (`GRM-N: <msg>`) and current (`GRM-N <msg>`) merge commit formats.
- Full PR workflow documented in `AGENTS.md` and `README.md` (Vikunja task → branch → implement → commit → PR → review → address comments → approve → merge).
### Changed
- Parameterized all hardcoded configuration values as Ansible variables in `defaults/main.yml`:
- `gitea_runner_data_dir` — Runtime data directory
- `gitea_runner_config_dir` — Config directory
- `gitea_runner_binary_path` — Binary install path
- `gitea_runner_prune_until` — Prune age filter
- `gitea_runner_prune_schedule` — Prune timer schedule
- `gitea_runner_prune_label` — Docker label for pruning
- `gitea_runner_service_restart_sec` — systemd restart interval
- `gitea_runner_service_user` — Service user
- `gitea_runner_log_level` — Runner log level
- `gitea_runner_container_label` — Container label
- `gitea_runner_file` — Runner metadata file
- `docker_gpg_key_path` — Docker GPG key path
- Added `console_scripts` entry point in `pyproject.toml` (`grm = "gitea_runner_manager.cli:cli"`).
- Added shared `molecule/common/prepare.yml` to eliminate duplicated prepare playbooks.
- Extracted repeated systemd availability check into `tasks/systemd_check.yml`.
- Added idempotence checks to all Molecule scenarios.
- Comprehensive README overhaul with Architecture, Configuration, Development, Testing, and Troubleshooting sections.
- API URLs and repo configuration in `config.py` are now overridable via environment variables (`GRM_GITEA_API_URL`, `GRM_VIKUNJA_API_URL`, `GRM_REPO_OWNER`, `GRM_REPO_NAME`, `GRM_VIKUNJA_PROJECT_ID`).
- `remove-runner.yml` now disables lingering and removes subuid/subgid entries for complete cleanup.
### Security
- **Critical fix**: Registration tokens and admin tokens are no longer passed via `--extra-vars` on the command line (CWE-214). Extra-vars are now written to a temporary JSON file with `0600` permissions and passed via `--extra-vars @tempfile`, which is deleted after execution. This prevents secrets from being visible in the process list (`ps aux`).
### Changed
- Replaced legacy runner terminology with `gitea_runner` / `gitea-runner` / `Gitea Runner`.
- Updated default Docker image from `gitea/gitea_runner` to `gitea/runner`.
- `Makefile` now uses the installed `grm` console script instead of `python grm`.
- `pyproject.toml` ruff and pyright target versions updated from `py311` to `py312` to match `requires-python = ">=3.12"`.
- `BRANCH_PROTECTION_CONFIG` updated with correct Gitea Actions status check contexts (including `(pull_request)` suffix) and `required_approvals: 0` for auto-merge.
- `CONVENTIONAL_RE` no longer matches `BREAKING CHANGE` as a commit type (it is a footer, not a type).
- `rootless_docker.yml` apt cache update now only runs when the Docker repo file changes (idempotent, but always refreshes on first add).
- `service.yml` and `prune.yml` template creation tasks are not guarded by `docker_rootless_setup` (templates just create files, they don't need Docker; molecule tests set `docker_rootless_setup: false` but still verify the service file exists).
- `molecule_all.sh` now sources the platform list from `distribute_molecule.py` to avoid duplication.
### Removed
- Deleted `setup.py` (redundant with `pyproject.toml`).
- Deleted `grm` shell entrypoint script (replaced by `console_scripts`).
- Deleted `initial-plan.md` and `tests/integration/test_provision.py` (dead code).
- Removed empty `__init__.py` files from `tests/` directories.
- Removed unused `runner_validated` fact from `validate.yml`.
- Removed duplicate `prune.yml` and `integration_test.yml` includes from `install_runner.yml` (already included from `main.yml`).
- Removed dead `tasks/config.yml` (never included by any playbook).
- Removed dead `templates/gitea-runner.service.j2` (legacy system-level service, replaced by rootless `gitea-runner-user.service.j2`).
- Removed dead "Reload systemd" handler (system-level reload, never notified, wrong scope for user services).
- Removed dead `scripts/run_molecule_parallel.py` and its test (replaced by `molecule_ci_guard.py`).
### Fixed
- Molecule idempotence failures caused by non-idempotent service restart.
- Missing `/etc/docker` directory handling in Molecule tests.
- `ansible-lint` formatting warnings (yaml empty lines).
- Verify playbooks now explicitly load role defaults so parameterized variables are available during verification.
- Duplicate execution of prune and integration test tasks during installation (were included from both `main.yml` and `install_runner.yml`).
- apt cache update reporting `changed` on every run due to `cache_valid_time: 0`.
- SSH-based remote execution via Ansible
- Automatic registration token generation
- Docker and binary installation modes
- Integration test verification after installation
+10 -9
View File
@@ -46,19 +46,20 @@ commit_preprocessors = [
commit_parsers = [
{ message = "^feat", group = "<!-- 0 -->Features" },
{ message = "^fix", group = "<!-- 1 -->Bug Fixes" },
{ message = "^doc", group = "<!-- 3 -->Documentation" },
{ message = "^perf", group = "<!-- 4 -->Performance" },
{ message = "^refactor", group = "<!-- 2 -->Refactor" },
{ message = "^style", group = "<!-- 5 -->Styling" },
{ message = "^test", group = "<!-- 6 -->Testing" },
{ message = "^chore\\(release\\): prepare for", skip = true },
{ message = "^chore\\(deps.*\\)", skip = true },
{ message = "^chore\\(pr\\)", skip = true },
{ message = "^chore\\(pull\\)", skip = true },
{ message = "^chore|^ci", group = "<!-- 7 -->Miscellaneous Tasks" },
# Skip infrastructure-only commits — they don't affect users
{ message = "^doc", skip = true },
{ message = "^test", skip = true },
{ message = "^style", skip = true },
{ message = "^chore", skip = true },
{ message = "^ci", skip = true },
# Skip release commits — they are release artifacts, not features
{ message = "^release:", skip = true },
{ body = ".*security", group = "<!-- 8 -->Security" },
{ message = "^revert", group = "<!-- 9 -->Revert" },
{ message = ".*", group = "<!-- 10 -->Other" },
# Skip anything that doesn't match above — safe default
{ message = ".*", skip = true },
]
[bump]
+7 -7
View File
@@ -6,20 +6,20 @@ A lean command-line tool to automate the installation, configuration, and lifecy
## User Documentation
- [Getting Started](Getting-Started) — Installation, quick start, first run
- [Getting Started](Getting-Started.-) — Installation, quick start, first run
- [Installation](Installation) — Prerequisites, setup, multiple instances
- [CLI Commands](CLI-Commands) — All commands with arguments and options
- [CLI Commands](CLI-Commands.-) — All commands with arguments and options
- [Troubleshooting](Troubleshooting) — Common issues and solutions
- [FAQ](FAQ) — Frequently asked questions
## Technical Documentation
- [Architecture](Architecture) — High-level design, component interactions, data flow
- [Development Setup](Development-Setup) — Environment setup, dependencies, local testing
- [CI/CD Workflow](CI-CD-Workflow) — How CI works, release process, branch protection
- [Testing Strategy](Testing-Strategy) — Unit, integration, and Molecule tests
- [Decision Log](Decision-Log) — Key technical decisions and rationale
- [Contributing Guide](Contributing-Guide) — Coding standards, PR workflow, commit rules
- [Development Setup](Development-Setup.-) — Environment setup, dependencies, local testing
- [CI/CD Workflow](CI-CD-Workflow.-) — How CI works, release process, branch protection
- [Testing Strategy](Testing-Strategy.-) — Unit, integration, and Molecule tests
- [Decision Log](Decision-Log.-) — Key technical decisions and rationale
- [Contributing Guide](Contributing-Guide.-) — Coding standards, PR workflow, commit rules
## Quick Links
+2 -2
View File
@@ -50,7 +50,7 @@ gitea_runner_manager = ["translations.json"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "--cov=src/gitea_runner_manager --cov=scripts --cov=scripts/ci --cov-report=term-missing --cov-fail-under=100"
addopts = "--cov=src/gitea_runner_manager --cov=scripts --cov-report=term-missing --cov-fail-under=100"
markers = [
"integration: marks tests as integration tests (not counted in coverage)",
]
@@ -68,6 +68,6 @@ quote-style = "double"
indent-style = "space"
[tool.pyright]
include = ["src", "scripts", "scripts/ci"]
include = ["src", "scripts"]
pythonVersion = "3.12"
strict = ["src/gitea_runner_manager"]
+9 -8
View File
@@ -17,9 +17,8 @@ Classification strategy (safe-by-default):
Workflow-only paths (infrastructure no release needed):
- .gitea/workflows/** Gitea Actions workflows
- scripts/ci/** CI/CD automation scripts
- scripts/*.sh Shell scripts (setup, molecule runners)
- scripts/__init__.py Package init for scripts
- scripts/** All scripts (CI/CD, dev tools, setup)
- src/gitea_runner_manager/__init__.py Version file (release artifact)
- docs/** Documentation
- tests/** Test files
- hooks/** Git hooks
@@ -38,7 +37,7 @@ Classification strategy (safe-by-default):
Everything else is user-facing (tool changes release needed),
including but not limited to:
- src/gitea_runner_manager/** Python CLI source
- src/gitea_runner_manager/*.py Python CLI source (except __init__.py)
- ansible/** Ansible role
- pyproject.toml Package metadata
- Any new file type not in the allowlist
@@ -63,10 +62,12 @@ WORKFLOW_ONLY_PATTERNS = frozenset(
[
# CI/CD infrastructure
".gitea/",
"scripts/ci/",
"scripts/setup.sh",
"scripts/molecule_all.sh",
"scripts/__init__.py",
# All scripts are infrastructure (CI/CD, dev tools, setup)
# User-facing code lives in src/gitea_runner_manager/
"scripts/",
# Version file — only contains __version__, not user-facing code.
# Version bumps are a release artifact, not a feature.
"src/gitea_runner_manager/__init__.py",
# Documentation
"docs/",
"AGENTS.md",
+13 -2
View File
@@ -78,8 +78,19 @@ def main(commit_msg: str, commit_sha: str) -> None:
task_id = extract_task_id(commit_msg)
if not task_id:
click.echo(_("No task ID in commit message, skipping Vikunja update. All good — nothing to do here!"))
return
# Allow release commits without GRM-N prefix
first_line = commit_msg.split("\n")[0]
if re.match(r"^release: v\d+\.\d+\.\d+", first_line):
click.echo(_("Release commit without task ID, skipping Vikunja update."))
return
# Non-release commits must have GRM-N prefix — fail loudly
raise click.ClickException(
_(
"No task ID (GRM-N) found in commit message: {msg}\n"
"All non-release commits on master must follow format: GRM-N <type>: <description>",
msg=first_line,
)
)
client = VikunjaClient(VIKUNJA_API_URL, token)
vikunja_task_id = 0
+164 -7
View File
@@ -6,18 +6,20 @@ map file paths to wiki page titles, and creates/updates wiki pages via the
Gitea API. Pages that exist in the wiki but not in the mapping are left
untouched (not deleted).
Gitea 1.26 wiki API endpoints:
- Create: POST /repos/{owner}/{repo}/wiki/new {title, content, message}
- Update: PATCH /repos/{owner}/{repo}/wiki/page/{sub_url} {title, content, message}
Gitea 1.26 wiki API endpoints (all use content_base64, NOT content):
- Create: POST /repos/{owner}/{repo}/wiki/new {title, content_base64, message}
- Update: PATCH /repos/{owner}/{repo}/wiki/page/{sub_url} {title, content_base64, message}
- List: GET /repos/{owner}/{repo}/wiki/pages [{title, sub_url, ...}]
- Fetch: GET /repos/{owner}/{repo}/wiki/page/{sub_url} {title, content_base64, ...}
- Delete: DELETE /repos/{owner}/{repo}/wiki/page/{sub_url}
Usage:
REPO_TOKEN=<token> python3 scripts/sync_wiki.py [--dry-run] [--repo owner/repo]
REPO_TOKEN=<token> python3 scripts/ci/sync_wiki.py [--dry-run] [--repo owner/repo]
"""
from __future__ import annotations
import base64
import json
import os
from pathlib import Path
@@ -49,6 +51,23 @@ def read_doc_content(file_path: str) -> str:
return f.read()
def encode_content(content: str) -> str:
"""Encode content as base64 for the Gitea wiki API.
The Gitea wiki API requires content_base64, not plain content.
Sending plain content silently fails (pages are created/updated
but with empty content).
"""
return base64.b64encode(content.encode("utf-8")).decode("ascii")
def decode_content(content_b64: str) -> str:
"""Decode base64 content from the Gitea wiki API."""
if not content_b64:
return ""
return base64.b64decode(content_b64).decode("utf-8")
def list_wiki_pages(client: GiteaClient) -> dict[str, str]:
"""List existing wiki pages, returning {title: sub_url}."""
try:
@@ -58,6 +77,15 @@ def list_wiki_pages(client: GiteaClient) -> dict[str, str]:
return {page.get("title", ""): page.get("sub_url", page.get("title", "")) for page in pages}
def fetch_page_content(client: GiteaClient, sub_url: str) -> str:
"""Fetch a wiki page's content by sub_url, decoded from base64."""
try:
page = client._request("GET", f"/wiki/page/{sub_url}").json()
return decode_content(page.get("content_base64", ""))
except APIError:
return ""
def sync_page(
client: GiteaClient,
page_title: str,
@@ -73,13 +101,19 @@ def sync_page(
click.echo(_("[dry-run] Would sync page: {title} ({chars} chars)", title=page_title, chars=len(content)))
return "skipped"
content_b64 = encode_content(content)
if page_title in existing_pages:
# Update existing page via PATCH
sub_url = existing_pages[page_title]
client._request(
"PATCH",
f"/wiki/page/{sub_url}",
json={"title": page_title, "content": content, "message": f"Sync from docs/ — update {page_title}"},
json={
"title": page_title,
"content_base64": content_b64,
"message": f"Sync from docs/ — update {page_title}",
},
)
return "updated"
@@ -87,15 +121,93 @@ def sync_page(
client._request(
"POST",
"/wiki/new",
json={"title": page_title, "content": content, "message": f"Sync from docs/ — create {page_title}"},
json={
"title": page_title,
"content_base64": content_b64,
"message": f"Sync from docs/ — create {page_title}",
},
)
return "created"
def verify_wiki_page(
client: GiteaClient, page_title: str, expected_content: str, existing_pages: dict[str, str]
) -> bool:
"""Verify that a wiki page has non-empty content matching the docs.
Returns True if the page content matches, False otherwise.
"""
if page_title not in existing_pages:
return False
sub_url = existing_pages[page_title]
actual = fetch_page_content(client, sub_url)
return actual.strip() == expected_content.strip()
def verify_wiki_integrity(
client: GiteaClient,
mapping: dict[str, str],
synced: dict[str, str],
) -> list[str]:
"""Comprehensive wiki verification.
Checks:
1. Every mapped page exists in the wiki
2. Every mapped page has non-empty content
3. Every mapped page's content matches the docs
4. No stale pages exist in the wiki (pages not in mapping)
5. Page count matches
Returns a list of failure messages (empty if all checks pass).
"""
failures: list[str] = []
existing_pages = list_wiki_pages(client)
expected_titles = set(mapping.values())
# Check 1: Page count
if len(existing_pages) != len(expected_titles):
failures.append(f"Page count mismatch: wiki has {len(existing_pages)}, mapping has {len(expected_titles)}")
# Check 2: Missing pages (in mapping but not in wiki)
missing = expected_titles - set(existing_pages.keys())
for title in sorted(missing):
failures.append(f"Missing page: {title}")
# Check 3: Stale pages (in wiki but not in mapping)
stale = set(existing_pages.keys()) - expected_titles
for title in sorted(stale):
failures.append(f"Stale page (not in mapping): {title}")
# Check 4: Content verification
for page_title, expected_content in sorted(synced.items()):
ok = verify_wiki_page(client, page_title, expected_content, existing_pages)
if not ok:
sub_url = existing_pages.get(page_title, "?")
actual = fetch_page_content(client, sub_url)
if not actual.strip():
failures.append(f"Empty content: {page_title}")
else:
failures.append(f"Content mismatch: {page_title}")
return failures
@click.command()
@click.option("--dry-run", is_flag=True, default=False, help="Show what would happen without making changes.")
@click.option("--repo", default=None, help="Repository in owner/name format (auto-detected if omitted).")
def main(dry_run: bool, repo: str | None) -> None:
@click.option(
"--verify",
is_flag=True,
default=False,
help="After syncing, verify each page has non-empty content. Exit 1 if any page is empty or mismatched.",
)
@click.option(
"--strict",
is_flag=True,
default=False,
help="Full integrity check: verify page count, missing pages, stale pages, and content. Implies --verify.",
)
def main(dry_run: bool, repo: str | None, verify: bool, strict: bool) -> None:
token = os.environ.get("REPO_TOKEN", "")
if not token:
raise click.ClickException(_("ERROR: REPO_TOKEN is not set."))
@@ -121,6 +233,7 @@ def main(dry_run: bool, repo: str | None) -> None:
created = 0
updated = 0
skipped = 0
synced: dict[str, str] = {} # title -> content, for verification
for file_path, page_title in sorted(mapping.items()):
try:
@@ -130,6 +243,11 @@ def main(dry_run: bool, repo: str | None) -> None:
skipped += 1
continue
if not content.strip():
click.echo(_("WARNING: File {file} is empty — skipping.", file=file_path))
skipped += 1
continue
result = sync_page(client, page_title, content, existing_pages, dry_run)
if result == "created":
created += 1
@@ -140,6 +258,8 @@ def main(dry_run: bool, repo: str | None) -> None:
else:
skipped += 1
synced[page_title] = content
click.echo(
_(
"\nDone! Created: {created}, Updated: {updated}, Skipped: {skipped}",
@@ -149,6 +269,43 @@ def main(dry_run: bool, repo: str | None) -> None:
)
)
# --strict implies --verify
do_verify = verify or strict
if do_verify and not dry_run:
if strict:
click.echo(_("\nRunning full wiki integrity check..."))
failures = verify_wiki_integrity(client, mapping, synced)
if failures:
click.echo(_("\nIntegrity check FAILED ({count} issues):", count=len(failures)))
for f in failures:
click.echo(f" - {f}")
raise click.ClickException(_("Wiki integrity check failed — {count} issue(s)", count=len(failures)))
click.echo(_("\nIntegrity check passed — all {count} pages verified.", count=len(synced)))
else:
click.echo(_("\nVerifying wiki pages have content..."))
# Re-fetch the page list to get updated sub_urls
existing_pages = list_wiki_pages(client)
failures = 0
for page_title, expected_content in sorted(synced.items()):
ok = verify_wiki_page(client, page_title, expected_content, existing_pages)
if ok:
click.echo(_(" OK: {title} ({chars} chars)", title=page_title, chars=len(expected_content)))
else:
click.echo(_(" FAIL: {title} — content mismatch or empty!", title=page_title))
failures += 1
if failures > 0:
click.echo(
_(
"\nVerification FAILED: {failures} page(s) have empty or mismatched content!",
failures=failures,
)
)
raise click.ClickException(
_("Wiki verification failed — {failures} page(s) empty or mismatched", failures=failures)
)
click.echo(_("\nVerification passed — all wiki pages have correct content."))
if __name__ == "__main__": # pragma: no cover
main()
+1 -1
View File
@@ -1,3 +1,3 @@
"""Gitea Runner Manager — lean CLI for managing Gitea Actions runners."""
__version__ = "0.3.2"
__version__ = "0.5.0"
+11 -6
View File
@@ -34,12 +34,12 @@ class TestIsUserFacing:
def test_ci_scripts_are_not_user_facing(self) -> None:
assert is_user_facing("scripts/ci/release.py") is False
def test_dev_scripts_are_user_facing(self) -> None:
"""Dev scripts (check_test_speed, configure_repo) are NOT in the
workflow-only allowlist, so they default to user-facing."""
assert is_user_facing("scripts/check_test_speed.py") is True
assert is_user_facing("scripts/configure_repo.py") is True
assert is_user_facing("scripts/install_checkmake.py") is True
def test_dev_scripts_are_not_user_facing(self) -> None:
"""All scripts under scripts/ are infrastructure (CI/CD, dev tools).
User-facing code lives in src/gitea_runner_manager/."""
assert is_user_facing("scripts/check_test_speed.py") is False
assert is_user_facing("scripts/configure_repo.py") is False
assert is_user_facing("scripts/install_checkmake.py") is False
def test_shell_scripts_are_not_user_facing(self) -> None:
assert is_user_facing("scripts/setup.sh") is False
@@ -48,6 +48,11 @@ class TestIsUserFacing:
def test_scripts_init_is_not_user_facing(self) -> None:
assert is_user_facing("scripts/__init__.py") is False
def test_version_file_is_not_user_facing(self) -> None:
"""__init__.py only contains __version__ — a release artifact,
not user-facing code. Version bumps alone should not trigger releases."""
assert is_user_facing("src/gitea_runner_manager/__init__.py") is False
def test_docs_are_not_user_facing(self) -> None:
assert is_user_facing("docs/user/getting-started.md") is False
+11 -1
View File
@@ -130,10 +130,20 @@ class TestMain:
assert "VIKUNJA_TOKEN" in result.output
@patch.dict("os.environ", {"VIKUNJA_TOKEN": "tok"})
def test_no_task_id_skips(self) -> None:
def test_no_task_id_non_release_fails(self) -> None:
"""Non-release commits without GRM-N prefix should fail."""
runner = CliRunner()
result = runner.invoke(main, ["fix: resolve bug"])
assert result.exit_code == 1
assert "No task ID" in result.output
@patch.dict("os.environ", {"VIKUNJA_TOKEN": "tok"})
def test_release_commit_without_task_id_skips(self) -> None:
"""Release commits without GRM-N prefix should skip gracefully."""
runner = CliRunner()
result = runner.invoke(main, ["release: v0.3.2"])
assert result.exit_code == 0
assert "Release commit" in result.output
assert "skipping" in result.output
@patch.dict("os.environ", {"VIKUNJA_TOKEN": "tok"})
+298 -2
View File
@@ -1,5 +1,6 @@
"""Unit tests for scripts/ci/sync_wiki.py."""
import base64
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -8,14 +9,47 @@ import pytest
from click.testing import CliRunner
from scripts.ci.sync_wiki import (
decode_content,
encode_content,
fetch_page_content,
list_wiki_pages,
load_mapping,
main,
read_doc_content,
sync_page,
verify_wiki_integrity,
verify_wiki_page,
)
class TestEncodeContent:
def test_encodes_utf8_to_base64(self) -> None:
result = encode_content("# Hello World")
assert result == base64.b64encode(b"# Hello World").decode("ascii")
def test_encodes_empty_string(self) -> None:
assert encode_content("") == ""
def test_encodes_unicode(self) -> None:
result = encode_content("# Café — résumé")
decoded = base64.b64decode(result).decode("utf-8")
assert decoded == "# Café — résumé"
class TestDecodeContent:
def test_decodes_base64_to_utf8(self) -> None:
encoded = base64.b64encode(b"# Hello").decode("ascii")
assert decode_content(encoded) == "# Hello"
def test_empty_string_returns_empty(self) -> None:
assert decode_content("") == ""
def test_roundtrip(self) -> None:
original = "# Wiki Page\n\nContent with **markdown**."
encoded = encode_content(original)
assert decode_content(encoded) == original
class TestLoadMapping:
def test_loads_mapping(self, tmp_path: Path) -> None:
mapping_file = tmp_path / "mapping.json"
@@ -64,6 +98,27 @@ class TestListWikiPages:
assert result == {"Home": "Home", "Getting-Started": "Getting-Started.-"}
class TestFetchPageContent:
def test_fetches_and_decodes_content(self) -> None:
client = MagicMock()
encoded = base64.b64encode(b"# Hello Wiki").decode("ascii")
client._request.return_value.json.return_value = {"content_base64": encoded}
result = fetch_page_content(client, "Home")
assert result == "# Hello Wiki"
def test_returns_empty_on_api_error(self) -> None:
from gitea_runner_manager.exceptions import APIError
client = MagicMock()
client._request.side_effect = APIError(404, "not found")
assert fetch_page_content(client, "Missing") == ""
def test_returns_empty_for_empty_content(self) -> None:
client = MagicMock()
client._request.return_value.json.return_value = {"content_base64": ""}
assert fetch_page_content(client, "Home") == ""
class TestSyncPage:
def test_dry_run_skips(self) -> None:
client = MagicMock()
@@ -71,7 +126,7 @@ class TestSyncPage:
assert result == "skipped"
client._request.assert_not_called()
def test_creates_new_page(self) -> None:
def test_creates_new_page_with_base64(self) -> None:
client = MagicMock()
result = sync_page(client, "New-Page", "# Content", {}, dry_run=False)
assert result == "created"
@@ -79,8 +134,13 @@ class TestSyncPage:
call_args = client._request.call_args
assert call_args.args[0] == "POST"
assert call_args.args[1] == "/wiki/new"
# Verify content_base64 is used, not content
payload = call_args.kwargs["json"]
assert "content_base64" in payload
assert "content" not in payload
assert base64.b64decode(payload["content_base64"]).decode("utf-8") == "# Content"
def test_updates_existing_page(self) -> None:
def test_updates_existing_page_with_base64(self) -> None:
client = MagicMock()
existing = {"Existing-Page": "Existing-Page.-"}
result = sync_page(client, "Existing-Page", "# Updated", existing, dry_run=False)
@@ -89,6 +149,123 @@ class TestSyncPage:
call_args = client._request.call_args
assert call_args.args[0] == "PATCH"
assert "/wiki/page/Existing-Page.-" in call_args.args[1]
# Verify content_base64 is used
payload = call_args.kwargs["json"]
assert "content_base64" in payload
assert "content" not in payload
assert base64.b64decode(payload["content_base64"]).decode("utf-8") == "# Updated"
class TestVerifyWikiPage:
def test_verifies_matching_content(self) -> None:
client = MagicMock()
encoded = base64.b64encode(b"# Hello Wiki").decode("ascii")
client._request.return_value.json.return_value = {"content_base64": encoded}
existing = {"Home": "Home"}
assert verify_wiki_page(client, "Home", "# Hello Wiki", existing) is True
def test_fails_on_mismatch(self) -> None:
client = MagicMock()
encoded = base64.b64encode(b"# Old Content").decode("ascii")
client._request.return_value.json.return_value = {"content_base64": encoded}
existing = {"Home": "Home"}
assert verify_wiki_page(client, "Home", "# New Content", existing) is False
def test_fails_on_empty_wiki_content(self) -> None:
client = MagicMock()
client._request.return_value.json.return_value = {"content_base64": ""}
existing = {"Home": "Home"}
assert verify_wiki_page(client, "Home", "# Expected", existing) is False
def test_fails_when_page_not_in_existing(self) -> None:
client = MagicMock()
assert verify_wiki_page(client, "Missing", "# Content", {}) is False
class TestVerifyWikiIntegrity:
def _make_client(self, pages: dict[str, str], contents: dict[str, str]) -> MagicMock:
"""Create a mock client that returns the given pages and contents."""
client = MagicMock()
# list_wiki_pages calls GET /wiki/pages
page_list = [{"title": t, "sub_url": s} for t, s in pages.items()]
# fetch_page_content calls GET /wiki/page/{sub_url}
def mock_request(method, path, **kwargs):
resp = MagicMock()
if path == "/wiki/pages":
resp.json.return_value = page_list
elif path.startswith("/wiki/page/"):
sub_url = path.replace("/wiki/page/", "")
content = contents.get(sub_url, "")
encoded = base64.b64encode(content.encode()).decode("ascii") if content else ""
resp.json.return_value = {"content_base64": encoded}
return resp
client._request.side_effect = mock_request
return client
def test_all_good_no_failures(self) -> None:
pages = {"Home": "Home", "FAQ": "FAQ"}
contents = {"Home": "# Home", "FAQ": "# FAQ"}
client = self._make_client(pages, contents)
mapping = {"index.md": "Home", "faq.md": "FAQ"}
synced = {"Home": "# Home", "FAQ": "# FAQ"}
failures = verify_wiki_integrity(client, mapping, synced)
assert failures == []
def test_missing_page_detected(self) -> None:
pages = {"Home": "Home"} # FAQ missing from wiki
contents = {"Home": "# Home"}
client = self._make_client(pages, contents)
mapping = {"index.md": "Home", "faq.md": "FAQ"}
synced = {"Home": "# Home"}
failures = verify_wiki_integrity(client, mapping, synced)
assert any("Missing page: FAQ" in f for f in failures)
def test_stale_page_detected(self) -> None:
pages = {"Home": "Home", "Old-Page": "Old-Page"} # Old-Page not in mapping
contents = {"Home": "# Home", "Old-Page": "# Old"}
client = self._make_client(pages, contents)
mapping = {"index.md": "Home"}
synced = {"Home": "# Home"}
failures = verify_wiki_integrity(client, mapping, synced)
assert any("Stale page" in f and "Old-Page" in f for f in failures)
def test_page_count_mismatch_detected(self) -> None:
pages = {"Home": "Home", "Extra": "Extra"}
contents = {"Home": "# Home", "Extra": "# Extra"}
client = self._make_client(pages, contents)
mapping = {"index.md": "Home"}
synced = {"Home": "# Home"}
failures = verify_wiki_integrity(client, mapping, synced)
assert any("Page count mismatch" in f for f in failures)
def test_empty_content_detected(self) -> None:
pages = {"Home": "Home"}
contents = {"Home": ""} # Empty content
client = self._make_client(pages, contents)
mapping = {"index.md": "Home"}
synced = {"Home": "# Expected Content"}
failures = verify_wiki_integrity(client, mapping, synced)
assert any("Empty content: Home" in f for f in failures)
def test_content_mismatch_detected(self) -> None:
pages = {"Home": "Home"}
contents = {"Home": "# Wrong Content"}
client = self._make_client(pages, contents)
mapping = {"index.md": "Home"}
synced = {"Home": "# Correct Content"}
failures = verify_wiki_integrity(client, mapping, synced)
assert any("Content mismatch: Home" in f for f in failures)
def test_multiple_failures_all_reported(self) -> None:
pages = {"Home": "Home", "Stale": "Stale"}
contents = {"Home": "", "Stale": "# Stale"}
client = self._make_client(pages, contents)
mapping = {"index.md": "Home", "faq.md": "FAQ"} # FAQ missing
synced = {"Home": "# Home Content"}
failures = verify_wiki_integrity(client, mapping, synced)
assert len(failures) >= 3 # count mismatch, missing FAQ, stale Stale, empty Home
class TestMain:
@@ -168,6 +345,21 @@ class TestMain:
assert "not found" in result.output
assert "Skipped: 1" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_empty_doc_file_skipped(self, mock_client_cls: MagicMock) -> None:
"""Test that empty doc files are skipped with a warning."""
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"empty.md": "Empty-Page"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value=" \n "):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={}):
runner = CliRunner()
result = runner.invoke(main, ["--dry-run", "--repo", "owner/repo"])
assert result.exit_code == 0
assert "empty" in result.output.lower()
assert "Skipped: 1" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_create_and_update(self, mock_client_cls: MagicMock) -> None:
@@ -185,3 +377,107 @@ class TestMain:
assert result.exit_code == 0
assert "Created: 1" in result.output
assert "Updated: 1" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_verify_passes(self, mock_client_cls: MagicMock) -> None:
"""Test that --verify passes when content matches."""
mock_client = MagicMock()
mock_client_cls.return_value = mock_client
encoded = base64.b64encode(b"# Home Content").decode("ascii")
# list_wiki_pages returns {"Home": "Home"}, fetch returns encoded content
mock_client._request.return_value.json.return_value = {"content_base64": encoded}
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"index.md": "Home"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value="# Home Content"):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={"Home": "Home"}):
with patch("scripts.ci.sync_wiki.verify_wiki_page", return_value=True):
runner = CliRunner()
result = runner.invoke(main, ["--repo", "owner/repo", "--verify"])
assert result.exit_code == 0
assert "Verification passed" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_verify_fails_on_empty_content(self, mock_client_cls: MagicMock) -> None:
"""Test that --verify fails when wiki pages have empty content."""
mock_client = MagicMock()
mock_client_cls.return_value = mock_client
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"index.md": "Home"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value="# Home Content"):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={"Home": "Home"}):
with patch("scripts.ci.sync_wiki.verify_wiki_page", return_value=False):
runner = CliRunner()
result = runner.invoke(main, ["--repo", "owner/repo", "--verify"])
assert result.exit_code == 1
assert "FAIL" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_verify_skipped_in_dry_run(self, mock_client_cls: MagicMock) -> None:
"""Test that --verify is skipped during dry-run."""
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"index.md": "Home"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value="# Home"):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={}):
runner = CliRunner()
result = runner.invoke(main, ["--dry-run", "--verify", "--repo", "owner/repo"])
assert result.exit_code == 0
assert "Verification" not in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_strict_passes(self, mock_client_cls: MagicMock) -> None:
"""Test that --strict passes when integrity check succeeds."""
mock_client = MagicMock()
mock_client_cls.return_value = mock_client
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"index.md": "Home"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value="# Home"):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={"Home": "Home"}):
with patch("scripts.ci.sync_wiki.verify_wiki_integrity", return_value=[]):
runner = CliRunner()
result = runner.invoke(main, ["--repo", "owner/repo", "--strict"])
assert result.exit_code == 0
assert "Integrity check passed" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_strict_fails_on_integrity_issues(self, mock_client_cls: MagicMock) -> None:
"""Test that --strict fails when integrity check finds issues."""
mock_client = MagicMock()
mock_client_cls.return_value = mock_client
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"index.md": "Home"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value="# Home"):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={"Home": "Home"}):
with patch(
"scripts.ci.sync_wiki.verify_wiki_integrity",
return_value=["Missing page: FAQ", "Stale page: Old-Page"],
):
runner = CliRunner()
result = runner.invoke(main, ["--repo", "owner/repo", "--strict"])
assert result.exit_code == 1
assert "Integrity check FAILED" in result.output
assert "Missing page: FAQ" in result.output
assert "Stale page: Old-Page" in result.output
@patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True)
@patch("scripts.ci.sync_wiki.GiteaClient")
def test_strict_skipped_in_dry_run(self, mock_client_cls: MagicMock) -> None:
"""Test that --strict verification is skipped during dry-run."""
with patch("scripts.ci.sync_wiki.MAPPING_FILE") as mock_mapping:
mock_mapping.exists.return_value = True
with patch("scripts.ci.sync_wiki.load_mapping", return_value={"index.md": "Home"}):
with patch("scripts.ci.sync_wiki.read_doc_content", return_value="# Home"):
with patch("scripts.ci.sync_wiki.list_wiki_pages", return_value={}):
runner = CliRunner()
result = runner.invoke(main, ["--dry-run", "--strict", "--repo", "owner/repo"])
assert result.exit_code == 0
assert "Integrity check" not in result.output