From 9e71d383bf59573a1dd48964a2c7900a57161973 Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Fri, 11 Feb 2022 16:51:44 +0100 Subject: internationalize using Babel this commit also makes the sdist tarball generated by setuptools REUSE-compliant --- src/hydrilla/util/__init__.py | 2 +- src/hydrilla/util/_util.py | 30 +++++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) (limited to 'src/hydrilla/util') diff --git a/src/hydrilla/util/__init__.py b/src/hydrilla/util/__init__.py index 2a69e0d..3a13831 100644 --- a/src/hydrilla/util/__init__.py +++ b/src/hydrilla/util/__init__.py @@ -5,4 +5,4 @@ # Available under the terms of Creative Commons Zero v1.0 Universal. from ._util import strip_json_comments, normalize_version, parse_version, \ - version_string, validator_for + version_string, validator_for, get_gettext diff --git a/src/hydrilla/util/_util.py b/src/hydrilla/util/_util.py index 9bebdc1..c7e9f47 100644 --- a/src/hydrilla/util/_util.py +++ b/src/hydrilla/util/_util.py @@ -26,6 +26,8 @@ import re import json +import locale +import gettext from pathlib import Path from typing import Optional @@ -71,7 +73,7 @@ def strip_json_comments(text: str) -> str: # ignore this error, let json module report it stripped = line elif len(match[2]) == 1: - raise json.JSONDecodeError('bad comment', text, + raise json.JSONDecodeError(_('bad_comment'), text, processed + len(match[1])) else: stripped = match[1] @@ -127,3 +129,29 @@ def validator_for(schema_filename: str) -> Draft7Validator: """ return Draft7Validator(resolver.resolve(schema_filename)[1], resolver=resolver) + +def get_gettext(domain: str, lang: Optional[str]=None): + """ + Configure translation and return its gettext() function. + + If `lang` is set, look for translations for `lang`. Otherwise, try to + determine system's default language and use that. + """ + # https://stackoverflow.com/questions/3425294/how-to-detect-the-os-default-language-in-python + # But I am not going to surrender to Microbugs' nonfree, crappy OS to test + # it, to the lines inside try: may fail. + try: + from ctypes.windll import kernel32 as windll + lang = locale.windows_locale[windll.GetUserDefaultUILanguage()] + except: + lang = locale.getdefaultlocale()[0] or 'C' + + translation = gettext.translation( + domain, + localedir=(here.parent / 'locales'), + languages=[lang, 'en_US'] + ) + + return translation.gettext + +_ = get_gettext('hydrilla_builder') -- cgit v1.2.3