Skip to content
Merged
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
19 changes: 19 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Lint

on: [push, pull_request, workflow_dispatch]

env:
FORCE_COLOR: 1

jobs:
lint:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: "3.x"
- uses: tox-dev/action-pre-commit-uv@v1
2 changes: 1 addition & 1 deletion .github/workflows/update.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.x"
- uses: astral-sh/setup-uv@v4
- uses: astral-sh/setup-uv@v5
- uses: actions/checkout@v4
- run: sudo apt-get install -y gettext
- run: uv run generate.py # generates "index.html"
Expand Down
38 changes: 38 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.4
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
- id: forbid-submodules
- id: trailing-whitespace

- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.30.0
hooks:
- id: check-github-workflows
Comment on lines +22 to +25
Copy link
Collaborator

Choose a reason for hiding this comment

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

Isn't it superfluous? (Unless I'm missing something.) We don't store JSON schemas AFAIC nor have it in a near perspective.

Copy link
Member Author

@hugovk hugovk Dec 30, 2024

Choose a reason for hiding this comment

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

It can help with the files in .github/workflows/. For example, if we'd accidentally put runs-on: ubuntu it would say:

.github/workflows/update.yml:11:14: label "ubuntu" is unknown. available labels are "windows-latest", "windows-latest-8-cores", "windows-2025", "windows-2022", "windows-2019", "ubuntu-latest", "ubuntu-latest-4-cores", "ubuntu-latest-8-cores", "ubuntu-latest-16-cores", "ubuntu-24.04", "ubuntu-22.04", "ubuntu-20.04", "macos-latest", "macos-latest-xl", "macos-latest-xlarge", "macos-latest-large", "macos-15-xlarge", "macos-15-large", "macos-15", "macos-14-xl", "macos-14-xlarge", "macos-14-large", "macos-14", "macos-13-xl", "macos-13-xlarge", "macos-13-large", "macos-13", "self-hosted", "x64", "arm", "arm64", "linux", "macos", "windows". if it is a custom label for self-hosted runner, set list of labels in actionlint.yaml config file [runner-label]

Copy link
Collaborator

Choose a reason for hiding this comment

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

ah, yaml is a superset of json, so it makes sense; though doesn't https://github.com/rhysd/actionlint cover also the workflow files schema validation?


- repo: https://github.com/rhysd/actionlint
rev: v1.7.5
hooks:
- id: actionlint

- repo: meta
hooks:
- id: check-hooks-apply
- id: check-useless-excludes

ci:
autoupdate_schedule: quarterly
12 changes: 9 additions & 3 deletions completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ def branches_from_devguide(devguide_dir: Path) -> list[str]:
p = devguide_dir.joinpath('include/release-cycle.json')
data = json.loads(p.read_text())
return [
branch for branch in data if data[branch]["status"] in ("bugfix", "security")
branch for branch in data if data[branch]['status'] in ('bugfix', 'security')
]


def get_completion(clones_dir: str, repo: str) -> tuple[float, int]:
clone_path = Path(clones_dir, repo)
for branch in branches_from_devguide(Path(clones_dir, 'devguide')) + ['master']:
try:
git.Repo.clone_from(f'https://github.com/{repo}.git', clone_path, branch=branch)
git.Repo.clone_from(
f'https://github.com/{repo}.git', clone_path, branch=branch
)
except git.GitCommandError:
print(f'failed to clone {repo} {branch}')
translators_number = 0
Expand All @@ -32,6 +34,10 @@ def get_completion(clones_dir: str, repo: str) -> tuple[float, int]:
break
with TemporaryDirectory() as tmpdir:
completion = potodo.merge_and_scan_path(
clone_path, pot_path=Path(clones_dir, 'cpython/Doc/build/gettext'), merge_path=Path(tmpdir), hide_reserved=False, api_url=''
clone_path,
pot_path=Path(clones_dir, 'cpython/Doc/build/gettext'),
merge_path=Path(tmpdir),
hide_reserved=False,
api_url='',
).completion
return completion, translators_number
23 changes: 17 additions & 6 deletions generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,22 @@
generation_time = datetime.now(timezone.utc)

with TemporaryDirectory() as clones_dir:
Repo.clone_from(f'https://github.com/python/devguide.git', devguide_dir := Path(clones_dir, 'devguide'), depth=1)
Repo.clone_from(
'https://github.com/python/devguide.git',
devguide_dir := Path(clones_dir, 'devguide'),
depth=1,
)
latest_branch = branches_from_devguide(devguide_dir)[0]
Repo.clone_from(
f'https://github.com/python/cpython.git', Path(clones_dir, 'cpython'), depth=1, branch=latest_branch
'https://github.com/python/cpython.git',
Path(clones_dir, 'cpython'),
depth=1,
branch=latest_branch,
)
subprocess.run(['make', '-C', Path(clones_dir, 'cpython/Doc'), 'venv'], check=True)
subprocess.run(['make', '-C', Path(clones_dir, 'cpython/Doc'), 'gettext'], check=True)
subprocess.run(
['make', '-C', Path(clones_dir, 'cpython/Doc'), 'gettext'], check=True
)
switcher_languages = list(switcher.get_languages())
for language, repo in repositories.get_languages_and_repos(devguide_dir):
if repo:
Expand Down Expand Up @@ -78,7 +87,7 @@
<a href="https://github.com/{{ repo }}" target="_blank">
{{ language }}
</a>
</td>
</td>
<td data-label="build">
{% if in_switcher %}
<a href="https://docs.python.org/{{ language }}/">in switcher</a>
Expand Down Expand Up @@ -111,7 +120,9 @@
"""
)

output = template.render(completion_progress=completion_progress, generation_time=generation_time)
output = template.render(
completion_progress=completion_progress, generation_time=generation_time
)

with open("index.html", "w") as file:
with open('index.html', 'w') as file:
file.write(output)
9 changes: 6 additions & 3 deletions repositories.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import tempfile
import pathlib
import re
from typing import Generator, Optional
Expand All @@ -7,14 +6,18 @@
from docutils.nodes import table, row


def get_languages_and_repos(devguide_dir: pathlib.Path) -> Generator[tuple[str, Optional[str]], None, None]:
def get_languages_and_repos(
devguide_dir: pathlib.Path,
) -> Generator[tuple[str, Optional[str]], None, None]:
translating = devguide_dir.joinpath('documentation/translating.rst').read_text()
doctree = core.publish_doctree(translating)

for node in doctree.traverse(table):
for row_node in node.traverse(row)[1:]:
language = row_node[0].astext()
repo = row_node[2].astext()
language_code = re.match(r'.* \((.*)\)', language).group(1).lower().replace('_', '-')
language_code = (
re.match(r'.* \((.*)\)', language).group(1).lower().replace('_', '-')
)
repo_match = re.match(':github:`GitHub <(.*)>`', repo)
yield language_code, repo_match and repo_match.group(1)
2 changes: 2 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[format]
quote-style = "single"
19 changes: 9 additions & 10 deletions switcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,31 @@
"""

import tomllib
from collections import defaultdict
from typing import Generator

import requests


def get_languages() -> Generator[str, None, None]:
data = requests.get(
"https://raw.githubusercontent.com/"
"python/docsbuild-scripts/refs/heads/main/config.toml",
'https://raw.githubusercontent.com/'
'python/docsbuild-scripts/refs/heads/main/config.toml',
timeout=10,
).text
config = tomllib.loads(data)
languages = config["languages"]
defaults = config["defaults"]
languages = config['languages']
defaults = config['defaults']
for code, language in languages.items():
if language.get("in_prod", defaults["in_prod"]):
yield code.lower().replace("_", "-")
if language.get('in_prod', defaults['in_prod']):
yield code.lower().replace('_', '-')


def main() -> None:
languages = list(get_languages())
print(languages)
for code in ("en", "pl", "ar", "zh-cn"):
print(f"{code}: {code in languages}")
for code in ('en', 'pl', 'ar', 'zh-cn'):
print(f'{code}: {code in languages}')


if __name__ == "__main__":
if __name__ == '__main__':
main()
4 changes: 3 additions & 1 deletion translators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ def get_number(path: Path) -> int:
from_git_history = get_number_from_git_history(path)
return max(from_headers, from_git_history)


def get_number_from_git_history(path: Path) -> int:
return len(Repo(path).git.shortlog('-s', 'HEAD').splitlines())


def yield_from_headers(path: Path) -> Generator[str, None, None]:
for file in path.rglob('*.po'):
try:
Expand All @@ -21,7 +23,7 @@ def yield_from_headers(path: Path) -> Generator[str, None, None]:
continue
if 'Translators:' not in header:
continue
for translator_record in header[header.index('Translators:') + 1:]:
for translator_record in header[header.index('Translators:') + 1 :]:
try:
translator, _year = translator_record.split(', ')
except ValueError:
Expand Down
11 changes: 8 additions & 3 deletions visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@


def get_number_of_visitors(language: str) -> int:
param = urllib.parse.urlencode({'filters': f'[["contains","event:page",["/{language}/"]]]'})
param = urllib.parse.urlencode(
{'filters': f'[["contains","event:page",["/{language}/"]]]'}
)
r = requests.get(f'https://plausible.io/docs.python.org/export?{param}', timeout=10)
with zipfile.ZipFile(io.BytesIO(r.content), 'r') as z, z.open('visitors.csv') as csv_file:
with (
zipfile.ZipFile(io.BytesIO(r.content), 'r') as z,
z.open('visitors.csv') as csv_file,
):
csv_reader = csv.DictReader(io.TextIOWrapper(csv_file))
return sum(int(row["visitors"]) for row in csv_reader)
return sum(int(row['visitors']) for row in csv_reader)
Loading