Create argparse type "existing_dir[_empty]"
[pyi2ncommon] / src / argparse_helpers.py
index 91e64d2..93e4bad 100644 (file)
@@ -28,7 +28,7 @@ Featuring
 """
 
 from argparse import ArgumentParser, ArgumentTypeError
-from os.path import isfile
+from os.path import isfile, isdir
 
 
 class ArgParserWantsExit(Exception):
@@ -44,7 +44,7 @@ class ArgParserWantsExit(Exception):
 class NonExitingParser(ArgumentParser):
     """ArgumentParser that does not call sys.exit(2) on parse failure.
 
-    Calling sys.exit also just raises a SystemExit exception. But that is not
+    Calling `sys.exit` also just raises a SystemExit exception. But that is not
     a subclass of Exception and not as explicit and specific as this one.
 
     Convenient e.g. for global try-except blocks e.g. in a daemon::
@@ -88,3 +88,23 @@ def existing_file_or_empty(filename=''):
     if not filename.strip():
         return ''
     return existing_file(filename)
+
+
+def existing_dir(path):
+    """
+    Function that raises ArgumentTypeError if argument is not an existing directory.
+
+    .. seealso:: :py:func:`existing_file`, :py:func:`existing_dir_or_empty`
+    """
+    if isdir(path):
+        return path
+    raise ArgumentTypeError('{} is not an existing directory'.format(path))
+
+
+def existing_dir_or_empty(path=''):
+    """
+    Like :py:func:`existing_dir` but accepts empty path (returns '' then).
+    """
+    if not path.strip():
+        return ''
+    return existing_dir(path)