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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ coverage.xml

# Translations
*.mo
/python_docs_theme/locale/**/*.js
*.pot

# Django stuff:
Expand Down
45 changes: 45 additions & 0 deletions babel_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

import argparse
import ast
import json
import subprocess
import tomllib
from pathlib import Path

from babel.messages.pofile import read_po
from hatchling.builders.hooks.plugin.interface import BuildHookInterface

# Global variables used by pybabel below (paths relative to PROJECT_DIR)
Expand Down Expand Up @@ -107,6 +109,49 @@ def compile_catalogs(locale: str) -> None:
cmd.extend(["-l", locale])
subprocess.run(cmd, cwd=PROJECT_DIR, check=True)

locale_dirs = PROJECT_DIR / LOCALES_DIR
catalogs = (
[locale_dirs / locale / "LC_MESSAGES" / f"{DOMAIN}.po"]
if locale
else sorted(locale_dirs.glob(f"*/LC_MESSAGES/{DOMAIN}.po"))
)
for pofile in catalogs:
compile_js_catalog(pofile)


def compile_js_catalog(pofile: Path) -> None:
"""Export translated JavaScript messages from the PO catalog."""
jsfile = pofile.with_suffix(".js")
with pofile.open("rb") as f:
source = read_po(f)
if source.fuzzy:
jsfile.unlink(missing_ok=True)
return
messages = {}
for message in source:
if not any(filename.endswith(".js") for filename, _ in message.locations):
continue
if message.context is not None or message.fuzzy or not message.string:
continue
if message.pluralizable and not all(message.string):
continue
msgid = message.id[0] if message.pluralizable else message.id
messages[msgid] = message.string
serialized = json.dumps(
{
"locale": str(source.locale),
"messages": messages,
"plural_expr": f"Number({source.plural_expr})",
},
ensure_ascii=True,
sort_keys=True,
)
jsfile.write_text(
f"// {DOMAIN} translations for {pofile.parents[1].name}\n"
f"Documentation.addTranslations({serialized});\n",
encoding="utf-8",
)


class CustomBuildHook(BuildHookInterface):
def initialize(self, version: str, build_data: dict[str, object]) -> None:
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ entry-points."sphinx.html_themes".python_docs_theme = "python_docs_theme"

[tool.hatch]
version.path = "python_docs_theme/__init__.py"
build.artifacts = [ "python_docs_theme/locale/**/*.mo" ]
build.artifacts = [
"python_docs_theme/locale/**/*.js",
"python_docs_theme/locale/**/*.mo",
]
build.hooks.custom.path = "babel_runner.py"
build.targets.wheel.packages = [ "python_docs_theme" ]
build.targets.wheel.exclude = [
Expand Down
26 changes: 26 additions & 0 deletions python_docs_theme/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from gettext import find
from pathlib import Path
from shutil import copyfile

from sphinx.locale import get_translation

Expand Down Expand Up @@ -37,12 +39,36 @@ def combined(message: str) -> str:
context["_"] = context["gettext"] = context["ngettext"] = combined


def get_js_catalog(app: Sphinx) -> Path | None:
catalog = find(
MESSAGE_CATALOG_NAME,
localedir=LOCALE_DIR,
languages=[app.config.language or "en"],
)
if catalog is not None:
js_catalog = Path(catalog).with_suffix(".js")
if js_catalog.is_file():
return js_catalog
return None


def add_js_translations(app: Sphinx) -> None:
if app.builder.format != "html":
return
if catalog := get_js_catalog(app):
static_dir = Path(app.outdir) / "_static"
static_dir.mkdir(parents=True, exist_ok=True)
copyfile(catalog, static_dir / "python-docs-theme-translations.js")
app.add_js_file("python-docs-theme-translations.js")


def setup(app: Sphinx) -> ExtensionMetadata:
app.require_sphinx("7.3")

app.add_html_theme("python_docs_theme", str(THEME_PATH))
app.add_message_catalog(MESSAGE_CATALOG_NAME, LOCALE_DIR)
app.connect("html-page-context", add_translation_to_context)
app.connect("builder-inited", add_js_translations)

return {
"version": __version__,
Expand Down
Loading