Ejemplo n.º 1
0
 def load(cls, path, locale=None, domain='messages'):
   """Load the translations from the given path."""
   from babel.core import parse_locale
   lang, script, territory, variant = parse_locale(locale)
   parsed_locale = '_'.join(filter(None, [lang, script, territory, variant]))
   catalog = os.path.join(path, parsed_locale, 'LC_MESSAGES', domain + '.mo')
   if os.path.isfile(catalog):
     return KayTranslations(fileobj=open(catalog, 'rb'), locale=locale)
   else:
     return KayTranslations(fileobj=None, locale=locale)
Ejemplo n.º 2
0
def test_parse_locale():
    assert core.parse_locale("zh_CN") == ("zh", "CN", None, None)
    assert core.parse_locale("zh_Hans_CN") == ("zh", "CN", "Hans", None)
    assert core.parse_locale("zh-CN", sep="-") == ("zh", "CN", None, None)

    with pytest.raises(ValueError) as excinfo:
        core.parse_locale("not_a_LOCALE_String")
    assert excinfo.value.args[0] == "'not_a_LOCALE_String' is not a valid locale identifier"

    assert core.parse_locale("it_IT@euro") == ("it", "IT", None, None)
    assert core.parse_locale("en_US.UTF-8") == ("en", "US", None, None)
    assert core.parse_locale("de_DE.iso885915@euro") == ("de", "DE", None, None)
Ejemplo n.º 3
0
def test_parse_locale():
    assert core.parse_locale('zh_CN') == ('zh', 'CN', None, None)
    assert core.parse_locale('zh_Hans_CN') == ('zh', 'CN', 'Hans', None)
    assert core.parse_locale('zh-CN', sep='-') == ('zh', 'CN', None, None)

    with pytest.raises(ValueError) as excinfo:
        core.parse_locale('not_a_LOCALE_String')
    assert (excinfo.value.args[0] ==
            "'not_a_LOCALE_String' is not a valid locale identifier")

    assert core.parse_locale('it_IT@euro') == ('it', 'IT', None, None)
    assert core.parse_locale('en_US.UTF-8') == ('en', 'US', None, None)
    assert (core.parse_locale('de_DE.iso885915@euro') ==
            ('de', 'DE', None, None))
Ejemplo n.º 4
0
def load_locale_data(locales):
    '''
    Load Localized Currency Data for a list of Locales

    Data is stored hierarchically by language, with keys corresponding to each
    locale within that language (as well as a key for the base language data).
    When locale data is the same as its parent language, the keys are removed
    to compress the total amount of data.  The nvlps Locale class loader will
    then look to the parent language for missing keys.
    '''
    langs = set([parse_locale(l)[0] for l in locales])
    locale_data = dict([(l, dict()) for l in langs])

    # Load Locale Information for each base Language first
    for l in langs:
        locale_data[l][l] = load_for_locale(l, None)

    # Load Sub-Locales
    for ll in locales:
        lang, region, _, _ = parse_locale(ll)
        if region is None:
            continue

        parent_data = locale_data[lang][lang] \
            if lang in locale_data \
            else None

        data = load_for_locale(ll, parent_data)

        # Always store the locale key even if there are no overrides. This
        # helps the Locale loader not freak out when it can't find a locale key
        # and does not take up much extra room in the JSON.
        locale_data[lang][ll] = data if data is not None else dict()

        # if data is not None:
        #    locale_data[lang][ll] = data

    return locale_data
Ejemplo n.º 5
0
def get_console_locale(env=None, lang=LANG):
    """Return negotiated locale for console by LANG environment and
    [trac] default_language."""
    if has_babel:
        from babel.core import Locale, UnknownLocaleError, parse_locale
        try:
            lang = '_'.join(filter(None, parse_locale(lang)))
        except:
            lang = None
        default = env.config.get('trac', 'default_language', '') \
                  if env else None
        try:
            return get_negotiated_locale([lang, default]) or Locale.default()
        except UnknownLocaleError:
            pass
    return None
Ejemplo n.º 6
0
def get_console_locale(env=None, lang=LANG):
    """Return negotiated locale for console by LANG environment and
    [trac] default_language."""
    if has_babel:
        from babel.core import Locale, UnknownLocaleError, parse_locale
        try:
            lang = '_'.join(filter(None, parse_locale(lang)))
        except:
            lang = None
        default = env.config.get('trac', 'default_language', '') \
                  if env else None
        try:
            return get_negotiated_locale([lang, default]) or Locale.default()
        except UnknownLocaleError:
            pass
    return None
Ejemplo n.º 7
0
    "logoUrl": generateLogoUrl,
    "generationTime": generationTime,
    "locationsAndCategories": locationsAndCategories,
    "libraryName": config["libraryName"],
    "locales": config["languages"],
    "defaultLocale": config["defaultLanguage"],
    "allCategories": allCategories,
    "media": media,
    "formatIdentifier": formatIdentifier
}
log.debug("sharedTemplateVars: {0}".format(sharedTemplateVars))

# We need to write a version of every page for every locale
for locale in config["languages"]:
    log.info("Generating pages for locale: {0}".format(locale))
    language = parse_locale(locale)[0]
    log.debug("Parsed language {0} from locale {1}".format(language, locale))

    if (locale == config["defaultLanguage"]):
        fileNamePrefix = ""
    else:
        fileNamePrefix = locale

    # Initialise the locale
    translation = Translations.load("locale", [locale])
    jinja2Env.install_gettext_translations(translation)

    # Write the pages
    for page in [
            x for x in os.listdir(workDir + "/templates")
            if (os.path.splitext(x)[1] == ".j2" and x[0] != "_")
Ejemplo n.º 8
0
def load_for_locale(locale, parent):
    '''
    Load Localized Currency Data for a Single Locale

    Localized data stored for each locale includes:

    LC_NUMERIC Information
    ----------------------
    - Decimal Point Symbol
    - Digit Grouping Symbol
    - Plus Sign
    - Minus Sign
    - Percent Sign
    - Permille Sign
    - Exponential Sign
    - Superscripting Exponent
    - String representing infinity
    - String representing a non-numeric value

    Currency Formatting Information
    -------------------------------
    - Basic Numeric Format
    - Currency Numeric Format
    - Accounting Numeric Format

    Currency Localization Data
    --------------------------
    - Localized Currency Symbols
    - Localized Currency Names
    - Local Default Currency
    '''
    L = Locale.parse(locale)
    data = dict()

    # Load Locale Information
    data = {
        'd'  : L.number_symbols['decimal'],
        'g'  : L.number_symbols['group'],
        'p'  : L.number_symbols['plusSign'],
        'm'  : L.number_symbols['minusSign'],
        'pc' : L.number_symbols['percentSign'],
        'pm' : L.number_symbols['perMille'],
        'e'  : L.number_symbols['exponential'],
        'x'  : L.number_symbols['superscriptingExponent'],

        'inf': L.number_symbols['infinity'],
        'nan': L.number_symbols['nan'],

        'np' : L.decimal_formats[None].pattern,
        'cp' : L.currency_formats['standard'].pattern,
        'ap' : L.currency_formats['accounting'].pattern,

        # Currency Symbols
        'cs' : dict([
            (k, v) for k, v in L.currency_symbols.items()
            if k in NVLPS_CURRENCY_LIST
        ]),

        # Currency Names
        'cn' : dict([
            (k, v) for k, v in L.currencies.items()
            if k in NVLPS_CURRENCY_LIST
        ]),
    }

    # Load Locale Currency
    territory = L.territory
    if (territory is None) and (L.language in NVLPS_LOCALE_ALIASES):
        territory = parse_locale(NVLPS_LOCALE_ALIASES[L.language])[1]
    if territory is not None:
        currencies = get_territory_currencies(territory)
        if currencies and len(currencies) > 0:
            data['c'] = currencies[0]

    # Remove Redundant Information contained in Parent
    if parent is not None:
        data = make_locale_overlay(data, parent)

    # Return Locale Data
    return data if len(data) > 0 else None