Anonymous avatar Anonymous committed 6c06570

Soften dependency on setuptools. Extraction methods can now be referenced using a special section in the mapping configuration, mapping short names to fully-qualified function references.

Comments (0)

Files changed (4)

babel/messages/catalog.py

         ``(message, errors)`` tuple, where ``message`` is the `Message` object
         and ``errors`` is a sequence of `TranslationError` objects.
 
+        :note: this feature requires ``setuptools``/``pkg_resources`` to be
+               installed; if it is not, this method will simply return an empty
+               iterator
         :rtype: ``iterator``
         """
         checkers = []
-        from pkg_resources import working_set
-        for entry_point in working_set.iter_entry_points('babel.checkers'):
-            checkers.append(entry_point.load())
-
-        for message in self._messages.values():
-            errors = []
-            for checker in checkers:
-                try:
-                    checker(self, message)
-                except TranslationError, e:
-                    errors.append(e)
-            if errors:
-                yield message, errors
+        try:
+            from pkg_resources import working_set
+        except ImportError:
+            return
+        else:
+            for entry_point in working_set.iter_entry_points('babel.checkers'):
+                checkers.append(entry_point.load())
+            for message in self._messages.values():
+                errors = []
+                for checker in checkers:
+                    try:
+                        checker(self, message)
+                    except TranslationError, e:
+                        errors.append(e)
+                if errors:
+                    yield message, errors
 
     def update(self, template, no_fuzzy_matching=False):
         """Update the catalog based on the given template catalog.

babel/messages/extract.py

     ...     print message
     (3, u'Hello, world!', [])
 
-    :param method: a string specifying the extraction method (.e.g. "python")
+    :param method: a string specifying the extraction method (.e.g. "python");
+                   if this is a simple name, the extraction function will be
+                   looked up by entry point; if it is an explicit reference
+                   to a function (of the form ``package.module:funcname``), the
+                   corresponding function will be imported and used
     :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
     :rtype: `list`
     :raise ValueError: if the extraction method is not registered
     """
-    from pkg_resources import working_set
+    if ':' in method:
+        module, clsname = method.split(':', 1)
+        func = getattr(__import__(module, {}, {}, [clsname]), clsname)
+    else:
+        try:
+            from pkg_resources import working_set
+        except ImportError:
+            # pkg_resources is not available, so we resort to looking up the
+            # builtin extractors directly
+            builtin = {'ignore': extract_nothing, 'python': extract_python}
+            func = builtin.get(method)
+        else:
+            for entry_point in working_set.iter_entry_points(GROUP_NAME,
+                                                             method):
+                func = entry_point.load(require=True)
+                break
+    if func is None:
+        raise ValueError('Unknown extraction method %r' % method)
 
-    for entry_point in working_set.iter_entry_points(GROUP_NAME, method):
-        func = entry_point.load(require=True)
-        results = func(fileobj, keywords.keys(), comment_tags,
-                       options=options or {})
-        for lineno, funcname, messages, comments in results:
-            if funcname:
-                spec = keywords[funcname] or (1,)
-            else:
-                spec = (1,)
-            if not isinstance(messages, (list, tuple)):
-                messages = [messages]
+    results = func(fileobj, keywords.keys(), comment_tags,
+                   options=options or {})
+    for lineno, funcname, messages, comments in results:
+        if funcname:
+            spec = keywords[funcname] or (1,)
+        else:
+            spec = (1,)
+        if not isinstance(messages, (list, tuple)):
+            messages = [messages]
 
-            msgs = []
-            # Validate the messages against the keyword's specification
-            invalid = False
-            for index in spec:
-                message = messages[index - 1]
-                if message is None:
-                    invalid = True
-                    break
-                msgs.append(message)
-            if invalid:
-                continue
+        msgs = []
+        # Validate the messages against the keyword's specification
+        invalid = False
+        for index in spec:
+            message = messages[index - 1]
+            if message is None:
+                invalid = True
+                break
+            msgs.append(message)
+        if invalid:
+            continue
 
-            first_msg_index = spec[0] - 1
-            if not messages[first_msg_index]:
-                # An empty string msgid isn't valid, emit a warning
-                where = '%s:%i' % (hasattr(fileobj, 'name') and \
-                                       fileobj.name or '(unknown)', lineno)
-                print >> sys.stderr, empty_msgid_warning % where
-                continue
+        first_msg_index = spec[0] - 1
+        if not messages[first_msg_index]:
+            # An empty string msgid isn't valid, emit a warning
+            where = '%s:%i' % (hasattr(fileobj, 'name') and \
+                                   fileobj.name or '(unknown)', lineno)
+            print >> sys.stderr, empty_msgid_warning % where
+            continue
 
-            messages = tuple(msgs)
-            if len(messages) == 1:
-                messages = messages[0]
-            yield lineno, messages, comments
-        return
-
-    raise ValueError('Unknown extraction method %r' % method)
+        messages = tuple(msgs)
+        if len(messages) == 1:
+            messages = messages[0]
+        yield lineno, messages, comments
 
 def extract_nothing(fileobj, keywords, comment_tags, options):
     """Pseudo extractor that does not actually extract anything, but simply

babel/messages/frontend.py

     """Parse an extraction method mapping from a file-like object.
 
     >>> buf = StringIO('''
+    ... [extractors]
+    ... custom = mypackage.module:myfunc
+    ... 
     ... # Python source files
     ... [python: **.py]
     ...
     ... [genshi: **/templates/**.txt]
     ... template_class = genshi.template:TextTemplate
     ... encoding = latin-1
+    ... 
+    ... # Some custom extractor
+    ... [custom: **/custom/*.*]
     ... ''')
 
     >>> method_map, options_map = parse_mapping(buf)
+    >>> len(method_map)
+    4
 
     >>> method_map[0]
     ('**.py', 'python')
     >>> options_map['**/templates/**.txt']['encoding']
     'latin-1'
 
+    >>> method_map[3]
+    ('**/custom/*.*', 'mypackage.module:myfunc')
+    >>> options_map['**/custom/*.*']
+    {}
+
     :param fileobj: a readable file-like object containing the configuration
                     text to parse
     :return: a `(method_map, options_map)` tuple
     :rtype: `tuple`
     :see: `extract_from_directory`
     """
+    extractors = {}
     method_map = []
     options_map = {}
 
     parser._sections = odict(parser._sections) # We need ordered sections
     parser.readfp(fileobj, filename)
     for section in parser.sections():
-        method, pattern = [part.strip() for part in section.split(':', 1)]
-        method_map.append((pattern, method))
-        options_map[pattern] = dict(parser.items(section))
+        if section == 'extractors':
+            extractors = dict(parser.items(section))
+        else:
+            method, pattern = [part.strip() for part in section.split(':', 1)]
+            method_map.append((pattern, method))
+            options_map[pattern] = dict(parser.items(section))
+
+    if extractors:
+        for idx, (pattern, method) in enumerate(method_map):
+            if method in extractors:
+                method = extractors[method]
+            method_map[idx] = (pattern, method)
 
     return (method_map, options_map)
 
 =============================
 
 .. contents:: Contents
-   :depth: 2
+   :depth: 3
 .. sectnum::
 
 
 extraction methods, which is described below.
 
 
+.. _`frontends`:
+
+----------
+Front-Ends
+----------
+
+Babel provides two different front-ends to access its functionality for working
+with message catalogs:
+
+ * A `Command-line interface <cmdline.html>`_, and
+ * `Integration with distutils/setuptools <setup.html>`_
+
+Which one you choose depends on the nature of your project. For most modern
+Python projects, the distutils/setuptools integration is probably more
+convenient.
+
+
 .. _`mapping`:
 
 -------------------------------------------
 
     # Extraction from Python source files
     
-    [python: foobar/**.py]
+    [python: **.py]
     
     # Extraction from Genshi HTML and text templates
     
-    [genshi: foobar/**/templates/**.html]
+    [genshi: **/templates/**.html]
     ignore_tags = script,style
     include_attrs = alt title summary
     
-    [genshi: foobar/**/templates/**.txt]
+    [genshi: **/templates/**.txt]
     template_class = genshi.template:TextTemplate
     encoding = ISO-8819-15
 
 The configuration file syntax is based on the format commonly found in ``.INI``
 files on Windows systems, and as supported by the ``ConfigParser`` module in
-the Python standard libraries. Section names (the strings enclosed in square
+the Python standard library. Section names (the strings enclosed in square
 brackets) specify both the name of the extraction method, and the extended glob
 pattern to specify the files that this extraction method should be used for,
 separated by a colon. The options in the sections are passed to the extraction
 extension ``.txt`` in any directory.
 
 Lines that start with a ``#`` or ``;`` character are ignored and can be used
-for comments. Empty lines are also ignored, too.
+for comments. Empty lines are ignored, too.
 
 .. note:: if you're performing message extraction using the command Babel
-          provides for integration into ``setup.py`` scripts (see below), you
-          can also provide this configuration in a different way, namely as a
-          keyword argument to the ``setup()`` function.
+          provides for integration into ``setup.py`` scripts, you can also 
+          provide this configuration in a different way, namely as a keyword 
+          argument to the ``setup()`` function. See `Distutils/Setuptools 
+          Integration`_ for more information.
 
+.. _`distutils/setuptools integration`: setup.html
 
-----------
-Front-Ends
-----------
 
-Babel provides two different front-ends to access its functionality for working
-with message catalogs:
+Default Extraction Methods
+--------------------------
 
- * A `Command-line interface <cmdline.html>`_, and
- * `Integration with distutils/setuptools <setup.html>`_
+Babel comes with only two builtin extractors: ``python`` (which extracts 
+messages from Python source files) and ``ignore`` (which extracts nothing).
 
-Which one you choose depends on the nature of your project. For most modern
-Python projects, the distutils/setuptools integration is probably more
-convenient.
+The ``python`` extractor is by default mapped to the glob pattern ``**.py``,
+meaning it'll be applied to all files with the ``.py`` extension in any 
+directory. If you specify your own mapping configuration, this default mapping
+is not discarded, so you need to explicitly add it to your mapping (as shown in
+the example above.)
+
+
+.. _`referencing extraction methods`:
+
+Referencing Extraction Methods
+------------------------------
+
+To be able to use short extraction method names such as “genshi”, you need to 
+have `pkg_resources`_ installed, and the package implementing that extraction
+method needs to have been installed with its meta data (the `egg-info`_).
+
+If this is not possible for some reason, you need to map the short names to 
+fully qualified function names in an extract section in the mapping 
+configuration. For example:
+
+.. code-block:: ini
+
+    # Some custom extraction method
+    
+    [extractors]
+    custom = mypackage.module:extract_custom
+    
+    [custom: **.ctm]
+    some_option = foo
+
+Note that the builtin extraction methods ``python`` and ``ignore`` are available
+by default, even if `pkg_resources`_ is not installed. You should never need to
+explicitly define them in the ``[extractors]`` section.
+
+.. _`egg-info`: http://peak.telecommunity.com/DevCenter/PythonEggs
+.. _`pkg_resources`: http://peak.telecommunity.com/DevCenter/PkgResources
 
 
 --------------------------
 the name of the function (separated by a colon) implementing the actual
 extraction.
 
+.. note:: As shown in `Referencing Extraction Methods`_, declaring an entry
+          point is not  strictly required, as users can still reference the
+          extraction  function directly. But whenever possible, the entry point
+          should be  declared to make configuration more convenient.
+
 .. _`setuptools`: http://peak.telecommunity.com/DevCenter/setuptools
 
-Comments Tags And Translator Comments Explanation
-.................................................
+
+-------------------
+Translator Comments
+-------------------
 
 First of all what are comments tags. Comments tags are excerpts of text to
 search for in comments, only comments, right before the `python gettext`_
 
 Now, you might ask, why would I need that?
 
-Consider this simple case; you have a menu item called “Manual”. You know what
+Consider this simple case; you have a menu item called “manual”. You know what
 it means, but when the translator sees this they will wonder did you mean:
 
 1. a document or help manual, or
 “The installation manual” helps to clarify the situation and makes a translator
 more productive.
 
-**More examples of the need for translation comments**
-
-Real world examples are best. This is a discussion over the use of the word
-“Forward” in Northern Sotho:
-
-“When you go forward. You go ‘Pele’, but when you forward the document,
-you ‘Fetišetša pele’. So if you just say forward, we don’t know what you are
-talking about.
-It is better if it's in a sentence. But in this case i think we will use ‘pele’
-because on the string no. 86 and 88 there is “show previous page in history”
-and “show next page in history”.
-
-Were the translators guess correct? I think so, but it makes it so much easier
-if they don’t need to be super `sleuths`_ as well as translators.
-
- .. _`sleuths`: http://www.thefreedictionary.com/sleuth
-
-
-*Explanation Borrowed From:* `Wordforge`_
-
- .. _`Wordforge`: http://www.wordforge.org/static/translation_comments.html
-
-**Note**: Translator comments are currently only supported in python source
-code.
-
+.. note:: Whether translator comments can be extracted depends on the extraction
+          method in use. The Python extractor provided by Babel does implement
+          this feature, but others may not.
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.