~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/export_pot.py

  • Committer: Martin Packman
  • Date: 2012-01-05 09:50:04 UTC
  • mfrom: (6424 +trunk)
  • mto: This revision was merged to the branch mainline in revision 6426.
  • Revision ID: martin.packman@canonical.com-20120105095004-mia9xb7y0efmto0v
Merge bzr.dev to resolve conflicts in bzrlib.builtins

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
# with Python under the Python License, which is GPL compatible.
19
19
 
20
20
"""Extract docstrings from Bazaar commands.
 
21
 
 
22
This module only handles bzrlib 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.
21
27
"""
22
28
 
 
29
from __future__ import absolute_import
 
30
 
23
31
import inspect
24
32
import os
25
33
 
27
35
    commands as _mod_commands,
28
36
    errors,
29
37
    help_topics,
 
38
    option,
30
39
    plugin,
 
40
    help,
31
41
    )
32
42
from bzrlib.trace import (
33
43
    mutter,
34
44
    note,
35
45
    )
 
46
from bzrlib.i18n import gettext
36
47
 
37
48
 
38
49
def _escape(s):
60
71
    return s
61
72
 
62
73
 
63
 
_FOUND_MSGID = None # set by entry function.
64
 
 
65
 
def _poentry(outf, path, lineno, s, comment=None):
66
 
    if s in _FOUND_MSGID:
67
 
        return
68
 
    _FOUND_MSGID.add(s)
69
 
    if comment is None:
70
 
        comment = ''
71
 
    else:
72
 
        comment = "# %s\n" % comment
73
 
    mutter("Exporting msg %r at line %d in %r", s[:20], lineno, path)
74
 
    print >>outf, ('#: %s:%d\n' % (path, lineno) +
75
 
           comment+
76
 
           'msgid %s\n' % _normalize(s) +
77
 
           'msgstr ""\n')
78
 
 
79
 
def _poentry_per_paragraph(outf, path, lineno, msgid, filter=lambda x: False):
80
 
    # TODO: How to split long help?
81
 
    paragraphs = msgid.split('\n\n')
82
 
    for p in paragraphs:
83
 
        if filter(p):
84
 
            continue
85
 
        _poentry(outf, path, lineno, p)
86
 
        lineno += p.count('\n') + 2
87
 
 
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
 
 
 
74
def _parse_source(source_text):
 
75
    """Get object to lineno mappings from given source_text"""
95
76
    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
101
 
        offsets[node.s] = node.lineno - node.s.count('\n')
102
 
 
103
 
    _LAST_CACHED_SRC = src
104
 
    _LAST_CACHE = offsets.copy()
105
 
    return offsets
106
 
 
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'
112
 
    offsets = _offsets_of_literal(src)
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):
119
 
            lineno = offsets.get(opt.title, 9999)
120
 
            if lineno == 9999:
121
 
                note("%r is not found in bzrlib/option.py" % opt.title)
122
 
            _poentry(outf, path, lineno, opt.title,
123
 
                     'title of %r option' % name)
124
 
        if getattr(opt, 'help', None):
125
 
            lineno = offsets.get(opt.help, 9999)
126
 
            if lineno == 9999:
127
 
                note("%r is not found in bzrlib/option.py" % opt.help)
128
 
            _poentry(outf, path, lineno, opt.help,
129
 
                     'help of %r option' % name)
130
 
 
131
 
def _command_options(outf, path, cmd):
132
 
    src, default_lineno = inspect.findsource(cmd.__class__)
133
 
    offsets = _offsets_of_literal(''.join(src))
 
77
    cls_to_lineno = {}
 
78
    str_to_lineno = {}
 
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
 
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])))
 
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
        self.outf.write(
 
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
 
 
161
    def poentry_in_context(self, context, string, comment=None):
 
162
        context = context.from_string(string)
 
163
        self.poentry(context.path, context.lineno, string, comment)
 
164
 
 
165
    def poentry_per_paragraph(self, path, lineno, msgid, include=None):
 
166
        # TODO: How to split long help?
 
167
        paragraphs = msgid.split('\n\n')
 
168
        if include is not None:
 
169
            paragraphs = filter(include, paragraphs)
 
170
        for p in paragraphs:
 
171
            self.poentry(path, lineno, p)
 
172
            lineno += p.count('\n') + 2
 
173
 
 
174
    def get_context(self, obj):
 
175
        module = inspect.getmodule(obj)
 
176
        try:
 
177
            context = self._module_contexts[module.__name__]
 
178
        except KeyError:
 
179
            context = _ModuleContext.from_module(module)
 
180
            self._module_contexts[module.__name__] = context
 
181
        if inspect.isclass(obj):
 
182
            context = context.from_class(obj)
 
183
        return context
 
184
 
 
185
 
 
186
def _write_option(exporter, context, opt, note):
 
187
    if getattr(opt, 'hidden', False):
 
188
        return   
 
189
    optname = opt.name
 
190
    if getattr(opt, 'title', None):
 
191
        exporter.poentry_in_context(context, opt.title,
 
192
            "title of {name!r} {what}".format(name=optname, what=note))
 
193
    for name, _, _, helptxt in opt.iter_switches():
 
194
        if name != optname:
 
195
            if opt.is_hidden(name):
 
196
                continue
 
197
            name = "=".join([optname, name])
 
198
        if helptxt:
 
199
            exporter.poentry_in_context(context, helptxt,
 
200
                "help of {name!r} {what}".format(name=name, what=note))
 
201
 
 
202
 
 
203
def _standard_options(exporter):
 
204
    OPTIONS = option.Option.OPTIONS
 
205
    context = exporter.get_context(option)
 
206
    for name in sorted(OPTIONS.keys()):
 
207
        opt = OPTIONS[name]
 
208
        _write_option(exporter, context.from_string(name), opt, "option")
 
209
 
 
210
 
 
211
def _command_options(exporter, context, cmd):
 
212
    note = "option of {0!r} command".format(cmd.name())
134
213
    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):
141
 
            lineno = offsets.get(opt.title, default_lineno)
142
 
            _poentry(outf, path, lineno, opt.title,
143
 
                     'title of %r option of %r command' % (name, cmd.name()))
144
 
        if getattr(opt, 'help', None):
145
 
            lineno = offsets.get(opt.help, default_lineno)
146
 
            _poentry(outf, path, lineno, opt.help,
147
 
                     'help of %r option of %r command' % (name, cmd.name()))
148
 
 
149
 
 
150
 
def _write_command_help(outf, cmd):
151
 
    path = inspect.getfile(cmd.__class__)
152
 
    if path.endswith('.pyc'):
153
 
        path = path[:-1]
154
 
    path = os.path.relpath(path)
155
 
    src, lineno = inspect.findsource(cmd.__class__)
156
 
    offsets = _offsets_of_literal(''.join(src))
157
 
    lineno = offsets[cmd.__doc__]
158
 
    doc = inspect.getdoc(cmd)
159
 
 
160
 
    def filter(p):
 
214
        # String values in Command option lists are for global options
 
215
        if not isinstance(opt, str):
 
216
            _write_option(exporter, context, opt, note)
 
217
 
 
218
 
 
219
def _write_command_help(exporter, cmd):
 
220
    context = exporter.get_context(cmd.__class__)
 
221
    rawdoc = cmd.__doc__
 
222
    dcontext = context.from_string(rawdoc)
 
223
    doc = inspect.cleandoc(rawdoc)
 
224
 
 
225
    def exclude_usage(p):
161
226
        # ':Usage:' has special meaning in help topics.
162
227
        # This is usage example of command and should not be translated.
163
 
        if p.splitlines()[0] == ':Usage:':
 
228
        if p.splitlines()[0] != ':Usage:':
164
229
            return True
165
230
 
166
 
    _poentry_per_paragraph(outf, path, lineno, doc, filter)
167
 
    _command_options(outf, path, cmd)
168
 
 
169
 
 
170
 
def _command_helps(outf):
 
231
    exporter.poentry_per_paragraph(dcontext.path, dcontext.lineno, doc,
 
232
        exclude_usage)
 
233
    _command_options(exporter, context, cmd)
 
234
 
 
235
 
 
236
def _command_helps(exporter, plugin_name=None):
171
237
    """Extract docstrings from path.
172
238
 
173
239
    This respects the Bazaar cmdtable/table convention and will
180
246
        command = _mod_commands.get_cmd_object(cmd_name, False)
181
247
        if command.hidden:
182
248
            continue
183
 
        note("Exporting messages from builtin command: %s", cmd_name)
184
 
        _write_command_help(outf, command)
 
249
        if plugin_name is not None:
 
250
            # only export builtins if we are not exporting plugin commands
 
251
            continue
 
252
        note(gettext("Exporting messages from builtin command: %s"), cmd_name)
 
253
        _write_command_help(exporter, command)
185
254
 
186
255
    plugin_path = plugin.get_core_plugin_path()
187
256
    core_plugins = glob(plugin_path + '/*/__init__.py')
188
257
    core_plugins = [os.path.basename(os.path.dirname(p))
189
258
                        for p in core_plugins]
190
 
    # core plugins
 
259
    # plugins
191
260
    for cmd_name in _mod_commands.plugin_command_names():
192
261
        command = _mod_commands.get_cmd_object(cmd_name, False)
193
262
        if command.hidden:
194
263
            continue
195
 
        if command.plugin_name() not in core_plugins:
 
264
        if plugin_name is not None and command.plugin_name() != plugin_name:
 
265
            # if we are exporting plugin commands, skip plugins we have not specified.
 
266
            continue
 
267
        if plugin_name is None and command.plugin_name() not in core_plugins:
196
268
            # skip non-core plugins
197
269
            # TODO: Support extracting from third party plugins.
198
270
            continue
199
 
        note("Exporting messages from plugin command: %s in %s",
200
 
             cmd_name, command.plugin_name())
201
 
        _write_command_help(outf, command)
202
 
 
203
 
 
204
 
def _error_messages(outf):
 
271
        note(gettext("Exporting messages from plugin command: {0} in {1}").format(
 
272
             cmd_name, command.plugin_name() ))
 
273
        _write_command_help(exporter, command)
 
274
 
 
275
 
 
276
def _error_messages(exporter):
205
277
    """Extract fmt string from bzrlib.errors."""
206
 
    path = errors.__file__
207
 
    if path.endswith('.pyc'):
208
 
        path = path[:-1]
209
 
    offsets = _offsets_of_literal(open(path).read())
210
 
 
 
278
    context = exporter.get_context(errors)
211
279
    base_klass = errors.BzrError
212
280
    for name in dir(errors):
213
281
        klass = getattr(errors, name)
221
289
            continue
222
290
        fmt = getattr(klass, "_fmt", None)
223
291
        if fmt:
224
 
            note("Exporting message from error: %s", name)
225
 
            _poentry(outf, 'bzrlib/errors.py',
226
 
                     offsets.get(fmt, 9999), fmt)
227
 
 
228
 
def _help_topics(outf):
 
292
            note(gettext("Exporting message from error: %s"), name)
 
293
            exporter.poentry_in_context(context, fmt)
 
294
 
 
295
 
 
296
def _help_topics(exporter):
229
297
    topic_registry = help_topics.topic_registry
230
298
    for key in topic_registry.keys():
231
299
        doc = topic_registry.get(key)
232
300
        if isinstance(doc, str):
233
 
            _poentry_per_paragraph(
234
 
                    outf,
 
301
            exporter.poentry_per_paragraph(
235
302
                    'dummy/help_topics/'+key+'/detail.txt',
236
303
                    1, doc)
237
 
 
 
304
        elif callable(doc): # help topics from files
 
305
            exporter.poentry_per_paragraph(
 
306
                    'en/help_topics/'+key+'.txt',
 
307
                    1, doc(key))
238
308
        summary = topic_registry.get_summary(key)
239
309
        if summary is not None:
240
 
            _poentry(outf, 'dummy/help_topics/'+key+'/summary.txt',
 
310
            exporter.poentry('dummy/help_topics/'+key+'/summary.txt',
241
311
                     1, summary)
242
312
 
243
 
def export_pot(outf):
244
 
    global _FOUND_MSGID
245
 
    _FOUND_MSGID = set()
246
 
    _standard_options(outf)
247
 
    _command_helps(outf)
248
 
    _error_messages(outf)
249
 
    # disable exporting help topics until we decide  how to translate it.
250
 
    #_help_topics(outf)
 
313
 
 
314
def export_pot(outf, plugin=None, include_duplicates=False):
 
315
    exporter = _PotExporter(outf, include_duplicates)
 
316
    if plugin is None:
 
317
        _standard_options(exporter)
 
318
        _command_helps(exporter)
 
319
        _error_messages(exporter)
 
320
        _help_topics(exporter)
 
321
    else:
 
322
        _command_helps(exporter, plugin)