Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/update.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<language-code>` 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-<language-code>.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-<language-code>.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.
11 changes: 7 additions & 4 deletions generate_build_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear published spellcheck JSON when a repository is unavailable

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>.json with null. The deployment steps in .github/workflows/update.yml use clean: 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 👍 / 👎.

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,
)


Expand Down
137 changes: 137 additions & 0 deletions pospell_check.py
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)
4 changes: 2 additions & 2 deletions src/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}
}
Expand Down
13 changes: 13 additions & 0 deletions templates/build-details.html.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<th>last updated</th>
<th>build warnings*</th>
<th>lint failures</th>
<th>pospell check</th>
</tr>
</thead>
<tbody>
Expand All @@ -39,12 +40,24 @@
{{ metadata[1] }}
{% endif %}
</td>
<td data-label="pospell">
{% if metadata[3] is not none %}
<a href="warnings-pospell-{{ project.language.code }}.txt">{{ metadata[3] }}</a>
{% else %}
unavailable
{% endif %}
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
<p>* number of Sphinx build process warnings</p>
<p>
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.
</p>
<p>
Last updated at {{ generation_time.strftime("%A, %-d %B %Y, %-H:%M:%S %Z") }} (in {{ duration // 60 }}:{{ "{:02}".format(duration % 60) }} minutes).
</p>
Expand Down
84 changes: 84 additions & 0 deletions tests/test_build_details.py
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)
Loading
Loading