def handle(self, *args, **options): if args: # mimics puente.management.commands.extract for a list of files outputdir = os.path.join(settings.ROOT, 'locale', 'templates', 'LC_MESSAGES') if not os.path.isdir(outputdir): os.makedirs(outputdir) catalog = Catalog( header_comment='', project=get_setting('PROJECT'), version=get_setting('VERSION'), msgid_bugs_address=get_setting('MSGID_BUGS_ADDRESS'), charset='utf-8', ) for filename, lineno, msg, cmts, ctxt in extract_from_files(args): catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts, context=ctxt) with open(os.path.join(outputdir, '%s.pot' % DOMAIN), 'wb') as fp: write_po(fp, catalog, width=80) else: # This is basically a wrapper around the puente extract # command, we might want to do some things around this in the # future gettext_extract() pot_to_langfiles(DOMAIN)
def handle(self, *args, **options): return merge_command( create=options.get('create'), base_dir=get_setting('BASE_DIR'), standalone_domains=get_setting('STANDALONE_DOMAINS'), languages=getattr(settings, 'LANGUAGES', []) )
def handle(self, *args, **options): filenames = options['filenames'] if filenames: # mimics puente.management.commands.extract for a list of files outputdir = os.path.join(settings.ROOT, 'locale', 'templates', 'LC_MESSAGES') if not os.path.isdir(outputdir): os.makedirs(outputdir) catalog = Catalog( header_comment='', project=get_setting('PROJECT'), version=get_setting('VERSION'), msgid_bugs_address=get_setting('MSGID_BUGS_ADDRESS'), charset='utf-8', ) for filename, lineno, msg, cmts, ctxt in extract_from_files( filenames): catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts, context=ctxt) with open(os.path.join(outputdir, '%s.pot' % DOMAIN), 'wb') as fp: write_po(fp, catalog, width=80) else: # This is basically a wrapper around the puente extract # command, we might want to do some things around this in the # future gettext_extract() pot_to_langfiles(DOMAIN)
def handle(self, *args, **options): return merge_command( create=options.get('create'), backup=options.get('backup'), base_dir=get_setting('BASE_DIR'), domain_methods=get_setting('DOMAIN_METHODS'), languages=getattr(settings, 'LANGUAGES', []) )
def handle(self, *args, **options): return merge_command( create=options.get("create"), backup=options.get("backup"), base_dir=get_setting("BASE_DIR"), domain_methods=get_setting("DOMAIN_METHODS"), languages=getattr(settings, "LANGUAGES", []), )
def fake_extract_command(filename, fileobj, method, options=generate_options_map(), keywords=get_setting('KEYWORDS'), comment_tags=get_setting('COMMENT_TAGS')): catalog = Catalog(charset='utf-8') extracted = fake_extract_from_dir(filename, fileobj, method, options, keywords, comment_tags) for filename, lineno, msg, cmts, ctxt in extracted: catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts, context=ctxt) po_out = StringIO() write_po(po_out, catalog, width=80, omit_header=True) return unicode(po_out.getvalue())
def test_missing_pot_file(self, tmpdir): with pytest.raises(CommandError): merge_command( create=True, base_dir=str(tmpdir), standalone_domains=get_setting('STANDALONE_DOMAINS'), languages=['de', 'en-US', 'fr'] )
def add_arguments(self, parser): parser.add_argument( "--output-dir", "-o", default=os.path.join(get_setting("BASE_DIR"), "locale", "templates", "LC_MESSAGES"), dest="outputdir", help=("The directory where extracted files will be placed. " "(Default: %%default)"), ),
def add_arguments(self, parser): parser.add_argument( '--output-dir', '-o', default=os.path.join(get_setting('BASE_DIR'), 'locale', 'templates', 'LC_MESSAGES'), dest='outputdir', help=( 'The directory where extracted files will be placed. ' '(Default: %%default)' ) ),
def handle(self, *args, **options): return extract_command( # Command line arguments outputdir=options.get('outputdir'), # From settings.py domain_methods=get_setting('DOMAIN_METHODS'), text_domain=get_setting('TEXT_DOMAIN'), keywords=get_setting('KEYWORDS'), comment_tags=get_setting('COMMENT_TAGS'), base_dir=get_setting('BASE_DIR'), project=get_setting('PROJECT'), version=get_setting('VERSION'), msgid_bugs_address=get_setting('MSGID_BUGS_ADDRESS'), )
def handle(self, *args, **options): return extract_command( # Command line arguments outputdir=options.get('outputdir'), # From settings.py domain_methods=get_setting('DOMAIN_METHODS'), text_domain=get_setting('TEXT_DOMAIN'), keywords=get_setting('KEYWORDS'), comment_tags=get_setting('COMMENT_TAGS'), base_dir=get_setting('BASE_DIR'), project=get_setting('PROJECT'), version=get_setting('VERSION'), msgid_bugs_address=get_setting('MSGID_BUGS_ADDRESS'), )
def handle(self, *args, **options): return extract_command( # Command line arguments outputdir=options.get("outputdir"), # From settings.py domain_methods=get_setting("DOMAIN_METHODS"), text_domain=get_setting("TEXT_DOMAIN"), keywords=get_setting("KEYWORDS"), comment_tags=get_setting("COMMENT_TAGS"), base_dir=get_setting("BASE_DIR"), project=get_setting("PROJECT"), version=get_setting("VERSION"), msgid_bugs_address=get_setting("MSGID_BUGS_ADDRESS"), )
def add_arguments(self, parser): parser.add_argument( "--domain", "-d", default=DEFAULT_DOMAIN_VALUE, dest="domain", help=( 'The domain of the message files. If "all" ' "everything will be extracted and combined into " "%s.pot. (default: %%%%default)." % get_setting("TEXT_DOMAIN") ), ) parser.add_argument( "--output-dir", "-o", default=os.path.join(get_setting("ROOT"), "locale", "templates", "LC_MESSAGES"), dest="outputdir", help=("The directory where extracted files will be placed. " "(Default: %%default)"), ) parser.add_argument( "-c", "--create", action="store_true", dest="create", default=False, help="Create output-dir if missing" )
def handle(self, *args, **options): return extract_command( # Command line arguments domain=options.get("domain"), outputdir=options.get("outputdir"), # From settings.py domain_methods=get_setting("DOMAIN_METHODS"), standalone_domains=get_setting("STANDALONE_DOMAINS"), text_domain=get_setting("TEXT_DOMAIN"), keywords=get_setting("KEYWORDS"), comment_tags=get_setting("COMMENT_TAGS"), base_dir=get_setting("BASE_DIR"), )
def test_basic(self, tmpdir): locale_dir = tmpdir.join('locale') build_filesystem(str(locale_dir), { 'templates/LC_MESSAGES/django.pot': dedent("""\ #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\\n" "Report-Msgid-Bugs-To: \\n" "POT-Creation-Date: 2015-10-28 16:18+0000\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n" "Language-Team: LANGUAGE <*****@*****.**>\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=UTF-8\\n" "Content-Transfer-Encoding: 8bit\\n" "X-Generator: Translate Toolkit 1.13.0\\n" #: foo.html:2 msgid "html string" msgstr "" #: foo.html:3 msgid "html trans block" msgstr "" #: foo.py:1 msgid "python string" msgstr "" """), }) merge_command( create=True, base_dir=str(tmpdir), standalone_domains=get_setting('STANDALONE_DOMAINS'), languages=['de', 'en-US', 'fr'] ) assert locale_dir.join('de', 'LC_MESSAGES', 'django.po').exists() assert locale_dir.join('en_US', 'LC_MESSAGES', 'django.po').exists() assert locale_dir.join('fr', 'LC_MESSAGES', 'django.po').exists()
def extract_from_files(filenames, method_map=METHODS, options_map=generate_options_map(), keywords=get_setting('KEYWORDS'), comment_tags=get_setting('COMMENT_TAGS'), callback=extract_callback, strip_comment_tags=False): """Extract messages from any source files found in the given iterable. This function generates tuples of the form: ``(filename, lineno, message, comments)`` Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param filenames: an iterable of filenames relative to the ROOT of the project :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :return: an iterator over ``(filename, lineno, funcname, message)`` tuples :rtype: ``iterator`` :see: `pathmatch` """ # adapted from babel.messages.extract.extract_from_dir for filename in filenames: matched = False for pattern, method in method_map: if pathmatch(pattern, filename): matched = True filepath = os.path.join(settings.ROOT, filename) if not os.path.exists(filepath): print '! %s does not exist!' % filename break options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments, context in\ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): yield filename, lineno, message, comments, context break if not matched: print '! %s does not match any domain methods!' % filename
def handle(self, *args, **options): return merge_command(create=options.get('create'), backup=options.get('backup'), base_dir=get_setting('BASE_DIR'), domain_methods=get_setting('DOMAIN_METHODS'), languages=getattr(settings, 'LANGUAGES', []))
def extract_from_files(filenames, method_map=METHODS, options_map=generate_options_map(), keywords=get_setting('KEYWORDS'), comment_tags=get_setting('COMMENT_TAGS'), callback=extract_callback, strip_comment_tags=False): """Extract messages from any source files found in the given iterable. This function generates tuples of the form: ``(filename, lineno, message, comments)`` Which extraction method is used per file is determined by the `method_map` parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping: >>> method_map = [ ... ('**.py', 'python') ... ] This basically says that files with the filename extension ".py" should be processed by the "python" extraction method. Files that don't match any of the mapping patterns are ignored. See the documentation of the `pathmatch` function for details on the pattern syntax. The following extended mapping would also use the "genshi" extraction method on any file in "templates" subdirectory: >>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ] The dictionary provided by the optional `options_map` parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings). The glob patterns of the `options_map` do not necessarily need to be the same as those used in the method mapping. For example, while all files in the ``templates`` folders in an application may be Genshi applications, the options for those files may differ based on extension: >>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... } :param filenames: an iterable of filenames relative to the ROOT of the project :param method_map: a list of ``(pattern, method)`` tuples that maps of extraction method names to extended glob patterns :param options_map: a dictionary of additional options (optional) :param keywords: a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings :param comment_tags: a list of tags of translator comments to search for and include in the results :param callback: a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order :param strip_comment_tags: a flag that if set to `True` causes all comment tags to be removed from the collected comments. :return: an iterator over ``(filename, lineno, funcname, message)`` tuples :rtype: ``iterator`` :see: `pathmatch` """ # adapted from babel.messages.extract.extract_from_dir for filename in filenames: matched = False for pattern, method in method_map: if pathmatch(pattern, filename): matched = True filepath = os.path.join(settings.ROOT, filename) if not os.path.exists(filepath): print('! %s does not exist!' % filename) break options = {} for opattern, odict in options_map.items(): if pathmatch(opattern, filename): options = odict if callback: callback(filename, method, options) for lineno, message, comments, context in\ extract_from_file(method, filepath, keywords=keywords, comment_tags=comment_tags, options=options, strip_comment_tags=strip_comment_tags): yield filename, lineno, message, comments, context break if not matched: print('! %s does not match any domain methods!' % filename)
def handle(self, *args, **options): # Must monkeypatch first to fix InternationalizationExtension # stomping issues! See docstring for details. monkeypatch_i18n() # Get all the settings we need; we uppercase them so they're # obviously setings DOMAIN_METHODS = get_setting("DOMAIN_METHODS") STANDALONE_DOMAINS = get_setting("STANDALONE_DOMAINS") KEYWORDS = get_setting("KEYWORDS") COMMENT_TAGS = get_setting("COMMENT_TAGS") ROOT = get_setting("ROOT") keywords_dict = dict([(keyword, None) for keyword in KEYWORDS]) domains = options.get("domain") outputdir = os.path.abspath(options.get("outputdir")) if not os.path.isdir(outputdir): if not options.get("create"): print ( "Output directory must exist (%s) unless -c option is " "given. Specify one with --output-dir" % outputdir ) # FIXME: This should return a non-zero exit code and # print to stderr however that works in Django. return "FAILURE\n" os.makedirs(outputdir) if domains == DEFAULT_DOMAIN_VALUE: domains = DOMAIN_METHODS.keys() else: domains = [domains] def callback(filename, method, options): if method != "ignore": print " %s" % filename for domain in domains: print "Extracting all strings in domain %s..." % (domain) methods = DOMAIN_METHODS[domain] extracted = extract_from_dir( ROOT, method_map=methods, keywords=keywords_dict, comment_tags=COMMENT_TAGS, callback=callback, options_map=generate_options_map(), ) catalog = create_pofile_from_babel(extracted) if not os.path.exists(outputdir): # FIXME: This should return a non-zero exit code and # print to stderr and be consistent raise Exception("Expected %s to exist... BAILING" % outputdir) catalog.savefile(os.path.join(outputdir, "%s.pot" % domain)) not_standalone_domains = [dom for dom in domains if dom not in STANDALONE_DOMAINS] pot_files = [] for dom in not_standalone_domains: pot_files.append(os.path.join(outputdir, "%s.pot" % dom)) if len(pot_files) > 1: pot_file = get_setting("TEXT_DOMAIN") + ".pot" print ("Concatenating the non-standalone domains into %s" % pot_file) final_out = os.path.join(outputdir, pot_file) # We add final_out back on because msgcat will combine all # specified files. We'll redirect everything back in to # final_out in a minute. pot_files.append(final_out) meltingpot = tempfile.TemporaryFile() p1 = Popen(["msgcat"] + pot_files, stdout=meltingpot) p1.communicate() meltingpot.seek(0) # w+ truncates the file first with open(final_out, "w+") as final: final.write(meltingpot.read()) meltingpot.close() for dom in not_standalone_domains: os.remove(os.path.join(outputdir, "%s.pot" % dom)) print "Done"
def handle(self, *args, **options): ROOT = get_setting("ROOT") STANDALONE_DOMAINS = get_setting("STANDALONE_DOMAINS") locale_dir = os.path.join(ROOT, "locale") if options.get("create"): for lang in getattr(settings, "LANGUAGES", []): d = os.path.join(locale_dir, lang.replace("-", "_"), "LC_MESSAGES") if not os.path.exists(d): os.makedirs(d) for domain in STANDALONE_DOMAINS: print "Merging %s strings to each locale..." % domain domain_pot = os.path.join(locale_dir, "templates", "LC_MESSAGES", "%s.pot" % domain) if not os.path.isfile(domain_pot): sys.exit("Can not find %s.pot" % domain) for locale in os.listdir(locale_dir): if ( not os.path.isdir(os.path.join(locale_dir, locale)) or locale.startswith(".") or locale == "templates" or locale == "compendia" ): continue compendium = os.path.join(locale_dir, "compendia", "%s.compendium" % locale) domain_po = os.path.join(locale_dir, locale, "LC_MESSAGES", "%s.po" % domain) if not os.path.isfile(domain_po): print " Can not find (%s). Creating..." % (domain_po) if not call(["which", "msginit"], stdout=PIPE) == 0: raise Exception("You do not have gettext installed.") p1 = Popen( [ "msginit", "--no-translator", "--locale=%s" % locale, "--input=%s" % domain_pot, "--output-file=%s" % domain_po, "--width=200", ] ) p1.communicate() print "Merging %s.po for %s" % (domain, locale) domain_pot_file = open(domain_pot) if locale == "en_US": enmerged = TemporaryFile("w+t") p2 = Popen(["msgen", "-"], stdin=domain_pot_file, stdout=enmerged) p2.communicate() mergeme = enmerged else: mergeme = domain_pot_file mergeme.seek(0) command = ["msgmerge", "--update", "--width=200", domain_po, "-"] if os.path.isfile(compendium): print "(using a compendium)" command.insert(1, "--compendium=%s" % compendium) p3 = Popen(command, stdin=mergeme) p3.communicate() mergeme.close() print "Domain %s finished" % domain print "All finished"