Repository navigation
Pospell build details #214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
m-aciek
wants to merge
4
commits into
main
Choose a base branch
from
pospell-build-details
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
1f4bc22
Add pospell reports to build details
m-aciek 2b2f7b5
Publish spellcheck JSON for downstream consumers
m-aciek db62059
Display spellcheck findings without matching report metadata
m-aciek 1660724
Use the automatic GitHub token for spellcheck artifacts
m-aciek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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('<th>pospell check</th>', page) | ||
| if count is None: | ||
| self.assertIn('unavailable', page) | ||
| self.assertNotIn('href="warnings-pospell-fr.txt"', page) | ||
| else: | ||
| self.assertIn( | ||
| f'<a href="warnings-pospell-fr.txt">{count}</a>', page | ||
| ) | ||
| self.assertIn('href="warnings-fr.txt">1</a>', page) | ||
| self.assertIn('href="warnings-lint-fr.txt">2</a>', page) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If a language previously had a published report but its repository is subsequently removed from the devguide table, this early return bypasses the code that replaces
spellcheck-<language>.jsonwithnull. The deployment steps in.github/workflows/update.ymluseclean: false, so the previously published JSON remains accessible indefinitely, and downstream consumers continue receiving findings from a repository the dashboard no longer tracks. Write the unavailable-report sentinel for this path as well.Useful? React with 👍 / 👎.