Rename a flag.
[python_utils.git] / argparse_utils.py
1 #!/usr/bin/python3
2
3 import argparse
4 import logging
5 import os
6
7 import string_utils
8
9 logger = logging.getLogger(__name__)
10
11
12 class ActionNoYes(argparse.Action):
13     def __init__(
14             self,
15             option_strings,
16             dest,
17             default=None,
18             required=False,
19             help=None
20     ):
21         if default is None:
22             msg = 'You must provide a default with Yes/No action'
23             logger.critical(msg)
24             raise ValueError(msg)
25         if len(option_strings) != 1:
26             msg = 'Only single argument is allowed with YesNo action'
27             logger.critical(msg)
28             raise ValueError(msg)
29         opt = option_strings[0]
30         if not opt.startswith('--'):
31             msg = 'Yes/No arguments must be prefixed with --'
32             logger.critical(msg)
33             raise ValueError(msg)
34
35         opt = opt[2:]
36         opts = ['--' + opt, '--no_' + opt]
37         super().__init__(
38             opts,
39             dest,
40             nargs=0,
41             const=None,
42             default=default,
43             required=required,
44             help=help
45         )
46
47     def __call__(self, parser, namespace, values, option_strings=None):
48         if (
49                 option_strings.startswith('--no-') or
50                 option_strings.startswith('--no_')
51         ):
52             setattr(namespace, self.dest, False)
53         else:
54             setattr(namespace, self.dest, True)
55
56
57 def valid_bool(v):
58     if isinstance(v, bool):
59         return v
60     return string_utils.to_bool(v)
61
62
63 def valid_ip(ip: str) -> str:
64     s = string_utils.extract_ip_v4(ip.strip())
65     if s is not None:
66         return s
67     msg = f"{ip} is an invalid IP address"
68     logger.warning(msg)
69     raise argparse.ArgumentTypeError(msg)
70
71
72 def valid_mac(mac: str) -> str:
73     s = string_utils.extract_mac_address(mac)
74     if s is not None:
75         return s
76     msg = f"{mac} is an invalid MAC address"
77     logger.warning(msg)
78     raise argparse.ArgumentTypeError(msg)
79
80
81 def valid_percentage(num: str) -> float:
82     n = float(num)
83     if 0.0 <= n <= 100.0:
84         return n
85     msg = f"{num} is an invalid percentage; expected 0 <= n <= 100.0"
86     logger.warning(msg)
87     raise argparse.ArgumentTypeError(msg)
88
89
90 def valid_filename(filename: str) -> str:
91     s = filename.strip()
92     if os.path.exists(s):
93         return s
94     msg = f"{filename} was not found and is therefore invalid."
95     logger.warning(msg)
96     raise argparse.ArgumentTypeError(msg)