view babel/messages/extract.py @ 57:a6183d300a6e

* The `extract_messages` distutils command now operators on configurable input directories again, instead of the complete current directory. The `input_dirs` default to the package directories. * Add a pseudo extractor called ?ignore? for #10.
author cmlenz
date Fri, 08 Jun 2007 11:28:15 +0000
parents 27fba894d3ca
children 84d400066b71
line wrap: on
line source
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.

"""Basic infrastructure for extracting localizable messages from source files.

This module defines an extensible system for collecting localizable message
strings from a variety of sources. A native extractor for Python source files
is builtin, extractors for other sources can be added using very simple plugins.

The main entry points into the extraction functionality are the functions
`extract_from_dir` and `extract_from_file`.
"""

import os
try:
    set
except NameError:
    from sets import Set as set
import sys
from tokenize import generate_tokens, NAME, OP, STRING

from babel.util import pathmatch, relpath

__all__ = ['extract', 'extract_from_dir', 'extract_from_file']
__docformat__ = 'restructuredtext en'

GROUP_NAME = 'babel.extractors'

DEFAULT_KEYWORDS = {
    '_': None,
    'gettext': None,
    'ngettext': (1, 2),
    'ugettext': None,
    'ungettext': (1, 2),
    'dgettext': (2,),
    'dngettext': (2, 3),
}

DEFAULT_MAPPING = {'**.py': 'python'}

def extract_from_dir(dirname=os.getcwd(), method_map=DEFAULT_MAPPING,
                     options_map=None, keywords=DEFAULT_KEYWORDS,
                     callback=None):
    """Extract messages from any source files found in the given directory.
    
    This function generates tuples of the form:
    
        ``(filename, lineno, message)``
    
    Which extraction method is used per file is determined by the `method_map`
    parameter, which maps extended glob patterns to extraction method names.
    For example, the following is the default mapping:
    
    >>> method_map = {
    ...     '**.py': 'python'
    ... }
    
    This basically says that files with the filename extension ".py" at any
    level inside the directory should be processed by the "python" extraction
    method. Files that don't match any of the mapping patterns are ignored. See
    the documentation of the `pathmatch` function for details on the pattern
    syntax.
    
    The following extended mapping would also use the "genshi" extraction method
    on any file in "templates" subdirectory:
    
    >>> method_map = {
    ...     '**/templates/**.*': 'genshi',
    ...     '**.py': 'python'
    ... }
    
    The dictionary provided by the optional `options_map` parameter augments
    the mapping data. It too uses extended glob patterns as keys, but the values
    are dictionaries mapping options names to option values (both strings).
    
    The glob patterns of the `options_map` do not necessarily need to be the
    same as those used in the pattern. For example, while all files in the
    ``templates`` folders in an application may be Genshi applications, the
    options for those files may differ based on extension:
    
    >>> options_map = {
    ...     '**/templates/**.txt': {
    ...         'template_class': 'genshi.template.text.TextTemplate',
    ...         'encoding': 'latin-1'
    ...     },
    ...     '**/templates/**.html': {
    ...         'include_attrs': ''
    ...     }
    ... }
    
    :param dirname: the path to the directory to extract messages from
    :param method_map: a mapping of extraction method names to extended glob
                       patterns
    :param options_map: a dictionary of additional options (optional)
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param callback: a function that is called for every file that message are
                     extracted from, just before the extraction itself is
                     performed; the function is passed the filename and the
                     options dictionary as positional arguments, in that order
    :return: an iterator over ``(filename, lineno, funcname, message)`` tuples
    :rtype: ``iterator``
    :see: `pathmatch`
    """
    if options_map is None:
        options_map = {}

    # Sort methods by pattern length
    # FIXME: we'll probably need to preserve the user-supplied order in the
    #        frontends
    methods = method_map.items()
    methods.sort(lambda a,b: -cmp(len(a[0]), len(b[0])))

    absname = os.path.abspath(dirname)
    for root, dirnames, filenames in os.walk(absname):
        for subdir in dirnames:
            if subdir.startswith('.') or subdir.startswith('_'):
                dirnames.remove(subdir)
        for filename in filenames:
            filename = relpath(
                os.path.join(root, filename).replace(os.sep, '/'),
                dirname
            )
            for pattern, method in methods:
                if pathmatch(pattern, filename):
                    filepath = os.path.join(absname, filename)
                    options = {}
                    for opattern, odict in options_map.items():
                        if pathmatch(opattern, filename):
                            options = odict
                    if callback:
                        callback(filename, method, options)
                    for lineno, message in extract_from_file(method, filepath,
                                                             keywords=keywords,
                                                             options=options):
                        yield filename, lineno, message
                    break

def extract_from_file(method, filename, keywords=DEFAULT_KEYWORDS,
                      options=None):
    """Extract messages from a specific file.
    
    This function returns a list of tuples of the form:
    
        ``(lineno, funcname, message)``
    
    :param filename: the path to the file to extract messages from
    :param method: a string specifying the extraction method (.e.g. "python")
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param options: a dictionary of additional options (optional)
    :return: the list of extracted messages
    :rtype: `list`
    """
    fileobj = open(filename, 'U')
    try:
        return list(extract(method, fileobj, keywords, options=options))
    finally:
        fileobj.close()

def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, options=None):
    """Extract messages from the given file-like object using the specified
    extraction method.
    
    This function returns a list of tuples of the form:
    
        ``(lineno, message)``
    
    The implementation dispatches the actual extraction to plugins, based on the
    value of the ``method`` parameter.
    
    >>> source = '''# foo module
    ... def run(argv):
    ...    print _('Hello, world!')
    ... '''
    
    >>> from StringIO import StringIO
    >>> for message in extract('python', StringIO(source)):
    ...     print message
    (3, 'Hello, world!')
    
    :param method: a string specifying the extraction method (.e.g. "python")
    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a dictionary mapping keywords (i.e. names of functions
                     that should be recognized as translation functions) to
                     tuples that specify which of their arguments contain
                     localizable strings
    :param options: a dictionary of additional options (optional)
    :return: the list of extracted messages
    :rtype: `list`
    :raise ValueError: if the extraction method is not registered
    """
    from pkg_resources import working_set

    for entry_point in working_set.iter_entry_points(GROUP_NAME, method):
        func = entry_point.load(require=True)
        m = []
        for lineno, funcname, messages in func(fileobj, keywords.keys(),
                                               options=options or {}):
            if isinstance(messages, (list, tuple)):
                msgs = []
                for index in keywords[funcname]:
                    msgs.append(messages[index - 1])
                messages = tuple(msgs)
                if len(messages) == 1:
                    messages = messages[0]
            yield lineno, messages
        return

    raise ValueError('Unknown extraction method %r' % method)

def extract_nothing(fileobj, keywords, options):
    """Pseudo extractor that does not actually extract anything, but simply
    returns an empty list.
    """
    return []

def extract_genshi(fileobj, keywords, options):
    """Extract messages from Genshi templates.
    
    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should be
                     recognized as translation functions
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message)`` tuples
    :rtype: ``iterator``
    """
    from genshi.filters.i18n import Translator
    from genshi.template import MarkupTemplate

    template_class = options.get('template_class', MarkupTemplate)
    if isinstance(template_class, basestring):
        module, clsname = template_class.split(':', 1)
        template_class = getattr(__import__(module, {}, {}, [clsname]), clsname)
    encoding = options.get('encoding', None)

    ignore_tags = options.get('ignore_tags', Translator.IGNORE_TAGS)
    if isinstance(ignore_tags, basestring):
        ignore_tags = ignore_tags.split()
    include_attrs = options.get('include_attrs', Translator.INCLUDE_ATTRS)
    if isinstance(include_attrs, basestring):
        include_attrs = include_attrs.split()

    tmpl = template_class(fileobj, filename=getattr(fileobj, 'name'),
                          encoding=encoding)
    translator = Translator(None, ignore_tags, include_attrs)
    for message in translator.extract(tmpl.stream, gettext_functions=keywords):
        yield message

def extract_python(fileobj, keywords, options):
    """Extract messages from Python source code.
    
    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should be
                     recognized as translation functions
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message)`` tuples
    :rtype: ``iterator``
    """
    funcname = None
    lineno = None
    buf = []
    messages = []
    in_args = False

    tokens = generate_tokens(fileobj.readline)
    for tok, value, (lineno, _), _, _ in tokens:
        if funcname and tok == OP and value == '(':
            in_args = True
        elif funcname and in_args:
            if tok == OP and value == ')':
                in_args = False
                if buf:
                    messages.append(''.join(buf))
                    del buf[:]
                if filter(None, messages):
                    if len(messages) > 1:
                        messages = tuple(messages)
                    else:
                        messages = messages[0]
                    yield lineno, funcname, messages
                funcname = lineno = None
                messages = []
            elif tok == STRING:
                if lineno is None:
                    lineno = stup[0]
                # Unwrap quotes in a safe manner
                buf.append(eval(value, {'__builtins__':{}}, {}))
            elif tok == OP and value == ',':
                messages.append(''.join(buf))
                del buf[:]
        elif funcname:
            funcname = None
        elif tok == NAME and value in keywords:
            funcname = value
Copyright (C) 2012-2017 Edgewall Software