1+ import io
12import os
23import pathlib
34import shutil
5+ import string
46import subprocess
57
8+ from babel .messages .pofile import read_po , write_po
69import fire
710
811MSG_DIR = pathlib .Path (__file__ ).parent .parent .parent
@@ -40,6 +43,14 @@ def chdir_Doc():
4043 os .chdir (MSG_DIR / "../cpython/Doc" )
4144
4245
46+ def remove_nonprintables (text ):
47+ nps = '' .join (sorted (set (chr (i )
48+ for i in range (128 )) - set (string .printable )))
49+ table = str .maketrans (nps , nps [0 ] * len (nps ))
50+ text = text .translate (table ).replace (nps [0 ], '' )
51+ return text .lstrip ()
52+
53+
4354class Command :
4455 def init (self ):
4556 """Initialize .pdk."""
@@ -63,15 +74,48 @@ def watch(self):
6374 sh ("make -e SPHINXOPTS=\" -D language='ko'\" htmllive" )
6475
6576 def extract (self ):
66- """Extract translatable messages into pot files."""
77+ """Extract translatable messages into . pot files."""
6778 chdir_Doc ()
6879 sh ("make gettext" )
6980
7081 def update (self ):
71- """Apply the updates from pot files to po files."""
82+ """Apply the updates from pot files to . po files."""
7283 chdir_Doc ()
7384 sh ("sphinx-intl update -p build/gettext -l ko" )
7485
86+ def format (self , pofile ):
87+ """Format a .po file."""
88+ with open (pofile ) as f :
89+ idata = f .read ()
90+ f = io .StringIO (idata )
91+ catalog = read_po (f , abort_invalid = True )
92+
93+ for msg in catalog :
94+ if not msg .id or not msg .string or msg .fuzzy :
95+ continue
96+ msg .string = remove_nonprintables (msg .string )
97+
98+ f = io .BytesIO ()
99+ write_po (f , catalog )
100+ odata = f .getvalue ()
101+ if idata .encode () != odata :
102+ with open (pofile , 'wb' ) as f :
103+ f .write (odata )
104+ else :
105+ print ('already formatted' )
106+ fuzzy_count = empty_count = 0
107+ for msg in catalog :
108+ if not msg .id :
109+ continue
110+ if msg .fuzzy :
111+ fuzzy_count += 1
112+ elif not msg .string :
113+ empty_count += 1
114+ if fuzzy_count :
115+ print (f'{ fuzzy_count } fuzzy messages found' )
116+ if empty_count :
117+ print (f'{ empty_count } untranslated messages found' )
118+
75119
76120def main ():
77121 fire .Fire (Command )
0 commit comments