~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 10:37:58 UTC
  • mto: This revision was merged to the branch mainline in revision 6427.
  • Revision ID: martin.packman@canonical.com-20120105103758-wzftnmsip5iv9n2g
Revert addition of get_message_encoding function

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
 
23
29
import inspect
27
33
    commands as _mod_commands,
28
34
    errors,
29
35
    help_topics,
 
36
    option,
30
37
    plugin,
 
38
    help,
31
39
    )
32
40
from bzrlib.trace import (
33
41
    mutter,
34
42
    note,
35
43
    )
 
44
from bzrlib.i18n import gettext
36
45
 
37
46
 
38
47
def _escape(s):
60
69
    return s
61
70
 
62
71
 
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
 
 
 
72
def _parse_source(source_text):
 
73
    """Get object to lineno mappings from given source_text"""
95
74
    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))
 
75
    cls_to_lineno = {}
 
76
    str_to_lineno = {}
 
77
    for node in ast.walk(ast.parse(source_text)):
 
78
        # TODO: worry about duplicates?
 
79
        if isinstance(node, ast.ClassDef):
 
80
            # TODO: worry about nesting?
 
81
            cls_to_lineno[node.name] = node.lineno
 
82
        elif isinstance(node, ast.Str):
 
83
            # Python AST gives location of string literal as the line the
 
84
            # string terminates on. It's more useful to have the line the
 
85
            # string begins on. Unfortunately, counting back newlines is
 
86
            # only an approximation as the AST is ignorant of escaping.
 
87
            str_to_lineno[node.s] = node.lineno - node.s.count('\n')
 
88
    return cls_to_lineno, str_to_lineno
 
89
 
 
90
 
 
91
class _ModuleContext(object):
 
92
    """Record of the location within a source tree"""
 
93
 
 
94
    def __init__(self, path, lineno=1, _source_info=None):
 
95
        self.path = path
 
96
        self.lineno = lineno
 
97
        if _source_info is not None:
 
98
            self._cls_to_lineno, self._str_to_lineno = _source_info
 
99
 
 
100
    @classmethod
 
101
    def from_module(cls, module):
 
102
        """Get new context from module object and parse source for linenos"""
 
103
        sourcepath = inspect.getsourcefile(module)
 
104
        # TODO: fix this to do the right thing rather than rely on cwd
 
105
        relpath = os.path.relpath(sourcepath)
 
106
        return cls(relpath,
 
107
            _source_info=_parse_source("".join(inspect.findsource(module)[0])))
 
108
 
 
109
    def from_class(self, cls):
 
110
        """Get new context with same details but lineno of class in source"""
 
111
        try:
 
112
            lineno = self._cls_to_lineno[cls.__name__]
 
113
        except (AttributeError, KeyError):
 
114
            mutter("Definition of %r not found in %r", cls, self.path)
 
115
            return self
 
116
        return self.__class__(self.path, lineno,
 
117
            (self._cls_to_lineno, self._str_to_lineno))
 
118
 
 
119
    def from_string(self, string):
 
120
        """Get new context with same details but lineno of string in source"""
 
121
        try:
 
122
            lineno = self._str_to_lineno[string]
 
123
        except (AttributeError, KeyError):
 
124
            mutter("String %r not found in %r", string[:20], self.path)
 
125
            return self
 
126
        return self.__class__(self.path, lineno,
 
127
            (self._cls_to_lineno, self._str_to_lineno))
 
128
 
 
129
 
 
130
class _PotExporter(object):
 
131
    """Write message details to output stream in .pot file format"""
 
132
 
 
133
    def __init__(self, outf, include_duplicates=False):
 
134
        self.outf = outf
 
135
        if include_duplicates:
 
136
            self._msgids = None
 
137
        else:
 
138
            self._msgids = set()
 
139
        self._module_contexts = {}
 
140
 
 
141
    def poentry(self, path, lineno, s, comment=None):
 
142
        if self._msgids is not None:
 
143
            if s in self._msgids:
 
144
                return
 
145
            self._msgids.add(s)
 
146
        if comment is None:
 
147
            comment = ''
 
148
        else:
 
149
            comment = "# %s\n" % comment
 
150
        mutter("Exporting msg %r at line %d in %r", s[:20], lineno, path)
 
151
        self.outf.write(
 
152
            "#: {path}:{lineno}\n"
 
153
            "{comment}"
 
154
            "msgid {msg}\n"
 
155
            "msgstr \"\"\n"
 
156
            "\n".format(
 
157
                path=path, lineno=lineno, comment=comment, msg=_normalize(s)))
 
158
 
 
159
    def poentry_in_context(self, context, string, comment=None):
 
160
        context = context.from_string(string)
 
161
        self.poentry(context.path, context.lineno, string, comment)
 
162
 
 
163
    def poentry_per_paragraph(self, path, lineno, msgid, include=None):
 
164
        # TODO: How to split long help?
 
165
        paragraphs = msgid.split('\n\n')
 
166
        if include is not None:
 
167
            paragraphs = filter(include, paragraphs)
 
168
        for p in paragraphs:
 
169
            self.poentry(path, lineno, p)
 
170
            lineno += p.count('\n') + 2
 
171
 
 
172
    def get_context(self, obj):
 
173
        module = inspect.getmodule(obj)
 
174
        try:
 
175
            context = self._module_contexts[module.__name__]
 
176
        except KeyError:
 
177
            context = _ModuleContext.from_module(module)
 
178
            self._module_contexts[module.__name__] = context
 
179
        if inspect.isclass(obj):
 
180
            context = context.from_class(obj)
 
181
        return context
 
182
 
 
183
 
 
184
def _write_option(exporter, context, opt, note):
 
185
    if getattr(opt, 'hidden', False):
 
186
        return   
 
187
    optname = opt.name
 
188
    if getattr(opt, 'title', None):
 
189
        exporter.poentry_in_context(context, opt.title,
 
190
            "title of {name!r} {what}".format(name=optname, what=note))
 
191
    for name, _, _, helptxt in opt.iter_switches():
 
192
        if name != optname:
 
193
            if opt.is_hidden(name):
 
194
                continue
 
195
            name = "=".join([optname, name])
 
196
        if helptxt:
 
197
            exporter.poentry_in_context(context, helptxt,
 
198
                "help of {name!r} {what}".format(name=name, what=note))
 
199
 
 
200
 
 
201
def _standard_options(exporter):
 
202
    OPTIONS = option.Option.OPTIONS
 
203
    context = exporter.get_context(option)
 
204
    for name in sorted(OPTIONS.keys()):
 
205
        opt = OPTIONS[name]
 
206
        _write_option(exporter, context.from_string(name), opt, "option")
 
207
 
 
208
 
 
209
def _command_options(exporter, context, cmd):
 
210
    note = "option of {0!r} command".format(cmd.name())
134
211
    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):
 
212
        # String values in Command option lists are for global options
 
213
        if not isinstance(opt, str):
 
214
            _write_option(exporter, context, opt, note)
 
215
 
 
216
 
 
217
def _write_command_help(exporter, cmd):
 
218
    context = exporter.get_context(cmd.__class__)
 
219
    rawdoc = cmd.__doc__
 
220
    dcontext = context.from_string(rawdoc)
 
221
    doc = inspect.cleandoc(rawdoc)
 
222
 
 
223
    def exclude_usage(p):
161
224
        # ':Usage:' has special meaning in help topics.
162
225
        # This is usage example of command and should not be translated.
163
 
        if p.splitlines()[0] == ':Usage:':
 
226
        if p.splitlines()[0] != ':Usage:':
164
227
            return True
165
228
 
166
 
    _poentry_per_paragraph(outf, path, lineno, doc, filter)
167
 
    _command_options(outf, path, cmd)
168
 
 
169
 
 
170
 
def _command_helps(outf):
 
229
    exporter.poentry_per_paragraph(dcontext.path, dcontext.lineno, doc,
 
230
        exclude_usage)
 
231
    _command_options(exporter, context, cmd)
 
232
 
 
233
 
 
234
def _command_helps(exporter, plugin_name=None):
171
235
    """Extract docstrings from path.
172
236
 
173
237
    This respects the Bazaar cmdtable/table convention and will
180
244
        command = _mod_commands.get_cmd_object(cmd_name, False)
181
245
        if command.hidden:
182
246
            continue
183
 
        note("Exporting messages from builtin command: %s", cmd_name)
184
 
        _write_command_help(outf, command)
 
247
        if plugin_name is not None:
 
248
            # only export builtins if we are not exporting plugin commands
 
249
            continue
 
250
        note(gettext("Exporting messages from builtin command: %s"), cmd_name)
 
251
        _write_command_help(exporter, command)
185
252
 
186
253
    plugin_path = plugin.get_core_plugin_path()
187
254
    core_plugins = glob(plugin_path + '/*/__init__.py')
188
255
    core_plugins = [os.path.basename(os.path.dirname(p))
189
256
                        for p in core_plugins]
190
 
    # core plugins
 
257
    # plugins
191
258
    for cmd_name in _mod_commands.plugin_command_names():
192
259
        command = _mod_commands.get_cmd_object(cmd_name, False)
193
260
        if command.hidden:
194
261
            continue
195
 
        if command.plugin_name() not in core_plugins:
 
262
        if plugin_name is not None and command.plugin_name() != plugin_name:
 
263
            # if we are exporting plugin commands, skip plugins we have not specified.
 
264
            continue
 
265
        if plugin_name is None and command.plugin_name() not in core_plugins:
196
266
            # skip non-core plugins
197
267
            # TODO: Support extracting from third party plugins.
198
268
            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):
 
269
        note(gettext("Exporting messages from plugin command: {0} in {1}").format(
 
270
             cmd_name, command.plugin_name() ))
 
271
        _write_command_help(exporter, command)
 
272
 
 
273
 
 
274
def _error_messages(exporter):
205
275
    """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
 
 
 
276
    context = exporter.get_context(errors)
211
277
    base_klass = errors.BzrError
212
278
    for name in dir(errors):
213
279
        klass = getattr(errors, name)
221
287
            continue
222
288
        fmt = getattr(klass, "_fmt", None)
223
289
        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):
 
290
            note(gettext("Exporting message from error: %s"), name)
 
291
            exporter.poentry_in_context(context, fmt)
 
292
 
 
293
 
 
294
def _help_topics(exporter):
229
295
    topic_registry = help_topics.topic_registry
230
296
    for key in topic_registry.keys():
231
297
        doc = topic_registry.get(key)
232
298
        if isinstance(doc, str):
233
 
            _poentry_per_paragraph(
234
 
                    outf,
 
299
            exporter.poentry_per_paragraph(
235
300
                    'dummy/help_topics/'+key+'/detail.txt',
236
301
                    1, doc)
237
 
 
 
302
        elif callable(doc): # help topics from files
 
303
            exporter.poentry_per_paragraph(
 
304
                    'en/help_topics/'+key+'.txt',
 
305
                    1, doc(key))
238
306
        summary = topic_registry.get_summary(key)
239
307
        if summary is not None:
240
 
            _poentry(outf, 'dummy/help_topics/'+key+'/summary.txt',
 
308
            exporter.poentry('dummy/help_topics/'+key+'/summary.txt',
241
309
                     1, summary)
242
310
 
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)
 
311
 
 
312
def export_pot(outf, plugin=None, include_duplicates=False):
 
313
    exporter = _PotExporter(outf, include_duplicates)
 
314
    if plugin is None:
 
315
        _standard_options(exporter)
 
316
        _command_helps(exporter)
 
317
        _error_messages(exporter)
 
318
        _help_topics(exporter)
 
319
    else:
 
320
        _command_helps(exporter, plugin)