Debian Codegraph @

babel_runner.py

raw
1 """Script for handling translations with Babel"""
2
3 from __future__ import annotations
4
5 import argparse
6 import ast
7 import subprocess
8 import tomllib
9 from pathlib import Path
10
11 from hatchling.builders.hooks.plugin.interface import BuildHookInterface
12
13 # Global variables used by pybabel below (paths relative to PROJECT_DIR)
14 DOMAIN = "python-docs-theme"
15 COPYRIGHT_HOLDER = "Python Software Foundation"
16 SOURCE_DIR = "python_docs_theme"
17 MAPPING_FILE = ".babel.cfg"
18
19 PROJECT_DIR = Path(__file__).resolve().parent
20 PYPROJECT_TOML = Path(PROJECT_DIR, "pyproject.toml")
21 INIT_PY = PROJECT_DIR / SOURCE_DIR / "__init__.py"
22 LOCALES_DIR = Path(f"{SOURCE_DIR}", "locale")
23 POT_FILE = Path(LOCALES_DIR, f"{DOMAIN}.pot")
24
25
26 def get_project_info() -> dict:
27 """Retrieve project's info to populate the message catalog template"""
28 pyproject_text = PYPROJECT_TOML.read_text(encoding="utf-8")
29 project_data = tomllib.loads(pyproject_text)["project"]
30
31 # read __version__ from __init__.py
32 for child in ast.parse(INIT_PY.read_bytes()).body:
33 if not isinstance(child, ast.Assign):
34 continue
35 target = child.targets[0]
36 if not isinstance(target, ast.Name) or target.id != "__version__":
37 continue
38 version_node = child.value
39 if not isinstance(version_node, ast.Constant):
40 continue
41 project_data["version"] = version_node.value
42 break
43
44 return project_data
45
46
47 def extract_messages() -> None:
48 """Extract messages from all source files into message catalog template"""
49 Path(PROJECT_DIR, LOCALES_DIR).mkdir(parents=True, exist_ok=True)
50 project_data = get_project_info()
51 subprocess.run(
52 [
53 "pybabel",
54 "extract",
55 "-F",
56 MAPPING_FILE,
57 "--copyright-holder",
58 COPYRIGHT_HOLDER,
59 "--project",
60 project_data["name"],
61 "--version",
62 project_data["version"],
63 "--msgid-bugs-address",
64 project_data["urls"]["Issue tracker"],
65 "-o",
66 POT_FILE,
67 SOURCE_DIR,
68 ],
69 cwd=PROJECT_DIR,
70 check=True,
71 )
72
73
74 def init_locale(locale: str) -> None:
75 """Initialize a new locale based on existing message catalog template"""
76 pofile = PROJECT_DIR / LOCALES_DIR / locale / "LC_MESSAGES" / f"{DOMAIN}.po"
77 if pofile.exists():
78 print(f"There is already a message catalog for locale {locale}, skipping.")
79 return
80 cmd = [
81 "pybabel",
82 "init",
83 "-i",
84 POT_FILE,
85 "-d",
86 LOCALES_DIR,
87 "-D",
88 DOMAIN,
89 "-l",
90 locale,
91 ]
92 subprocess.run(cmd, cwd=PROJECT_DIR, check=True)
93
94
95 def update_catalogs(locale: str) -> None:
96 """Update translations from existing message catalogs"""
97 cmd = ["pybabel", "update", "-i", POT_FILE, "-d", LOCALES_DIR, "-D", DOMAIN]
98 if locale:
99 cmd.extend(["-l", locale])
100 subprocess.run(cmd, cwd=PROJECT_DIR, check=True)
101
102
103 def compile_catalogs(locale: str) -> None:
104 """Compile existing message catalogs"""
105 cmd = ["pybabel", "compile", "-d", LOCALES_DIR, "-D", DOMAIN]
106 if locale:
107 cmd.extend(["-l", locale])
108 subprocess.run(cmd, cwd=PROJECT_DIR, check=True)
109
110
111 class CustomBuildHook(BuildHookInterface):
112 def initialize(self, version: str, build_data: dict[str, object]) -> None:
113 compile_catalogs("")
114
115
116 def main() -> None:
117 parser = argparse.ArgumentParser(description=__doc__)
118 parser.add_argument(
119 "command",
120 choices=["extract", "init", "update", "compile"],
121 help="command to be executed",
122 )
123 parser.add_argument(
124 "-l",
125 "--locale",
126 default="",
127 help="language code (needed for init, optional for update and compile)",
128 )
129
130 args = parser.parse_args()
131 locale = args.locale
132
133 if args.command == "extract":
134 extract_messages()
135 elif args.command == "init":
136 if not locale:
137 parser.error("init requires passing the --locale option")
138 init_locale(locale)
139 elif args.command == "update":
140 update_catalogs(locale)
141 elif args.command == "compile":
142 compile_catalogs(locale)
143
144
145 if __name__ == "__main__":
146 main()