diff babel/catalog/frontend.py @ 53:52dbebdd3789

Fixed a bug regarding plural msgid's handling when writing the `.pot` file. Renamed old `write_po` to `write_pot` which is what it actually does and also adds space to the new `write_po`. Changed tests accordingly. Added support to create new localized catalogs from a catalog template, `write_po`..
author palgarvio
date Thu, 07 Jun 2007 22:48:47 +0000
parents 3664c93860f1
children cc3c6cfe909d
line wrap: on
line diff
--- a/babel/catalog/frontend.py
+++ b/babel/catalog/frontend.py
@@ -24,9 +24,12 @@
 import sys
 
 from babel import __version__ as VERSION
+from babel import Locale
+from babel.core import UnknownLocaleError
 from babel.catalog.extract import extract_from_dir, DEFAULT_KEYWORDS, \
                                   DEFAULT_MAPPING
-from babel.catalog.pofile import write_po
+from babel.catalog.pofile import write_po, write_pot
+from babel.catalog.plurals import PLURALS
 
 __all__ = ['extract_messages', 'check_message_extractors', 'main']
 __docformat__ = 'restructuredtext en'
@@ -147,31 +150,15 @@
                 filepath = os.path.normpath(filename)
                 messages.append((filepath, lineno, funcname, message, None))
 
-            log.info('writing PO file to %s' % self.output_file)
-            write_po(outfile, messages, project=self.distribution.get_name(),
+            log.info('writing PO template file to %s' % self.output_file)
+            write_pot(outfile, messages, project=self.distribution.get_name(),
                      version=self.distribution.get_version(), width=self.width,
                      charset=self.charset, no_location=self.no_location,
                      omit_header=self.omit_header)
         finally:
             outfile.close()
 
-def check_message_extractors(dist, name, value):
-    """Validate the ``message_extractors`` keyword argument to ``setup()``.
-    
-    :param dist: the distutils/setuptools ``Distribution`` object
-    :param name: the name of the keyword argument (should always be
-                 "message_extractors")
-    :param value: the value of the keyword argument
-    :raise `DistutilsSetupError`: if the value is not valid
-    :see: `Adding setup() arguments
-           <http://peak.telecommunity.com/DevCenter/setuptools#adding-setup-arguments>`_
-    """
-    assert name == 'message_extractors'
-    if not isinstance(value, (basestring, dict)):
-        raise DistutilsSetupError('the value of the "extract_messages" '
-                                  'parameter must be a string or dictionary')
-
-def main(argv=sys.argv):
+def extract_cmdline(argv=sys.argv):
     """Command-line interface.
     
     This function provides a simple command-line interface to the message
@@ -259,6 +246,135 @@
     finally:
         if options.output:
             outfile.close()
+            
+class new_catalog(Command):
+    """New catalog command for use in ``setup.py`` scripts.
+
+    If correctly installed, this command is available to Setuptools-using
+    setup scripts automatically. For projects using plain old ``distutils``,
+    the command needs to be registered explicitly in ``setup.py``::
+
+        from babel.catalog.frontend import new_catalog
+
+        setup(
+            ...
+            cmdclass = {'new_catalog': new_catalog}
+        )
+
+    :see: `Integrating new distutils commands <http://docs.python.org/dist/node32.html>`_
+    :see: `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_
+    """
+
+    description = 'create new catalogs based on a catalog template'
+    user_options = [
+        ('input-file=', 'i',
+         'name of the input file'),
+        ('output-dir=', 'd',
+         'path to output directory'),
+        ('output-file=', 'o',
+         "name of the output file (default "
+         "'<output_dir>/<locale>.po')"),
+        ('locale=', 'l',
+         'locale for the new localized catalog'),
+        ('first-author=', None,
+         'name of first author'),
+        ('first-author-email=', None,
+         'email of first author')
+    ]
+
+    def initialize_options(self):
+        self.output_dir = None
+        self.output_file = None
+        self.input_file = None
+        self.locale = None
+        self.first_author = None
+        self.first_author_email = None
+
+    def finalize_options(self):
+        if not self.input_file:
+            raise DistutilsOptionError('you must specify the input file')
+        
+        if not self.locale:
+            raise DistutilsOptionError('you must provide a locale for the '
+                                       'new catalog')
+        else:
+            try:
+                locale = Locale.parse(self.locale)
+            except UnknownLocaleError, error:
+                log.error(error)
+                sys.exit(1)
+                
+        self._locale_parts = self.locale.split('_')
+        self._language = None
+        self._country = None
+        _locale = Locale('en')
+        if len(self._locale_parts) == 2:
+            if self._locale_parts[0] == self._locale_parts[1].lower():
+                # Remove country part if equal to language
+                locale = self._locale_parts[0]
+            else:
+                locale = self.locale
+            self._language = _locale.languages[self._locale_parts[0]]
+            self._country = _locale.territories[self._locale_parts[1]]
+        else:
+            locale = self._locale_parts[0]
+            self._language = _locale.languages[locale]
+            
+        if not self.output_file and not self.output_dir:
+            raise DistutilsOptionError('you must specify the output directory')
+        
+        if not self.output_file and self.output_dir:
+            self.output_file = os.path.join(self.output_dir, locale + '.po')
+
+
+    def run(self):
+        outfile = open(self.output_file, 'w')
+        infile = open(self.input_file, 'r')
+        
+        if PLURALS.has_key(self.locale):
+            # Try <language>_<COUNTRY>
+            plurals = PLURALS[self.locale]
+        elif PLURALS.has_key(self._locale_parts[0]):
+            # Try <language>
+            plurals = PLURALS[self._locale_parts[0]]
+        else:
+            plurals = ('INTEGER', 'EXPRESSION')
+            
+        if self._country:
+            logline = 'Creating %%s (%s) %%r PO from %%r' % self._country + \
+                      ' PO template' 
+        else:
+            logline = 'Creating %s %r PO from %r PO template'
+        log.info(logline, self._language, self.output_file, self.input_file)
+        
+        write_po(outfile, infile, self._language, country=self._country,
+                 project=self.distribution.get_name(),
+                 version=self.distribution.get_version(),
+                 charset=self.charset, plurals=plurals,
+                 first_author=self.first_author,
+                 first_author_email=self.first_author_email)
+        infile.close()
+        outfile.close()
+
+            
+def new_catalog_cmdline(argv=sys.argv):
+    pass
+
+def check_message_extractors(dist, name, value):
+    """Validate the ``message_extractors`` keyword argument to ``setup()``.
+    
+    :param dist: the distutils/setuptools ``Distribution`` object
+    :param name: the name of the keyword argument (should always be
+                 "message_extractors")
+    :param value: the value of the keyword argument
+    :raise `DistutilsSetupError`: if the value is not valid
+    :see: `Adding setup() arguments
+           <http://peak.telecommunity.com/DevCenter/setuptools#adding-setup-arguments>`_
+    """
+    assert name == 'message_extractors'
+    if not isinstance(value, (basestring, dict)):
+        raise DistutilsSetupError('the value of the "extract_messages" '
+                                  'parameter must be a string or dictionary')
 
 def parse_mapping(fileobj, filename=None):
     """Parse an extraction method mapping from a file-like object.
@@ -333,4 +449,4 @@
     return keywords
 
 if __name__ == '__main__':
-    main()
+    extract_cmdline()
Copyright (C) 2012-2017 Edgewall Software