def run(self): import os import pathlib from unittest.mock import patch from babel.messages.frontend import CommandLineInterface fix_pyqt_import() try: from PyQt5.pylupdate_main import main as pylupdate_main except ImportError: print( "PyQt5 not installed, skipping `parsec.core.gui.ui` generation." ) return self.announce("Generating ui translation files", level=distutils.log.INFO) ui_dir = pathlib.Path("parsec/core/gui") tr_dir = ui_dir / "tr" os.makedirs(tr_dir, exist_ok=True) new_args = ["pylupdate", str(ui_dir / "parsec-gui.pro")] with patch("sys.argv", new_args): pylupdate_main() files = [ str(f) for f in ui_dir.iterdir() if f.is_file() and f.suffix == ".py" ] files.sort() files.append(str(tr_dir / "parsec_en.ts")) args = [ "_", "extract", "-s", "--no-location", "-F", ".babel.cfg", "--omit-header", "-o", str(tr_dir / "translation.pot"), *files, ] CommandLineInterface().run(args) languages = ["fr", "en"] for lang in languages: po_file = tr_dir / f"parsec_{lang}.po" if not po_file.is_file(): po_file.touch() args = [ "_", "update", "-i", str(tr_dir / "translation.pot"), "-o", str(po_file), "-l", lang, ] CommandLineInterface().run(args)
def run(self, args): """ :type args: list[str] """ args.insert(0, sys.argv[0]) cli = CommandLineInterface() cli.run(args)
def configure_cli_command(cmdline): """ Helper to configure a command class, but not run it just yet. :param cmdline: The command line (sans the executable name) :return: Command instance """ args = shlex.split(cmdline) cli = CommandLineInterface() cmdinst = cli._configure_command(cmdname=args[0], argv=args[1:]) return cmdinst
def compile_messages(): """Compila las traducciones de los archivos .po a .mo""" args = [ 'pybabel', 'compile', '-d', 'biblat_manager/webapp/translations' ] return CommandLineInterface().run(args)
def compile_translations(): from babel.messages.frontend import CommandLineInterface os.chdir(root_directory()) res = True for language in available_languages(): po_file = join(LOCALE_DIR, language, "LC_MESSAGES", "%s.po" % APPLICATION_NAME) if language != "en": msgid = None with open(po_file, "br") as f: for line in f: line = line.decode("utf-8").rstrip() if msgid is None: if line.startswith("msgid "): msgid = line[len("msgid "):] if msgid == '""': msgid = None else: if line.startswith("msgstr "): msgstr = line[len("msgstr "):] if msgstr == '""': res = False print("Found untranslated message for %s: %s" % (language, msgid)) msgid = None CommandLineInterface().run([__file__, "compile", "-D", APPLICATION_NAME, "-i", po_file, "-d", LOCALE_DIR, "-l", language, "--statistics"]) return res
def open_translations( locale: str, directory_path: Path) -> Optional[gettext.GNUTranslations]: locale_path_name = locale.replace('-', '_') po_file_path = directory_path / 'locale' / locale_path_name / 'LC_MESSAGES' / 'betty.po' try: translation_version = hashfile(po_file_path) except FileNotFoundError: return None translation_cache_directory_path = fs.CACHE_DIRECTORY_PATH / 'translations' / translation_version cache_directory_path = translation_cache_directory_path / locale_path_name / 'LC_MESSAGES' mo_file_path = cache_directory_path / 'betty.mo' with suppress(FileNotFoundError): with open(mo_file_path, 'rb') as f: return gettext.GNUTranslations(f) cache_directory_path.mkdir(exist_ok=True, parents=True) with suppress(FileExistsError): shutil.copyfile(po_file_path, cache_directory_path / 'betty.po') with contextlib.redirect_stdout(StringIO()): CommandLineInterface().run([ '', 'compile', '-d', translation_cache_directory_path, '-l', locale_path_name, '-D', 'betty' ]) with open(mo_file_path, 'rb') as f: return gettext.GNUTranslations(f)
def open_translations( locale: str, directory_path: str) -> Optional[gettext.GNUTranslations]: locale_path_name = locale.replace('-', '_') po_file_path = path.join(directory_path, 'locale', locale_path_name, 'LC_MESSAGES', 'betty.po') try: translation_version = hashfile(po_file_path) except FileNotFoundError: return None translation_cache_directory_path = path.join(_CACHE_DIRECTORY_PATH, 'translations', translation_version) cache_directory_path = path.join(translation_cache_directory_path, locale_path_name, 'LC_MESSAGES') mo_file_path = path.join(cache_directory_path, 'betty.mo') with suppress(FileNotFoundError): with open(mo_file_path, 'rb') as f: return gettext.GNUTranslations(f) makedirs(cache_directory_path, exist_ok=True) with suppress(FileExistsError): shutil.copyfile(po_file_path, path.join(cache_directory_path, 'betty.po')) with contextlib.redirect_stdout(StringIO()): CommandLineInterface().run([ '', 'compile', '-d', translation_cache_directory_path, '-l', locale_path_name, '-D', 'betty' ]) with open(mo_file_path, 'rb') as f: return gettext.GNUTranslations(f)
def extract_translations(): from babel.messages.frontend import CommandLineInterface os.chdir(root_directory()) pot_file = join(LOCALE_DIR, "%s.pot" % APPLICATION_NAME) CommandLineInterface().run([__file__, "extract", "-w", "225", "-o", pot_file, "--mapping", join(os.path.dirname(__file__), "mapping.cfg"), "backend"]) for language in available_languages(): po_file = join(LOCALE_DIR, language, "LC_MESSAGES", "%s.po" % APPLICATION_NAME) args = ["-D", APPLICATION_NAME, "-i", pot_file, "-d", LOCALE_DIR, "--no-wrap", "-l", language] command = "update" if os.path.exists(po_file) else "init" if os.path.exists(po_file): args.append("--no-fuzzy-matching") CommandLineInterface().run([__file__, command] + args) return True
def extract_locales(): output_dir = "locales" Path(output_dir).mkdir(parents=True, exist_ok=True) CommandLineInterface().run([ "pybabel", "extract", APP_DIR, "-o", os.path.join(output_dir, f"{APP_DIR}.pot"), ])
def update_catalog(): """ Actualiza los catálogos a partir de las cadenas en: biblat_manager/webapp/translations/messages.pot """ args = [ 'pybabel', 'update', '-i', 'biblat_manager/webapp/translations/messages.pot', '-d', 'biblat_manager/webapp/translations' ] return CommandLineInterface().run(args)
def make_messages(): """ Escanea biblat_manager/webapp buscando strings traducible y el resultado lo almacena en: biblat_manager/webapp/translations/messages.pot """ args = [ 'pybabel', 'extract', '-F', 'biblat_manager/config/babel.cfg', '-k', 'lazy_gettext', '-k', '__', '-o', 'biblat_manager/webapp/translations/messages.pot', '.' ] return CommandLineInterface().run(args)
def create_catalog(): """ Crea los catálogos para los idiomas definidos en biblat_manager/config, a partir de las cadenas en: biblat_manager/webapp/translations/messages.pot """ for lang in settings.Config.LANGUAGES: args = [ 'pybabel', 'init', '-i', 'biblat_manager/webapp/translations/messages.pot', '-d', 'biblat_manager/webapp/translations', '-l', '%s' % lang ] CommandLineInterface().run(args)
def run(self): import os import pathlib from babel.messages.frontend import CommandLineInterface self.announce("Compiling ui translation files", level=distutils.log.INFO) ui_dir = pathlib.Path("parsec/core/gui") tr_dir = ui_dir / "tr" rc_dir = ui_dir / "rc" / "translations" os.makedirs(rc_dir, exist_ok=True) languages = ["fr", "en"] for lang in languages: args = [ "_", "compile", "-i", str(tr_dir / f"parsec_{lang}.po"), "-o", str(rc_dir / f"parsec_{lang}.mo"), ] CommandLineInterface().run(args)
def init_locales(): output_dir = "locales" input_file = os.path.join(output_dir, f"{APP_DIR}.pot") CommandLineInterface().run( ["pybabel", "init", "-i", input_file, "-d", output_dir, "-l", LOCALE])
def _run(self, *params): """Run a pybabel command.""" cmd = ['pybabel', '-q'] + list(params) CommandLineInterface().run(cmd)
def compile_catalog(self): CommandLineInterface().run(['pybabel', 'compile', '-d', TRANSLATIONS])
def update_catalog(self, loc): CommandLineInterface().run(['pybabel', 'update', '-l', loc, '-i', MESSAGES, '-d', TRANSLATIONS, '--previous'])
def compile_locales(): input_dir = "locales" CommandLineInterface().run( ["pybabel", "compile", "-d", input_dir, "--statistics"])
#! python import sys from babel.messages.frontend import CommandLineInterface width = '79' if __name__ == '__main__': if sys.argv[1] == "extract": CommandLineInterface().run([ 'pybabel', 'extract', '--sort-by-file', '--project=monkq', 'monkq', '-o', 'monkq/utils/translations/monkq.pot', '-w', width ]) elif sys.argv[1] == "init": CommandLineInterface().run([ 'pybabel', 'init', '-l', sys.argv[2], '-i', 'monkq/utils/translations/monkq.pot', '-d', 'monkq/utils/translations', '-D', 'monkq', '-w', width ]) elif sys.argv[1] == 'compile': CommandLineInterface().run([ 'pybabel', 'compile', '-d', 'monkq/utils/translations', '-D', 'monkq' ]) elif sys.argv[1] == 'update': CommandLineInterface().run([ 'pybabel', 'update', '-i', 'monkq/utils/translations/monkq.pot', '-D', 'monkq', '-d', 'monkq/utils/translations', '-w', width ]) else: print( "You have to provide the args choose from extract, init, compile, update"
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys PROJECT_ROOT = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'bin/i18n')) from babel.messages.frontend import CommandLineInterface if __name__ == '__main__': CommandLineInterface().run(sys.argv)
class BabelCommand(BaseCommand): name = "extract" description = "Extract messages from the source files and create the "\ "corresponding POTs, also used to update an existing POT" def __init__(self): super(BabelCommand, self).__init__() self.cmd = CommandLineInterface() self._args = ["", "-q"] def execute(self, command, *args, **kw): args = self._args + [command] + list(args) for k, v in kw.items(): args += ['-%s' % k, v] self.cmd.run(args) def get_files(self, locale, domain, path): po = "" mo = "" pot = "" if domain: pot = os.path.join(path, 'po', domain, '%s.pot' % domain) if locale and domain: po = os.path.join(path, 'po', domain, '%s.po' % locale) mo = os.path.join(path, 'locale', locale, 'LC_MESSAGES', '%s.mo' % domain) return pot, po, mo def extract(self, locale, domain, path): pot, po, mo = self.get_files(locale, domain, path) if not os.path.exists(os.path.join(path, 'po', domain)): os.makedirs(os.path.join(path, 'po', domain)) mappath = os.path.join(os.path.dirname(__file__), "mapping", "%s.cfg" % domain) os.chdir(path) print "Creating '%s'..." % pot self.execute("extract", '.', o=pot, F=mappath) def run(self, argv): self.parser.add_option("-l", "--locale", dest="locale", help="locale (e.g. en_US, fr_FR)") self.parser.add_option("-D", "--domain", dest="domain", help="domain (e.g. messages, javascript)") options, args = self.parser.parse_args(argv) modules = _get_modules(args[0]) domains = ["messages", "javascript"] if options.domain: domains = options.domain.split(",") for m, p in modules: for d in domains: self.extract(options.locale, d, p)
def _run(str): return CommandLineInterface().run([sys.argv[0]] + str.split(' '))
def __init__(self): super(BabelCommand, self).__init__() self.cmd = CommandLineInterface() self._args = ["", "-q"]
def run_babel(self, command, *argv): cmd = CommandLineInterface() cmd.run(['', '-q', command] + list(argv))
def run(self): from babel.messages.frontend import CommandLineInterface as BabelCLI BabelCLI.run()
def extract_text(self): os.makedirs(ROOT_DIR, exist_ok=True) CommandLineInterface().run(['pybabel', 'extract', '-F', 'babel.ini', '-k', '_ _Q gettext ngettext', '-o', MESSAGES, './', '--omit-header'])
import py import os import gettext from babel.messages.frontend import CommandLineInterface babel_cli = CommandLineInterface() class Translator(object): def __init__(self, rootdir, languages, dest_language=None, autocompile=True): self.rootdir = py.path.local(rootdir) self.languages = languages if dest_language is None: dest_language = languages[0] self.dest_language = dest_language self.langdir = self.rootdir.join('languages').ensure(dir=True) self.pot = self.langdir.join('template.pot') if autocompile: self.compile() self._init_tr() def _init_tr(self): self.tr = gettext.translation('messages', str(self.langdir), [self.dest_language], fallback=True) def reload(self):
def init_catalog(self, loc): CommandLineInterface().run(['pybabel', 'init', '-l', loc, '-i', MESSAGES, '-d', TRANSLATIONS])
def babel(args): cmdline = CommandLineInterface() cmdline.usage = 'pybabel %s %s' print "calling pybabel %s" % (" ".join(args)) cmdline.run([sys.argv[0]] + args)
def update_locales(): output_dir = "locales" input_file = os.path.join(output_dir, f"{APP_DIR}.pot") CommandLineInterface().run( ["pybabel", "update", "-i", input_file, "-d", output_dir])
proxies = { "http": proxy, "https": proxy } session.proxies.update(proxies) mod_getter = FactorioModGetter(username, password, session) try: sync_mod_locale(mod_getter, mod_names) except ValueError as e: print(e) elif args.subcommand in ["extract", "render"]: locale = args.locale if args.subcommand == "extract": localizer = Localizer() localizer.generate_template("locale/en") CommandLineInterface().run( ['pybabel', 'extract', '-F', 'babel.cfg', '-o', 'messages.pot', '.']) if os.path.exists(f"lang/{locale}"): CommandLineInterface().run( ['pybabel', 'update', '-i', 'messages.pot', '-d', 'lang', '-l', locale]) else: CommandLineInterface().run( ['pybabel', 'init', '-i', 'messages.pot', '-d', 'lang', '-l', locale]) os.remove("messages.pot") else: CommandLineInterface().run( ['pybabel', 'compile', '-f', '-d', 'lang']) localizer = Localizer() localizer.render_locale(locale) elif args.subcommand == "release": version = info["version"] dir_name = "bobsmodslocale" + "_" + version