9 from overrides import overrides
12 # This module is commonly used by others in here and should avoid
13 # taking any unnecessary dependencies back on them.
15 logger = logging.getLogger(__name__)
18 class ActionNoYes(argparse.Action):
20 self, option_strings, dest, default=None, required=False, help=None
23 msg = 'You must provide a default with Yes/No action'
26 if len(option_strings) != 1:
27 msg = 'Only single argument is allowed with YesNo action'
30 opt = option_strings[0]
31 if not opt.startswith('--'):
32 msg = 'Yes/No arguments must be prefixed with --'
37 opts = ['--' + opt, '--no_' + opt]
49 def __call__(self, parser, namespace, values, option_strings=None):
50 if option_strings.startswith('--no-') or option_strings.startswith(
53 setattr(namespace, self.dest, False)
55 setattr(namespace, self.dest, True)
58 def valid_bool(v: Any) -> bool:
60 If the string is a valid bool, return its value.
65 >>> valid_bool("true")
78 Traceback (most recent call last):
80 argparse.ArgumentTypeError: 12345
83 if isinstance(v, bool):
85 from string_utils import to_bool
90 raise argparse.ArgumentTypeError(v)
93 def valid_ip(ip: str) -> str:
95 If the string is a valid IPv4 address, return it. Otherwise raise
98 >>> valid_ip("1.2.3.4")
101 >>> valid_ip("localhost")
102 Traceback (most recent call last):
104 argparse.ArgumentTypeError: localhost is an invalid IP address
107 from string_utils import extract_ip_v4
109 s = extract_ip_v4(ip.strip())
112 msg = f"{ip} is an invalid IP address"
114 raise argparse.ArgumentTypeError(msg)
117 def valid_mac(mac: str) -> str:
119 If the string is a valid MAC address, return it. Otherwise raise
120 an ArgumentTypeError.
122 >>> valid_mac('12:23:3A:4F:55:66')
125 >>> valid_mac('12-23-3A-4F-55-66')
129 Traceback (most recent call last):
131 argparse.ArgumentTypeError: big is an invalid MAC address
134 from string_utils import extract_mac_address
136 s = extract_mac_address(mac)
139 msg = f"{mac} is an invalid MAC address"
141 raise argparse.ArgumentTypeError(msg)
144 def valid_percentage(num: str) -> float:
146 If the string is a valid percentage, return it. Otherwise raise
147 an ArgumentTypeError.
149 >>> valid_percentage("15%")
152 >>> valid_percentage('40')
155 >>> valid_percentage('115')
156 Traceback (most recent call last):
158 argparse.ArgumentTypeError: 115 is an invalid percentage; expected 0 <= n <= 100.0
163 if 0.0 <= n <= 100.0:
165 msg = f"{num} is an invalid percentage; expected 0 <= n <= 100.0"
167 raise argparse.ArgumentTypeError(msg)
170 def valid_filename(filename: str) -> str:
172 If the string is a valid filename, return it. Otherwise raise
173 an ArgumentTypeError.
175 >>> valid_filename('/tmp')
178 >>> valid_filename('wfwefwefwefwefwefwefwefwef')
179 Traceback (most recent call last):
181 argparse.ArgumentTypeError: wfwefwefwefwefwefwefwefwef was not found and is therefore invalid.
185 if os.path.exists(s):
187 msg = f"{filename} was not found and is therefore invalid."
189 raise argparse.ArgumentTypeError(msg)
192 def valid_date(txt: str) -> datetime.date:
193 """If the string is a valid date, return it. Otherwise raise
194 an ArgumentTypeError.
196 >>> valid_date('6/5/2021')
197 datetime.date(2021, 6, 5)
199 # Note: dates like 'next wednesday' work fine, they are just
200 # hard to test for without knowing when the testcase will be
202 >>> valid_date('next wednesday') # doctest: +ELLIPSIS
205 from string_utils import to_date
210 msg = f'Cannot parse argument as a date: {txt}'
212 raise argparse.ArgumentTypeError(msg)
215 def valid_datetime(txt: str) -> datetime.datetime:
216 """If the string is a valid datetime, return it. Otherwise raise
217 an ArgumentTypeError.
219 >>> valid_datetime('6/5/2021 3:01:02')
220 datetime.datetime(2021, 6, 5, 3, 1, 2)
222 # Again, these types of expressions work fine but are
223 # difficult to test with doctests because the answer is
224 # relative to the time the doctest is executed.
225 >>> valid_datetime('next christmas at 4:15am') # doctest: +ELLIPSIS
228 from string_utils import to_datetime
230 dt = to_datetime(txt)
233 msg = f'Cannot parse argument as datetime: {txt}'
235 raise argparse.ArgumentTypeError(msg)
238 def valid_duration(txt: str) -> datetime.timedelta:
239 """If the string is a valid time duration, return a
240 datetime.timedelta representing the period of time. Otherwise
241 maybe raise an ArgumentTypeError or potentially just treat the
242 time window as zero in length.
244 >>> valid_duration('3m')
245 datetime.timedelta(seconds=180)
247 >>> valid_duration('your mom')
248 datetime.timedelta(0)
251 from datetime_utils import parse_duration
254 secs = parse_duration(txt)
255 except Exception as e:
256 raise argparse.ArgumentTypeError(e)
258 return datetime.timedelta(seconds=secs)
261 if __name__ == '__main__':
264 doctest.ELLIPSIS_MARKER = '-ANYTHING-'