changeset 234:541b6d630575

Use logging module for output from CLI frontend.
author cmlenz
date Mon, 30 Jul 2007 20:28:43 +0000
parents 451aac9888f5
children d0cd235ede46
files babel/messages/frontend.py babel/messages/tests/data/project/i18n/de_DE/LC_MESSAGES/messages.po babel/messages/tests/frontend.py
diffstat 3 files changed, 105 insertions(+), 62 deletions(-) [+]
line wrap: on
line diff
--- a/babel/messages/frontend.py
+++ b/babel/messages/frontend.py
@@ -19,6 +19,7 @@
 from distutils import log
 from distutils.cmd import Command
 from distutils.errors import DistutilsOptionError, DistutilsSetupError
+import logging
 from optparse import OptionParser
 import os
 import re
@@ -295,8 +296,7 @@
                     if options:
                         optstr = ' (%s)' % ', '.join(['%s="%s"' % (k, v) for
                                                       k, v in options.items()])
-                    log.info('extracting messages from %s%s'
-                             % (filepath, optstr))
+                    log.info('extracting messages from %s%s', filepath, optstr)
 
                 extracted = extract_from_dir(dirname, method_map, options_map,
                                              keywords=self._keywords,
@@ -603,10 +603,25 @@
         self.parser.add_option('--list-locales', dest='list_locales',
                                action='store_true',
                                help="print all known locales and exit")
-        self.parser.set_defaults(list_locales=False)
+        self.parser.add_option('-v', '--verbose', action='store_const',
+                               dest='loglevel', const=logging.DEBUG,
+                               help='print as much as possible')
+        self.parser.add_option('-q', '--quiet', action='store_const',
+                               dest='loglevel', const=logging.ERROR,
+                               help='print as little as possible')
+        self.parser.set_defaults(list_locales=False, loglevel=logging.INFO)
 
         options, args = self.parser.parse_args(argv[1:])
 
+        # Configure logging
+        self.log = logging.getLogger('babel')
+        self.log.setLevel(options.loglevel)
+        handler = logging.StreamHandler()
+        handler.setLevel(options.loglevel)
+        formatter = logging.Formatter('%(message)s')
+        handler.setFormatter(formatter)
+        self.log.addHandler(handler)
+
         if options.list_locales:
             identifiers = localedata.list()
             longest = max([len(identifier) for identifier in identifiers])
@@ -716,20 +731,21 @@
                 for message in list(catalog)[1:]:
                     if message.string:
                         translated +=1
-                print "%d of %d messages (%d%%) translated in %r" % (
-                    translated, len(catalog), translated * 100 // len(catalog),
-                    po_file
-                )
+                self.log.info("%d of %d messages (%d%%) translated in %r",
+                              translated, len(catalog),
+                              translated * 100 // len(catalog), po_file)
 
             if catalog.fuzzy and not options.use_fuzzy:
-                print 'catalog %r is marked as fuzzy, skipping' % (po_file)
+                self.log.warn('catalog %r is marked as fuzzy, skipping',
+                              po_file)
                 continue
 
             for message, errors in catalog.check():
                 for error in errors:
-                    print 'error: %s:%d: %s' % (po_file, message.lineno, error)
+                    self.log.error('error: %s:%d: %s', po_file, message.lineno,
+                                   error)
 
-            print 'compiling catalog %r to %r' % (po_file, mo_file)
+            self.log.info('compiling catalog %r to %r', po_file, mo_file)
 
             outfile = open(mo_file, 'w')
             try:
@@ -840,13 +856,28 @@
             for dirname in args:
                 if not os.path.isdir(dirname):
                     parser.error('%r is not a directory' % dirname)
+
+                def callback(filename, method, options):
+                    if method == 'ignore':
+                        return
+                    filepath = os.path.normpath(os.path.join(dirname, filename))
+                    optstr = ''
+                    if options:
+                        optstr = ' (%s)' % ', '.join(['%s="%s"' % (k, v) for
+                                                      k, v in options.items()])
+                    self.log.info('extracting messages from %s%s', filepath,
+                                  optstr)
+
                 extracted = extract_from_dir(dirname, method_map, options_map,
-                                             keywords, options.comment_tags)
+                                             keywords, options.comment_tags,
+                                             callback=callback)
                 for filename, lineno, message, comments in extracted:
                     filepath = os.path.normpath(os.path.join(dirname, filename))
                     catalog.add(message, None, [(filepath, lineno)],
                                 auto_comments=comments)
 
+            if options.output not in (None, '-'):
+                self.log.info('writing PO template file to %s' % options.output)
             write_po(outfile, catalog, width=options.width,
                      no_location=options.no_location,
                      omit_header=options.omit_header,
@@ -909,8 +940,8 @@
         catalog.locale = locale
         catalog.revision_date = datetime.now(LOCALTZ)
 
-        print 'creating catalog %r based on %r' % (options.output_file,
-                                                   options.input_file)
+        self.log.info('creating catalog %r based on %r', options.output_file,
+                      options.input_file)
 
         outfile = open(options.output_file, 'w')
         try:
@@ -993,8 +1024,8 @@
             parser.error('no message catalogs found')
 
         for locale, filename in po_files:
-            print 'updating catalog %r based on %r' % (filename,
-                                                       options.input_file)
+            self.log.info('updating catalog %r based on %r', filename,
+                          options.input_file)
             infile = open(filename, 'U')
             try:
                 catalog = read_po(infile, locale=locale, domain=domain)
new file mode 100644
--- /dev/null
+++ b/babel/messages/tests/data/project/i18n/de_DE/LC_MESSAGES/messages.po
@@ -0,0 +1,33 @@
+# German (Germany) translations for TestProject.
+# Copyright (C) 2007 FooBar, Inc.
+# This file is distributed under the same license as the TestProject
+# project.
+# FIRST AUTHOR <EMAIL@ADDRESS>, 2007.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: TestProject 0.1\n"
+"Report-Msgid-Bugs-To: bugs.address@email.tld\n"
+"POT-Creation-Date: 2007-04-01 15:30+0200\n"
+"PO-Revision-Date: 2007-07-30 22:18+0200\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Language-Team: de_DE <LL@li.org>\n"
+"Plural-Forms: nplurals=2; plural=(n != 1)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Generated-By: Babel 0.9dev-r245\n"
+
+#. This will be a translator coment,
+#. that will include several lines
+#: project/file1.py:8
+msgid "bar"
+msgstr ""
+
+#: project/file2.py:9
+msgid "foobar"
+msgid_plural "foobars"
+msgstr[0] ""
+msgstr[1] ""
+
--- a/babel/messages/tests/frontend.py
+++ b/babel/messages/tests/frontend.py
@@ -430,7 +430,7 @@
         self.orig_argv = sys.argv
         self.orig_stdout = sys.stdout
         self.orig_stderr = sys.stderr
-        sys.argv = ['babel']
+        sys.argv = ['pybabel']
         sys.stdout = StringIO()
         sys.stderr = StringIO()
         self.cli = frontend.CommandLineInterface()
@@ -447,9 +447,9 @@
         except SystemExit, e:
             self.assertEqual(2, e.code)
             self.assertEqual("""\
-usage: babel command [options] [args]
+usage: pybabel command [options] [args]
 
-babel: error: incorrect number of arguments
+pybabel: error: incorrect number of arguments
 """, sys.stderr.getvalue().lower())
 
     def test_help(self):
@@ -459,12 +459,14 @@
         except SystemExit, e:
             self.assertEqual(0, e.code)
             self.assertEqual("""\
-usage: babel command [options] [args]
+usage: pybabel command [options] [args]
 
 options:
   --version       show program's version number and exit
   -h, --help      show this help message and exit
   --list-locales  print all known locales and exit
+  -v, --verbose   print as much as possible
+  -q, --quiet     print as little as possible
 
 commands:
   compile  compile message catalogs to mo files
@@ -632,55 +634,32 @@
        open(po_file, 'U').read())
 
     def test_compile_catalog(self):
-        po_file = os.path.join(self.datadir, 'project', 'i18n', 'en_US',
+        po_file = os.path.join(self.datadir, 'project', 'i18n', 'de_DE',
                                'LC_MESSAGES', 'messages.po')
-        pot_file = os.path.join(self.datadir, 'project', 'i18n', 'messages.pot')
-        try:
-            self.cli.run(sys.argv + ['init',
-                '--locale', 'en_US',
-                '-d', os.path.join(self.datadir, 'project', 'i18n'),
-                '-i', pot_file])
-        except SystemExit, e:
-            self.assertEqual(0, e.code)
-            assert os.path.isfile(po_file)
+        mo_file = po_file.replace('.po', '.mo')
+        self.cli.run(sys.argv + ['compile',
+            '--locale', 'de_DE',
+            '-d', os.path.join(self.datadir, 'project', 'i18n')])
+        assert not os.path.isfile(mo_file), 'Expected no file at %r' % mo_file
+        self.assertEqual("""\
+catalog %r is marked as fuzzy, skipping
+""" % (po_file), sys.stderr.getvalue())
+
+    def test_compile_fuzzy_catalog(self):
+        po_file = os.path.join(self.datadir, 'project', 'i18n', 'de_DE',
+                               'LC_MESSAGES', 'messages.po')
+        mo_file = po_file.replace('.po', '.mo')
         try:
             self.cli.run(sys.argv + ['compile',
-                '--locale', 'en_US',
+                '--locale', 'de_DE', '--use-fuzzy',
                 '-d', os.path.join(self.datadir, 'project', 'i18n')])
-        except SystemExit, e:
-            self.assertEqual(0, e.code)
-            mo_file = po_file.replace('.po', '.mo')
-            assert not os.path.isfile(mo_file)
+            assert os.path.isfile(mo_file)
             self.assertEqual("""\
-creating catalog %r based on %r
-catalog is marked as fuzzy, not compiling it
-""" % (po_file, pot_file), sys.stdout.getvalue())
-            shutil.rmtree(os.path.join(self.datadir, 'project', 'i18n',
-                                       'en_US'))
-
-    def test_compile_fuzzy_catalog(self):
-        self.setUp()
-        po_file = os.path.join(self.datadir, 'project', 'i18n', 'en_US',
-                               'LC_MESSAGES', 'messages.po')
-        pot_file = os.path.join(self.datadir, 'project', 'i18n', 'messages.pot')
-        try:
-            self.cli.run(sys.argv + ['init',
-                '--locale', 'en_US',
-                '-d', os.path.join(self.datadir, 'project', 'i18n'),
-                '-i', pot_file])
-        except SystemExit, e:
-            self.assertEqual(0, e.code)
-            assert os.path.isfile(po_file)
-        self.cli.run(sys.argv + ['compile',
-            '--locale', 'en_US', '--use-fuzzy',
-            '-d', os.path.join(self.datadir, 'project', 'i18n')])
-        mo_file = po_file.replace('.po', '.mo')
-        assert os.path.isfile(mo_file)
-        self.assertEqual("""\
-creating catalog %r based on %r
 compiling catalog %r to %r
-""" % (po_file, pot_file, po_file, mo_file), sys.stdout.getvalue())
-        shutil.rmtree(os.path.join(self.datadir, 'project', 'i18n', 'en_US'))
+""" % (po_file, mo_file), sys.stderr.getvalue())
+        finally:
+            if os.path.isfile(mo_file):
+                os.unlink(mo_file)
 
 
 def suite():
Copyright (C) 2012-2017 Edgewall Software