#!/usr/bin/python3 import argparse import datetime import logging import os # This module is commonly used by others in here and should avoid # taking any unnecessary dependencies back on them. logger = logging.getLogger(__name__) class ActionNoYes(argparse.Action): def __init__( self, option_strings, dest, default=None, required=False, help=None ): if default is None: msg = 'You must provide a default with Yes/No action' logger.critical(msg) raise ValueError(msg) if len(option_strings) != 1: msg = 'Only single argument is allowed with YesNo action' logger.critical(msg) raise ValueError(msg) opt = option_strings[0] if not opt.startswith('--'): msg = 'Yes/No arguments must be prefixed with --' logger.critical(msg) raise ValueError(msg) opt = opt[2:] opts = ['--' + opt, '--no_' + opt] super().__init__( opts, dest, nargs=0, const=None, default=default, required=required, help=help ) def __call__(self, parser, namespace, values, option_strings=None): if ( option_strings.startswith('--no-') or option_strings.startswith('--no_') ): setattr(namespace, self.dest, False) else: setattr(namespace, self.dest, True) def valid_bool(v): if isinstance(v, bool): return v from string_utils import to_bool return to_bool(v) def valid_ip(ip: str) -> str: from string_utils import extract_ip_v4 s = extract_ip_v4(ip.strip()) if s is not None: return s msg = f"{ip} is an invalid IP address" logger.warning(msg) raise argparse.ArgumentTypeError(msg) def valid_mac(mac: str) -> str: from string_utils import extract_mac_address s = extract_mac_address(mac) if s is not None: return s msg = f"{mac} is an invalid MAC address" logger.warning(msg) raise argparse.ArgumentTypeError(msg) def valid_percentage(num: str) -> float: num = num.strip('%') n = float(num) if 0.0 <= n <= 100.0: return n msg = f"{num} is an invalid percentage; expected 0 <= n <= 100.0" logger.warning(msg) raise argparse.ArgumentTypeError(msg) def valid_filename(filename: str) -> str: s = filename.strip() if os.path.exists(s): return s msg = f"{filename} was not found and is therefore invalid." logger.warning(msg) raise argparse.ArgumentTypeError(msg) def valid_date(txt: str) -> datetime.date: from string_utils import to_date date = to_date(txt) if date is not None: return date msg = f'Cannot parse argument as a date: {txt}' logger.warning(msg) raise argparse.ArgumentTypeError(msg) def valid_datetime(txt: str) -> datetime.datetime: from string_utils import to_datetime dt = to_datetime(txt) if dt is not None: return dt msg = f'Cannot parse argument as datetime: {txt}' logger.warning(msg) raise argparse.ArgumentTypeError(msg)