blob: cbf570af722741f15b021d3cf138ef69ccfb9016 [file] [log] [blame]
Matthew Treinish0db53772013-07-26 10:39:35 -04001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
3# Copyright 2012 Red Hat, Inc.
Matthew Treinish0db53772013-07-26 10:39:35 -04004# Copyright 2013 IBM Corp.
Matthew Treinishffa94d62013-09-11 18:09:17 +00005# All Rights Reserved.
Matthew Treinish0db53772013-07-26 10:39:35 -04006#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License. You may obtain
9# a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16# License for the specific language governing permissions and limitations
17# under the License.
18
19"""
20gettext for openstack-common modules.
21
22Usual usage in an openstack.common module:
23
24 from tempest.openstack.common.gettextutils import _
25"""
26
27import copy
28import gettext
Matthew Treinishffa94d62013-09-11 18:09:17 +000029import logging
Matthew Treinish0db53772013-07-26 10:39:35 -040030import os
31import re
Matthew Treinishffa94d62013-09-11 18:09:17 +000032try:
33 import UserString as _userString
34except ImportError:
35 import collections as _userString
Matthew Treinish0db53772013-07-26 10:39:35 -040036
Matthew Treinishffa94d62013-09-11 18:09:17 +000037from babel import localedata
Matthew Treinish0db53772013-07-26 10:39:35 -040038import six
39
40_localedir = os.environ.get('tempest'.upper() + '_LOCALEDIR')
41_t = gettext.translation('tempest', localedir=_localedir, fallback=True)
42
Matthew Treinishffa94d62013-09-11 18:09:17 +000043_AVAILABLE_LANGUAGES = {}
44USE_LAZY = False
45
46
47def enable_lazy():
48 """Convenience function for configuring _() to use lazy gettext
49
50 Call this at the start of execution to enable the gettextutils._
51 function to use lazy gettext functionality. This is useful if
52 your project is importing _ directly instead of using the
53 gettextutils.install() way of importing the _ function.
54 """
55 global USE_LAZY
56 USE_LAZY = True
57
Matthew Treinish0db53772013-07-26 10:39:35 -040058
59def _(msg):
Matthew Treinishffa94d62013-09-11 18:09:17 +000060 if USE_LAZY:
61 return Message(msg, 'tempest')
62 else:
63 return _t.ugettext(msg)
Matthew Treinish0db53772013-07-26 10:39:35 -040064
65
Matthew Treinishffa94d62013-09-11 18:09:17 +000066def install(domain, lazy=False):
Matthew Treinish0db53772013-07-26 10:39:35 -040067 """Install a _() function using the given translation domain.
68
69 Given a translation domain, install a _() function using gettext's
70 install() function.
71
72 The main difference from gettext.install() is that we allow
73 overriding the default localedir (e.g. /usr/share/locale) using
74 a translation-domain-specific environment variable (e.g.
75 NOVA_LOCALEDIR).
Matthew Treinishffa94d62013-09-11 18:09:17 +000076
77 :param domain: the translation domain
78 :param lazy: indicates whether or not to install the lazy _() function.
79 The lazy _() introduces a way to do deferred translation
80 of messages by installing a _ that builds Message objects,
81 instead of strings, which can then be lazily translated into
82 any available locale.
Matthew Treinish0db53772013-07-26 10:39:35 -040083 """
Matthew Treinishffa94d62013-09-11 18:09:17 +000084 if lazy:
85 # NOTE(mrodden): Lazy gettext functionality.
86 #
87 # The following introduces a deferred way to do translations on
88 # messages in OpenStack. We override the standard _() function
89 # and % (format string) operation to build Message objects that can
90 # later be translated when we have more information.
91 #
92 # Also included below is an example LocaleHandler that translates
93 # Messages to an associated locale, effectively allowing many logs,
94 # each with their own locale.
95
96 def _lazy_gettext(msg):
97 """Create and return a Message object.
98
99 Lazy gettext function for a given domain, it is a factory method
100 for a project/module to get a lazy gettext function for its own
101 translation domain (i.e. nova, glance, cinder, etc.)
102
103 Message encapsulates a string so that we can translate
104 it later when needed.
105 """
106 return Message(msg, domain)
107
108 import __builtin__
109 __builtin__.__dict__['_'] = _lazy_gettext
110 else:
111 localedir = '%s_LOCALEDIR' % domain.upper()
112 gettext.install(domain,
113 localedir=os.environ.get(localedir),
114 unicode=True)
Matthew Treinish0db53772013-07-26 10:39:35 -0400115
116
Matthew Treinishffa94d62013-09-11 18:09:17 +0000117class Message(_userString.UserString, object):
Matthew Treinish0db53772013-07-26 10:39:35 -0400118 """Class used to encapsulate translatable messages."""
119 def __init__(self, msg, domain):
120 # _msg is the gettext msgid and should never change
121 self._msg = msg
122 self._left_extra_msg = ''
123 self._right_extra_msg = ''
124 self.params = None
125 self.locale = None
126 self.domain = domain
127
128 @property
129 def data(self):
130 # NOTE(mrodden): this should always resolve to a unicode string
131 # that best represents the state of the message currently
132
133 localedir = os.environ.get(self.domain.upper() + '_LOCALEDIR')
134 if self.locale:
135 lang = gettext.translation(self.domain,
136 localedir=localedir,
137 languages=[self.locale],
138 fallback=True)
139 else:
140 # use system locale for translations
141 lang = gettext.translation(self.domain,
142 localedir=localedir,
143 fallback=True)
144
145 full_msg = (self._left_extra_msg +
146 lang.ugettext(self._msg) +
147 self._right_extra_msg)
148
149 if self.params is not None:
150 full_msg = full_msg % self.params
151
152 return six.text_type(full_msg)
153
154 def _save_dictionary_parameter(self, dict_param):
155 full_msg = self.data
156 # look for %(blah) fields in string;
157 # ignore %% and deal with the
158 # case where % is first character on the line
Matthew Treinishffa94d62013-09-11 18:09:17 +0000159 keys = re.findall('(?:[^%]|^)?%\((\w*)\)[a-z]', full_msg)
Matthew Treinish0db53772013-07-26 10:39:35 -0400160
161 # if we don't find any %(blah) blocks but have a %s
162 if not keys and re.findall('(?:[^%]|^)%[a-z]', full_msg):
163 # apparently the full dictionary is the parameter
164 params = copy.deepcopy(dict_param)
165 else:
166 params = {}
167 for key in keys:
168 try:
169 params[key] = copy.deepcopy(dict_param[key])
170 except TypeError:
171 # cast uncopyable thing to unicode string
172 params[key] = unicode(dict_param[key])
173
174 return params
175
176 def _save_parameters(self, other):
177 # we check for None later to see if
178 # we actually have parameters to inject,
179 # so encapsulate if our parameter is actually None
180 if other is None:
181 self.params = (other, )
182 elif isinstance(other, dict):
183 self.params = self._save_dictionary_parameter(other)
184 else:
185 # fallback to casting to unicode,
186 # this will handle the problematic python code-like
187 # objects that cannot be deep-copied
188 try:
189 self.params = copy.deepcopy(other)
190 except TypeError:
191 self.params = unicode(other)
192
193 return self
194
195 # overrides to be more string-like
196 def __unicode__(self):
197 return self.data
198
199 def __str__(self):
200 return self.data.encode('utf-8')
201
202 def __getstate__(self):
203 to_copy = ['_msg', '_right_extra_msg', '_left_extra_msg',
204 'domain', 'params', 'locale']
205 new_dict = self.__dict__.fromkeys(to_copy)
206 for attr in to_copy:
207 new_dict[attr] = copy.deepcopy(self.__dict__[attr])
208
209 return new_dict
210
211 def __setstate__(self, state):
212 for (k, v) in state.items():
213 setattr(self, k, v)
214
215 # operator overloads
216 def __add__(self, other):
217 copied = copy.deepcopy(self)
218 copied._right_extra_msg += other.__str__()
219 return copied
220
221 def __radd__(self, other):
222 copied = copy.deepcopy(self)
223 copied._left_extra_msg += other.__str__()
224 return copied
225
226 def __mod__(self, other):
227 # do a format string to catch and raise
228 # any possible KeyErrors from missing parameters
229 self.data % other
230 copied = copy.deepcopy(self)
231 return copied._save_parameters(other)
232
233 def __mul__(self, other):
234 return self.data * other
235
236 def __rmul__(self, other):
237 return other * self.data
238
239 def __getitem__(self, key):
240 return self.data[key]
241
242 def __getslice__(self, start, end):
243 return self.data.__getslice__(start, end)
244
245 def __getattribute__(self, name):
246 # NOTE(mrodden): handle lossy operations that we can't deal with yet
247 # These override the UserString implementation, since UserString
248 # uses our __class__ attribute to try and build a new message
249 # after running the inner data string through the operation.
250 # At that point, we have lost the gettext message id and can just
251 # safely resolve to a string instead.
252 ops = ['capitalize', 'center', 'decode', 'encode',
253 'expandtabs', 'ljust', 'lstrip', 'replace', 'rjust', 'rstrip',
254 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
255 if name in ops:
256 return getattr(self.data, name)
257 else:
Matthew Treinishffa94d62013-09-11 18:09:17 +0000258 return _userString.UserString.__getattribute__(self, name)
259
260
261def get_available_languages(domain):
262 """Lists the available languages for the given translation domain.
263
264 :param domain: the domain to get languages for
265 """
266 if domain in _AVAILABLE_LANGUAGES:
267 return copy.copy(_AVAILABLE_LANGUAGES[domain])
268
269 localedir = '%s_LOCALEDIR' % domain.upper()
270 find = lambda x: gettext.find(domain,
271 localedir=os.environ.get(localedir),
272 languages=[x])
273
274 # NOTE(mrodden): en_US should always be available (and first in case
275 # order matters) since our in-line message strings are en_US
276 language_list = ['en_US']
277 # NOTE(luisg): Babel <1.0 used a function called list(), which was
278 # renamed to locale_identifiers() in >=1.0, the requirements master list
279 # requires >=0.9.6, uncapped, so defensively work with both. We can remove
280 # this check when the master list updates to >=1.0, and all projects udpate
281 list_identifiers = (getattr(localedata, 'list', None) or
282 getattr(localedata, 'locale_identifiers'))
283 locale_identifiers = list_identifiers()
284 for i in locale_identifiers:
285 if find(i) is not None:
286 language_list.append(i)
287 _AVAILABLE_LANGUAGES[domain] = language_list
288 return copy.copy(language_list)
289
290
291def get_localized_message(message, user_locale):
292 """Gets a localized version of the given message in the given locale."""
293 if isinstance(message, Message):
294 if user_locale:
295 message.locale = user_locale
296 return unicode(message)
297 else:
298 return message
Matthew Treinish0db53772013-07-26 10:39:35 -0400299
300
301class LocaleHandler(logging.Handler):
302 """Handler that can have a locale associated to translate Messages.
303
304 A quick example of how to utilize the Message class above.
305 LocaleHandler takes a locale and a target logging.Handler object
306 to forward LogRecord objects to after translating the internal Message.
307 """
308
309 def __init__(self, locale, target):
310 """Initialize a LocaleHandler
311
312 :param locale: locale to use for translating messages
313 :param target: logging.Handler object to forward
314 LogRecord objects to after translation
315 """
316 logging.Handler.__init__(self)
317 self.locale = locale
318 self.target = target
319
320 def emit(self, record):
321 if isinstance(record.msg, Message):
322 # set the locale and resolve to a string
323 record.msg.locale = self.locale
324
325 self.target.emit(record)