over/over/callback.py
2017-11-23 16:01:21 +01:00

113 lines
1.9 KiB
Python

#! /usr/bin/env python3
# encoding: utf-8
# --------------------------------------------------
import os
# --------------------------------------------------
def boolean(arg):
"""
Converts
- "True", "true" or "1" ⇒ True
- "False", "false" or "0" ⇒ False
@while converting argument to bool
"""
if arg in (True, "True", "true", "1"):
return True
elif arg in (False, "False", "false", "0"):
return False
else:
raise ValueError(arg)
def booleans(*args):
"""
Converts each
- "True", "true" or "1" ⇒ True
- "False", "false" or "0" ⇒ False
@while converting arguments to bools
"""
out = []
for arg in args:
out.append(boolean(arg))
return out
def strings(*args):
"""
Converts each element to str.
@while converting arguments to strings
"""
out = []
for arg in args:
out.append(str(arg))
return out
def directory(exists=False, writable=False, gio=False):
"""
Returns a directory callback that raises hell if:
- the supplied directory doesn't exist and `exists` is True
- isn't writable and `writable` is True
- isn't a valid Gio path and `gio` is True
@while generating a callback
"""
if gio:
raise NotImplementedError("Gio support is not yet here")
def cb(arg):
path = os.path.abspath(os.path.expanduser(arg))
if not os.path.isdir(path) and exists:
raise FileNotFoundError("%s (%s) does not exist" %(arg, path))
if writable and not os.access(path, os.W_OK | os.X_OK):
raise PermissionError("%s exists but is not writable" %(arg))
return path
return cb
def integer(arg):
"""
Converts
- "0x2a" ⇒ 42
- "0o52" ⇒ 42
- "42" ⇒ 42
@while converting argument to int
"""
if type(arg) == int:
return arg
if len(arg) > 2:
if arg[1] == "x":
return int(arg, 16)
elif arg[1] == "o":
return int(arg, 8)
return int(arg)
def integers(*args):
"""
@while converting arguments to ints
"""
out = []
for arg in args:
out.append(integer(arg))
return out