/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/export_pot.py

  • Committer: Martin
  • Date: 2018-11-16 16:38:22 UTC
  • mto: This revision was merged to the branch mainline in revision 7172.
  • Revision ID: gzlist@googlemail.com-20181116163822-yg1h1cdng6w7w9kn
Make --profile-imports work on Python 3

Also tweak heading to line up correctly.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2011 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
# The normalize function is taken from pygettext which is distributed
 
18
# with Python under the Python License, which is GPL compatible.
 
19
 
 
20
"""Extract docstrings from Bazaar commands.
 
21
 
 
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.
 
27
"""
 
28
 
 
29
from __future__ import absolute_import
 
30
 
 
31
import inspect
 
32
import os
 
33
 
 
34
import breezy
 
35
from . import (
 
36
    commands as _mod_commands,
 
37
    errors,
 
38
    help_topics,
 
39
    option,
 
40
    plugin as _mod_plugin,
 
41
    )
 
42
from .sixish import PY3
 
43
from .trace import (
 
44
    mutter,
 
45
    note,
 
46
    )
 
47
from .i18n import gettext
 
48
 
 
49
 
 
50
def _escape(s):
 
51
    s = (s.replace('\\', '\\\\')
 
52
        .replace('\n', '\\n')
 
53
        .replace('\r', '\\r')
 
54
        .replace('\t', '\\t')
 
55
        .replace('"', '\\"')
 
56
        )
 
57
    return s
 
58
 
 
59
def _normalize(s):
 
60
    # This converts the various Python string types into a format that
 
61
    # is appropriate for .po files, namely much closer to C style.
 
62
    lines = s.split('\n')
 
63
    if len(lines) == 1:
 
64
        s = '"' + _escape(s) + '"'
 
65
    else:
 
66
        if not lines[-1]:
 
67
            del lines[-1]
 
68
            lines[-1] = lines[-1] + '\n'
 
69
        lineterm = '\\n"\n"'
 
70
        s = '""\n"' + lineterm.join(map(_escape, lines)) + '"'
 
71
    return s
 
72
 
 
73
 
 
74
def _parse_source(source_text, filename='<unknown>'):
 
75
    """Get object to lineno mappings from given source_text"""
 
76
    import ast
 
77
    cls_to_lineno = {}
 
78
    str_to_lineno = {}
 
79
    for node in ast.walk(ast.parse(source_text, filename)):
 
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
 
91
 
 
92
 
 
93
class _ModuleContext(object):
 
94
    """Record of the location within a source tree"""
 
95
 
 
96
    def __init__(self, path, lineno=1, _source_info=None):
 
97
        self.path = path
 
98
        self.lineno = lineno
 
99
        if _source_info is not None:
 
100
            self._cls_to_lineno, self._str_to_lineno = _source_info
 
101
 
 
102
    @classmethod
 
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)
 
108
        return cls(relpath,
 
109
            _source_info=_parse_source("".join(inspect.findsource(module)[0]), module.__file__))
 
110
 
 
111
    def from_class(self, cls):
 
112
        """Get new context with same details but lineno of class in source"""
 
113
        try:
 
114
            lineno = self._cls_to_lineno[cls.__name__]
 
115
        except (AttributeError, KeyError):
 
116
            mutter("Definition of %r not found in %r", cls, self.path)
 
117
            return self
 
118
        return self.__class__(self.path, lineno,
 
119
            (self._cls_to_lineno, self._str_to_lineno))
 
120
 
 
121
    def from_string(self, string):
 
122
        """Get new context with same details but lineno of string in source"""
 
123
        try:
 
124
            lineno = self._str_to_lineno[string]
 
125
        except (AttributeError, KeyError):
 
126
            mutter("String %r not found in %r", string[:20], self.path)
 
127
            return self
 
128
        return self.__class__(self.path, lineno,
 
129
            (self._cls_to_lineno, self._str_to_lineno))
 
130
 
 
131
 
 
132
class _PotExporter(object):
 
133
    """Write message details to output stream in .pot file format"""
 
134
 
 
135
    def __init__(self, outf, include_duplicates=False):
 
136
        self.outf = outf
 
137
        if include_duplicates:
 
138
            self._msgids = None
 
139
        else:
 
140
            self._msgids = set()
 
141
        self._module_contexts = {}
 
142
 
 
143
    def poentry(self, path, lineno, s, comment=None):
 
144
        if self._msgids is not None:
 
145
            if s in self._msgids:
 
146
                return
 
147
            self._msgids.add(s)
 
148
        if comment is None:
 
149
            comment = ''
 
150
        else:
 
151
            comment = "# %s\n" % comment
 
152
        mutter("Exporting msg %r at line %d in %r", s[:20], lineno, path)
 
153
        line = (
 
154
            "#: {path}:{lineno}\n"
 
155
            "{comment}"
 
156
            "msgid {msg}\n"
 
157
            "msgstr \"\"\n"
 
158
            "\n".format(
 
159
                path=path, lineno=lineno, comment=comment, msg=_normalize(s)))
 
160
        if not PY3:
 
161
            line = line.decode('utf-8')
 
162
        self.outf.write(line)
 
163
 
 
164
    def poentry_in_context(self, context, string, comment=None):
 
165
        context = context.from_string(string)
 
166
        self.poentry(context.path, context.lineno, string, comment)
 
167
 
 
168
    def poentry_per_paragraph(self, path, lineno, msgid, include=None):
 
169
        # TODO: How to split long help?
 
170
        paragraphs = msgid.split('\n\n')
 
171
        if include is not None:
 
172
            paragraphs = filter(include, paragraphs)
 
173
        for p in paragraphs:
 
174
            self.poentry(path, lineno, p)
 
175
            lineno += p.count('\n') + 2
 
176
 
 
177
    def get_context(self, obj):
 
178
        module = inspect.getmodule(obj)
 
179
        try:
 
180
            context = self._module_contexts[module.__name__]
 
181
        except KeyError:
 
182
            context = _ModuleContext.from_module(module)
 
183
            self._module_contexts[module.__name__] = context
 
184
        if inspect.isclass(obj):
 
185
            context = context.from_class(obj)
 
186
        return context
 
187
 
 
188
 
 
189
def _write_option(exporter, context, opt, note):
 
190
    if getattr(opt, 'hidden', False):
 
191
        return   
 
192
    optname = opt.name
 
193
    if getattr(opt, 'title', None):
 
194
        exporter.poentry_in_context(context, opt.title,
 
195
            "title of {name!r} {what}".format(name=optname, what=note))
 
196
    for name, _, _, helptxt in opt.iter_switches():
 
197
        if name != optname:
 
198
            if opt.is_hidden(name):
 
199
                continue
 
200
            name = "=".join([optname, name])
 
201
        if helptxt:
 
202
            exporter.poentry_in_context(context, helptxt,
 
203
                "help of {name!r} {what}".format(name=name, what=note))
 
204
 
 
205
 
 
206
def _standard_options(exporter):
 
207
    OPTIONS = option.Option.OPTIONS
 
208
    context = exporter.get_context(option)
 
209
    for name in sorted(OPTIONS):
 
210
        opt = OPTIONS[name]
 
211
        _write_option(exporter, context.from_string(name), opt, "option")
 
212
 
 
213
 
 
214
def _command_options(exporter, context, cmd):
 
215
    note = "option of {0!r} command".format(cmd.name())
 
216
    for opt in cmd.takes_options:
 
217
        # String values in Command option lists are for global options
 
218
        if not isinstance(opt, str):
 
219
            _write_option(exporter, context, opt, note)
 
220
 
 
221
 
 
222
def _write_command_help(exporter, cmd):
 
223
    context = exporter.get_context(cmd.__class__)
 
224
    rawdoc = cmd.__doc__
 
225
    dcontext = context.from_string(rawdoc)
 
226
    doc = inspect.cleandoc(rawdoc)
 
227
 
 
228
    def exclude_usage(p):
 
229
        # ':Usage:' has special meaning in help topics.
 
230
        # This is usage example of command and should not be translated.
 
231
        if p.splitlines()[0] != ':Usage:':
 
232
            return True
 
233
 
 
234
    exporter.poentry_per_paragraph(dcontext.path, dcontext.lineno, doc,
 
235
        exclude_usage)
 
236
    _command_options(exporter, context, cmd)
 
237
 
 
238
 
 
239
def _command_helps(exporter, plugin_name=None):
 
240
    """Extract docstrings from path.
 
241
 
 
242
    This respects the Bazaar cmdtable/table convention and will
 
243
    only extract docstrings from functions mentioned in these tables.
 
244
    """
 
245
 
 
246
    # builtin commands
 
247
    for cmd_name in _mod_commands.builtin_command_names():
 
248
        command = _mod_commands.get_cmd_object(cmd_name, False)
 
249
        if command.hidden:
 
250
            continue
 
251
        if plugin_name is not None:
 
252
            # only export builtins if we are not exporting plugin commands
 
253
            continue
 
254
        note(gettext("Exporting messages from builtin command: %s"), cmd_name)
 
255
        _write_command_help(exporter, command)
 
256
 
 
257
    plugins = _mod_plugin.plugins()
 
258
    if plugin_name is not None and plugin_name not in plugins:
 
259
        raise errors.BzrError(gettext('Plugin %s is not loaded' % plugin_name))
 
260
    core_plugins = set(
 
261
            name for name in plugins
 
262
            if plugins[name].path().startswith(breezy.__path__[0]))
 
263
    # plugins
 
264
    for cmd_name in _mod_commands.plugin_command_names():
 
265
        command = _mod_commands.get_cmd_object(cmd_name, False)
 
266
        if command.hidden:
 
267
            continue
 
268
        if plugin_name is not None and command.plugin_name() != plugin_name:
 
269
            # if we are exporting plugin commands, skip plugins we have not
 
270
            # specified.
 
271
            continue
 
272
        if plugin_name is None and command.plugin_name() not in core_plugins:
 
273
            # skip non-core plugins
 
274
            # TODO: Support extracting from third party plugins.
 
275
            continue
 
276
        note(gettext("Exporting messages from plugin command: {0} in {1}").format(
 
277
             cmd_name, command.plugin_name() ))
 
278
        _write_command_help(exporter, command)
 
279
 
 
280
 
 
281
def _error_messages(exporter):
 
282
    """Extract fmt string from breezy.errors."""
 
283
    context = exporter.get_context(errors)
 
284
    base_klass = errors.BzrError
 
285
    for name in dir(errors):
 
286
        klass = getattr(errors, name)
 
287
        if not inspect.isclass(klass):
 
288
            continue
 
289
        if not issubclass(klass, base_klass):
 
290
            continue
 
291
        if klass is base_klass:
 
292
            continue
 
293
        if klass.internal_error:
 
294
            continue
 
295
        fmt = getattr(klass, "_fmt", None)
 
296
        if fmt:
 
297
            note(gettext("Exporting message from error: %s"), name)
 
298
            exporter.poentry_in_context(context, fmt)
 
299
 
 
300
 
 
301
def _help_topics(exporter):
 
302
    topic_registry = help_topics.topic_registry
 
303
    for key in topic_registry.keys():
 
304
        doc = topic_registry.get(key)
 
305
        if isinstance(doc, str):
 
306
            exporter.poentry_per_paragraph(
 
307
                    'dummy/help_topics/'+key+'/detail.txt',
 
308
                    1, doc)
 
309
        elif callable(doc): # help topics from files
 
310
            exporter.poentry_per_paragraph(
 
311
                    'en/help_topics/'+key+'.txt',
 
312
                    1, doc(key))
 
313
        summary = topic_registry.get_summary(key)
 
314
        if summary is not None:
 
315
            exporter.poentry('dummy/help_topics/'+key+'/summary.txt',
 
316
                     1, summary)
 
317
 
 
318
 
 
319
def export_pot(outf, plugin=None, include_duplicates=False):
 
320
    exporter = _PotExporter(outf, include_duplicates)
 
321
    if plugin is None:
 
322
        _standard_options(exporter)
 
323
        _command_helps(exporter)
 
324
        _error_messages(exporter)
 
325
        _help_topics(exporter)
 
326
    else:
 
327
        _command_helps(exporter, plugin)