3 # © Copyright 2021-2022, Scott Gasch
5 """Helpers for commandline argument parsing."""
11 from typing import Any
13 from overrides import overrides
15 # This module is commonly used by others in here and should avoid
16 # taking any unnecessary dependencies back on them.
18 logger = logging.getLogger(__name__)
21 class ActionNoYes(argparse.Action):
22 """An argparse Action that allows for commandline arguments like this:
28 help='Should we enable the thing?'
31 This creates cmdline arguments:
38 def __init__(self, option_strings, dest, default=None, required=False, help=None):
40 msg = 'You must provide a default with Yes/No action'
43 if len(option_strings) != 1:
44 msg = 'Only single argument is allowed with NoYes action'
47 opt = option_strings[0]
48 if not opt.startswith('--'):
49 msg = 'Yes/No arguments must be prefixed with --'
54 opts = ['--' + opt, '--no_' + opt]
66 def __call__(self, parser, namespace, values, option_strings=None):
67 if option_strings.startswith('--no-') or option_strings.startswith('--no_'):
68 setattr(namespace, self.dest, False)
70 setattr(namespace, self.dest, True)
73 def valid_bool(v: Any) -> bool:
75 If the string is a valid bool, return its value.
80 >>> valid_bool("true")
93 Traceback (most recent call last):
95 argparse.ArgumentTypeError: 12345
98 if isinstance(v, bool):
100 from string_utils import to_bool
104 except Exception as e:
105 raise argparse.ArgumentTypeError(v) from e
108 def valid_ip(ip: str) -> str:
110 If the string is a valid IPv4 address, return it. Otherwise raise
111 an ArgumentTypeError.
113 >>> valid_ip("1.2.3.4")
116 >>> valid_ip("localhost")
117 Traceback (most recent call last):
119 argparse.ArgumentTypeError: localhost is an invalid IP address
122 from string_utils import extract_ip_v4
124 s = extract_ip_v4(ip.strip())
127 msg = f"{ip} is an invalid IP address"
129 raise argparse.ArgumentTypeError(msg)
132 def valid_mac(mac: str) -> str:
134 If the string is a valid MAC address, return it. Otherwise raise
135 an ArgumentTypeError.
137 >>> valid_mac('12:23:3A:4F:55:66')
140 >>> valid_mac('12-23-3A-4F-55-66')
144 Traceback (most recent call last):
146 argparse.ArgumentTypeError: big is an invalid MAC address
149 from string_utils import extract_mac_address
151 s = extract_mac_address(mac)
154 msg = f"{mac} is an invalid MAC address"
156 raise argparse.ArgumentTypeError(msg)
159 def valid_percentage(num: str) -> float:
161 If the string is a valid percentage, return it. Otherwise raise
162 an ArgumentTypeError.
164 >>> valid_percentage("15%")
167 >>> valid_percentage('40')
170 >>> valid_percentage('115')
171 Traceback (most recent call last):
173 argparse.ArgumentTypeError: 115 is an invalid percentage; expected 0 <= n <= 100.0
178 if 0.0 <= n <= 100.0:
180 msg = f"{num} is an invalid percentage; expected 0 <= n <= 100.0"
182 raise argparse.ArgumentTypeError(msg)
185 def valid_filename(filename: str) -> str:
187 If the string is a valid filename, return it. Otherwise raise
188 an ArgumentTypeError.
190 >>> valid_filename('/tmp')
193 >>> valid_filename('wfwefwefwefwefwefwefwefwef')
194 Traceback (most recent call last):
196 argparse.ArgumentTypeError: wfwefwefwefwefwefwefwefwef was not found and is therefore invalid.
200 if os.path.exists(s):
202 msg = f"{filename} was not found and is therefore invalid."
204 raise argparse.ArgumentTypeError(msg)
207 def valid_date(txt: str) -> datetime.date:
208 """If the string is a valid date, return it. Otherwise raise
209 an ArgumentTypeError.
211 >>> valid_date('6/5/2021')
212 datetime.date(2021, 6, 5)
214 # Note: dates like 'next wednesday' work fine, they are just
215 # hard to test for without knowing when the testcase will be
217 >>> valid_date('next wednesday') # doctest: +ELLIPSIS
220 from string_utils import to_date
225 msg = f'Cannot parse argument as a date: {txt}'
227 raise argparse.ArgumentTypeError(msg)
230 def valid_datetime(txt: str) -> datetime.datetime:
231 """If the string is a valid datetime, return it. Otherwise raise
232 an ArgumentTypeError.
234 >>> valid_datetime('6/5/2021 3:01:02')
235 datetime.datetime(2021, 6, 5, 3, 1, 2)
237 # Again, these types of expressions work fine but are
238 # difficult to test with doctests because the answer is
239 # relative to the time the doctest is executed.
240 >>> valid_datetime('next christmas at 4:15am') # doctest: +ELLIPSIS
243 from string_utils import to_datetime
245 dt = to_datetime(txt)
248 msg = f'Cannot parse argument as datetime: {txt}'
250 raise argparse.ArgumentTypeError(msg)
253 def valid_duration(txt: str) -> datetime.timedelta:
254 """If the string is a valid time duration, return a
255 datetime.timedelta representing the period of time. Otherwise
256 maybe raise an ArgumentTypeError or potentially just treat the
257 time window as zero in length.
259 >>> valid_duration('3m')
260 datetime.timedelta(seconds=180)
262 >>> valid_duration('your mom')
263 datetime.timedelta(0)
266 from datetime_utils import parse_duration
269 secs = parse_duration(txt)
270 return datetime.timedelta(seconds=secs)
271 except Exception as e:
273 raise argparse.ArgumentTypeError(e) from e
276 if __name__ == '__main__':
279 doctest.ELLIPSIS_MARKER = '-ANYTHING-'