1
# Copyright (C) 2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
# The normalize function is taken from pygettext which is distributed
18
# with Python under the Python License, which is GPL compatible.
20
"""Extract docstrings from Bazaar commands.
22
This module only handles breezy objects that use strings not directly wrapped
23
by a gettext() call. To generate a complete translation template file, this
24
output needs to be combined with that of xgettext or a similar command for
25
extracting those strings, as is done in the bzr Makefile. Sorting the output
26
is also left to that stage of the process.
29
from __future__ import absolute_import
36
commands as _mod_commands,
40
plugin as _mod_plugin,
47
from .i18n import gettext
51
s = (s.replace('\\', '\\\\')
60
# This converts the various Python string types into a format that
61
# is appropriate for .po files, namely much closer to C style.
64
s = '"' + _escape(s) + '"'
68
lines[-1] = lines[-1] + '\n'
70
s = '""\n"' + lineterm.join(map(_escape, lines)) + '"'
74
def _parse_source(source_text):
75
"""Get object to lineno mappings from given source_text"""
79
for node in ast.walk(ast.parse(source_text)):
80
# TODO: worry about duplicates?
81
if isinstance(node, ast.ClassDef):
82
# TODO: worry about nesting?
83
cls_to_lineno[node.name] = node.lineno
84
elif isinstance(node, ast.Str):
85
# Python AST gives location of string literal as the line the
86
# string terminates on. It's more useful to have the line the
87
# string begins on. Unfortunately, counting back newlines is
88
# only an approximation as the AST is ignorant of escaping.
89
str_to_lineno[node.s] = node.lineno - node.s.count('\n')
90
return cls_to_lineno, str_to_lineno
93
class _ModuleContext(object):
94
"""Record of the location within a source tree"""
96
def __init__(self, path, lineno=1, _source_info=None):
99
if _source_info is not None:
100
self._cls_to_lineno, self._str_to_lineno = _source_info
103
def from_module(cls, module):
104
"""Get new context from module object and parse source for linenos"""
105
sourcepath = inspect.getsourcefile(module)
106
# TODO: fix this to do the right thing rather than rely on cwd
107
relpath = os.path.relpath(sourcepath)
109
_source_info=_parse_source("".join(inspect.findsource(module)[0])))
111
def from_class(self, cls):
112
"""Get new context with same details but lineno of class in source"""
114
lineno = self._cls_to_lineno[cls.__name__]
115
except (AttributeError, KeyError):
116
mutter("Definition of %r not found in %r", cls, self.path)
118
return self.__class__(self.path, lineno,
119
(self._cls_to_lineno, self._str_to_lineno))
121
def from_string(self, string):
122
"""Get new context with same details but lineno of string in source"""
124
lineno = self._str_to_lineno[string]
125
except (AttributeError, KeyError):
126
mutter("String %r not found in %r", string[:20], self.path)
128
return self.__class__(self.path, lineno,
129
(self._cls_to_lineno, self._str_to_lineno))
132
class _PotExporter(object):
133
"""Write message details to output stream in .pot file format"""
135
def __init__(self, outf, include_duplicates=False):
137
if include_duplicates:
141
self._module_contexts = {}
143
def poentry(self, path, lineno, s, comment=None):
144
if self._msgids is not None:
145
if s in self._msgids:
151
comment = "# %s\n" % comment
152
mutter("Exporting msg %r at line %d in %r", s[:20], lineno, path)
154
"#: {path}:{lineno}\n"
159
path=path, lineno=lineno, comment=comment, msg=_normalize(s)))
160
self.outf.write(line.encode('utf-8'))
162
def poentry_in_context(self, context, string, comment=None):
163
context = context.from_string(string)
164
self.poentry(context.path, context.lineno, string, comment)
166
def poentry_per_paragraph(self, path, lineno, msgid, include=None):
167
# TODO: How to split long help?
168
paragraphs = msgid.split('\n\n')
169
if include is not None:
170
paragraphs = filter(include, paragraphs)
172
self.poentry(path, lineno, p)
173
lineno += p.count('\n') + 2
175
def get_context(self, obj):
176
module = inspect.getmodule(obj)
178
context = self._module_contexts[module.__name__]
180
context = _ModuleContext.from_module(module)
181
self._module_contexts[module.__name__] = context
182
if inspect.isclass(obj):
183
context = context.from_class(obj)
187
def _write_option(exporter, context, opt, note):
188
if getattr(opt, 'hidden', False):
191
if getattr(opt, 'title', None):
192
exporter.poentry_in_context(context, opt.title,
193
"title of {name!r} {what}".format(name=optname, what=note))
194
for name, _, _, helptxt in opt.iter_switches():
196
if opt.is_hidden(name):
198
name = "=".join([optname, name])
200
exporter.poentry_in_context(context, helptxt,
201
"help of {name!r} {what}".format(name=name, what=note))
204
def _standard_options(exporter):
205
OPTIONS = option.Option.OPTIONS
206
context = exporter.get_context(option)
207
for name in sorted(OPTIONS):
209
_write_option(exporter, context.from_string(name), opt, "option")
212
def _command_options(exporter, context, cmd):
213
note = "option of {0!r} command".format(cmd.name())
214
for opt in cmd.takes_options:
215
# String values in Command option lists are for global options
216
if not isinstance(opt, str):
217
_write_option(exporter, context, opt, note)
220
def _write_command_help(exporter, cmd):
221
context = exporter.get_context(cmd.__class__)
223
dcontext = context.from_string(rawdoc)
224
doc = inspect.cleandoc(rawdoc)
226
def exclude_usage(p):
227
# ':Usage:' has special meaning in help topics.
228
# This is usage example of command and should not be translated.
229
if p.splitlines()[0] != ':Usage:':
232
exporter.poentry_per_paragraph(dcontext.path, dcontext.lineno, doc,
234
_command_options(exporter, context, cmd)
237
def _command_helps(exporter, plugin_name=None):
238
"""Extract docstrings from path.
240
This respects the Bazaar cmdtable/table convention and will
241
only extract docstrings from functions mentioned in these tables.
245
for cmd_name in _mod_commands.builtin_command_names():
246
command = _mod_commands.get_cmd_object(cmd_name, False)
249
if plugin_name is not None:
250
# only export builtins if we are not exporting plugin commands
252
note(gettext("Exporting messages from builtin command: %s"), cmd_name)
253
_write_command_help(exporter, command)
255
plugins = _mod_plugin.plugins()
256
if plugin_name is not None and plugin_name not in plugins:
257
raise errors.BzrError(gettext('Plugin %s is not loaded' % plugin_name))
259
name for name in plugins
260
if plugins[name].path().startswith(breezy.__path__[0]))
262
for cmd_name in _mod_commands.plugin_command_names():
263
command = _mod_commands.get_cmd_object(cmd_name, False)
266
if plugin_name is not None and command.plugin_name() != plugin_name:
267
# if we are exporting plugin commands, skip plugins we have not
270
if plugin_name is None and command.plugin_name() not in core_plugins:
271
# skip non-core plugins
272
# TODO: Support extracting from third party plugins.
274
note(gettext("Exporting messages from plugin command: {0} in {1}").format(
275
cmd_name, command.plugin_name() ))
276
_write_command_help(exporter, command)
279
def _error_messages(exporter):
280
"""Extract fmt string from breezy.errors."""
281
context = exporter.get_context(errors)
282
base_klass = errors.BzrError
283
for name in dir(errors):
284
klass = getattr(errors, name)
285
if not inspect.isclass(klass):
287
if not issubclass(klass, base_klass):
289
if klass is base_klass:
291
if klass.internal_error:
293
fmt = getattr(klass, "_fmt", None)
295
note(gettext("Exporting message from error: %s"), name)
296
exporter.poentry_in_context(context, fmt)
299
def _help_topics(exporter):
300
topic_registry = help_topics.topic_registry
301
for key in topic_registry.keys():
302
doc = topic_registry.get(key)
303
if isinstance(doc, str):
304
exporter.poentry_per_paragraph(
305
'dummy/help_topics/'+key+'/detail.txt',
307
elif callable(doc): # help topics from files
308
exporter.poentry_per_paragraph(
309
'en/help_topics/'+key+'.txt',
311
summary = topic_registry.get_summary(key)
312
if summary is not None:
313
exporter.poentry('dummy/help_topics/'+key+'/summary.txt',
317
def export_pot(outf, plugin=None, include_duplicates=False):
318
exporter = _PotExporter(outf, include_duplicates)
320
_standard_options(exporter)
321
_command_helps(exporter)
322
_error_messages(exporter)
323
_help_topics(exporter)
325
_command_helps(exporter, plugin)