From b36d521ff6d4f7a994d4472c25f8267b6e268d41 Mon Sep 17 00:00:00 2001
From: Huanxuan Ao <huanxuan.ao@easystack.cn>
Date: Tue, 7 Jun 2016 19:16:24 +0800
Subject: [PATCH] Fix i18n supports in commom

I checked all the files in openstackclient/common
and fixed the missing i18n supprots.

Change-Id: Id7f76a24aae663f5832ef9bcf1bd5a6b7081af24
Partial-bug: #1574965
---
 openstackclient/common/availability_zone.py |  9 ++--
 openstackclient/common/configuration.py     |  5 +-
 openstackclient/common/extension.py         | 16 +++++--
 openstackclient/common/limits.py            | 18 ++++---
 openstackclient/common/module.py            |  3 +-
 openstackclient/common/parseractions.py     | 14 +++---
 openstackclient/common/quota.py             | 15 +++---
 openstackclient/common/utils.py             | 53 +++++++++++++--------
 8 files changed, 83 insertions(+), 50 deletions(-)

diff --git a/openstackclient/common/availability_zone.py b/openstackclient/common/availability_zone.py
index 3b0270ad7f..df30313741 100644
--- a/openstackclient/common/availability_zone.py
+++ b/openstackclient/common/availability_zone.py
@@ -92,17 +92,20 @@ class ListAvailabilityZone(command.Lister):
             '--compute',
             action='store_true',
             default=False,
-            help='List compute availability zones')
+            help=_('List compute availability zones'),
+        )
         parser.add_argument(
             '--network',
             action='store_true',
             default=False,
-            help='List network availability zones')
+            help=_('List network availability zones'),
+        )
         parser.add_argument(
             '--volume',
             action='store_true',
             default=False,
-            help='List volume availability zones')
+            help=_('List volume availability zones'),
+        )
         parser.add_argument(
             '--long',
             action='store_true',
diff --git a/openstackclient/common/configuration.py b/openstackclient/common/configuration.py
index a70e4d1436..ba4de12d81 100644
--- a/openstackclient/common/configuration.py
+++ b/openstackclient/common/configuration.py
@@ -16,6 +16,7 @@
 import six
 
 from openstackclient.common import command
+from openstackclient.i18n import _
 
 REDACTED = "<redacted>"
 
@@ -31,13 +32,13 @@ class ShowConfiguration(command.ShowOne):
             dest="mask",
             action="store_true",
             default=True,
-            help="Attempt to mask passwords (default)",
+            help=_("Attempt to mask passwords (default)"),
         )
         mask_group.add_argument(
             "--unmask",
             dest="mask",
             action="store_false",
-            help="Show password in clear text",
+            help=_("Show password in clear text"),
         )
         return parser
 
diff --git a/openstackclient/common/extension.py b/openstackclient/common/extension.py
index 8b556b4cb2..ab46e7d8b0 100644
--- a/openstackclient/common/extension.py
+++ b/openstackclient/common/extension.py
@@ -19,6 +19,7 @@ import itertools
 
 from openstackclient.common import command
 from openstackclient.common import utils
+from openstackclient.i18n import _
 
 
 class ListExtension(command.Lister):
@@ -30,27 +31,32 @@ class ListExtension(command.Lister):
             '--compute',
             action='store_true',
             default=False,
-            help='List extensions for the Compute API')
+            help=_('List extensions for the Compute API'),
+        )
         parser.add_argument(
             '--identity',
             action='store_true',
             default=False,
-            help='List extensions for the Identity API')
+            help=_('List extensions for the Identity API'),
+        )
         parser.add_argument(
             '--network',
             action='store_true',
             default=False,
-            help='List extensions for the Network API')
+            help=_('List extensions for the Network API'),
+        )
         parser.add_argument(
             '--volume',
             action='store_true',
             default=False,
-            help='List extensions for the Block Storage API')
+            help=_('List extensions for the Block Storage API'),
+        )
         parser.add_argument(
             '--long',
             action='store_true',
             default=False,
-            help='List additional fields in output')
+            help=_('List additional fields in output'),
+        )
         return parser
 
     def take_action(self, parsed_args):
diff --git a/openstackclient/common/limits.py b/openstackclient/common/limits.py
index 1f87abf3de..939b9efb3e 100644
--- a/openstackclient/common/limits.py
+++ b/openstackclient/common/limits.py
@@ -19,6 +19,7 @@ import itertools
 
 from openstackclient.common import command
 from openstackclient.common import utils
+from openstackclient.i18n import _
 from openstackclient.identity import common as identity_common
 
 
@@ -33,30 +34,33 @@ class ShowLimits(command.Lister):
             dest="is_absolute",
             action="store_true",
             default=False,
-            help="Show absolute limits")
+            help=_("Show absolute limits"),
+        )
         type_group.add_argument(
             "--rate",
             dest="is_rate",
             action="store_true",
             default=False,
-            help="Show rate limits")
+            help=_("Show rate limits"),
+        )
         parser.add_argument(
             "--reserved",
             dest="is_reserved",
             action="store_true",
             default=False,
-            help="Include reservations count [only valid with --absolute]")
+            help=_("Include reservations count [only valid with --absolute]"),
+        )
         parser.add_argument(
             '--project',
             metavar='<project>',
-            help='Show limits for a specific project (name or ID)'
-                 ' [only valid with --absolute]',
+            help=_('Show limits for a specific project (name or ID)'
+                   ' [only valid with --absolute]'),
         )
         parser.add_argument(
             '--domain',
             metavar='<domain>',
-            help='Domain the project belongs to (name or ID)'
-                 ' [only valid with --absolute]',
+            help=_('Domain the project belongs to (name or ID)'
+                   ' [only valid with --absolute]'),
         )
         return parser
 
diff --git a/openstackclient/common/module.py b/openstackclient/common/module.py
index 30c67c683f..11895f7aca 100644
--- a/openstackclient/common/module.py
+++ b/openstackclient/common/module.py
@@ -20,6 +20,7 @@ import sys
 
 from openstackclient.common import command
 from openstackclient.common import utils
+from openstackclient.i18n import _
 
 
 class ListCommand(command.Lister):
@@ -61,7 +62,7 @@ class ListModule(command.ShowOne):
             '--all',
             action='store_true',
             default=False,
-            help='Show all modules that have version information',
+            help=_('Show all modules that have version information'),
         )
         return parser
 
diff --git a/openstackclient/common/parseractions.py b/openstackclient/common/parseractions.py
index 77798f9024..c535b4f352 100644
--- a/openstackclient/common/parseractions.py
+++ b/openstackclient/common/parseractions.py
@@ -87,8 +87,8 @@ class MultiKeyValueAction(argparse.Action):
             if '=' in kv:
                 params.update([kv.split('=', 1)])
             else:
-                msg = ("Expected key=value pairs separated by comma, "
-                       "but got: %s" % (str(kv)))
+                msg = _("Expected key=value pairs separated by comma, "
+                        "but got: %s") % (str(kv))
                 raise argparse.ArgumentTypeError(msg)
 
         # Check key validation
@@ -139,12 +139,13 @@ class RangeAction(argparse.Action):
             if int(range[0]) <= int(range[1]):
                 setattr(namespace, self.dest, (int(range[0]), int(range[1])))
             else:
-                msg = "Invalid range, %s is not less than %s" % \
-                    (range[0], range[1])
+                msg = (_("Invalid range, %(range0)s is not "
+                         "less than %(range1)s")
+                       % {'range0': range[0], 'range1': range[1]})
                 raise argparse.ArgumentError(self, msg)
         else:
             # Too many values
-            msg = "Invalid range, too many values"
+            msg = _("Invalid range, too many values")
             raise argparse.ArgumentError(self, msg)
 
 
@@ -158,5 +159,6 @@ class NonNegativeAction(argparse.Action):
         if int(values) >= 0:
             setattr(namespace, self.dest, values)
         else:
-            msg = "%s expected a non-negative integer" % (str(option_string))
+            msg = (_("%s expected a non-negative integer")
+                   % (str(option_string)))
             raise argparse.ArgumentTypeError(msg)
diff --git a/openstackclient/common/quota.py b/openstackclient/common/quota.py
index f85d550b78..67e442b324 100644
--- a/openstackclient/common/quota.py
+++ b/openstackclient/common/quota.py
@@ -21,6 +21,7 @@ import sys
 
 from openstackclient.common import command
 from openstackclient.common import utils
+from openstackclient.i18n import _
 
 
 # List the quota items, map the internal argument name to the option
@@ -84,14 +85,14 @@ class SetQuota(command.Command):
         parser.add_argument(
             'project',
             metavar='<project/class>',
-            help='Set quotas for this project or class (name/ID)',
+            help=_('Set quotas for this project or class (name/ID)'),
         )
         parser.add_argument(
             '--class',
             dest='quota_class',
             action='store_true',
             default=False,
-            help='Set quotas for <class>',
+            help=_('Set quotas for <class>'),
         )
         for k, v in self._build_options_list():
             parser.add_argument(
@@ -99,12 +100,12 @@ class SetQuota(command.Command):
                 metavar='<%s>' % v,
                 dest=k,
                 type=int,
-                help='New value for the %s quota' % v,
+                help=_('New value for the %s quota') % v,
             )
         parser.add_argument(
             '--volume-type',
             metavar='<volume-type>',
-            help='Set quotas for a specific <volume-type>',
+            help=_('Set quotas for a specific <volume-type>'),
         )
         return parser
 
@@ -187,7 +188,7 @@ class ShowQuota(command.ShowOne):
             'project',
             metavar='<project/class>',
             nargs='?',
-            help='Show quotas for this project or class (name or ID)',
+            help=_('Show quotas for this project or class (name or ID)'),
         )
         type_group = parser.add_mutually_exclusive_group()
         type_group.add_argument(
@@ -195,14 +196,14 @@ class ShowQuota(command.ShowOne):
             dest='quota_class',
             action='store_true',
             default=False,
-            help='Show quotas for <class>',
+            help=_('Show quotas for <class>'),
         )
         type_group.add_argument(
             '--default',
             dest='default',
             action='store_true',
             default=False,
-            help='Show default quotas for <project>'
+            help=_('Show default quotas for <project>')
         )
         return parser
 
diff --git a/openstackclient/common/utils.py b/openstackclient/common/utils.py
index daa65c25fc..5e058547b4 100644
--- a/openstackclient/common/utils.py
+++ b/openstackclient/common/utils.py
@@ -24,6 +24,7 @@ import time
 from oslo_utils import importutils
 
 from openstackclient.common import exceptions
+from openstackclient.i18n import _
 
 
 def find_resource(manager, name_or_id, **kwargs):
@@ -90,13 +91,19 @@ def find_resource(manager, name_or_id, **kwargs):
     #                 of client exceptions.
     except Exception as ex:
         if type(ex).__name__ == 'NotFound':
-            msg = "No %s with a name or ID of '%s' exists." % \
-                (manager.resource_class.__name__.lower(), name_or_id)
-            raise exceptions.CommandError(msg)
+            msg = _("No %(resource)s with a name or ID "
+                    "of '%(name_or_id)s' exists.")
+            raise exceptions.CommandError(
+                msg % {'resource': manager.resource_class.__name__.lower(),
+                       'name_or_id': name_or_id}
+            )
         if type(ex).__name__ == 'NoUniqueMatch':
-            msg = "More than one %s exists with the name '%s'." % \
-                (manager.resource_class.__name__.lower(), name_or_id)
-            raise exceptions.CommandError(msg)
+            msg = _("More than one %(resource)s exists with "
+                    "the name '%(name_or_id)s'.")
+            raise exceptions.CommandError(
+                msg % {'resource': manager.resource_class.__name__.lower(),
+                       'name_or_id': name_or_id}
+            )
         else:
             pass
 
@@ -107,7 +114,7 @@ def find_resource(manager, name_or_id, **kwargs):
             return resource
     else:
         # we found no match, report back this error:
-        msg = "Could not find resource %s" % name_or_id
+        msg = _("Could not find resource %s") % name_or_id
         raise exceptions.CommandError(msg)
 
 
@@ -152,7 +159,7 @@ def get_field(item, field):
         else:
             return getattr(item, field)
     except Exception:
-        msg = "Resource doesn't have field %s" % field
+        msg = _("Resource doesn't have field %s") % field
         raise exceptions.CommandError(msg)
 
 
@@ -234,14 +241,17 @@ def sort_items(items, sort_str):
         if ':' in sort_key:
             sort_key, direction = sort_key.split(':', 1)
             if not sort_key:
-                msg = "empty string is not a valid sort key"
+                msg = _("empty string is not a valid sort key")
                 raise exceptions.CommandError(msg)
             if direction not in ['asc', 'desc']:
                 if not direction:
                     direction = "empty string"
-                msg = ("%s is not a valid sort direction for sort key %s, "
-                       "use asc or desc instead" % (direction, sort_key))
-                raise exceptions.CommandError(msg)
+                msg = _("%(direction)s is not a valid sort direction for "
+                        "sort key %(sort_key)s, use asc or desc instead")
+                raise exceptions.CommandError(
+                    msg % {'direction': direction,
+                           'sort_key': sort_key}
+                )
             if direction == 'desc':
                 reverse = True
         items.sort(key=lambda item: get_field(item, sort_key),
@@ -273,9 +283,13 @@ def get_client_class(api_name, version, version_map):
     try:
         client_path = version_map[str(version)]
     except (KeyError, ValueError):
-        msg = "Invalid %s client version '%s'. must be one of: %s" % (
-              (api_name, version, ', '.join(list(version_map.keys()))))
-        raise exceptions.UnsupportedVersion(msg)
+        msg = _("Invalid %(api_name)s client version '%(version)s'. "
+                "must be one of: %(version_map)s")
+        raise exceptions.UnsupportedVersion(
+            msg % {'api_name': api_name,
+                   'version': version,
+                   'version_map': ', '.join(list(version_map.keys()))}
+        )
 
     return importutils.import_class(client_path)
 
@@ -391,9 +405,10 @@ def get_password(stdin, prompt=None, confirm=True):
                     return first_pass
                 print("The passwords entered were not the same")
         except EOFError:  # Ctl-D
-            raise exceptions.CommandError("Error reading password.")
-    raise exceptions.CommandError("There was a request to be prompted for a"
-                                  " password and a terminal was not detected.")
+            raise exceptions.CommandError(_("Error reading password."))
+    raise exceptions.CommandError(_("There was a request to be prompted "
+                                    "for a password and a terminal was "
+                                    "not detected."))
 
 
 def read_blob_file_contents(blob_file):
@@ -402,7 +417,7 @@ def read_blob_file_contents(blob_file):
             blob = file.read().strip()
         return blob
     except IOError:
-        msg = "Error occurred trying to read from file %s"
+        msg = _("Error occurred trying to read from file %s")
         raise exceptions.CommandError(msg % blob_file)