]> Frank Brehm's Git Trees - pixelpark/pp-admin-tools.git/commitdiff
Adding translation markers to lib/pp_admintools/cfg_app.py
authorFrank Brehm <frank@brehm-online.com>
Fri, 26 Nov 2021 10:44:30 +0000 (11:44 +0100)
committerFrank Brehm <frank@brehm-online.com>
Fri, 26 Nov 2021 10:44:39 +0000 (11:44 +0100)
lib/pp_admintools/cfg_app.py

index 4b6eb4a6fcf32936b3254f19ef71f140af897d77..0e22d731db7e77a9ba321a101aa67a976fd8e81a 100644 (file)
@@ -49,11 +49,15 @@ from .merge import merge_structure
 
 from .mailaddress import MailAddress
 
-__version__ = '0.9.0'
+from .xlate import XLATOR
+
+__version__ = '0.9.1'
 LOG = logging.getLogger(__name__)
 
 VALID_MAIL_METHODS = ('smtp', 'sendmail')
 
+_ = XLATOR.gettext
+
 
 # =============================================================================
 class PpCfgAppError(PpAppError):
@@ -73,12 +77,12 @@ class PpConfigApplication(BaseApplication):
         'frank.brehm@pixelpark.com'
     ]
     default_mail_cc = [
-        'thomas.kotschok@pixelpark.com',
+        'thomas.dalichow@pixelpark.com',
     ]
 
-    default_reply_to = 'frank.brehm@pixelpark.com'
+    default_reply_to = 'solution@pixelpark.com'
 
-    default_mail_server = 'mx.pixelpark.net'
+    default_mail_server = 'mx.pixelpark.com'
 
     current_user_name = pwd.getpwuid(os.getuid()).pw_name
     current_user_gecos = pwd.getpwuid(os.getuid()).pw_gecos
@@ -136,13 +140,13 @@ class PpConfigApplication(BaseApplication):
                 for stem in cfg_stems:
                     s = str(stem).strip()
                     if not s:
-                        msg = "Invalid configuration stem {!r} given.".format(stem)
+                        msg = _("Invalid configuration stem {!r} given.").format(stem)
                         raise PpCfgAppError(msg)
                     self.cfg_stems.append(s)
             else:
                 s = str(cfg_stems).strip()
                 if not s:
-                    msg = "Invalid configuration stem {!r} given.".format(cfg_stems)
+                    msg = _("Invalid configuration stem {!r} given.").format(cfg_stems)
                     raise PpCfgAppError(msg)
                 self.cfg_stems.append(s)
         else:
@@ -183,7 +187,7 @@ class PpConfigApplication(BaseApplication):
         try:
             codec = codecs.lookup(value)
         except Exception as e:
-            msg = "{c} on setting encoding {v!r}: {e}".format(
+            msg = _("{c} on setting encoding {v!r}: {e}").format(
                 c=e.__class__.__name__, v=value, e=e)
             LOG.error(msg)
         else:
@@ -237,40 +241,40 @@ class PpConfigApplication(BaseApplication):
         methods in descendant classes.
         """
 
-        mail_group = self.arg_parser.add_argument_group('Mailing options')
+        mail_group = self.arg_parser.add_argument_group(_('Mailing options'))
 
         mail_group.add_argument(
             '--recipients', '--mail-recipients',
-            metavar="ADDRESS", nargs='+', dest="mail_recipients",
-            help="Mail addresses of all recipients for mails generated by this script."
+            metavar=_("ADDRESS"), nargs='+', dest="mail_recipients",
+            help=_("Mail addresses of all recipients for mails generated by this script.")
         )
 
         mail_group.add_argument(
             '--cc', '--mail-cc',
-            metavar="ADDRESS", nargs='*', dest="mail_cc",
-            help="Mail addresses of all CC recipients for mails generated by this script."
+            metavar=_("ADDRESS"), nargs='*', dest="mail_cc",
+            help=_("Mail addresses of all CC recipients for mails generated by this script.")
         )
 
         mail_group.add_argument(
             '--reply-to', '--mail-reply-to',
-            metavar="ADDRESS", dest="mail_reply_to",
-            help="Reply mail address for mails generated by this script."
+            metavar=_("ADDRESS"), dest="mail_reply_to",
+            help=_("Reply mail address for mails generated by this script.")
         )
 
         mail_group.add_argument(
             '--mail-method',
-            metavar="METHOD", choices=VALID_MAIL_METHODS, dest="mail_method",
-            help=(
+            metavar=_("METHOD"), choices=VALID_MAIL_METHODS, dest="mail_method",
+            help=_(
                 "Method for sending the mails generated by this script. "
-                "Valid values: {v}, default: {d!r}.".format(
+                "Valid values: {v}, default: {d!r}.").format(
                     v=', '.join(map(lambda x: repr(x), VALID_MAIL_METHODS)),
-                    d=self.mail_method))
+                    d=self.mail_method)
         )
 
         mail_group.add_argument(
             '--mail-server',
-            metavar="SERVER", dest="mail_server",
-            help=(
+            metavar=_("SERVER"), dest="mail_server",
+            help=_(
                 "Mail server for submitting generated by this script if "
                 "the mail method of this script is 'smtp'. Default: {!r}.").format(
                 self.mail_server)
@@ -278,33 +282,34 @@ class PpConfigApplication(BaseApplication):
 
         mail_group.add_argument(
             '--smtp-port',
-            metavar="PORT", type=int, dest='smtp_port',
-            help=(
+            metavar=_("PORT"), type=int, dest='smtp_port',
+            help=_(
                 "The port to use for submitting generated by this script if "
-                "the mail method of this script is 'smtp'. Default: {}.".format(self.smtp_port))
+                "the mail method of this script is 'smtp'. Default: {}.").format(self.smtp_port)
         )
 
-        cfgfile_group = self.arg_parser.add_argument_group('Config file options')
+        cfgfile_group = self.arg_parser.add_argument_group(_('Config file options'))
 
         cfgfile_group.add_argument(
             "-C", "--cfgfile", "--cfg-file", "--config",
-            metavar="FILE", nargs='+', dest="cfg_file",
-            help="Configuration files to use additional to the standard configuration files.",
+            metavar=_("FILE"), nargs='+', dest="cfg_file",
+            help=_("Configuration files to use additional to the standard configuration files."),
         )
 
+        reference = (
+            'https://docs.python.org/3/library/logging.config.html#logging-config-dictschema')
         cfgfile_group.add_argument(
             "--log-cfgfile",
-            metavar="FILE", dest="log_cfgfile",
-            help=(
+            metavar=_("FILE"), dest="log_cfgfile",
+            help=_(
                 "Configuration file for logging in JSON format. "
-                "See https://docs.python.org/3/library/logging.config.html"
-                "#logging-config-dictschema how the structures has to be defined.")
+                "See {!r} how the structures has to be defined.").format(reference),
         )
 
         cfgfile_group.add_argument(
             "--cfg-encoding",
-            metavar="ENCODING", dest="cfg_encoding", default=self.cfg_encoding,
-            help=(
+            metavar=_("ENCODING"), dest="cfg_encoding", default=self.cfg_encoding,
+            help=_(
                 "The encoding character set of the configuration files "
                 "(default: %(default)r)."),
         )
@@ -337,7 +342,7 @@ class PpConfigApplication(BaseApplication):
         work_dir = os.path.abspath(os.path.join(mod_dir, '..'))
         work_etc_dir = os.path.join(work_dir, 'etc')
         if self.verbose > 1:
-            LOG.debug("Searching for {!r} ...".format(work_etc_dir))
+            LOG.debug(_("Searching for {!r} ...").format(work_etc_dir))
         for cfg_basename in cfg_basenames:
             self.cfg_files.append(os.path.join(work_etc_dir, cfg_basename))
 
@@ -383,7 +388,7 @@ class PpConfigApplication(BaseApplication):
         work_dir = os.path.abspath(os.path.join(mod_dir, '..'))
         work_etc_dir = os.path.join(work_dir, 'etc')
         if self.verbose > 1:
-            LOG.debug("Searching for {!r} ...".format(work_etc_dir))
+            LOG.debug(_("Searching for {!r} ...").format(work_etc_dir))
         self.log_cfg_files.append(os.path.join(work_etc_dir, cfg_basename))
 
         # add $HOME/.config/app.ini
@@ -403,7 +408,7 @@ class PpConfigApplication(BaseApplication):
             self.log_cfg_files.append(cmdline_cfg)
 
         if self.verbose > 1:
-            LOG.debug("Log config files:\n{}".format(pp(self.log_cfg_files)))
+            LOG.debug(_("Log config files:") + '\n' + pp(self.log_cfg_files))
 
     # -------------------------------------------------------------------------
     def _init_logging_from_jsonfile(self):
@@ -417,20 +422,20 @@ class PpConfigApplication(BaseApplication):
         for cfg_file in reversed(self.log_cfg_files):
 
             if self.verbose > 1:
-                LOG.debug("Searching for {!r} ...".format(cfg_file))
+                LOG.debug(_("Searching for {!r} ...").format(cfg_file))
 
             if not os.path.exists(cfg_file):
                 continue
             if not os.path.isfile(cfg_file):
                 continue
             if not os.access(cfg_file, os.R_OK):
-                msg = "No read access to {!r}.".format(cfg_file)
+                msg = _("No read access to {!r}.").format(cfg_file)
                 self.handle_error(msg, "File error")
                 continue
 
             log_cfg = None
             if self.verbose > 1:
-                LOG.debug("Reading and evaluating {!r} ...".format(cfg_file))
+                LOG.debug(_("Reading and evaluating {!r} ...").format(cfg_file))
             with open(cfg_file, 'r', **open_opts) as fh:
                 try:
                     log_cfg = json.load(fh)
@@ -446,11 +451,11 @@ class PpConfigApplication(BaseApplication):
                         handler = log_cfg['handlers'][handler_name]
                         handler['level'] = 'DEBUG'
             if self.verbose > 1:
-                LOG.debug("Evaluated configuration from JSON:\n{} ...".format(pp(log_cfg)))
+                LOG.debug(_("Evaluated configuration from JSON:") + '\n' + pp(log_cfg))
             try:
                 logging.config.dictConfig(log_cfg)
             except Exception as e:
-                msg = "Wrong file {!r} - ".format(cfg_file) + str(e)
+                msg = _("Wrong file {!r} - ").format(cfg_file) + str(e)
                 self.handle_error(msg, e.__class__.__name__)
                 continue
             found = True
@@ -492,13 +497,13 @@ class PpConfigApplication(BaseApplication):
 
         for cfg_file in self.cfg_files:
             if self.verbose > 2:
-                LOG.debug("Searching for {!r} ...".format(cfg_file))
+                LOG.debug(_("Searching for {!r} ...").format(cfg_file))
             if not os.path.isfile(cfg_file):
                 if self.verbose > 3:
-                    LOG.debug("Config file {!r} not found.".format(cfg_file))
+                    LOG.debug(_("Config file {!r} not found.").format(cfg_file))
                 continue
             if self.verbose > 1:
-                LOG.debug("Reading {!r} ...".format(cfg_file))
+                LOG.debug(_("Reading {!r} ...").format(cfg_file))
 
             config = configparser.ConfigParser()
             try:
@@ -509,9 +514,9 @@ class PpConfigApplication(BaseApplication):
                     else:
                         config.read_file(stream)
             except ConfigParseError as e:
-                msg = "Wrong configuration in {!r} found: ".format(cfg_file)
+                msg = _("Wrong configuration in {!r} found: ").format(cfg_file)
                 msg += str(e)
-                self.handle_error(msg, "Configuration error")
+                self.handle_error(msg, _("Configuration error"))
                 continue
 
             cfg = {}
@@ -522,12 +527,11 @@ class PpConfigApplication(BaseApplication):
                     k = key.lower()
                     cfg[section][k] = value
             if self.verbose > 2:
-                LOG.debug("Evaluated config from {f!r}:\n{c}".format(
-                    f=cfg_file, c=pp(cfg)))
+                LOG.debug(_("Evaluated config from {!r}:").format(cfg_file) + '\n' + pp(cfg))
             self.cfg = merge_structure(self.cfg, cfg)
 
         if self.verbose > 1:
-            LOG.debug("Evaluated config total:\n{}".format(pp(self.cfg)))
+            LOG.debug(_("Evaluated config total:") + '\n' + pp(self.cfg))
 
     # -------------------------------------------------------------------------
     def _perform_config(self):
@@ -550,18 +554,18 @@ class PpConfigApplication(BaseApplication):
         self._perform_mail_cmdline_options()
 
         if self.config_has_errors:
-            LOG.error("There are errors in configuration.")
+            LOG.error(_("There are errors in configuration."))
             self.exit(1)
         else:
-            LOG.debug("There are no errors in configuration.")
+            LOG.debug(_("There are no errors in configuration."))
             self.config_has_errors = False
 
     # -------------------------------------------------------------------------
     def _perform_config_general(self, section, section_name):
 
         if self.verbose > 2:
-            LOG.debug("Evaluating config section {n!r}:\n{s}".format(
-                n=section_name, s=pp(section)))
+            LOG.debug(
+                _("Evaluating config section {!r}:").format(section_name) + '\n' + pp(section))
 
         if 'verbose' in section:
             v = section['verbose']
@@ -583,8 +587,8 @@ class PpConfigApplication(BaseApplication):
     def _perform_config_mail(self, section, section_name):
 
         if self.verbose > 2:
-            LOG.debug("Evaluating config section {n!r}:\n{s}".format(
-                n=section_name, s=pp(section)))
+            LOG.debug(
+                _("Evaluating config section {!r}:").format(section_name) + '\n' + pp(section))
 
         self._perform_config_mail_rcpt(section, section_name)
         self._perform_config_mail_cc(section, section_name)
@@ -608,10 +612,9 @@ class PpConfigApplication(BaseApplication):
                     if token not in self.mail_recipients:
                         self.mail_recipients.append(token)
                 else:
-                    msg = (
+                    msg = _(
                         "Found invalid recipient mail address {!r} "
-                        "in configuration.").format(
-                        token)
+                        "in configuration.").format(token)
                     LOG.error(msg)
 
     # -------------------------------------------------------------------------
@@ -625,13 +628,13 @@ class PpConfigApplication(BaseApplication):
         if v:
             tokens = self.whitespace_re.split(v)
             if self.verbose > 1:
-                LOG.debug("CC addresses:\n{}".format(pp(tokens)))
+                LOG.debug(_("CC addresses:") + '\n' + pp(tokens))
             for token in tokens:
                 if MailAddress.valid_address(token):
                     if token not in self.mail_cc:
                         self.mail_cc.append(token)
                 else:
-                    msg = "Found invalid cc mail address {!r} in configuration.".format(
+                    msg = _("Found invalid cc mail address {!r} in configuration.").format(
                         token)
                     LOG.error(msg)
 
@@ -649,7 +652,7 @@ class PpConfigApplication(BaseApplication):
                 if MailAddress.valid_address(tokens[0]):
                     self.reply_to = tokens[0]
                 else:
-                    msg = "Found invalid reply mail address {!r} in configuration.".format(
+                    msg = _("Found invalid reply mail address {!r} in configuration.").format(
                         tokens[0])
                     LOG.error(msg)
 
@@ -664,7 +667,7 @@ class PpConfigApplication(BaseApplication):
             if v in VALID_MAIL_METHODS:
                 self.mail_method = v
             else:
-                msg = "Found invalid mail method {!r} in configuration.".format(
+                msg = _("Found invalid mail method {!r} in configuration.").format(
                     section['mail_method'])
                 LOG.error(msg)
 
@@ -689,11 +692,11 @@ class PpConfigApplication(BaseApplication):
         try:
             port = int(v)
         except (ValueError, TypeError):
-            msg = "Found invalid SMTP port number {!r} in configuration.".format(v)
+            msg = _("Found invalid SMTP port number {!r} in configuration.").format(v)
             LOG.error(msg)
         else:
             if port <= 0:
-                msg = "Found invalid SMTP port number {!r} in configuration.".format(port)
+                msg = _("Found invalid SMTP port number {!r} in configuration.").format(port)
                 LOG.error(msg)
             else:
                 self.smtp_port = port
@@ -716,7 +719,7 @@ class PpConfigApplication(BaseApplication):
         v = getattr(self.args, 'smtp_port', None)
         if v is not None:
             if v <= 0:
-                msg = "Got invalid SMTP port number {!r}.".format(v)
+                msg = _("Got invalid SMTP port number {!r}.").format(v)
                 LOG.error(msg)
             else:
                 self.smtp_port = v
@@ -734,10 +737,10 @@ class PpConfigApplication(BaseApplication):
                         if token not in self.mail_recipients:
                             self.mail_recipients.append(token)
                     else:
-                        msg = "Got invalid recipient mail address {!r}.".format(token)
+                        msg = _("Got invalid recipient mail address {!r}.").format(token)
                         LOG.error(msg)
         if not self.mail_recipients:
-            msg = "Did not found any valid recipient mail addresses."
+            msg = ("Did not found any valid recipient mail addresses.")
             LOG.error(msg)
 
     # -------------------------------------------------------------------------
@@ -755,7 +758,7 @@ class PpConfigApplication(BaseApplication):
                     if token not in self.mail_cc:
                         self.mail_cc.append(token)
                 else:
-                    msg = "Got invalid CC mail address {!r}.".format(token)
+                    msg = _("Got invalid CC mail address {!r}.").format(token)
                     LOG.error(msg)
 
     # -------------------------------------------------------------------------
@@ -770,7 +773,7 @@ class PpConfigApplication(BaseApplication):
             if MailAddress.valid_address(tokens[0]):
                 self.reply_to = tokens[0]
             else:
-                msg = "Got invalid reply mail address {!r}.".format(
+                msg = _("Got invalid reply mail address {!r}.").format(
                     tokens[0])
                 LOG.error(msg)
 
@@ -801,7 +804,7 @@ class PpConfigApplication(BaseApplication):
             mail['Cc'] = ', '.join(self.mail_cc)
 
         if self.verbose > 1:
-            LOG.debug("Mail to send:\n{}".format(mail.as_string(unixfrom=True)))
+            LOG.debug(_("Mail to send:") + '\n' + mail.as_string(unixfrom=True))
 
         if self.mail_method == 'smtp':
             self._send_mail_smtp(mail)
@@ -834,13 +837,13 @@ class PpConfigApplication(BaseApplication):
                 break
 
         if not sendmail:
-            msg = "Did not found sendmail executable."
+            msg = _("Did not found sendmail executable.")
             LOG.error(msg)
             return
 
         cmd = [sendmail, "-t", "-oi"]
         cmd_str = ' '.join(map(lambda x: pipes.quote(x), cmd))
-        LOG.debug("Executing: {}".format(cmd_str))
+        LOG.debug(_("Executing: {}").format(cmd_str))
 
         p = Popen(cmd, stdin=PIPE, universal_newlines=True)
         p.communicate(mail.as_string())
@@ -866,21 +869,24 @@ class PpConfigApplication(BaseApplication):
         zone_name = RE_DOT_AT_END.sub('', domain)
 
         if self.verbose > 1:
-            LOG.debug("Checking, whether {!r} is a local zone.".format(zone_name))
+            LOG.debug(_("Checking, whether {!r} is a local zone.").format(zone_name))
 
         tld = zone_name.split('.')[-1]
         if tld in ('intern', 'internal', 'local', 'localdomain', 'lokal'):
-            LOG.debug("Zone {!r} has a local TLD {!r}.".format(zone_name, tld))
+            LOG.debug(_("Zone {zone!r} has the local TLD {tld!r}.").format(
+                zone=zone_name, tld=tld))
             return True
 
         zone_base = zone_name.split('.')[0]
         if zone_base in ('intern', 'internal', 'local', 'localdomain', 'lokal'):
-            LOG.debug("Zone {!r} has a local base {!r}.".format(zone_name, tld))
+            LOG.debug(_("Zone {zone!r} has the local base name {n!r}.").format(
+                zone=zone_name, n=zone_base))
             return True
 
         if tld != 'arpa':
             if self.verbose > 2:
-                LOG.debug("Zone {!r} has a public TLD {!r}.".format(zone_name, tld))
+                LOG.debug(_("Zone {zone!r} has the public TLD {tld!r}.").format(
+                    zone=zone_name, tld=tld))
                 return False
 
         if zone_name.endswith('.in-addr.arpa'):
@@ -888,7 +894,8 @@ class PpConfigApplication(BaseApplication):
             for tupel in reversed(zone_name.replace('.in-addr.arpa', '').split('.')):
                 tupels.append(tupel)
             if self.verbose > 2:
-                LOG.debug("Got IPv4 tupels from zone {!r}: {}".format(zone_name, pp(tupels)))
+                LOG.debug(
+                    _("Got IPv4 tupels from zone {!r}:").format(zone_name) + ' ' + pp(tupels))
             bitmask = None
             if len(tupels) == 1:
                 bitmask = 8
@@ -903,27 +910,27 @@ class PpConfigApplication(BaseApplication):
                 bitmask = 24
                 tupels.append('0')
             else:
-                LOG.warn("Could not interprete reverse IPv4 zone {!r}.".format(zone_name))
+                LOG.warn(_("Could not interprete reverse IPv4 zone {!r}.").format(zone_name))
                 return False
             net_address = '.'.join(tupels) + '/{}'.format(bitmask)
             if self.verbose > 2:
-                LOG.debug(
-                    "Got IPv4 network address of zone {!r}: {!r}.".format(
-                        zone_name, net_address))
+                LOG.debug(_("Got IPv4 network address of zone {zone!r}: {nw!r}.").format(
+                    zone=zone_name, nw=net_address))
             network = ipaddress.ip_network(net_address)
             if network.is_global:
                 if self.verbose > 1:
                     LOG.debug(
-                        "The network {!r} of zone {!r} is allocated for public networks.".format(
-                            net_address, zone_name))
+                        _("The network {nw!r} of zone {zone!r} is allocated for public "
+                            "networks.").format(nw=net_address, zone=zone_name))
                 return False
-            LOG.debug("The network {!r} of zone {!r} is allocated for local networks.".format(
-                net_address, zone_name))
+            LOG.debug(_(
+                "The network {nw!r} of zone {zone!r} is allocated for local networks.").format(
+                    nw=net_address, zone=zone_name))
             return True
 
         if self.verbose > 2:
-            LOG.debug(
-                "Zone {!r} seems to be a reverse zone for a public network.".format(zone_name))
+            LOG.debug(_("Zone {!r} seems to be a reverse zone for a public network.").format(
+                zone_name))
         return False