def get_time(value, now=None): """Convert a parameter to a timestamp. Based on the passed value create a timestamp that represents the value. Both absolute and relative forms are supported. Example: >>> get_time('2017-06-03') 1496448000 >>> now = arrow.utcnow().replace(microsecond=0).timestamp >>> get_time('+2d') == now + 2*60*60*24 True Valid time units for relative values are described in :class:`TimeUnits`. If a time unit is not provided the default is :py:attr:`TimeUnits.days`. Additionally, for relative values, the current time can be specified by passing an :class:`~arrow.arrow.Arrow` instance as the ``now`` argument. Example: >>> today = get_time('2017-06-03') >>> get_time('+1d', arrow.get(today)) 1496534400 Args: value (str): the value to convert now (:obj:`~arrow.arrow.Arrow`, optional): the base time to use for relative values. Returns: int: a timestamp Raises: clize.errors.CliValueError: if the value cannot be converted. """ now = arrow.utcnow() if not now else now.replace(microsecond=0) if not value: return now.timestamp if value.startswith('-') or value.startswith('+'): op = value[0] val = value[1:] try: num = ''.join([c for c in val if c.isdigit()]) if len(num) < len(val): unit = TimeUnits(val[len(num):]) else: unit = TimeUnits('d') d = now.replace(**{unit.name: int(op + num)}) return d.timestamp except ValueError: pass try: return arrow.get(value).timestamp except arrow.parser.ParserError as e: raise errors.CliValueError(e)
def validate_permissions(self): mode = self.kwargs.get('mode', 'r') exists = os.access(self.arg, os.F_OK) if not exists: if 'r' in mode and '+' not in mode: raise errors.CliValueError('File does not exist: {0!r}'.format( self.arg)) else: dirname = os.path.dirname(self.arg) if os.access(dirname, os.W_OK): return if not os.path.exists(dirname): raise errors.CliValueError( 'Directory does not exist: {0!r}'.format(self.arg)) elif os.access(self.arg, os.W_OK): return raise errors.CliValueError('Permission denied: {0!r}'.format(self.arg))
def with_format(wrapped, fmt=DEFAULT_FORMAT, *args, **kwargs): """Provide ``--format`` argument. Args: format (str, optional): one of :class:`Format` values. Defaults to ``'text'``. Raises: clize.errors.CliValueError: if the format argument is invalid. """ if fmt.writer is None: raise errors.CliValueError( '{} is unavailable (missing requirements?)'.format(fmt.value)) return wrapped(fmt=Format(fmt), *args, **kwargs)
def outages(filters=None, backend=None, fmt=None, config=None): """List outages. Args: filters (dict): parameters to filter outages with. backend (object): the backend instace object fmt (Format): what format to output data as. config (dict): the settings object """ outages = get_outages(backend, **filters) try: cfg = config[fmt.value] except (TypeError, KeyError): raise errors.CliValueError( "Missing configuration for format {}".format(fmt.value)) fmt.writer(sys.stdout, outages, fields=Outage.fields(), config=cfg)
def with_backend(wrapped, backend=DEFAULT_BACKEND, *args, **kwargs): """Provide ``--backend`` option that initializes a backend. Args: backend (str, optional): the name of the backend. Defaults to ``'pingdom'``. Raises: clize.errors.CliValueError: if the backend configuration is missing """ try: cfg = kwargs.get('config', {})[backend] except (TypeError, KeyError): raise errors.CliValueError( "Missing configuration for backend {}".format(backend)) impl = get_backend(backend).from_config(cfg) return wrapped(backend=impl, *args, **kwargs)
def get_log_level(level): """Convert a value to a log level. Converts a case-insensitive log level name to the corresponding integer value from Python's :mod:`logging` package. Example: >>> assert logging.DEBUG == get_log_level('debug') Args: level (str): the value to convert Returns: int: a log level from the :mod:`logging` package. Raises: clize.errors.CliValueError: if the value cannot be converted. """ try: return getattr(logging, level.upper()) except AttributeError: raise errors.CliValueError('Invalid log level: {}'.format(level))