From 1f4bc22e0eac6e1327b10218cc2273ce1ea64b8c Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Sun, 22 Nov 2026 13:51:16 +0100 Subject: [PATCH 1/4] Add pospell reports to build details --- .github/workflows/update.yml | 3 + README.md | 14 ++ generate_build_details.py | 23 +++- pospell_check.py | 138 +++++++++++++++++++ src/style.css | 4 +- templates/build-details.html.jinja | 13 ++ tests/test_build_details.py | 85 ++++++++++++ tests/test_pospell_check.py | 208 +++++++++++++++++++++++++++++ 8 files changed, 479 insertions(+), 9 deletions(-) create mode 100644 pospell_check.py create mode 100644 tests/test_build_details.py create mode 100644 tests/test_pospell_check.py diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 8f3710cbd..85f4e188b 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -10,6 +10,7 @@ jobs: update: runs-on: ubuntu-latest permissions: + actions: read contents: write pull-requests: write steps: @@ -59,6 +60,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: ${{ secrets.SPELLCHECK_REPORTS_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..a18bb8ffd 100644 --- a/README.md +++ b/README.md @@ -6,3 +6,17 @@ 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 `python-docs-pl/SPELLCHECK_REPORT.md`. +Set `GH_TOKEN` (or `GITHUB_TOKEN`) to a token able to read those Actions artifacts +when running locally. The update workflow uses `SPELLCHECK_REPORTS_TOKEN` when +configured, falling back to its GitHub token. A separate token needs Actions read +access to the translation repositories whose artifacts it downloads. +Only complete reports from completed push, schedule, or manual runs in the same +repository and translation branch 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. diff --git a/generate_build_details.py b/generate_build_details.py index 075cc7c08..e5fd836a3 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, @@ -33,24 +34,32 @@ def get_projects_build_details( def get_build_details( - language: Language, repo: str | None, completion: float, clones_dir: str -) -> tuple[int, int, datetime | None]: + language: Language, + repo: str | None, + completion: float, + branch: str, + clones_dir: str, +) -> 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, branch, 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, ) def get_language_repo_and_completion( project: LanguageProjectData, -) -> tuple[Language, str | None, float]: - return project.language, project.repository, project.completion +) -> tuple[Language, str | None, float, str]: + return project.language, project.repository, project.completion, project.branch if __name__ == '__main__': diff --git a/pospell_check.py b/pospell_check.py new file mode 100644 index 000000000..18dc8335f --- /dev/null +++ b/pospell_check.py @@ -0,0 +1,138 @@ +"""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, branch: 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_branch'] != branch + 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' + and report.get('repository') == repo + and report.get('language') == language_code + and report.get('docs_version') == branch + ): + # 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, branch: str, language_code: str) -> int | None: + filepath = Path(f'build/warnings-pospell-{language_code}.txt') + filepath.unlink(missing_ok=True) + try: + report = download_report(repo, branch, 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 + failures = format_failures(report) + header = '\n'.join( + f'{field}: {report.get(field, "")}' + for field in ( + 'repository', + 'docs_version', + 'created_at', + 'translations_revision', + 'run_url', + ) + ) + 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..458e8cc07 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 for the translation branch. + Reports may predate the latest translation updates; the report file includes its date and revision. + 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..c9d9f79fd --- /dev/null +++ b/tests/test_build_details.py @@ -0,0 +1,85 @@ +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_translation_branch_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, + '3.15', + directory, + ) + self.assertEqual( + result, (2, 3, updated, 4) if completion else (0, 0, updated, 4) + ) + pospell.assert_called_with('python/python-docs-pl', '3.15', '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..1f64b035a --- /dev/null +++ b/tests/test_pospell_check.py @@ -0,0 +1,208 @@ +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', + 'run_url': f'https://github.com/{self.repo}/actions/runs/123', + '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.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, '3.15', 'pl') + + def test_failed_run_with_complete_report_counts_entries_and_writes_log(self): + self.assertEqual(self.store(), 1) + 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.report['run_url'], + ): + 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.api.side_effect = None + self.api.return_value = b'{"artifacts": []}' + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + + def test_expired_wrong_branch_and_fork_artifacts_are_skipped(self): + candidates = [copy.deepcopy(self.artifact) for _ in range(3)] + candidates[0]['expired'] = True + candidates[1]['workflow_run']['head_branch'] = '3.14' + candidates[2]['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()) + + 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.run = original + + def test_incompatible_or_malformed_reports_are_unavailable(self): + for field, value in ( + ('schema_version', 2), + ('status', 'error'), + ('repository', 'fork/python-docs-pl'), + ('language', 'fr'), + ('docs_version', '3.14'), + ('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.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.api.side_effect = HTTPError('Forbidden') + with self.assertLogs('pydocs-translation-dashboard', level='WARNING'): + self.assertIsNone(self.store()) + self.assertFalse(self.output.exists()) + + 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()) + + +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') From 2b2f7b5a211806462f8f66484da6d04775a8fe04 Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Sun, 22 Nov 2026 15:00:37 +0100 Subject: [PATCH 2/4] Publish spellcheck JSON for downstream consumers --- .github/workflows/update.yml | 1 - README.md | 6 ++++++ pospell_check.py | 6 ++++++ tests/test_pospell_check.py | 10 ++++++++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 85f4e188b..b9a5de1b6 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -10,7 +10,6 @@ jobs: update: runs-on: ubuntu-latest permissions: - actions: read contents: write pull-requests: write steps: diff --git a/README.md b/README.md index a18bb8ffd..9da72aab4 100644 --- a/README.md +++ b/README.md @@ -20,3 +20,9 @@ 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 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/pospell_check.py b/pospell_check.py index 18dc8335f..65adfde71 100644 --- a/pospell_check.py +++ b/pospell_check.py @@ -111,6 +111,9 @@ def format_failures(report: dict) -> list[str]: def store_and_count_failures(repo: str, branch: 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, branch, language_code) @@ -119,6 +122,9 @@ def store_and_count_failures(repo: str, branch: str, language_code: str) -> int 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, "")}' diff --git a/tests/test_pospell_check.py b/tests/test_pospell_check.py index 1f64b035a..f652cf356 100644 --- a/tests/test_pospell_check.py +++ b/tests/test_pospell_check.py @@ -62,6 +62,7 @@ def setUp(self): } 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): @@ -79,6 +80,7 @@ def store(self): 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', @@ -99,10 +101,12 @@ def test_clean_report_writes_zero(self): 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_wrong_branch_and_fork_artifacts_are_skipped(self): candidates = [copy.deepcopy(self.artifact) for _ in range(3)] @@ -114,6 +118,7 @@ def test_expired_wrong_branch_and_fork_artifacts_are_skipped(self): 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 ( @@ -127,6 +132,7 @@ def test_pr_incomplete_and_wrong_repository_runs_are_skipped(self): 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): @@ -145,6 +151,7 @@ def test_incompatible_or_malformed_reports_are_unavailable(self): 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): @@ -176,10 +183,12 @@ def api(endpoint): 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 @@ -188,6 +197,7 @@ def test_corrupt_archive_is_skipped(self): ) self.assertIsNone(self.store()) self.assertFalse(self.output.exists()) + self.assertIsNone(json.loads(self.published.read_text())) class TestGitHubAPI(unittest.TestCase): From db620595788b81d66fc4d6c6f32820d8879e8078 Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Tue, 1 Dec 2026 23:50:06 +0100 Subject: [PATCH 3/4] Display spellcheck findings without matching report metadata --- README.md | 8 ++++-- generate_build_details.py | 14 +++------- pospell_check.py | 17 ++++-------- templates/build-details.html.jinja | 4 +-- tests/test_build_details.py | 7 ++--- tests/test_pospell_check.py | 44 +++++++++++++++++++++++------- 6 files changed, 54 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 9da72aab4..d2b7ea79c 100644 --- a/README.md +++ b/README.md @@ -9,17 +9,21 @@ There are two entrypoints: Build details downloads pospell results from each translation repository's `spellcheck-` Actions artifact, containing `spellcheck.json` in the -schema version 1 described in `python-docs-pl/SPELLCHECK_REPORT.md`. +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`) to a token able to read those Actions artifacts when running locally. The update workflow uses `SPELLCHECK_REPORTS_TOKEN` when configured, falling back to its GitHub token. A separate token needs Actions read access to the translation repositories whose artifacts it downloads. Only complete reports from completed push, schedule, or manual runs in the same -repository and translation branch are used, including runs that failed because +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 diff --git a/generate_build_details.py b/generate_build_details.py index e5fd836a3..dbbc366c5 100644 --- a/generate_build_details.py +++ b/generate_build_details.py @@ -34,18 +34,12 @@ def get_projects_build_details( def get_build_details( - language: Language, - repo: str | None, - completion: float, - branch: str, - clones_dir: str, + language: Language, repo: str | None, completion: float, clones_dir: str ) -> tuple[int, int, datetime | None, int | None]: if not repo or not (repo_path := Path(clones_dir, 'translations', repo)).exists(): return 0, 0, None, None latest_commit = Repo(repo_path).head.commit.committed_datetime - spelling_failures = pospell_check.store_and_count_failures( - repo, branch, language.code - ) + spelling_failures = pospell_check.store_and_count_failures(repo, language.code) if not completion: return 0, 0, latest_commit, spelling_failures return ( @@ -58,8 +52,8 @@ def get_build_details( def get_language_repo_and_completion( project: LanguageProjectData, -) -> tuple[Language, str | None, float, str]: - return project.language, project.repository, project.completion, project.branch +) -> tuple[Language, str | None, float]: + return project.language, project.repository, project.completion if __name__ == '__main__': diff --git a/pospell_check.py b/pospell_check.py index 65adfde71..87cedf24b 100644 --- a/pospell_check.py +++ b/pospell_check.py @@ -29,7 +29,7 @@ def github_api(endpoint: str) -> bytes: return response.data -def download_report(repo: str, branch: str, language_code: str) -> dict | None: +def download_report(repo: str, language_code: str) -> dict | None: """Find the newest complete report, including runs with spelling failures.""" page = 1 while True: @@ -41,11 +41,7 @@ def download_report(repo: str, branch: str, language_code: str) -> dict | None: ] for artifact in artifacts: run = artifact['workflow_run'] - if ( - artifact['expired'] - or run['head_branch'] != branch - or run['head_repository_id'] != run['repository_id'] - ): + 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 ( @@ -64,9 +60,6 @@ def download_report(repo: str, branch: str, language_code: str) -> dict | None: isinstance(report, dict) and report.get('schema_version') == 1 and report.get('status') == 'complete' - and report.get('repository') == repo - and report.get('language') == language_code - and report.get('docs_version') == branch ): # Validate findings before accepting a candidate as usable. format_failures(report) @@ -109,14 +102,14 @@ def format_failures(report: dict) -> list[str]: return failures -def store_and_count_failures(repo: str, branch: str, language_code: str) -> int | None: +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, branch, language_code) + 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 @@ -133,8 +126,8 @@ def store_and_count_failures(repo: str, branch: str, language_code: str) -> int 'docs_version', 'created_at', 'translations_revision', - 'run_url', ) + if field in report ) filepath.write_text( f'{header}\nEntries with spelling findings: {len(failures)}\n\n' diff --git a/templates/build-details.html.jinja b/templates/build-details.html.jinja index 458e8cc07..b94bfef14 100644 --- a/templates/build-details.html.jinja +++ b/templates/build-details.html.jinja @@ -54,8 +54,8 @@

* number of Sphinx build process warnings

- Pospell check counts PO entries with spelling findings in the latest complete report for the translation branch. - Reports may predate the latest translation updates; the report file includes its date and revision. + 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.

diff --git a/tests/test_build_details.py b/tests/test_build_details.py index c9d9f79fd..6a5f94d65 100644 --- a/tests/test_build_details.py +++ b/tests/test_build_details.py @@ -13,7 +13,7 @@ class TestBuildDetails(unittest.TestCase): - def test_pospell_uses_translation_branch_even_with_zero_completion(self): + def test_pospell_uses_repository_even_with_zero_completion(self): with ( tempfile.TemporaryDirectory() as directory, patch('generate_build_details.Repo') as repo, @@ -36,20 +36,19 @@ def test_pospell_uses_translation_branch_even_with_zero_completion(self): Language('pl', 'Polish'), 'python/python-docs-pl', completion, - '3.15', directory, ) self.assertEqual( result, (2, 3, updated, 4) if completion else (0, 0, updated, 4) ) - pospell.assert_called_with('python/python-docs-pl', '3.15', 'pl') + 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, '', ''), + get_build_details(Language('pl', 'Polish'), None, 0, ''), (0, 0, None, None), ) fetch.assert_not_called() diff --git a/tests/test_pospell_check.py b/tests/test_pospell_check.py index f652cf356..8fd0adba3 100644 --- a/tests/test_pospell_check.py +++ b/tests/test_pospell_check.py @@ -29,7 +29,6 @@ def setUp(self): 'docs_version': '3.15', 'created_at': '2026-11-21T00:00:00+00:00', 'translations_revision': 'checked-commit', - 'run_url': f'https://github.com/{self.repo}/actions/runs/123', 'catalogs': { 'tutorial/guide.po': { 'findings': [ @@ -76,7 +75,7 @@ def github_api(self, endpoint): return archive.getvalue() def store(self): - return pospell_check.store_and_count_failures(self.repo, '3.15', 'pl') + 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) @@ -89,7 +88,6 @@ def test_failed_run_with_complete_report_counts_entries_and_writes_log(self): 'msgid_plural: "Sources"', self.report['created_at'], self.report['translations_revision'], - self.report['run_url'], ): self.assertIn(text, log) self.assertIn('name=spellcheck-pl', self.api.call_args_list[0].args[0]) @@ -108,11 +106,10 @@ def test_missing_report_removes_previous_log(self): self.assertFalse(self.output.exists()) self.assertIsNone(json.loads(self.published.read_text())) - def test_expired_wrong_branch_and_fork_artifacts_are_skipped(self): - candidates = [copy.deepcopy(self.artifact) for _ in range(3)] + 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_branch'] = '3.14' - candidates[2]['workflow_run']['head_repository_id'] = 99 + 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()) @@ -139,9 +136,6 @@ def test_incompatible_or_malformed_reports_are_unavailable(self): for field, value in ( ('schema_version', 2), ('status', 'error'), - ('repository', 'fork/python-docs-pl'), - ('language', 'fr'), - ('docs_version', '3.14'), ('catalogs', []), ('catalogs', {'bugs.po': {'findings': None}}), ('catalogs', {'bugs.po': {'findings': [{}]}}), @@ -199,6 +193,36 @@ def test_corrupt_archive_is_skipped(self): 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): From 1660724f2395523d7545b8f7e222278a5f39eb71 Mon Sep 17 00:00:00 2001 From: Maciej Olko Date: Thu, 3 Dec 2026 11:46:24 +0100 Subject: [PATCH 4/4] Use the automatic GitHub token for spellcheck artifacts --- .github/workflows/update.yml | 2 +- README.md | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index b9a5de1b6..02e998c25 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -60,7 +60,7 @@ jobs: cat build/index.html - run: uv run generate_build_details.py # generates build-details.html env: - GH_TOKEN: ${{ secrets.SPELLCHECK_REPORTS_TOKEN || github.token }} + 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 d2b7ea79c..4148be7d3 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,9 @@ There are two entrypoints: 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`) to a token able to read those Actions artifacts -when running locally. The update workflow uses `SPELLCHECK_REPORTS_TOKEN` when -configured, falling back to its GitHub token. A separate token needs Actions read -access to the translation repositories whose artifacts it downloads. +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,