1
# DistUpgradeGettext.py - safe wrapper around gettext
3
# Copyright (c) 2008 Canonical
5
# Author: Michael Vogt <michael.vogt@ubuntu.com>
7
# This program is free software; you can redistribute it and/or
8
# modify it under the terms of the GNU General Public License as
9
# published by the Free Software Foundation; either version 2 of the
10
# License, or (at your option) any later version.
12
# This program is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU General Public License for more details.
17
# You should have received a copy of the GNU General Public License
18
# along with this program; if not, write to the Free Software
19
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23
import gettext as mygettext
24
_gettext_method = "gettext"
25
_ngettext_method = "ngettext"
28
def _verify(message, translated):
30
helper that verifies that the message and the translated
31
message have the same number (and type) of % args
33
arguments_in_message = message.count("%") - message.count("\%")
34
arguments_in_translation = translated.count("%") - translated.count("\%")
35
return arguments_in_message == arguments_in_translation
38
_translation_singleton = None
42
"""Return a suitable gettext.*Translations instance."""
43
global _translation_singleton
44
if _translation_singleton is None:
45
domain = mygettext.textdomain()
46
_translation_singleton = mygettext.translation(
47
domain, mygettext.bindtextdomain(domain), fallback=True)
48
return _translation_singleton
51
def unicode_gettext(translation, message):
52
return getattr(translation, _gettext_method)(message)
55
def unicode_ngettext(translation, singular, plural, n):
56
return getattr(translation, _ngettext_method)(singular, plural, n)
61
version of gettext that logs errors but does not crash on incorrect
66
translated_msg = unicode_gettext(_translation(), message)
67
if not _verify(message, translated_msg):
69
"incorrect translation for message '%s' to '%s' "
70
"(wrong number of arguments)" % (message, translated_msg))
75
def ngettext(msgid1, msgid2, n):
77
version of ngettext that logs errors but does not crash on incorrect
80
translated_msg = unicode_ngettext(_translation(), msgid1, msgid2, n)
81
if not _verify(msgid1, translated_msg):
83
"incorrect translation for ngettext message "
84
"'%s' plural: '%s' to '%s' (wrong number of arguments)" % (
85
msgid1, msgid2, translated_msg))
86
# dumb fallback to not crash