1+ """Please note that this script requires a Transifex API token to run."""
2+ import glob
3+ import subprocess
4+ from functools import partial
5+ from pathlib import Path
6+ import re
7+ import os
8+
9+ run = partial (subprocess .run , check = True )
10+
11+
12+ def init_project ():
13+ run (["tx" , "init" ])
14+
15+
16+ def add_files (project_name : str ):
17+ run (
18+ [
19+ "tx" ,
20+ "add" ,
21+ "remote" ,
22+ "--file-filter" ,
23+ "trans/<lang>/<resource_slug>.<ext>" ,
24+ f"https://www.transifex.com/python-doc/{ project_name } /dashboard/" ,
25+ ]
26+ )
27+
28+
29+ FILTER_PATTERN = re .compile (
30+ r"^(?P<prefix>file_filter( *)=( *))(?P<resource>.+)$" , re .MULTILINE
31+ )
32+
33+
34+ def name_replacer (match : re .Match [str ]):
35+ prefix , resource = match .group ("prefix" , "resource" )
36+ override_prefix = prefix .replace ("file_filter" , "trans.zh_CN" )
37+ pattern = (
38+ resource .replace ("trans/<lang>/" , "" )
39+ .replace ("glossary_" , "glossary" )
40+ .replace ("--" , "/" )
41+ .replace ("_" , "?" )
42+ )
43+ matches = list (glob .glob (pattern .replace (".po" , ".rst" )))
44+ if not matches :
45+ print ("missing" , pattern )
46+ return f"{ prefix } { resource } \n { override_prefix } { pattern .replace ('?' , '_' )} "
47+ elif len (matches ) == 1 :
48+ filename = matches [0 ].replace (".rst" , ".po" ).replace ("\\ " , "/" )
49+ else :
50+ raise ValueError ("multi match" , resource , pattern , matches )
51+ return f"{ prefix } { resource } \n { override_prefix } { filename } "
52+
53+
54+ def patch_config (path : str ):
55+ tx_config_path = Path (".tx" , "config" )
56+
57+ config_content = tx_config_path .read_text ("utf-8" )
58+
59+ cwd = os .getcwd ()
60+ os .chdir (path )
61+ config_content = FILTER_PATTERN .sub (name_replacer , config_content )
62+ config_content = re .sub (r'replace_edited_strings.*\n' ,'' , config_content )
63+ config_content = re .sub (r'keep_translations.*\n' ,'' , config_content )
64+ config_content = re .sub (r'0\ntrans\.ru.*\n' ,'0\n ' , config_content )
65+ config_content = config_content .replace (' =' ,'=' )
66+ os .chdir (cwd )
67+
68+ tx_config_path .write_text (config_content , "utf-8" )
69+
70+
71+ if __name__ == "__main__" :
72+ from argparse import ArgumentParser
73+
74+ parser = ArgumentParser ()
75+
76+ parser .add_argument ("--token" , default = "" )
77+ parser .add_argument ("--project-name" , required = True )
78+ parser .add_argument ("--doc-path" , required = True )
79+
80+ params = parser .parse_args ()
81+
82+ if params .token :
83+ os .environ ["TX_TOKEN" ] = params .token
84+
85+ init_project ()
86+ add_files (params .project_name )
87+ patch_config (params .doc_path )
0 commit comments