diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 8f3710cbd..02e998c25 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -59,6 +59,8 @@ jobs: diff --color=always -u index.html-public build/index.html || : cat build/index.html - run: uv run generate_build_details.py # generates build-details.html + env: + GH_TOKEN: ${{ github.token }} - name: Deploy build details view 🚀 if: github.event_name != 'pull_request' uses: JamesIves/github-pages-deploy-action@fa24774553152dd7873cd16ebd8d959b010c5445 # v4.9.0 diff --git a/README.md b/README.md index 4f543af7a..4148be7d3 100644 --- a/README.md +++ b/README.md @@ -6,3 +6,26 @@ This project generates a dashboard presenting the Python documentation translati There are two entrypoints: - `generate.py`: Generates dashboard HTML and JSON files. - `generate_build_details.py`: Generates the build details HTML file and log files for each translation project. + +Build details downloads pospell results from each translation repository's +`spellcheck-` Actions artifact, containing `spellcheck.json` in the +schema version 1 described in the [pospell documentation](https://git.afpy.org/maciek/pospell/src/branch/feat/json-reports/README.md). +Set `GH_TOKEN` (or `GITHUB_TOKEN`) when running locally. The update workflow uses +its automatic `GITHUB_TOKEN` to download artifacts from public translation +repositories. +Only complete reports from completed push, schedule, or manual runs in the same +repository are used, including runs that failed because +they found spelling issues. The count is the number of PO entries with findings, +and links to `warnings-pospell-.txt`, with suspect words, entry +identities, and report provenance. Missing, expired, invalid, or inaccessible +reports are shown as unavailable. Reports can predate the current checkout. +The dashboard shows all findings as reported, including findings from another +branch or version. It does not compare report metadata or PO entries against the +current checkout. The repository and language artifact name select the source; +metadata inside the report is informational. + +The same report is published unchanged at +`https://translations.python.org/spellcheck-.json` for consumers such +as `potodo-docs-priority`. The file contains JSON `null` when no usable report is +available, replacing any previously published report. Consumers need no GitHub +token; only this dashboard downloads Actions artifacts. diff --git a/generate_build_details.py b/generate_build_details.py index 075cc7c08..dbbc366c5 100644 --- a/generate_build_details.py +++ b/generate_build_details.py @@ -13,6 +13,7 @@ from urllib3 import request import build_warnings +import pospell_check import sphinx_lint from generate import LanguageProjectData from repositories import Language @@ -23,7 +24,7 @@ def get_projects_build_details( completion_progress: Sequence[LanguageProjectData], -) -> Iterator[tuple[int, int, datetime | None]]: +) -> Iterator[tuple[int, int, datetime | None, int | None]]: with concurrent.futures.ProcessPoolExecutor() as executor: return executor.map( get_build_details, @@ -34,16 +35,18 @@ def get_projects_build_details( def get_build_details( language: Language, repo: str | None, completion: float, clones_dir: str -) -> tuple[int, int, datetime | None]: +) -> tuple[int, int, datetime | None, int | None]: if not repo or not (repo_path := Path(clones_dir, 'translations', repo)).exists(): - return 0, 0, None + return 0, 0, None, None latest_commit = Repo(repo_path).head.commit.committed_datetime + spelling_failures = pospell_check.store_and_count_failures(repo, language.code) if not completion: - return 0, 0, latest_commit + return 0, 0, latest_commit, spelling_failures return ( build_warnings.number(clones_dir, repo, language.code), sphinx_lint.store_and_count_failures(clones_dir, repo, language.code), latest_commit, + spelling_failures, ) diff --git a/pospell_check.py b/pospell_check.py new file mode 100644 index 000000000..87cedf24b --- /dev/null +++ b/pospell_check.py @@ -0,0 +1,137 @@ +"""Fetch spelling results published by translation repositories.""" + +import io +import json +import logging +import os +import zipfile +from pathlib import Path +from urllib.parse import urlencode + +from urllib3 import request +from urllib3.exceptions import HTTPError + +logger = logging.getLogger('pydocs-translation-dashboard') + + +def github_api(endpoint: str) -> bytes: + headers = { + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + } + if token := os.environ.get('GH_TOKEN') or os.environ.get('GITHUB_TOKEN'): + headers['Authorization'] = f'Bearer {token}' + response = request( + 'GET', f'https://api.github.com/{endpoint}', headers=headers, timeout=30 + ) + if response.status != 200: + raise HTTPError(f'GitHub returned HTTP {response.status} for {endpoint}') + return response.data + + +def download_report(repo: str, language_code: str) -> dict | None: + """Find the newest complete report, including runs with spelling failures.""" + page = 1 + while True: + query = urlencode( + {'name': f'spellcheck-{language_code}', 'per_page': 100, 'page': page} + ) + artifacts = json.loads(github_api(f'repos/{repo}/actions/artifacts?{query}'))[ + 'artifacts' + ] + for artifact in artifacts: + run = artifact['workflow_run'] + if artifact['expired'] or run['head_repository_id'] != run['repository_id']: + continue + details = json.loads(github_api(f'repos/{repo}/actions/runs/{run["id"]}')) + if ( + details['status'] != 'completed' + or details['event'] not in {'push', 'schedule', 'workflow_dispatch'} + or details['head_repository']['full_name'] != repo + ): + continue + try: + archive = github_api( + f'repos/{repo}/actions/artifacts/{artifact["id"]}/zip' + ) + with zipfile.ZipFile(io.BytesIO(archive)) as zipped: + report = json.loads(zipped.read('spellcheck.json')) + if ( + isinstance(report, dict) + and report.get('schema_version') == 1 + and report.get('status') == 'complete' + ): + # Validate findings before accepting a candidate as usable. + format_failures(report) + return report + except (ValueError, KeyError, TypeError, zipfile.BadZipFile): + logger.warning( + 'Invalid pospell artifact %s in %s', artifact['id'], repo + ) + if len(artifacts) < 100: + return None + page += 1 + + +def format_failures(report: dict) -> list[str]: + """Count affected entries, retaining their identities and suspect words.""" + failures = [] + if not isinstance(report['catalogs'], dict): + raise TypeError('Invalid pospell catalogs') + for resource, catalog in sorted(report['catalogs'].items()): + if not isinstance(catalog, dict) or not isinstance( + catalog.get('findings'), list + ): + raise TypeError('Invalid pospell findings') + for finding in catalog['findings']: + if ( + not isinstance(finding, dict) + or not isinstance(finding.get('msgid'), str) + or not isinstance(finding.get('words'), list) + or not finding['words'] + or not all(isinstance(word, str) for word in finding['words']) + ): + raise ValueError('Invalid pospell finding') + message = f'{resource}: {", ".join(finding["words"])}\n' + for field in ('msgctxt', 'msgid', 'msgid_plural'): + if finding.get(field) is not None: + message += ( + f' {field}: {json.dumps(finding[field], ensure_ascii=False)}\n' + ) + failures.append(message) + return failures + + +def store_and_count_failures(repo: str, language_code: str) -> int | None: + filepath = Path(f'build/warnings-pospell-{language_code}.txt') + report_path = filepath.with_name(f'spellcheck-{language_code}.json') + # Deploys retain existing files, so explicitly replace unavailable reports. + report_path.write_text('null\n', encoding='utf-8') + filepath.unlink(missing_ok=True) + try: + report = download_report(repo, language_code) + except (HTTPError, ValueError, KeyError, TypeError) as error: + logger.warning('Cannot fetch pospell report for %s: %s', repo, error) + return None + if report is None: + return None + report_path.write_text( + json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8' + ) + failures = format_failures(report) + header = '\n'.join( + f'{field}: {report.get(field, "")}' + for field in ( + 'repository', + 'docs_version', + 'created_at', + 'translations_revision', + ) + if field in report + ) + filepath.write_text( + f'{header}\nEntries with spelling findings: {len(failures)}\n\n' + + '\n'.join(failures), + encoding='utf-8', + ) + return len(failures) diff --git a/src/style.css b/src/style.css index 413f279fa..267e85271 100644 --- a/src/style.css +++ b/src/style.css @@ -258,7 +258,7 @@ th, td { th { background-color: var(--table-header-bg); } -td[data-label="warnings"], td[data-label="lint"] { +td[data-label="warnings"], td[data-label="lint"], td[data-label="pospell"] { text-align: right; } @@ -288,7 +288,7 @@ td[data-label="warnings"], td[data-label="lint"] { left: 10px; position: absolute; } - td[data-label="warnings"], td[data-label="lint"] { + td[data-label="warnings"], td[data-label="lint"], td[data-label="pospell"] { text-align: left; } } diff --git a/templates/build-details.html.jinja b/templates/build-details.html.jinja index 73bd73f5c..b94bfef14 100644 --- a/templates/build-details.html.jinja +++ b/templates/build-details.html.jinja @@ -16,6 +16,7 @@ last updated build warnings* lint failures + pospell check @@ -39,12 +40,24 @@ {{ metadata[1] }} {% endif %} + + {% if metadata[3] is not none %} + {{ metadata[3] }} + {% else %} + unavailable + {% endif %} + {% endif %} {% endfor %}

* number of Sphinx build process warnings

+

+ Pospell check counts PO entries with spelling findings in the latest complete report from the translation repository. + Findings and logs are shown as reported, without matching them against the current translations. Reports may predate the latest translation updates. + Unavailable means no usable report could be downloaded. +

Last updated at {{ generation_time.strftime("%A, %-d %B %Y, %-H:%M:%S %Z") }} (in {{ duration // 60 }}:{{ "{:02}".format(duration % 60) }} minutes).

diff --git a/tests/test_build_details.py b/tests/test_build_details.py new file mode 100644 index 000000000..6a5f94d65 --- /dev/null +++ b/tests/test_build_details.py @@ -0,0 +1,84 @@ +import tempfile +import unittest +from datetime import UTC, datetime +from pathlib import Path +from unittest.mock import patch + +import support +from jinja2 import Environment, FileSystemLoader + +with support.import_scripts(): + from generate_build_details import get_build_details + from repositories import Language + + +class TestBuildDetails(unittest.TestCase): + def test_pospell_uses_repository_even_with_zero_completion(self): + with ( + tempfile.TemporaryDirectory() as directory, + patch('generate_build_details.Repo') as repo, + patch('generate_build_details.build_warnings.number', return_value=2), + patch( + 'generate_build_details.sphinx_lint.store_and_count_failures', + return_value=3, + ), + patch( + 'generate_build_details.pospell_check.store_and_count_failures', + return_value=4, + ) as pospell, + ): + Path(directory, 'translations', 'python/python-docs-pl').mkdir(parents=True) + updated = datetime.now(UTC) + repo.return_value.head.commit.committed_datetime = updated + for completion in (0, 50): + with self.subTest(completion=completion): + result = get_build_details( + Language('pl', 'Polish'), + 'python/python-docs-pl', + completion, + directory, + ) + self.assertEqual( + result, (2, 3, updated, 4) if completion else (0, 0, updated, 4) + ) + pospell.assert_called_with('python/python-docs-pl', 'pl') + + def test_missing_repository_has_no_pospell_result(self): + with patch( + 'generate_build_details.pospell_check.store_and_count_failures' + ) as fetch: + self.assertEqual( + get_build_details(Language('pl', 'Polish'), None, 0, ''), + (0, 0, None, None), + ) + fetch.assert_not_called() + + def test_template_links_available_reports_including_zero(self): + env = Environment(loader=FileSystemLoader('templates')) + for count in (None, 0, 12): + with self.subTest(count=count): + page = env.get_template('build-details.html.jinja').render( + build_details=[ + ( + { + 'language': Language('fr', 'French'), + 'repository': 'python/python-docs-fr', + 'branch': '3.15', + 'completion': 50, + }, + (1, 2, datetime.now(UTC), count), + ) + ], + generation_time=datetime.now(UTC), + duration=0, + ) + self.assertIn('pospell check', page) + if count is None: + self.assertIn('unavailable', page) + self.assertNotIn('href="warnings-pospell-fr.txt"', page) + else: + self.assertIn( + f'{count}', page + ) + self.assertIn('href="warnings-fr.txt">1', page) + self.assertIn('href="warnings-lint-fr.txt">2', page) diff --git a/tests/test_pospell_check.py b/tests/test_pospell_check.py new file mode 100644 index 000000000..8fd0adba3 --- /dev/null +++ b/tests/test_pospell_check.py @@ -0,0 +1,242 @@ +import copy +import io +import json +import os +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest.mock import patch + +import support +from urllib3.exceptions import HTTPError + +with support.import_scripts(): + import pospell_check + + +class TestPospellCheck(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.output = Path(self.directory.name) / 'warnings-pospell-pl.txt' + self.repo = 'python/python-docs-pl' + self.report = { + 'schema_version': 1, + 'status': 'complete', + 'repository': self.repo, + 'language': 'pl', + 'docs_version': '3.15', + 'created_at': '2026-11-21T00:00:00+00:00', + 'translations_revision': 'checked-commit', + 'catalogs': { + 'tutorial/guide.po': { + 'findings': [ + { + 'msgctxt': 'context', + 'msgid': 'Source', + 'msgid_plural': 'Sources', + 'words': ['Błont', 'literufka'], + } + ] + }, + 'bugs.po': {'findings': []}, + }, + } + self.artifact = { + 'id': 1, + 'expired': False, + 'workflow_run': { + 'id': 123, + 'head_branch': '3.15', + 'repository_id': 10, + 'head_repository_id': 10, + }, + } + self.run = { + 'status': 'completed', + 'event': 'push', + 'conclusion': 'failure', + 'head_repository': {'full_name': self.repo}, + } + self.api = self.enterContext(patch('pospell_check.github_api')) + self.api.side_effect = self.github_api + self.published = self.output.with_name('spellcheck-pl.json') + self.enterContext(patch('pospell_check.Path', return_value=self.output)) + + def github_api(self, endpoint): + if '/artifacts?' in endpoint: + return json.dumps({'artifacts': [self.artifact]}).encode() + if '/runs/' in endpoint: + return json.dumps(self.run).encode() + archive = io.BytesIO() + with zipfile.ZipFile(archive, 'w') as zipped: + zipped.writestr('spellcheck.json', json.dumps(self.report)) + return archive.getvalue() + + def store(self): + return pospell_check.store_and_count_failures(self.repo, 'pl') + + def test_failed_run_with_complete_report_counts_entries_and_writes_log(self): + self.assertEqual(self.store(), 1) + self.assertEqual(json.loads(self.published.read_text()), self.report) + log = self.output.read_text(encoding='utf-8') + for text in ( + 'tutorial/guide.po: Błont, literufka', + 'msgctxt: "context"', + 'msgid: "Source"', + 'msgid_plural: "Sources"', + self.report['created_at'], + self.report['translations_revision'], + ): + self.assertIn(text, log) + self.assertIn('name=spellcheck-pl', self.api.call_args_list[0].args[0]) + + def test_clean_report_writes_zero(self): + self.report['catalogs']['tutorial/guide.po']['findings'] = [] + self.assertEqual(self.store(), 0) + self.assertIn('Entries with spelling findings: 0', self.output.read_text()) + + def test_missing_report_removes_previous_log(self): + self.output.write_text('old findings') + self.published.write_text(json.dumps(self.report)) + self.api.side_effect = None + self.api.return_value = b'{"artifacts": []}' + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) + + def test_expired_and_fork_artifacts_are_skipped(self): + candidates = [copy.deepcopy(self.artifact) for _ in range(2)] + candidates[0]['expired'] = True + candidates[1]['workflow_run']['head_repository_id'] = 99 + self.api.side_effect = None + self.api.return_value = json.dumps({'artifacts': candidates}).encode() + self.assertIsNone(self.store()) + self.assertEqual(self.api.call_count, 1) + self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) + + def test_pr_incomplete_and_wrong_repository_runs_are_skipped(self): + for changes in ( + {'event': 'pull_request'}, + {'event': 'pull_request_target'}, + {'status': 'in_progress'}, + {'head_repository': {'full_name': 'fork/python-docs-pl'}}, + ): + with self.subTest(changes=changes): + original = self.run.copy() + self.run.update(changes) + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) + self.run = original + + def test_incompatible_or_malformed_reports_are_unavailable(self): + for field, value in ( + ('schema_version', 2), + ('status', 'error'), + ('catalogs', []), + ('catalogs', {'bugs.po': {'findings': None}}), + ('catalogs', {'bugs.po': {'findings': [{}]}}), + ): + with self.subTest(field=field, value=value): + original = self.report.copy() + self.report[field] = value + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) + self.report = original + + def test_older_complete_report_is_used_after_incomplete_report(self): + original_api = self.github_api + + def api(endpoint): + if '/artifacts?' in endpoint: + return json.dumps( + {'artifacts': [self.artifact, {**self.artifact, 'id': 2}]} + ).encode() + self.report['status'] = 'error' if '/1/zip' in endpoint else 'complete' + return original_api(endpoint) + + self.api.side_effect = api + self.assertEqual(self.store(), 1) + + def test_artifacts_are_paginated(self): + expired = {**self.artifact, 'expired': True} + original_api = self.github_api + + def api(endpoint): + if '/artifacts?' in endpoint and '&page=1' in endpoint: + return json.dumps({'artifacts': [expired] * 100}).encode() + return original_api(endpoint) + + self.api.side_effect = api + self.assertEqual(self.store(), 1) + self.assertIn('page=2', self.api.call_args_list[1].args[0]) + + def test_download_failure_is_unavailable_and_removes_old_log(self): + self.output.write_text('old findings') + self.published.write_text(json.dumps(self.report)) + self.api.side_effect = HTTPError('Forbidden') + with self.assertLogs('pydocs-translation-dashboard', level='WARNING'): + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) + + def test_corrupt_archive_is_skipped(self): + original_api = self.github_api + self.api.side_effect = lambda endpoint: ( + b'not a zip' if endpoint.endswith('/zip') else original_api(endpoint) + ) + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) + + def test_counts_and_logs_are_as_reported_despite_branch_and_metadata_differences( + self, + ): + self.artifact['workflow_run']['head_branch'] = '3.14' + self.report.update( + repository='other/repository', language='fr', docs_version='3.14' + ) + self.report['catalogs']['removed.po'] = copy.deepcopy( + self.report['catalogs']['tutorial/guide.po'] + ) + self.report['catalogs']['removed.po']['findings'][0]['msgid'] = 'Removed source' + self.assertEqual(self.store(), 2) + self.assertEqual(json.loads(self.published.read_text()), self.report) + log = self.output.read_text() + self.assertIn('Entries with spelling findings: 2', log) + self.assertIn('removed.po: Błont, literufka', log) + self.assertIn('msgid: "Removed source"', log) + self.assertIn('repository: other/repository', log) + # The same findings remain usable when optional context is absent. + for field in ( + 'repository', + 'language', + 'docs_version', + 'created_at', + 'translations_revision', + ): + del self.report[field] + self.assertEqual(self.store(), 2) + self.assertEqual(json.loads(self.published.read_text()), self.report) + + +class TestGitHubAPI(unittest.TestCase): + def test_authentication_and_http_errors(self): + with ( + patch.dict(os.environ, {'GH_TOKEN': 'test-token'}), + patch('pospell_check.request') as request, + ): + request.return_value.status = 200 + request.return_value.data = b'report' + self.assertEqual(pospell_check.github_api('repos/owner/repo'), b'report') + self.assertEqual( + request.call_args.kwargs['headers']['Authorization'], + 'Bearer test-token', + ) + request.return_value.status = 403 + with self.assertRaises(HTTPError): + pospell_check.github_api('repos/owner/repo')