Skip to content

Commit

Permalink
Use custom gettext instead of modify environment variable
Browse files Browse the repository at this point in the history
  • Loading branch information
StdioA committed Aug 24, 2024
1 parent 09dbb90 commit 224ec7b
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 38 deletions.
16 changes: 10 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
LANGUAGES := en zh_CN zh_TW fr_FR ja_JP ko_KR de_DE es_ES

POT_FILE := locale/beanbot.pot
PO_FILES := $(foreach lang,$(LANGUAGES),locale/$(lang)/LC_MESSAGES/beanbot.po)
MO_FILES := $(foreach lang,$(LANGUAGES),locale/$(lang)/LC_MESSAGES/beanbot.mo)
DOMAIN := beanbot
POT_FILE := locale/$(DOMAIN).pot
PO_FILES := $(foreach lang,$(LANGUAGES),locale/$(lang)/LC_MESSAGES/$(DOMAIN).po)
MO_FILES := $(foreach lang,$(LANGUAGES),locale/$(lang)/LC_MESSAGES/$(DOMAIN).mo)

.PHONY: all gentranslations compiletranslations clean
.PHONY: all gentranslations compiletranslations clean lint

all: gentranslations compiletranslations

Expand All @@ -13,10 +14,10 @@ gentranslations: $(PO_FILES)
compiletranslations: $(MO_FILES)

$(POT_FILE): **/*.py
xgettext -d beanbot -o $@ $^
xgettext -d $(DOMAIN) -o $@ $^

define po_rule
locale/$(1)/LC_MESSAGES/beanbot.po: $(POT_FILE)
locale/$(1)/LC_MESSAGES/$(DOMAIN).po: $(POT_FILE)
@mkdir -p $$(dir $$@)
@if [ ! -f $$@ ]; then \
msginit -i $$< -o $$@ -l $(1); \
Expand All @@ -32,3 +33,6 @@ $(foreach lang,$(LANGUAGES),$(eval $(call po_rule,$(lang))))

# clean:
# rm -f $(POT_FILE) $(PO_FILES) $(MO_FILES)

lint:
@ruff check
2 changes: 1 addition & 1 deletion bean_utils/bean.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from pathlib import Path
from datetime import datetime
from decimal import Decimal
from gettext import gettext as _
from conf.i18n import gettext as _
import re
import shlex
import subprocess
Expand Down
2 changes: 1 addition & 1 deletion bots/controller.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import date
from dataclasses import dataclass
from gettext import gettext as _
from conf.i18n import gettext as _
from typing import List, Union, Any
from beancount.core.inventory import Inventory
import requests
Expand Down
2 changes: 1 addition & 1 deletion bots/mmbot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import click
from datetime import datetime, timedelta
from gettext import gettext as _
from conf.i18n import gettext as _
from mmpy_bot import Bot, Settings
from mmpy_bot import Plugin, listen_to, listen_webhook
from mmpy_bot.plugins.base import PluginManager
Expand Down
2 changes: 1 addition & 1 deletion bots/telegram_bot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# coding: utf-8
import time
from gettext import gettext as _
from conf.i18n import gettext as _
import logging
from datetime import timedelta, datetime
import telegram
Expand Down
13 changes: 13 additions & 0 deletions conf/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from .i18n import init_locale
from .config_data import Config


__all__ = ['config', 'init_locale', "load_config"]


config = None


def load_config(config_path):
global config
config = Config(config_path)
18 changes: 0 additions & 18 deletions conf.py → conf/config_data.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import yaml


Expand Down Expand Up @@ -53,20 +52,3 @@ def from_dict(cls, dictionary):
config = cls.__new__(cls)
config._config = ImmutableDict(dictionary) # noqa: SLF001
return config


config = None


def load_config(config_path):
global config
config = Config(config_path)


def set_locale():
if config.get("language") is not None:
# Only in this way can I override default language for gettext.gettext
os.environ['LANGUAGE'] = config.get("language")
# `install` also works, but it's not recommended after python 3.8, and it will cause lint error
# gettext.translation("beanbot", config.get("language"), fallback=True).install()
# Otherwise, I can write my own `_` function, which can take from `some_translation.gettext`
24 changes: 24 additions & 0 deletions conf/i18n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from pathlib import Path
import gettext as _gettext


_DOMAIN = 'beanbot'

gettext = _gettext.gettext


def init_locale():
"""Initialize the locale translation."""
from . import config
locale_dir = Path(__file__).parent.parent / 'locale'
language = config.get('language')
if language is not None:
# Use custom translation
translation = _gettext.translation(_DOMAIN, locale_dir, [language], fallback=True)
global gettext
gettext = translation.gettext
else:
# Use default translation, and load locale from env
_gettext.bindtextdomain(_DOMAIN, locale_dir)
_gettext.textdomain(_DOMAIN)

11 changes: 1 addition & 10 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import argparse
import gettext
import pathlib
import conf
import logging
from bean_utils.bean import init_bean_manager


def _init_locale():
locale_dir = pathlib.Path(__file__).parent / 'locale'
gettext.bindtextdomain('beanbot', locale_dir)
gettext.textdomain('beanbot')


if __name__ == "__main__":
# Init logging
logging.basicConfig(level=logging.INFO)
Expand All @@ -30,8 +22,7 @@ def _init_locale():
if args.command is not None:
conf.load_config(args.c)
# Init i18n
conf.set_locale()
_init_locale()
conf.init_locale()
init_bean_manager()

if args.command == "telegram":
Expand Down

0 comments on commit 224ec7b

Please sign in to comment.