Skip to content

Commit 4ef73d6

Browse files
authored
Drop template generation for updating .tx/config (#283)
* Add generate_txconfig.py * Move TEXT_TO_REPLACE outside function, move parse_args first * Drop cpython checkout and change language dir * Make environment variable available * Handle new path in potodo.sh * Fix script dir in commit.sh * Handle lang_dir in stats.py * Use Path to str * black
1 parent 8bad8cc commit 4ef73d6

File tree

6 files changed

+166
-40
lines changed

6 files changed

+166
-40
lines changed

.github/workflows/sync.yml

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -32,41 +32,22 @@ jobs:
3232
- name: Check out this repository
3333
uses: actions/checkout@v5
3434

35-
- name: Checkout CPython ${{ env.PYDOC_VERSION }}
36-
uses: actions/checkout@v5
37-
with:
38-
repository: 'python/cpython'
39-
ref: ${{ env.PYDOC_VERSION }}
40-
path: cpython
41-
4235
- name: Set language dir variable
4336
run:
44-
echo "LANGUAGE_DIR=cpython/Doc/locales/${{ env.PYDOC_LANGUAGE }}/LC_MESSAGES" >> $GITHUB_ENV
37+
echo "PYDOC_LANG_DIR=${{ env.PYDOC_VERSION }}" >> $GITHUB_ENV
4538

4639
- name: Checkout this repository ${{ env.PYDOC_VERSION }}
4740
uses: actions/checkout@v5
4841
with:
4942
ref: ${{ env.PYDOC_VERSION }}
50-
path: ${{ env.LANGUAGE_DIR }}
43+
path: ${{ env.PYDOC_LANG_DIR }}
5144

5245
- uses: actions/setup-python@v6
5346
with:
5447
python-version: ${{ inputs.version }}
5548
allow-prereleases: true
5649
cache: 'pip'
57-
cache-dependency-path: |
58-
requirements.txt
59-
cpython/Doc/requirements.txt
60-
61-
- name: Check for Transifex API Token availability
62-
id: secret-check
63-
# perform secret check & put boolean result as an output
64-
shell: bash
65-
run: |
66-
available=false
67-
[[ "${{ secrets.TX_TOKEN }}" != '' ]] && available=true
68-
echo "available=$available" >> $GITHUB_OUTPUT
69-
echo "available=$available"
50+
cache-dependency-path: requirements.txt
7051

7152
# 2- Install dependencies
7253

@@ -81,19 +62,19 @@ jobs:
8162
- name: Install Python dependencies
8263
run: |
8364
pip install -r requirements.txt
84-
make -C cpython/Doc venv
8565
8666
# 3- Pull translations
8767

88-
- name: Generate template files and Transifex config file
89-
run: ./scripts/generate_templates.sh
68+
- name: Generate updated .tx/config
69+
if: ${{ contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name) }}
70+
run: python scripts/generate_txconfig.py -p ./${{ env.PYDOC_LANG_DIR }} ${{ env.PYDOC_TX_PROJECT }}
9071

9172
- name: Pull translations from Transifex
9273
id: pull
9374
if: ${{ contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name) }}
9475
run: |
9576
# Clean up obsolete files
96-
find ./${{ env.LANGUAGE_DIR }} -name '*.po' -exec rm {} \;
77+
find ./${{ env.PYDOC_LANG_DIR }} -name '*.po' -exec rm {} \;
9778
./scripts/pull_translations.sh
9879
env:
9980
TX_TOKEN: ${{ secrets.TX_TOKEN }}
@@ -103,36 +84,42 @@ jobs:
10384
run: |
10485
newer_branch=${PYDOC_VERSION%%.*}.$((${PYDOC_VERSION##*.}+1))
10586
git clone --depth 1 --single-branch --branch $newer_branch https://github.com/python/python-docs-pt-br ${newer_branch}-dir
106-
pomerge --from ./${newer_branch}-dir/{**/,}*.po --to ./${{ env.LANGUAGE_DIR }}/{**/,}*.po
87+
pomerge --from ./${newer_branch}-dir/{**/,}*.po --to ./${{ env.PYDOC_LANG_DIR }}/{**/,}*.po
10788
rm -rf ./${newer_branch}-dir
10889
10990
- name: powrap
11091
if: steps.pull.outcome == 'success'
11192
run: |
112-
cd ./${{ env.LANGUAGE_DIR }}
93+
cd ./${{ env.PYDOC_LANG_DIR }}
11394
powrap *.po **/*.po
11495
11596
- name: Update statistics
11697
if: always()
11798
run: |
11899
./scripts/stats.py
119-
git -C ./${{ env.LANGUAGE_DIR }} diff stats.json
100+
git -C ./${{ env.PYDOC_LANG_DIR }} diff stats.json
101+
env:
102+
PYDOC_LANG_DIR: ${{ env.PYDOC_LANG_DIR }}
120103

121104
- name: Update potodo.md
122105
if: always()
123106
run: |
124107
./scripts/potodo.sh
125-
git diff ./${{ env.LANGUAGE_DIR }}/potodo.md
108+
git -C ./${{ env.PYDOC_LANG_DIR }} diff potodo.md
109+
env:
110+
PYDOC_LANG_DIR: ${{ env.PYDOC_LANG_DIR }}
126111

127112
# 4- Commit and push translations
128113

129114
- name: Commit
130115
run: ./scripts/commit.sh
116+
env:
117+
PYDOC_LANG_DIR: ${{ env.PYDOC_LANG_DIR }}
131118

132119
- name: Push
133120
if: ${{ contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name) }}
134121
run: |
135-
cd ./${{ env.LANGUAGE_DIR }}
122+
cd ./${{ env.PYDOC_LANG_DIR }}
136123
git push
137124
138125

scripts/commit.sh

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@
55

66
set -eu
77

8-
rootdir=$(realpath $(dirname $0))
9-
cd $rootdir/../cpython/Doc/locales/${PYDOC_LANGUAGE}/LC_MESSAGES
8+
test -n ${PYDOC_LANGUAGE+x}
9+
10+
rootdir=$(realpath $(dirname $0)/..)
11+
language_dir="${PYDOC_LANG_DIR:-$rootdir/cpython/Doc/locales/${PYDOC_LANGUAGE}/LC_MESSAGES}"
12+
13+
cd "$language_dir"
1014

1115
extra_files=".tx/config stats.json potodo.md"
1216

@@ -44,5 +48,5 @@ set -u
4448
# Commit only if there is any cached file
4549
if ! git diff-index --cached --quiet HEAD; then
4650
git add -v $extra_files
47-
git commit -vm "$($rootdir/generate_commit_msg.py)"
51+
git commit -vm "$($rootdir/scripts/generate_commit_msg.py)"
4852
fi

scripts/generate_txconfig.py

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Generate the .tx/config file based on the existing projects
4+
in Python docs Transifex project. Takes an project slug as
5+
positional argument, e.g. python-newest or python-313
6+
"""
7+
8+
import argparse
9+
import re
10+
import subprocess
11+
import sys
12+
from pathlib import Path
13+
14+
# Replaces required to fix the default values set by 'tx add remote' command.
15+
# Add or remove
16+
TEXT_TO_REPLACE = {
17+
"2_": "2.",
18+
"3_": "3.",
19+
"glossary_": "glossary",
20+
"collections_": "collections.",
21+
"compression_": "compression.",
22+
"concurrent_": "concurrent.",
23+
"curses_": "curses.",
24+
"email_": "email.",
25+
"html_": "html.",
26+
"http_": "http.",
27+
"importlib_resources_": "importlib.resources.",
28+
"importlib_": "importlib.",
29+
"logging_": "logging.",
30+
"multiprocessing_": "multiprocessing.",
31+
"os_": "os.",
32+
"string_": "string.",
33+
"sys_monitoring": "sys.monitoring",
34+
"tkinter_": "tkinter.",
35+
"unittest_": "unittest.",
36+
"urllib_": "urllib.",
37+
"xml_dom_": "xml.dom.",
38+
"xml_etree_": "xml.etree.",
39+
"xmlrpc_": "xmlrpc.",
40+
"xml_sax_": "xml.sax.",
41+
"xml_": "xml.",
42+
}
43+
44+
45+
def parse_args():
46+
parser = argparse.ArgumentParser(description=__doc__)
47+
parser.add_argument(
48+
"--root-path",
49+
"-p",
50+
default=Path("."),
51+
help="Path to the translation files, and also the .tx/config (defaults to current directory)",
52+
)
53+
parser.add_argument(
54+
"tx_project", help="Slug of the Transifex project to query resources from"
55+
)
56+
return parser.parse_args()
57+
58+
59+
def reset_tx_config(txconfig: Path):
60+
"""Create or reset the .tx/config file with basic header."""
61+
txconfig.parent.mkdir(exist_ok=True)
62+
txconfig.write_text("[main]\nhost = https://www.transifex.com\n", encoding="utf-8")
63+
print("Initialized .tx/config.")
64+
65+
66+
def populate_resources_from_remote(config_file: Path, tx_project: str):
67+
"""Add the remote resources from the Transifex project to .tx/config."""
68+
result = subprocess.run(
69+
[
70+
"tx",
71+
"--config",
72+
str(config_file),
73+
"add",
74+
"remote",
75+
"--file-filter",
76+
"<lang>/<resource_slug>.<ext>",
77+
f"https://app.transifex.com/python-doc/{tx_project}/",
78+
],
79+
check=True,
80+
)
81+
if result.returncode != 0:
82+
print("Failed to add the resources from remote:")
83+
print(result.stderr.strip())
84+
sys.exit(result.returncode)
85+
print("Added remote resources to Transifex.")
86+
87+
88+
def patch_config(txconfig: Path):
89+
"""Patch .tx/config to fixing PO filenames to match the expected."""
90+
content = txconfig.read_text(encoding="utf-8").splitlines()
91+
new_lines = []
92+
93+
for line in content:
94+
if line.startswith(("source_file", "source_lang")):
95+
continue
96+
97+
if line.startswith("file_filter"):
98+
line = line.replace("<lang>/", "")
99+
line = line.replace("--", "/")
100+
101+
for pattern, replacement in TEXT_TO_REPLACE.items():
102+
if pattern in line:
103+
line = line.replace(pattern, replacement)
104+
break
105+
106+
new_lines.append(line)
107+
108+
text = "\n".join(new_lines)
109+
110+
txconfig.write_text(text + "\n", encoding="utf-8")
111+
print("Updated .tx/config with character substitutions")
112+
113+
114+
def main():
115+
args = parse_args()
116+
config_path = Path(".tx/config")
117+
if args.root_path:
118+
config_path = args.root_path / config_path
119+
reset_tx_config(config_path)
120+
populate_resources_from_remote(config_path, args.tx_project)
121+
patch_config(config_path)
122+
123+
124+
if __name__ == "__main__":
125+
main()

scripts/potodo.sh

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@ test -n ${PYDOC_VERSION+x}
1010
test -n ${PYDOC_LANGUAGE+x}
1111

1212
rootdir=$(realpath $(dirname $0)/..)
13+
language_dir="${PYDOC_LANG_DIR:-$rootdir/cpython/Doc/locales/${PYDOC_LANGUAGE}/LC_MESSAGES}"
1314

14-
cd "$rootdir"/cpython/Doc/locales/${PYDOC_LANGUAGE}/LC_MESSAGES
15+
cd "$language_dir"
1516

1617
potodo --no-cache > potodo.md
1718

scripts/pull_translations.sh

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,12 @@
2020
set -xeu
2121

2222
test -n ${PYDOC_TX_PROJECT+x}
23+
test -n ${PYDOC_LANGUAGE+x}
2324

24-
cd "$(dirname $0)/../cpython/Doc/locales/${PYDOC_LANGUAGE}/LC_MESSAGES/"
25+
rootdir=$(realpath $(dirname $0)/..)
26+
language_dir="${PYDOC_LANG_DIR:-$rootdir/cpython/Doc/locales/${PYDOC_LANGUAGE}/LC_MESSAGES}"
27+
28+
cd "$language_dir"
2529

2630
# If a PO file is provided as input, convert it into Transifex resource
2731
# and add it be pulled (instead of pulling all translations files).

scripts/stats.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,16 @@
1717

1818
def main() -> None:
1919
"""Main function to generate translation stats."""
20-
language = os.environ.get("PYDOC_LANGUAGE")
21-
if not language:
22-
raise ValueError("Environment variable PYDOC_LANGUAGE is not set.")
2320

24-
pofiles_path = Path(f"cpython/Doc/locales/{language}/LC_MESSAGES")
21+
lang_dir = os.environ.get("PYDOC_LANG_DIR")
22+
if lang_dir:
23+
pofiles_path = Path(lang_dir)
24+
else:
25+
language = os.environ.get("PYDOC_LANGUAGE")
26+
if not language:
27+
raise ValueError("Environment variable PYDOC_LANGUAGE is not set.")
28+
pofiles_path = Path(f"cpython/Doc/locales/{language}/LC_MESSAGES")
29+
2530
if not pofiles_path.exists():
2631
raise FileNotFoundError(f"Path does not exist: {pofiles_path}")
2732

0 commit comments

Comments
 (0)