--- /dev/null
+# -*- coding: utf-8 -*-
+"""
+@author: Frank Brehm
+@contact: frank.brehm@pixelpark.com
+@copyright: © 2022 by Frank Brehm, Berlin
+@summary: A module containing some useful argparse actions.
+"""
+from __future__ import absolute_import
+
+# Standard modules
+import logging
+import argparse
+
+# Own modules
+from . import MAX_PORT_NUMBER, MAX_TIMEOUT
+
+from .xlate import XLATOR
+
+__version__ = '0.1.0'
+LOG = logging.getLogger(__name__)
+
+_ = XLATOR.gettext
+
+
+# =============================================================================
+class PortOptionAction(argparse.Action):
+
+ # -------------------------------------------------------------------------
+ def __init__(self, option_strings, what, *args, **kwargs):
+
+ self.what = what
+
+ super(PortOptionAction, self).__init__(option_strings=option_strings, *args, **kwargs)
+
+ # -------------------------------------------------------------------------
+ def __call__(self, parser, namespace, values, option_string=None):
+
+ if values is None:
+ setattr(namespace, self.dest, None)
+ return
+
+ try:
+ port = int(values)
+ except (ValueError, TypeError) as e:
+ msg = _("Value {v!r} for a {what} port is invalid:").format(v=values, what=what)
+ raise argparse.ArgumentError(self, msg)
+
+ if port <= 0 or port > MAX_PORT_NUMBER:
+ msg = _("Value {v!r} for a {what} port must be greater than 0 and less than {max}.")
+ msg = msg.format(v=values, what=what, max=(MAX_PORT_NUMBER + 1))
+ raise argparse.ArgumentError(self, msg)
+
+ setattr(namespace, self.dest, port)
+
+
+# =============================================================================
+class TimeoutOptionAction(argparse.Action):
+
+ # -------------------------------------------------------------------------
+ def __init__(self, option_strings, what, *args, **kwargs):
+
+ self.what = what
+
+ super(TimeoutOptionAction, self).__init__(option_strings=option_strings, *args, **kwargs)
+
+ # -------------------------------------------------------------------------
+ def __call__(self, parser, namespace, values, option_string=None):
+
+ if values is None:
+ setattr(namespace, self.dest, None)
+ return
+
+ try:
+ timeout = int(values)
+ except (ValueError, TypeError) as e:
+ msg = _("Value {v!r} for a timeout of {what} is invalid:").format(v=values, what=what)
+ raise argparse.ArgumentError(self, msg)
+
+ if port <= 0 or port > MAX_TIMEOUT:
+ msg = _(
+ "Value {v!r} for a timeout of {what} must be greater than 0 and less than {max}.")
+ msg = msg.format(v=values, what=what, max=(MAX_TIMEOUT + 1))
+ raise argparse.ArgumentError(self, msg)
+
+ setattr(namespace, self.dest, port)
+
+
+# =============================================================================
+if __name__ == "__main__":
+
+ pass
+
+# =============================================================================
+
+# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 list