Beispiel #1
0
 def setUp(self):
     # Use a locale which won't fail to run the tests
     os.environ['LANG'] = 'en_US.UTF-8'
     messages1 = [
         ('foo', {'string': 'Voh'}),
         ('foo', {'string': 'VohCTX', 'context': 'foo'}),
         (('foo1', 'foos1'), {'string': ('Voh1', 'Vohs1')}),
         (('foo1', 'foos1'), {'string': ('VohCTX1', 'VohsCTX1'), 'context': 'foo'}),
     ]
     messages2 = [
         ('foo', {'string': 'VohD'}),
         ('foo', {'string': 'VohCTXD', 'context': 'foo'}),
         (('foo1', 'foos1'), {'string': ('VohD1', 'VohsD1')}),
         (('foo1', 'foos1'), {'string': ('VohCTXD1', 'VohsCTXD1'), 'context': 'foo'}),
     ]
     catalog1 = Catalog(locale='en_GB', domain='messages')
     catalog2 = Catalog(locale='en_GB', domain='messages1')
     for ids, kwargs in messages1:
         catalog1.add(ids, **kwargs)
     for ids, kwargs in messages2:
         catalog2.add(ids, **kwargs)
     catalog1_fp = BytesIO()
     catalog2_fp = BytesIO()
     write_mo(catalog1_fp, catalog1)
     catalog1_fp.seek(0)
     write_mo(catalog2_fp, catalog2)
     catalog2_fp.seek(0)
     translations1 = support.Translations(catalog1_fp)
     translations2 = support.Translations(catalog2_fp, domain='messages1')
     self.translations = translations1.add(translations2, merge=False)
Beispiel #2
0
def test_catalog_merge_files():
    # Refs issues #92, #162
    t1 = support.Translations()
    assert t1.files == []
    t1._catalog["foo"] = "bar"
    fp = BytesIO()
    write_mo(fp, Catalog())
    fp.seek(0)
    fp.name = "pro.mo"
    t2 = support.Translations(fp)
    assert t2.files == ["pro.mo"]
    t2._catalog["bar"] = "quux"
    t1.merge(t2)
    assert t1.files == ["pro.mo"]
    assert set(t1._catalog.keys()) == {'', 'foo', 'bar'}
Beispiel #3
0
def get_translations():
    """Returns the correct gettext translations that should be used for
    this request.  This will never fail and return a dummy translation
    object if used outside of the request or if a translation cannot be
    found.
    """
    ctx = _get_current_context()

    if ctx is None:
        return support.NullTranslations()

    translations = getattr(ctx, 'babel_translations', None)
    if translations is None:
        translations = support.Translations()

        babel = current_app.extensions['babel']
        for dirname in babel.translation_directories:
            catalog = support.Translations.load(dirname, [get_locale()])
            translations.merge(catalog)
            # FIXME: Workaround for merge() being really, really stupid. It
            # does not copy _info, plural(), or any other instance variables
            # populated by GNUTranslations. We probably want to stop using
            # `support.Translations.merge` entirely.
            if hasattr(catalog, 'plural'):
                translations.plural = catalog.plural

        ctx.babel_translations = translations

    return translations
Beispiel #4
0
    def get_translations(self):
        ctx = _get_current_context()

        if ctx is None:
            return support.NullTranslations()

        cache = self.get_translations_cache(ctx)
        locale = get_locale()
        try:
            return cache[str(locale), self.domain]
        except KeyError:
            translations = support.Translations()

            for dirname in self.translation_directories:
                catalog = support.Translations.load(
                    dirname,
                    [locale],
                    self.domain
                )
                translations.merge(catalog)
                # FIXME: Workaround for merge() being really, really stupid. It
                # does not copy _info, plural(), or any other instance variables
                # populated by GNUTranslations. We probably want to stop using
                # `support.Translations.merge` entirely.
                if hasattr(catalog, 'plural'):
                    translations.plural = catalog.plural

            cache[str(locale), self.domain] = translations
            return translations
Beispiel #5
0
def get_translations(request=None):
    """Returns the correct gettext translations that should be used for
    this request.  This will never fail and return a dummy translation
    object if used outside of the request or if a translation cannot be
    found.
    """
    if request is None:
        return support.NullTranslations()

    request_ = get_request_container(request)
    translations = request_.get("babel_translations", None)
    if translations is None:
        app = request.app
        locale = get_locale(request)
        if locale in app.ctx.babel_translations:
            request_["babel_translations"] = app.ctx.babel_translations[locale]
            return app.ctx.babel_translations[locale]

        translations = support.Translations()
        babel = app.ctx.babel_instance
        for dirname in babel.translation_directories:
            catalog = support.Translations.load(dirname, [locale])
            translations.merge(catalog)
            # FIXME: Workaround for merge() being really, really stupid. It
            # does not copy _info, plural(), or any other instance variables
            # populated by GNUTranslations. We probably want to stop using
            # `support.Translations.merge` entirely.
            if hasattr(catalog, "plural"):
                translations.plural = catalog.plural

        request_["babel_translations"] = translations
        app.ctx.babel_translations[locale] = translations

    return translations
Beispiel #6
0
 def get_gettext_translations(self, locale):
     if locale in self._gettext_translations:
         return self._gettext_translations[locale]
     path, fp = self.find_mo_file(locale)
     if fp:
         trans = support.Translations(fp, domain='messages')
     else:
         trans = support.NullTranslations()
     self._gettext_translations[locale] = trans
     return trans
Beispiel #7
0
 def inject_translations(self, locale, content):
     po_file_to_merge = cStringIO.StringIO()
     po_file_to_merge.write(content)
     po_file_to_merge.seek(0)
     catalog_to_merge = pofile.read_po(po_file_to_merge, locale)
     mo_fp = cStringIO.StringIO()
     mofile.write_mo(mo_fp, catalog_to_merge)
     mo_fp.seek(0)
     translation_obj = support.Translations(mo_fp, domain='messages')
     self._gettext_translations[locale] = translation_obj
     self.pod.logger.info('Injected translations -> {}'.format(locale))
Beispiel #8
0
def test_catalog_merge_files():
    # Refs issues #92, #162
    t1 = support.Translations()
    assert t1.files == []
    t1._catalog["foo"] = "bar"
    if PY2:
        # Explicitly use the pure-Python `StringIO` class, as we need to
        # augment it with the `name` attribute, which we can't do for
        # `babel._compat.BytesIO`, which is `cStringIO.StringIO` under
        # `PY2`...
        from StringIO import StringIO
        fp = StringIO()
    else:
        fp = BytesIO()
    write_mo(fp, Catalog())
    fp.seek(0)
    fp.name = "pro.mo"
    t2 = support.Translations(fp)
    assert t2.files == ["pro.mo"]
    t2._catalog["bar"] = "quux"
    t1.merge(t2)
    assert t1.files == ["pro.mo"]
    assert set(t1._catalog.keys()) == {'', 'foo', 'bar'}
Beispiel #9
0
	def fixed_get_translations():
		"""Returns the correct gettext translations that should be used for
		this request.  This will never fail and return a dummy translation
		object if used outside of the request or if a translation cannot be
		found.
		"""
		ctx = _request_ctx_stack.top
		if ctx is None:
			return None
		translations = getattr(ctx, 'babel_translations', None)
		if translations is None:
			locale = flask.ext.babel.get_locale()
			translations = support.Translations()

			if str(locale) != default_locale:
				# plugin translations
				plugins = octoprint.plugin.plugin_manager().enabled_plugins
				for name, plugin in plugins.items():
					dirs = map(lambda x: os.path.join(x, "_plugins", name), additional_folders) + [os.path.join(plugin.location, 'translations')]
					for dirname in dirs:
						if not os.path.isdir(dirname):
							continue

						try:
							plugin_translations = support.Translations.load(dirname, [locale])
						except:
							logger.exception("Error while trying to load translations for plugin {name}".format(**locals()))
						else:
							if isinstance(plugin_translations, support.Translations):
								translations = translations.merge(plugin_translations)
								logger.debug("Using translation folder {dirname} for locale {locale} of plugin {name}".format(**locals()))
								break
					else:
						logger.debug("No translations for locale {locale} for plugin {name}".format(**locals()))

				# core translations
				dirs = additional_folders + [os.path.join(ctx.app.root_path, 'translations')]
				for dirname in dirs:
					core_translations = support.Translations.load(dirname, [locale])
					if isinstance(core_translations, support.Translations):
						logger.debug("Using translation folder {dirname} for locale {locale} of core translations".format(**locals()))
						break
				else:
					logger.debug("No core translations for locale {locale}")
				translations = translations.merge(core_translations)

			ctx.babel_translations = translations
		return translations
Beispiel #10
0
def get_translations():
    """Returns the correct gettext translations that should be used for
    this request.  This will never fail and return a dummy translation
    object if used outside of the request or if a translation cannot be
    found.
    """
    ctx = _get_current_context()

    translations = getattr(ctx, 'babel_translations', None)
    if translations is None:
        translations = support.Translations()

        babel = current_app.extensions['babel']
        for dirname in babel.translation_directories:
            translations.merge(
                support.Translations.load(dirname, [get_locale()]))

        ctx.babel_translations = translations

    return translations
Beispiel #11
0
 def setUp(self):
     fp = BytesIO()
     write_mo(fp, Catalog(locale='de'))
     fp.seek(0)
     self.translations = support.Translations(fp=fp)
     self.null_translations = support.NullTranslations(fp=fp)
Beispiel #12
0
import datetime
import locale
import os
import platform
import sys

from . import patches

import babel.core
from babel import support
from platform_utils import paths

DEFAULT_LOCALE = "en_US"
CURRENT_LOCALE = DEFAULT_LOCALE

active_translation = support.Translations()
application_locale_path = None


def install_global_translation(domain, locale_id=None, locale_path=None):
    """

    Args:
      domain:
      locale_id: If none supplied defaults to the system's current locale (Default value = None)
      locale_path: Base path where translations are located (Default value = None)

    Returns:

    """
    global active_translation