Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f818dd3

Browse files
committed
Backport update-translation.py from 3.12 branch to 3.11
1 parent 413ecff commit f818dd3

File tree

1 file changed

+123
-0
lines changed

1 file changed

+123
-0
lines changed

.update-translation.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""updates translation files for a language from the Weblate project and commits them"""
2+
3+
from argparse import ArgumentParser
4+
from dataclasses import dataclass
5+
from logging import basicConfig, error, info, warning
6+
from os import getenv
7+
from pathlib import Path
8+
from re import match
9+
from shutil import rmtree
10+
from subprocess import call, run
11+
12+
from tqdm import tqdm
13+
from tqdm.contrib.logging import logging_redirect_tqdm
14+
from wlc import Project, Weblate, WeblateThrottlingError
15+
16+
17+
def _update_translation(language: str, version: str, weblate_key: str) -> None:
18+
_call('git diff --exit-code')
19+
_clear_files()
20+
_download_translations(language, Version(version), weblate_key)
21+
changed = _get_changed_files()
22+
added = _get_new_files()
23+
if all_ := changed + added:
24+
_call(f'git add {" ".join(all_)}')
25+
_call('git commit -m "Update translation from Weblate"')
26+
_call('git restore .') # discard ignored files
27+
28+
29+
def _clear_files():
30+
for path in Path().iterdir():
31+
if path.name.startswith('.'):
32+
continue
33+
if path.is_dir() and not path.is_symlink():
34+
rmtree(path)
35+
if path.suffix == '.po':
36+
path.unlink()
37+
38+
39+
def _download_translations(language: str, version: "Version", weblate_key: str) -> None:
40+
weblate = Weblate(weblate_key, 'https://hosted.weblate.org/api/')
41+
project = Project(weblate, 'https://hosted.weblate.org/api/projects/python-docs/')
42+
_validate_language(language, project)
43+
with logging_redirect_tqdm():
44+
for selected_category in project.categories():
45+
if selected_category.name == version.weblate_category_name():
46+
break
47+
48+
for component in tqdm(project.list()):
49+
if component.category and component.category.name != selected_category.name:
50+
continue
51+
if component.is_glossary:
52+
continue
53+
translations = component.list()
54+
while (translation := next(translations, None)) and translation.language.code != 'pl':
55+
pass
56+
if not translation:
57+
info(f"{component.slug} doesn't have a {language} translation")
58+
continue
59+
try:
60+
content = translation.download()
61+
except WeblateThrottlingError:
62+
error(f'Throttled on {component.slug}', exc_info=True)
63+
break
64+
path = Path(component.filemask.removeprefix(f'*/{version.directory_name()}/'))
65+
path.parent.mkdir(exist_ok=True)
66+
path.write_bytes(content)
67+
68+
69+
@dataclass
70+
class Version:
71+
number: str
72+
73+
def is_latest(self):
74+
return self.number == "3.12"
75+
76+
def weblate_category_name(self):
77+
return self.number
78+
79+
def directory_name(self):
80+
return self.is_latest() and "latest" or self.number
81+
82+
83+
def _validate_language(language: str, project: Project) -> None:
84+
for l in project.languages():
85+
if l.code == language:
86+
break
87+
else:
88+
raise SystemError(f'{language} is an incorrect language')
89+
90+
91+
def _get_changed_files() -> list[str]:
92+
diff = _run("git diff -I'^\"POT-Creation-Date: ' --numstat")
93+
return [match(r'\d+\t\d+\t(.*)', line).group(1) for line in diff.splitlines()]
94+
95+
96+
def _get_new_files() -> list[str]:
97+
ls_files = _run('git ls-files -o -d --exclude-standard')
98+
return ls_files.splitlines()
99+
100+
101+
def _call(command: str):
102+
if (return_code := call(command, shell=True)) != 0:
103+
exit(return_code)
104+
105+
106+
def _run(command: str) -> str:
107+
if (process := run(command, shell=True, capture_output=True)).returncode != 0:
108+
exit(process.returncode)
109+
return process.stdout.decode()
110+
111+
112+
if __name__ == "__main__":
113+
parser = ArgumentParser(description=__doc__)
114+
parser.add_argument('language')
115+
parser.add_argument('version')
116+
options = parser.parse_args()
117+
118+
basicConfig(level='INFO')
119+
120+
if not (weblate_key := getenv('KEY')):
121+
warning('Not authenticated, you will be heavy throttled')
122+
123+
_update_translation(options.language, options.version, weblate_key=weblate_key)

0 commit comments

Comments
 (0)