/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
1
# Copyright (C) 2011 Canonical Ltd
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
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.
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
21
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
22
This module only handles breezy objects that use strings not directly wrapped
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
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.
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
27
"""
28
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
29
from __future__ import absolute_import
30
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
31
import inspect
32
import os
7290.47.2 by Jelmer Vernooij
More improvements to make tests success with Python 3.8.
33
import sys
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
34
6651.4.3 by Martin
Fix export-pot core plugin handling
35
import breezy
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
36
from . import (
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
37
    commands as _mod_commands,
38
    errors,
39
    help_topics,
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
40
    option,
6759.4.3 by Jelmer Vernooij
Avoid accessing global state.
41
    plugin as _mod_plugin,
5830.2.15 by INADA Naoki
Add debug trace.
42
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
43
from .trace import (
5830.2.15 by INADA Naoki
Add debug trace.
44
    mutter,
45
    note,
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
46
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
47
from .i18n import gettext
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
48
49
50
def _escape(s):
7027.3.7 by Jelmer Vernooij
drop broken tests.
51
    s = (s.replace('\\', '\\\\')
7143.15.2 by Jelmer Vernooij
Run autopep8.
52
         .replace('\n', '\\n')
53
         .replace('\r', '\\r')
54
         .replace('\t', '\\t')
55
         .replace('"', '\\"')
56
         )
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
57
    return s
58
7143.15.2 by Jelmer Vernooij
Run autopep8.
59
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
60
def _normalize(s):
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
61
    # This converts the various Python string types into a format that
62
    # is appropriate for .po files, namely much closer to C style.
7027.3.7 by Jelmer Vernooij
drop broken tests.
63
    lines = s.split('\n')
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
64
    if len(lines) == 1:
7027.3.7 by Jelmer Vernooij
drop broken tests.
65
        s = '"' + _escape(s) + '"'
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
66
    else:
67
        if not lines[-1]:
68
            del lines[-1]
69
            lines[-1] = lines[-1] + '\n'
70
        lineterm = '\\n"\n"'
7027.3.7 by Jelmer Vernooij
drop broken tests.
71
        s = '""\n"' + lineterm.join(map(_escape, lines)) + '"'
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
72
    return s
73
74
7027.3.7 by Jelmer Vernooij
drop broken tests.
75
def _parse_source(source_text, filename='<unknown>'):
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
76
    """Get object to lineno mappings from given source_text"""
77
    import ast
78
    cls_to_lineno = {}
79
    str_to_lineno = {}
7027.3.7 by Jelmer Vernooij
drop broken tests.
80
    for node in ast.walk(ast.parse(source_text, filename)):
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
81
        # TODO: worry about duplicates?
82
        if isinstance(node, ast.ClassDef):
83
            # TODO: worry about nesting?
84
            cls_to_lineno[node.name] = node.lineno
85
        elif isinstance(node, ast.Str):
86
            # Python AST gives location of string literal as the line the
87
            # string terminates on. It's more useful to have the line the
88
            # string begins on. Unfortunately, counting back newlines is
89
            # only an approximation as the AST is ignorant of escaping.
7290.47.2 by Jelmer Vernooij
More improvements to make tests success with Python 3.8.
90
            str_to_lineno[node.s] = node.lineno - (0 if sys.version_info >= (3, 8) else node.s.count('\n'))
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
91
    return cls_to_lineno, str_to_lineno
92
93
94
class _ModuleContext(object):
95
    """Record of the location within a source tree"""
96
97
    def __init__(self, path, lineno=1, _source_info=None):
98
        self.path = path
99
        self.lineno = lineno
100
        if _source_info is not None:
101
            self._cls_to_lineno, self._str_to_lineno = _source_info
102
103
    @classmethod
104
    def from_module(cls, module):
105
        """Get new context from module object and parse source for linenos"""
106
        sourcepath = inspect.getsourcefile(module)
107
        # TODO: fix this to do the right thing rather than rely on cwd
108
        relpath = os.path.relpath(sourcepath)
109
        return cls(relpath,
7143.15.2 by Jelmer Vernooij
Run autopep8.
110
                   _source_info=_parse_source("".join(inspect.findsource(module)[0]), module.__file__))
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
111
112
    def from_class(self, cls):
113
        """Get new context with same details but lineno of class in source"""
114
        try:
115
            lineno = self._cls_to_lineno[cls.__name__]
116
        except (AttributeError, KeyError):
117
            mutter("Definition of %r not found in %r", cls, self.path)
118
            return self
119
        return self.__class__(self.path, lineno,
7143.15.2 by Jelmer Vernooij
Run autopep8.
120
                              (self._cls_to_lineno, self._str_to_lineno))
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
121
122
    def from_string(self, string):
123
        """Get new context with same details but lineno of string in source"""
124
        try:
125
            lineno = self._str_to_lineno[string]
126
        except (AttributeError, KeyError):
127
            mutter("String %r not found in %r", string[:20], self.path)
128
            return self
129
        return self.__class__(self.path, lineno,
7143.15.2 by Jelmer Vernooij
Run autopep8.
130
                              (self._cls_to_lineno, self._str_to_lineno))
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
131
132
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
133
class _PotExporter(object):
134
    """Write message details to output stream in .pot file format"""
135
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
136
    def __init__(self, outf, include_duplicates=False):
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
137
        self.outf = outf
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
138
        if include_duplicates:
139
            self._msgids = None
140
        else:
141
            self._msgids = set()
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
142
        self._module_contexts = {}
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
143
144
    def poentry(self, path, lineno, s, comment=None):
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
145
        if self._msgids is not None:
146
            if s in self._msgids:
147
                return
148
            self._msgids.add(s)
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
149
        if comment is None:
150
            comment = ''
151
        else:
152
            comment = "# %s\n" % comment
153
        mutter("Exporting msg %r at line %d in %r", s[:20], lineno, path)
6973.11.1 by Jelmer Vernooij
Fix export_pot.
154
        line = (
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
155
            "#: {path}:{lineno}\n"
156
            "{comment}"
157
            "msgid {msg}\n"
158
            "msgstr \"\"\n"
159
            "\n".format(
160
                path=path, lineno=lineno, comment=comment, msg=_normalize(s)))
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
161
        self.outf.write(line)
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
162
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
163
    def poentry_in_context(self, context, string, comment=None):
164
        context = context.from_string(string)
165
        self.poentry(context.path, context.lineno, string, comment)
166
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
167
    def poentry_per_paragraph(self, path, lineno, msgid, include=None):
168
        # TODO: How to split long help?
169
        paragraphs = msgid.split('\n\n')
170
        if include is not None:
171
            paragraphs = filter(include, paragraphs)
172
        for p in paragraphs:
173
            self.poentry(path, lineno, p)
174
            lineno += p.count('\n') + 2
175
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
176
    def get_context(self, obj):
177
        module = inspect.getmodule(obj)
178
        try:
179
            context = self._module_contexts[module.__name__]
180
        except KeyError:
181
            context = _ModuleContext.from_module(module)
182
            self._module_contexts[module.__name__] = context
183
        if inspect.isclass(obj):
184
            context = context.from_class(obj)
185
        return context
186
187
188
def _write_option(exporter, context, opt, note):
189
    if getattr(opt, 'hidden', False):
7143.15.2 by Jelmer Vernooij
Run autopep8.
190
        return
6282.2.3 by Martin Packman
Export registry help to pot for unhidden option value switches
191
    optname = opt.name
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
192
    if getattr(opt, 'title', None):
193
        exporter.poentry_in_context(context, opt.title,
7143.15.2 by Jelmer Vernooij
Run autopep8.
194
                                    "title of {name!r} {what}".format(name=optname, what=note))
6282.2.3 by Martin Packman
Export registry help to pot for unhidden option value switches
195
    for name, _, _, helptxt in opt.iter_switches():
196
        if name != optname:
197
            if opt.is_hidden(name):
198
                continue
199
            name = "=".join([optname, name])
200
        if helptxt:
201
            exporter.poentry_in_context(context, helptxt,
7143.15.2 by Jelmer Vernooij
Run autopep8.
202
                                        "help of {name!r} {what}".format(name=name, what=note))
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
203
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
204
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
205
def _standard_options(exporter):
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
206
    OPTIONS = option.Option.OPTIONS
207
    context = exporter.get_context(option)
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
208
    for name in sorted(OPTIONS):
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
209
        opt = OPTIONS[name]
210
        _write_option(exporter, context.from_string(name), opt, "option")
211
212
213
def _command_options(exporter, context, cmd):
214
    note = "option of {0!r} command".format(cmd.name())
5830.2.17 by INADA Naoki
Split command specific options and standard options.
215
    for opt in cmd.takes_options:
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
216
        # String values in Command option lists are for global options
217
        if not isinstance(opt, str):
218
            _write_option(exporter, context, opt, note)
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
219
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
220
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
221
def _write_command_help(exporter, cmd):
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
222
    context = exporter.get_context(cmd.__class__)
223
    rawdoc = cmd.__doc__
224
    dcontext = context.from_string(rawdoc)
225
    doc = inspect.cleandoc(rawdoc)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
226
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
227
    def exclude_usage(p):
5875.3.20 by INADA Naoki
Add test for exporting command help.
228
        # ':Usage:' has special meaning in help topics.
229
        # This is usage example of command and should not be translated.
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
230
        if p.splitlines()[0] != ':Usage:':
5875.3.20 by INADA Naoki
Add test for exporting command help.
231
            return True
232
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
233
    exporter.poentry_per_paragraph(dcontext.path, dcontext.lineno, doc,
7143.15.2 by Jelmer Vernooij
Run autopep8.
234
                                   exclude_usage)
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
235
    _command_options(exporter, context, cmd)
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
236
237
238
def _command_helps(exporter, plugin_name=None):
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
239
    """Extract docstrings from path.
240
241
    This respects the Bazaar cmdtable/table convention and will
242
    only extract docstrings from functions mentioned in these tables.
243
    """
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
244
245
    # builtin commands
246
    for cmd_name in _mod_commands.builtin_command_names():
5830.2.16 by INADA Naoki
Skip hidden commands to focus important commands.
247
        command = _mod_commands.get_cmd_object(cmd_name, False)
248
        if command.hidden:
249
            continue
6162.4.5 by Jonathan Riddell
change export-pot --plugins option to --plugin which takes a plugin name rather than command name
250
        if plugin_name is not None:
6162.4.3 by Jonathan Riddell
add new option 'plugins' to 'export-pot' to export strings from given plugin commands help
251
            # only export builtins if we are not exporting plugin commands
252
            continue
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
253
        note(gettext("Exporting messages from builtin command: %s"), cmd_name)
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
254
        _write_command_help(exporter, command)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
255
6759.4.3 by Jelmer Vernooij
Avoid accessing global state.
256
    plugins = _mod_plugin.plugins()
6759.4.2 by Jelmer Vernooij
Use get_global_state>
257
    if plugin_name is not None and plugin_name not in plugins:
6703.1.4 by Jelmer Vernooij
Print an error when trying to export pot file from a plugin that doesn't exist.
258
        raise errors.BzrError(gettext('Plugin %s is not loaded' % plugin_name))
6759.4.3 by Jelmer Vernooij
Avoid accessing global state.
259
    core_plugins = set(
7143.15.2 by Jelmer Vernooij
Run autopep8.
260
        name for name in plugins
261
        if plugins[name].path().startswith(breezy.__path__[0]))
6162.4.3 by Jonathan Riddell
add new option 'plugins' to 'export-pot' to export strings from given plugin commands help
262
    # plugins
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
263
    for cmd_name in _mod_commands.plugin_command_names():
264
        command = _mod_commands.get_cmd_object(cmd_name, False)
5830.2.16 by INADA Naoki
Skip hidden commands to focus important commands.
265
        if command.hidden:
266
            continue
6162.4.5 by Jonathan Riddell
change export-pot --plugins option to --plugin which takes a plugin name rather than command name
267
        if plugin_name is not None and command.plugin_name() != plugin_name:
6759.4.3 by Jelmer Vernooij
Avoid accessing global state.
268
            # if we are exporting plugin commands, skip plugins we have not
269
            # specified.
6162.4.3 by Jonathan Riddell
add new option 'plugins' to 'export-pot' to export strings from given plugin commands help
270
            continue
6162.4.5 by Jonathan Riddell
change export-pot --plugins option to --plugin which takes a plugin name rather than command name
271
        if plugin_name is None and command.plugin_name() not in core_plugins:
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
272
            # skip non-core plugins
273
            # TODO: Support extracting from third party plugins.
274
            continue
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
275
        note(gettext("Exporting messages from plugin command: {0} in {1}").format(
7143.15.2 by Jelmer Vernooij
Run autopep8.
276
             cmd_name, command.plugin_name()))
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
277
        _write_command_help(exporter, command)
278
279
280
def _error_messages(exporter):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
281
    """Extract fmt string from breezy.errors."""
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
282
    context = exporter.get_context(errors)
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
283
    base_klass = errors.BzrError
284
    for name in dir(errors):
285
        klass = getattr(errors, name)
286
        if not inspect.isclass(klass):
287
            continue
288
        if not issubclass(klass, base_klass):
289
            continue
290
        if klass is base_klass:
291
            continue
292
        if klass.internal_error:
293
            continue
294
        fmt = getattr(klass, "_fmt", None)
295
        if fmt:
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
296
            note(gettext("Exporting message from error: %s"), name)
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
297
            exporter.poentry_in_context(context, fmt)
298
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
299
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
300
def _help_topics(exporter):
5830.2.14 by INADA Naoki
Cleanup import
301
    topic_registry = help_topics.topic_registry
5830.2.9 by INADA Naoki
Export from help_topics that is directly registered into
302
    for key in topic_registry.keys():
303
        doc = topic_registry.get(key)
304
        if isinstance(doc, str):
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
305
            exporter.poentry_per_paragraph(
7143.15.2 by Jelmer Vernooij
Run autopep8.
306
                'dummy/help_topics/' + key + '/detail.txt',
307
                1, doc)
308
        elif callable(doc):  # help topics from files
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
309
            exporter.poentry_per_paragraph(
7143.15.2 by Jelmer Vernooij
Run autopep8.
310
                'en/help_topics/' + key + '.txt',
311
                1, doc(key))
5830.2.9 by INADA Naoki
Export from help_topics that is directly registered into
312
        summary = topic_registry.get_summary(key)
313
        if summary is not None:
7143.15.2 by Jelmer Vernooij
Run autopep8.
314
            exporter.poentry('dummy/help_topics/' + key + '/summary.txt',
315
                             1, summary)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
316
6282.2.2 by Martin Packman
Add export_pot._ModuleContext class for more structured source location tracking, and share option writing logic
317
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
318
def export_pot(outf, plugin=None, include_duplicates=False):
319
    exporter = _PotExporter(outf, include_duplicates)
6162.4.5 by Jonathan Riddell
change export-pot --plugins option to --plugin which takes a plugin name rather than command name
320
    if plugin is None:
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
321
        _standard_options(exporter)
322
        _command_helps(exporter)
323
        _error_messages(exporter)
324
        _help_topics(exporter)
6162.4.3 by Jonathan Riddell
add new option 'plugins' to 'export-pot' to export strings from given plugin commands help
325
    else:
6282.2.1 by Martin Packman
Add export_pot._PotExporter class to avoid module global, and other minor cleanups
326
        _command_helps(exporter, plugin)