]> Frank Brehm's Git Trees - pixelpark/pp-admin-tools.git/commitdiff
Reorganizing argparse actions.
authorFrank Brehm <frank.brehm@pixelpark.com>
Tue, 30 Jan 2024 12:17:08 +0000 (13:17 +0100)
committerFrank Brehm <frank.brehm@pixelpark.com>
Tue, 30 Jan 2024 12:17:08 +0000 (13:17 +0100)
lib/pp_admintools/app/ldap.py
lib/pp_admintools/argparse_actions.py

index 220d0d1dd839c286d57d076b9026c9ce154e0be0..50d8c14d11164dc42461e9ef38fc20fb3d9534b6 100644 (file)
@@ -9,7 +9,6 @@
 from __future__ import absolute_import
 
 # Standard modules
-import argparse
 import logging
 import os
 import re
@@ -44,9 +43,11 @@ from ldap3.core.exceptions import LDAPSocketReceiveError
 
 # Own modules
 from . import BaseDPXApplication
-from .. import DEFAULT_CONFIG_DIR, MAX_PORT_NUMBER
+from .. import DEFAULT_CONFIG_DIR
 from .. import __version__ as GLOBAL_VERSION
 from .. import pp
+from ..argparse_actions import LdapPortOptionAction
+from ..argparse_actions import PasswordFileOptionAction
 from ..config.ldap import DEFAULT_TIMEOUT
 from ..config.ldap import LdapConfiguration, LdapConnectionInfo
 # from ..errors import DpxAppError
@@ -58,80 +59,13 @@ from ..errors import DpxLdapSessionError
 from ..errors import DpxWriteLdapItemError
 from ..xlate import XLATOR, format_list
 
-__version__ = '1.0.1'
+__version__ = '1.1.0'
 LOG = logging.getLogger(__name__)
 
 _ = XLATOR.gettext
 ngettext = XLATOR.ngettext
 
 
-# =============================================================================
-class PasswordFileOptionAction(argparse.Action):
-    """Argparse action for a password file."""
-
-    # -------------------------------------------------------------------------
-    def __init__(self, option_strings, must_exists=True, must_absolute=True, *args, **kwargs):
-        """Construct the action object."""
-        self.must_exists = bool(must_exists)
-        self.must_absolute = bool(must_absolute)
-
-        super(PasswordFileOptionAction, self).__init__(
-            option_strings=option_strings, *args, **kwargs)
-
-    # -------------------------------------------------------------------------
-    def __call__(self, parser, namespace, given_path, option_string=None):
-        """Call the option action."""
-        path = Path(given_path)
-        if self.must_absolute:
-            if not path.is_absolute():
-                msg = _('The path {!r} must be an absolute path.').format(given_path)
-                raise argparse.ArgumentError(self, msg)
-
-        if self.must_exists:
-
-            if not path.exists():
-                msg = _('The file {!r} does not exists.').format(str(path))
-                raise argparse.ArgumentError(self, msg)
-
-            if not path.is_file():
-                msg = _('The given path {!r} exists, but is not a regular file.').format(str(path))
-                raise argparse.ArgumentError(self, msg)
-
-            if not os.access(str(path), os.R_OK):
-                msg = _('The given file {!r} is not readable.').format(str(path))
-                raise argparse.ArgumentError(self, msg)
-
-        setattr(namespace, self.dest, path)
-
-
-# =============================================================================
-class LdapPortOptionAction(argparse.Action):
-    """Argparse action for the LDAP TCP (UDP?) port."""
-
-    # -------------------------------------------------------------------------
-    def __init__(self, option_strings, *args, **kwargs):
-        """Construct the action object."""
-        super(LdapPortOptionAction, self).__init__(
-            option_strings=option_strings, *args, **kwargs)
-
-    # -------------------------------------------------------------------------
-    def __call__(self, parser, namespace, given_port, option_string=None):
-        """Call the option action."""
-        try:
-            port = int(given_port)
-            if port <= 0 or port > MAX_PORT_NUMBER:
-                msg = _(
-                    'a port number must be greater than zero and less '
-                    'or equal to {}.').format(MAX_PORT_NUMBER)
-                raise ValueError(msg)
-        except (ValueError, TypeError) as e:
-            msg = _('Wrong port number {!r}:').format(given_port)
-            msg += ' ' + str(e)
-            raise argparse.ArgumentError(self, msg)
-
-        setattr(namespace, self.dest, port)
-
-
 # =============================================================================
 class BaseLdapApplication(BaseDPXApplication):
     """Base class for all application classes using LDAP."""
@@ -283,7 +217,7 @@ class BaseLdapApplication(BaseDPXApplication):
     # -----------------------------------------------------------
     @property
     def wait_on_read_error(self):
-        """The time in seconds to wait after a unseccessful read for the next try."""
+        """Return the time in seconds to wait after a unseccessful read for the next try."""
         return self._wait_on_read_error
 
     @wait_on_read_error.setter
index 3e8d739aa8a6e84ed876dfbb4d2368a4ba71bc43..49f922d0c8030151cf632ad5fd34d7118c58b637 100644 (file)
@@ -11,12 +11,17 @@ from __future__ import absolute_import
 # Standard modules
 import argparse
 import logging
+import os
+try:
+    from pathlib import Path
+except ImportError:
+    from pathlib2 import Path
 
 # Own modules
 from . import MAX_PORT_NUMBER
 from .xlate import XLATOR
 
-__version__ = '0.3.2'
+__version__ = '0.4.0'
 LOG = logging.getLogger(__name__)
 
 _ = XLATOR.gettext
@@ -160,6 +165,73 @@ class LimitedFloatOptionAction(argparse.Action):
         setattr(namespace, self.dest, val)
 
 
+# =============================================================================
+class PasswordFileOptionAction(argparse.Action):
+    """Argparse action for a password file."""
+
+    # -------------------------------------------------------------------------
+    def __init__(self, option_strings, must_exists=True, must_absolute=True, *args, **kwargs):
+        """Construct the action object."""
+        self.must_exists = bool(must_exists)
+        self.must_absolute = bool(must_absolute)
+
+        super(PasswordFileOptionAction, self).__init__(
+            option_strings=option_strings, *args, **kwargs)
+
+    # -------------------------------------------------------------------------
+    def __call__(self, parser, namespace, given_path, option_string=None):
+        """Call the option action."""
+        path = Path(given_path)
+        if self.must_absolute:
+            if not path.is_absolute():
+                msg = _('The path {!r} must be an absolute path.').format(given_path)
+                raise argparse.ArgumentError(self, msg)
+
+        if self.must_exists:
+
+            if not path.exists():
+                msg = _('The file {!r} does not exists.').format(str(path))
+                raise argparse.ArgumentError(self, msg)
+
+            if not path.is_file():
+                msg = _('The given path {!r} exists, but is not a regular file.').format(str(path))
+                raise argparse.ArgumentError(self, msg)
+
+            if not os.access(str(path), os.R_OK):
+                msg = _('The given file {!r} is not readable.').format(str(path))
+                raise argparse.ArgumentError(self, msg)
+
+        setattr(namespace, self.dest, path)
+
+
+# =============================================================================
+class LdapPortOptionAction(argparse.Action):
+    """Argparse action for the LDAP TCP (UDP?) port."""
+
+    # -------------------------------------------------------------------------
+    def __init__(self, option_strings, *args, **kwargs):
+        """Construct the action object."""
+        super(LdapPortOptionAction, self).__init__(
+            option_strings=option_strings, *args, **kwargs)
+
+    # -------------------------------------------------------------------------
+    def __call__(self, parser, namespace, given_port, option_string=None):
+        """Call the option action."""
+        try:
+            port = int(given_port)
+            if port <= 0 or port > MAX_PORT_NUMBER:
+                msg = _(
+                    'a port number must be greater than zero and less '
+                    'or equal to {}.').format(MAX_PORT_NUMBER)
+                raise ValueError(msg)
+        except (ValueError, TypeError) as e:
+            msg = _('Wrong port number {!r}:').format(given_port)
+            msg += ' ' + str(e)
+            raise argparse.ArgumentError(self, msg)
+
+        setattr(namespace, self.dest, port)
+
+
 # =============================================================================
 if __name__ == '__main__':