Exemplo n.º 1
0
 def __call__(self, arg: str) -> int:
     """Interpret the argument value."""
     if not arg:
         raise ArgumentTypeError("Expected value")
     parts = re.match(r"^(\d+)([kKmMgGtT]?)[bB]?$", arg)
     if not parts:
         raise ArgumentTypeError("Invalid format")
     size = int(parts[1])
     suffix = parts[2].upper()
     if suffix == "K":
         size = size << 10
     elif suffix == "M":
         size = size << 20
     elif suffix == "G":
         size = size << 30
     elif suffix == "T":
         size = size << 40
     if size < self.min_size:
         raise ArgumentTypeError(
             f"Size must be greater than or equal to {self.min_size}"
         )
     if self.max_size and size > self.max_size:
         raise ArgumentTypeError(
             f"Size must be less than or equal to {self.max_size}"
         )
     return size
Exemplo n.º 2
0
def restricted_float_or_int(arg: str) -> Union[float, int]:
    try:
        value = int(arg)
        if value < 0:
            raise ArgumentTypeError(f'{value} is less than 0')
    except ValueError:
        value = float(arg)
        if value < 0 or value > 1:
            raise ArgumentTypeError(f'{value} must be in [0,1]')

    return value
Exemplo n.º 3
0
def _istiff(fpath, data_tag):
    """
    Returns True if path provided is to a directory of tiffs, False if .hdf5 file.
    Raises ArgumentTypeError if format is not supported.
    """
    # Understand input data format
    if os.path.isdir(fpath):
        tiff_input = True
    elif fpath.split('.')[-1] in ("hdf5", "h5"):
        tiff_input = False
        if data_tag == "":
            raise ArgumentTypeError("dataset-name required for hdf5")
    else:
        raise ArgumentTypeError("input file type not recognized. must be tiff folder or hdf5 file")
    return tiff_input
Exemplo n.º 4
0
def parse_email_address(raw: str) -> EmailAddress:
    if len(raw) > 7:
        match = re.match(
            "^([a-zA-Z0-9_.+-]+)@([a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$",
            raw.lower().lstrip(string.whitespace).rstrip(string.whitespace))
        if match:
            return EmailAddress(match.group(1), match.group(2))
    raise ArgumentTypeError(f'{raw} is not a valid email address')
Exemplo n.º 5
0
 def __call__(self, arg: str) -> int:
     """Interpret the argument value."""
     if not arg:
         raise ArgumentTypeError("Expected integer value")
     try:
         val = int(arg)
     except ValueError:
         raise ArgumentTypeError(f"Invalid integer value: '{arg}'")
     if self.min_val is not None and val < self.min_val:
         raise ArgumentTypeError(
             f"Value must be greater than or equal to {self.min_val}"
         )
     if self.max_val is not None and val > self.max_val:
         raise ArgumentTypeError(
             f"Value must be less than or equal to {self.max_val}"
         )
     return val
Exemplo n.º 6
0
def str_to_bool(_inp):
    _inp = str(_inp)
    if _inp in ("yes", "Yes", "Y", "y", "True", "TRUE", "true"):
        return True
    elif _inp in ("no", "No", "N", "n", "False", "FALSE", "false"):
        return False
    else:
        raise ArgumentTypeError("Input not understood")
    return
Exemplo n.º 7
0
def parse_routes(routes_raw):
    routes = []
    try:
        for route_raw in routes_raw.split(','):
            prefix, url = route_raw.split('=')
            host, port = url.split(':')
            port = int(port)
            routes.append(Route(prefix, host, port))
    except ValueError:
        raise ArgumentTypeError(
            'Routes should be key-value pairs of prefix (can be empty string) '
            ' and host:port separated by commas. For example: '
            '--routes foo.bar=foo-bar.com:2003,spam=spam.org:2003')
    return routes
Exemplo n.º 8
0
    def __call__(self, string):
        # the special argument "-" means sys.stdin
        if string == "-":
            inp = sys.stdin.readlines()
            return self(inp[0].strip())

        # all other arguments are used as file names
        if path.isdir(string):
            return string
        relative_dir = path.join(f"{getcwd()}", "output", string)
        if path.isdir(relative_dir):
            return relative_dir
        args = {"filename": string}
        message = _("can't open '%(filename)s'")
        raise ArgumentTypeError(message % args)
Exemplo n.º 9
0
def positive_int(arg: str):
    value = int(arg)
    if value <= 0:
        raise ArgumentTypeError('Value must be greater than 0!')
    return value
Exemplo n.º 10
0
def _template(filename: str) -> str:
    try:
        with open(filename, 'r') as fin:
            return fin.read()
    except FileNotFoundError:
        raise ArgumentTypeError(f'{filename} does not exist')
Exemplo n.º 11
0
def restricted_float(arg: str) -> float:
    value = float(arg)
    if value < 0 or value > 1:
        raise ArgumentTypeError(f'{value} must be in [0,1]')

    return value