Skip to content

Instantly share code, notes, and snippets.

@martijnluinstra
Created June 16, 2018 19:58
Show Gist options
  • Save martijnluinstra/98dd183c315aad5963a3c7350a39d982 to your computer and use it in GitHub Desktop.
Save martijnluinstra/98dd183c315aad5963a3c7350a39d982 to your computer and use it in GitHub Desktop.
A Python 3 script that inverses the translation direction of a .po file and modifies the linked sources.
"""
For our PHP website, I needed to reverse the translation direction of the i18n functionality. The source code was all in
Dutch, but since international people had joined our team it made sense to change it to English in order to make their
work easier. This script was created to ease that process.
Please note that this isn't perfect: it won't correctly escape special characters that are inserted into the code, and
it also won't replace strings that contain escaped characters. It does make the entire process a lot less tedious, though.
Copyright (c) 2018 Martijn Luinstra
"""
import argparse
import os
import re
from babel.messages.catalog import Catalog
from babel.messages.pofile import read_po, write_po
parser = argparse.ArgumentParser(description='Reverse the translations of a PO-file and modify the respective code.')
parser.add_argument('po_file_in', type=argparse.FileType('rb'))
parser.add_argument('po_file_out', type=argparse.FileType('wb'))
parser.add_argument('--base-path', type=str, default=os.path.realpath(__file__))
args = parser.parse_args()
def replace_content(message):
for location in message.locations:
if not message.id:
continue
with open(os.path.join(args.base_path, location[0])) as f:
content = f.read()
if message.pluralizable:
new_content = re.sub(r'__N\((\s*)(\'|"){0}(\'|"),(\s*)(\'|"){1}(\'|")'.format(re.escape(message.id[0]), re.escape(message.id[1])),
r'__N(\g<1>\g<2>{}\g<3>,\g<4>\g<5>{}\g<6>'.format(message.string[0].replace('\\', '\\\\'), message.string[1].replace('\\', '\\\\')),
content, flags=re.MULTILINE)
else:
new_content = re.sub(r'__\((\s*)(\'|"){0}(\'|")'.format(re.escape(message.id)),
r'__(\g<1>\g<2>{}\g<3>'.format(message.string.replace('\\', '\\\\')),
content, flags=re.MULTILINE)
with open(os.path.join(args.base_path, location[0]), 'w') as f:
f.write(new_content)
def run():
catalog = read_po(args.po_file_in)
for message in catalog:
replace_content(message)
new_catalog.add(
message.string,
message.id,
message.locations,
message.flags,
message.auto_comments,
message.user_comments,
message.previous_id,
message.lineno,
message.context
)
write_po(args.po_file_out, new_catalog)
print ('Done! :)')
if __name__ == "__main__":
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment