~bzr-pqm/bzr/bzr.dev

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.
21
"""
22
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
23
import inspect
24
import os
25
26
from bzrlib import (
27
    commands as _mod_commands,
28
    errors,
29
    help_topics,
30
    plugin,
5830.2.15 by INADA Naoki
Add debug trace.
31
    )
32
from bzrlib.trace import (
33
    mutter,
34
    note,
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
35
    )
36
37
38
def _escape(s):
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
39
    s = (s.replace('\\', '\\\\')
40
        .replace('\n', '\\n')
41
        .replace('\r', '\\r')
42
        .replace('\t', '\\t')
43
        .replace('"', '\\"')
44
        )
45
    return s
46
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
47
def _normalize(s):
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
48
    # This converts the various Python string types into a format that
49
    # is appropriate for .po files, namely much closer to C style.
50
    lines = s.split('\n')
51
    if len(lines) == 1:
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
52
        s = '"' + _escape(s) + '"'
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
53
    else:
54
        if not lines[-1]:
55
            del lines[-1]
56
            lines[-1] = lines[-1] + '\n'
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
57
        lines = map(_escape, lines)
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
58
        lineterm = '\\n"\n"'
59
        s = '""\n"' + lineterm.join(lines) + '"'
60
    return s
61
62
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
63
_FOUND_MSGID = None # set by entry function.
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
64
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
65
def _poentry(outf, path, lineno, s, comment=None):
66
    if s in _FOUND_MSGID:
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
67
        return
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
68
    _FOUND_MSGID.add(s)
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
69
    if comment is None:
70
        comment = ''
71
    else:
72
        comment = "# %s\n" % comment
5830.2.15 by INADA Naoki
Add debug trace.
73
    mutter("Exporting msg %r at line %d in %r", s[:20], lineno, path)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
74
    print >>outf, ('#: %s:%d\n' % (path, lineno) +
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
75
           comment+
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
76
           'msgid %s\n' % _normalize(s) +
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
77
           'msgstr ""\n')
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
78
5875.3.20 by INADA Naoki
Add test for exporting command help.
79
def _poentry_per_paragraph(outf, path, lineno, msgid, filter=lambda x: False):
5830.2.18 by INADA Naoki
Add some tests for export_pot module.
80
    # TODO: How to split long help?
5830.2.2 by INADA Naoki
Split command's docstring per paragraph.
81
    paragraphs = msgid.split('\n\n')
82
    for p in paragraphs:
5875.3.20 by INADA Naoki
Add test for exporting command help.
83
        if filter(p):
5875.3.4 by INADA Naoki
Don't translate :Usage: sections.
84
            continue
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
85
        _poentry(outf, path, lineno, p)
5830.2.2 by INADA Naoki
Split command's docstring per paragraph.
86
        lineno += p.count('\n') + 2
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
87
5830.2.19 by INADA Naoki
Implement ast based offset detection.
88
_LAST_CACHE = _LAST_CACHED_SRC = None
89
90
def _offsets_of_literal(src):
91
    global _LAST_CACHE, _LAST_CACHED_SRC
92
    if src == _LAST_CACHED_SRC:
93
        return _LAST_CACHE.copy()
94
95
    import ast
96
    root = ast.parse(src)
97
    offsets = {}
98
    for node in ast.walk(root):
99
        if not isinstance(node, ast.Str):
100
            continue
5830.2.21 by INADA Naoki
Fix lineno of command help in pot
101
        offsets[node.s] = node.lineno - node.s.count('\n')
5830.2.19 by INADA Naoki
Implement ast based offset detection.
102
103
    _LAST_CACHED_SRC = src
104
    _LAST_CACHE = offsets.copy()
105
    return offsets
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
106
5830.2.17 by INADA Naoki
Split command specific options and standard options.
107
def _standard_options(outf):
108
    from bzrlib.option import Option
109
    src = inspect.findsource(Option)[0]
110
    src = ''.join(src)
111
    path = 'bzrlib/option.py'
5830.2.19 by INADA Naoki
Implement ast based offset detection.
112
    offsets = _offsets_of_literal(src)
5830.2.17 by INADA Naoki
Split command specific options and standard options.
113
114
    for name in sorted(Option.OPTIONS.keys()):
115
        opt = Option.OPTIONS[name]
116
        if getattr(opt, 'hidden', False):
117
            continue
118
        if getattr(opt, 'title', None):
5830.2.19 by INADA Naoki
Implement ast based offset detection.
119
            lineno = offsets.get(opt.title, 9999)
120
            if lineno == 9999:
121
                note("%r is not found in bzrlib/option.py" % opt.title)
5830.2.17 by INADA Naoki
Split command specific options and standard options.
122
            _poentry(outf, path, lineno, opt.title,
123
                     'title of %r option' % name)
124
        if getattr(opt, 'help', None):
5830.2.19 by INADA Naoki
Implement ast based offset detection.
125
            lineno = offsets.get(opt.help, 9999)
126
            if lineno == 9999:
127
                note("%r is not found in bzrlib/option.py" % opt.help)
5830.2.17 by INADA Naoki
Split command specific options and standard options.
128
            _poentry(outf, path, lineno, opt.help,
129
                     'help of %r option' % name)
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
130
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
131
def _command_options(outf, path, cmd):
5830.2.17 by INADA Naoki
Split command specific options and standard options.
132
    src, default_lineno = inspect.findsource(cmd.__class__)
5830.2.19 by INADA Naoki
Implement ast based offset detection.
133
    offsets = _offsets_of_literal(''.join(src))
5830.2.17 by INADA Naoki
Split command specific options and standard options.
134
    for opt in cmd.takes_options:
135
        if isinstance(opt, str):
136
            continue
137
        if getattr(opt, 'hidden', False):
138
            continue
139
        name = opt.name
140
        if getattr(opt, 'title', None):
5830.2.19 by INADA Naoki
Implement ast based offset detection.
141
            lineno = offsets.get(opt.title, default_lineno)
5830.2.17 by INADA Naoki
Split command specific options and standard options.
142
            _poentry(outf, path, lineno, opt.title,
143
                     'title of %r option of %r command' % (name, cmd.name()))
144
        if getattr(opt, 'help', None):
5830.2.19 by INADA Naoki
Implement ast based offset detection.
145
            lineno = offsets.get(opt.help, default_lineno)
5830.2.17 by INADA Naoki
Split command specific options and standard options.
146
            _poentry(outf, path, lineno, opt.help,
147
                     'help of %r option of %r command' % (name, cmd.name()))
5830.2.3 by INADA Naoki
bzrgettext extracts help message of command option too.
148
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
149
5875.3.20 by INADA Naoki
Add test for exporting command help.
150
def _write_command_help(outf, cmd):
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
151
    path = inspect.getfile(cmd.__class__)
152
    if path.endswith('.pyc'):
153
        path = path[:-1]
154
    path = os.path.relpath(path)
5830.2.21 by INADA Naoki
Fix lineno of command help in pot
155
    src, lineno = inspect.findsource(cmd.__class__)
156
    offsets = _offsets_of_literal(''.join(src))
157
    lineno = offsets[cmd.__doc__]
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
158
    doc = inspect.getdoc(cmd)
159
5875.3.20 by INADA Naoki
Add test for exporting command help.
160
    def filter(p):
161
        # ':Usage:' has special meaning in help topics.
162
        # This is usage example of command and should not be translated.
163
        if p.splitlines()[0] == ':Usage:':
164
            return True
165
166
    _poentry_per_paragraph(outf, path, lineno, doc, filter)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
167
    _command_options(outf, path, cmd)
168
5875.3.20 by INADA Naoki
Add test for exporting command help.
169
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
170
def _command_helps(outf):
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
171
    """Extract docstrings from path.
172
173
    This respects the Bazaar cmdtable/table convention and will
174
    only extract docstrings from functions mentioned in these tables.
175
    """
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
176
    from glob import glob
177
178
    # builtin commands
179
    for cmd_name in _mod_commands.builtin_command_names():
5830.2.16 by INADA Naoki
Skip hidden commands to focus important commands.
180
        command = _mod_commands.get_cmd_object(cmd_name, False)
181
        if command.hidden:
182
            continue
5830.2.15 by INADA Naoki
Add debug trace.
183
        note("Exporting messages from builtin command: %s", cmd_name)
5875.3.20 by INADA Naoki
Add test for exporting command help.
184
        _write_command_help(outf, command)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
185
5830.2.14 by INADA Naoki
Cleanup import
186
    plugin_path = plugin.get_core_plugin_path()
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
187
    core_plugins = glob(plugin_path + '/*/__init__.py')
188
    core_plugins = [os.path.basename(os.path.dirname(p))
189
                        for p in core_plugins]
190
    # core plugins
191
    for cmd_name in _mod_commands.plugin_command_names():
192
        command = _mod_commands.get_cmd_object(cmd_name, False)
5830.2.16 by INADA Naoki
Skip hidden commands to focus important commands.
193
        if command.hidden:
194
            continue
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
195
        if command.plugin_name() not in core_plugins:
196
            # skip non-core plugins
197
            # TODO: Support extracting from third party plugins.
198
            continue
5830.2.15 by INADA Naoki
Add debug trace.
199
        note("Exporting messages from plugin command: %s in %s",
200
             cmd_name, command.plugin_name())
5875.3.20 by INADA Naoki
Add test for exporting command help.
201
        _write_command_help(outf, command)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
202
203
204
def _error_messages(outf):
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
205
    """Extract fmt string from bzrlib.errors."""
5830.2.22 by INADA Naoki
Fix line no of error formats in bzr.pot
206
    path = errors.__file__
207
    if path.endswith('.pyc'):
208
        path = path[:-1]
209
    offsets = _offsets_of_literal(open(path).read())
210
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
211
    base_klass = errors.BzrError
212
    for name in dir(errors):
213
        klass = getattr(errors, name)
214
        if not inspect.isclass(klass):
215
            continue
216
        if not issubclass(klass, base_klass):
217
            continue
218
        if klass is base_klass:
219
            continue
220
        if klass.internal_error:
221
            continue
222
        fmt = getattr(klass, "_fmt", None)
223
        if fmt:
5830.2.15 by INADA Naoki
Add debug trace.
224
            note("Exporting message from error: %s", name)
225
            _poentry(outf, 'bzrlib/errors.py',
5830.2.22 by INADA Naoki
Fix line no of error formats in bzr.pot
226
                     offsets.get(fmt, 9999), fmt)
5830.2.1 by INADA Naoki
Add update-pot command to Makefile and tools/bzrgettext script that
227
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
228
def _help_topics(outf):
5830.2.14 by INADA Naoki
Cleanup import
229
    topic_registry = help_topics.topic_registry
5830.2.9 by INADA Naoki
Export from help_topics that is directly registered into
230
    for key in topic_registry.keys():
231
        doc = topic_registry.get(key)
232
        if isinstance(doc, str):
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
233
            _poentry_per_paragraph(
234
                    outf,
5830.2.11 by INADA Naoki
Change dummy file path for help topics.
235
                    'dummy/help_topics/'+key+'/detail.txt',
236
                    1, doc)
5830.2.9 by INADA Naoki
Export from help_topics that is directly registered into
237
238
        summary = topic_registry.get_summary(key)
239
        if summary is not None:
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
240
            _poentry(outf, 'dummy/help_topics/'+key+'/summary.txt',
241
                     1, summary)
242
243
def export_pot(outf):
244
    global _FOUND_MSGID
245
    _FOUND_MSGID = set()
5830.2.17 by INADA Naoki
Split command specific options and standard options.
246
    _standard_options(outf)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
247
    _command_helps(outf)
248
    _error_messages(outf)
5830.2.13 by INADA Naoki
Disable exporting help topics.
249
    # disable exporting help topics until we decide  how to translate it.
250
    #_help_topics(outf)