signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def check_author(author, **kwargs):
|
errors = []<EOL>authors = kwargs.get("<STR_LIT>")<EOL>if not authors:<EOL><INDENT>errors.append('<STR_LIT>' + _author_codes['<STR_LIT>'])<EOL>return errors<EOL><DEDENT>exclude_author_names = kwargs.get("<STR_LIT>")<EOL>if exclude_author_names and author in exclude_author_names:<EOL><INDENT>return []<EOL><DEDENT>path = kwargs.get("<STR_LIT:path>")<EOL>if not path:<EOL><INDENT>path = os.getcwd()<EOL><DEDENT>for afile in authors:<EOL><INDENT>if not os.path.exists(path + os.sep + afile):<EOL><INDENT>errors.append('<STR_LIT>' + _author_codes['<STR_LIT>'].format(afile))<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>return errors<EOL><DEDENT>status = subprocess.Popen(['<STR_LIT>', '<STR_LIT>', author] +<EOL>[path + os.sep + afile for afile in authors],<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>cwd=path).wait()<EOL>if status:<EOL><INDENT>errors.append('<STR_LIT>' + _author_codes['<STR_LIT>'].format(author))<EOL><DEDENT>return errors<EOL>
|
Check the presence of the author in the AUTHORS/THANKS files.
Rules:
- the author full name and email must appear in AUTHORS file
:param authors: name of AUTHORS files
:type authors: `list`
:param path: path to the repository home
:type path: str
:return: errors
:rtype: `list`
|
f3762:m10
|
def get_options(config=None):
|
if config is None:<EOL><INDENT>from . import config<EOL>config.get = lambda key, default=None: getattr(config, key, default)<EOL><DEDENT>base = {<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>", True),<EOL>"<STR_LIT>": config.get("<STR_LIT>", True),<EOL>"<STR_LIT>": config.get("<STR_LIT>", True),<EOL>"<STR_LIT>": config.get("<STR_LIT>", True),<EOL>"<STR_LIT:ignore>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>", True),<EOL>"<STR_LIT>": config.get("<STR_LIT>", []),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>"),<EOL>}<EOL>options = {}<EOL>for k, v in base.items():<EOL><INDENT>if v is not None:<EOL><INDENT>options[k] = v<EOL><DEDENT><DEDENT>return options<EOL>
|
Build the options from the config object.
|
f3762:m11
|
def run(self):
|
for msg in self.messages:<EOL><INDENT>col = getattr(msg, '<STR_LIT>', <NUM_LIT:0>)<EOL>yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__<EOL><DEDENT>
|
Yield the error messages.
|
f3762:c0:m0
|
def __init__(self, options):
|
super(_Report, self).__init__(options)<EOL>self.errors = []<EOL>
|
Initialize the reporter.
|
f3762:c1:m0
|
def error(self, line_number, offset, text, check):
|
code = super(_Report, self).error(line_number, offset, text, check)<EOL>if code:<EOL><INDENT>self.errors.append((line_number, offset + <NUM_LIT:1>, code, text, check))<EOL><DEDENT>
|
Run the checks and collect the errors.
|
f3762:c1:m1
|
@disable_on_env<EOL>def uuid(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if isinstance(value, uuid_.UUID):<EOL><INDENT>return value<EOL><DEDENT>try:<EOL><INDENT>value = uuid_.UUID(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>')<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` coerced to a :class:`UUID <python:uuid.UUID>` object /
:obj:`None <python:None>`
:rtype: :class:`UUID <python:uuid.UUID>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`UUID <python:uuid.UUID>`
|
f3771:m0
|
@disable_on_env<EOL>def string(value,<EOL>allow_empty = False,<EOL>coerce_value = False,<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>whitespace_padding = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>minimum_length = integer(minimum_length, allow_empty = True)<EOL>maximum_length = integer(maximum_length, allow_empty = True)<EOL>if coerce_value:<EOL><INDENT>value = str(value)<EOL><DEDENT>elif not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>' % value)<EOL><DEDENT>if value and maximum_length and len(value) > maximum_length:<EOL><INDENT>raise errors.MaximumLengthError(<EOL>'<STR_LIT>' % (value, maximum_length)<EOL>)<EOL><DEDENT>if value and minimum_length and len(value) < minimum_length:<EOL><INDENT>if whitespace_padding:<EOL><INDENT>value = value.ljust(minimum_length, '<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>raise errors.MinimumLengthError(<EOL>'<STR_LIT>' % (value, minimum_length)<EOL>)<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if
it is not already. If ``False``, will raise a :class:`ValueError` if ``value``
is not a string. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value``
is ``False``
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
|
f3771:m1
|
@disable_on_env<EOL>def iterable(value,<EOL>allow_empty = False,<EOL>forbid_literals = (str, bytes),<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif value is None:<EOL><INDENT>return None<EOL><DEDENT>minimum_length = integer(minimum_length, allow_empty = True, force_run = True) <EOL>maximum_length = integer(maximum_length, allow_empty = True, force_run = True) <EOL>if isinstance(value, forbid_literals) or not hasattr(value, '<STR_LIT>'):<EOL><INDENT>raise errors.NotAnIterableError('<STR_LIT>' % type(value))<EOL><DEDENT>if value and minimum_length is not None and len(value) < minimum_length:<EOL><INDENT>raise errors.MinimumLengthError(<EOL>'<STR_LIT>' % minimum_length<EOL>)<EOL><DEDENT>if value and maximum_length is not None and len(value) > maximum_length:<EOL><INDENT>raise errors.MaximumLengthError(<EOL>'<STR_LIT>' % maximum_length<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid iterable.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to :class:`str <python:str>` and
:class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: iterable / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotAnIterableError: if ``value`` is not a valid iterable or
:obj:`None <python:None>`
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
|
f3771:m2
|
@disable_on_env<EOL>def none(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if value is not None and not value and allow_empty:<EOL><INDENT>pass<EOL><DEDENT>elif (value is not None and not value) or value:<EOL><INDENT>raise errors.NotNoneError('<STR_LIT>')<EOL><DEDENT>return None<EOL>
|
Validate that ``value`` is :obj:`None <python:None>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty but **not** :obj:`None <python:None>`. If ``False``, raises a
:class:`NotNoneError` if ``value`` is empty but **not**
:obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: :obj:`None <python:None>`
:raises NotNoneError: if ``allow_empty`` is ``False`` and ``value`` is empty
but **not** :obj:`None <python:None>` and
|
f3771:m3
|
@disable_on_env<EOL>def not_empty(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and allow_empty:<EOL><INDENT>return None<EOL><DEDENT>elif not value:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>')<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is not empty.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
|
f3771:m4
|
@disable_on_env<EOL>def variable_name(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>parse('<STR_LIT>' % value)<EOL><DEDENT>except (SyntaxError, ValueError, TypeError):<EOL><INDENT>raise errors.InvalidVariableNameError(<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that the value is a valid Python variable name.
.. caution::
This function does **NOT** check whether the variable exists. It only
checks that the ``value`` would work as a Python variable (or class, or
function, etc.) name.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
|
f3771:m5
|
@disable_on_env<EOL>def dict(value,<EOL>allow_empty = False,<EOL>json_serializer = None,<EOL>**kwargs):
|
original_value = value<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if json_serializer is None:<EOL><INDENT>json_serializer = json_<EOL><DEDENT>if isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>value = json_serializer.loads(value)<EOL><DEDENT>except Exception:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % original_value<EOL>)<EOL><DEDENT>value = dict(value,<EOL>json_serializer = json_serializer)<EOL><DEDENT>if not isinstance(value, dict_):<EOL><INDENT>raise errors.NotADictError('<STR_LIT>' % original_value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a :class:`dict <python:dict>`.
.. hint::
If ``value`` is a string, this validator will assume it is a JSON
object and try to convert it into a :class:`dict <python:dict>`
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotADictError: if ``value`` is not a :class:`dict <python:dict>`
|
f3771:m6
|
@disable_on_env<EOL>def json(value,<EOL>schema = None,<EOL>allow_empty = False,<EOL>json_serializer = None,<EOL>**kwargs):
|
original_value = value<EOL>original_schema = schema<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not json_serializer:<EOL><INDENT>json_serializer = json_<EOL><DEDENT>if isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>value = json_serializer.loads(value)<EOL><DEDENT>except Exception:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % original_value<EOL>)<EOL><DEDENT><DEDENT>if isinstance(schema, str):<EOL><INDENT>try:<EOL><INDENT>schema = dict(schema,<EOL>allow_empty = allow_empty,<EOL>json_serializer = json_serializer,<EOL>**kwargs)<EOL><DEDENT>except Exception:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % original_schema<EOL>)<EOL><DEDENT><DEDENT>if not isinstance(value, (list, dict_)):<EOL><INDENT>raise errors.NotJSONError('<STR_LIT>' % original_value)<EOL><DEDENT>if original_schema and not isinstance(schema, dict_):<EOL><INDENT>raise errors.NotJSONError('<STR_LIT>' % original_schema)<EOL><DEDENT>if not schema:<EOL><INDENT>return value<EOL><DEDENT>try:<EOL><INDENT>jsonschema.validate(value, schema)<EOL><DEDENT>except jsonschema.exceptions.ValidationError as error:<EOL><INDENT>raise errors.JSONValidationError(error.message)<EOL><DEDENT>except jsonschema.exceptions.SchemaError as error:<EOL><INDENT>raise errors.NotJSONSchemaError(error.message)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
.. hint::
If either ``value`` or ``schema`` is a string, this validator will assume it is a
JSON object and try to convert it into a :class:`dict <python:dict>`.
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param schema: An optional JSON Schema against which ``value`` will be validated.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of
:class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotJSONError: if ``value`` cannot be deserialized from JSON
:raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object
:raises JSONValidationError: if ``value`` does not validate against the JSON Schema
|
f3771:m7
|
@disable_on_env<EOL>def date(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = True,<EOL>**kwargs):
|
<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>minimum = date(minimum, allow_empty = True, force_run = True) <EOL>maximum = date(maximum, allow_empty = True, force_run = True) <EOL>if not isinstance(value, date_types):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>elif isinstance(value, datetime_.datetime) and not coerce_value:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>elif isinstance(value, datetime_.datetime) and coerce_value:<EOL><INDENT>value = value.date()<EOL><DEDENT>elif isinstance(value, timestamp_types) and coerce_value:<EOL><INDENT>try:<EOL><INDENT>value = datetime_.date.fromtimestamp(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT><DEDENT>elif isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL>if coerce_value:<EOL><INDENT>value = value.date()<EOL><DEDENT>else:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>if len(value) > <NUM_LIT:10> and not coerce_value:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>if '<STR_LIT:U+0020>' in value:<EOL><INDENT>value = value.split('<STR_LIT:U+0020>')[<NUM_LIT:0>]<EOL><DEDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = value.split('<STR_LIT:T>')[<NUM_LIT:0>]<EOL><DEDENT>if len(value) != <NUM_LIT:10>:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>try:<EOL><INDENT>year = int(value[:<NUM_LIT:4>])<EOL>month = int(value[<NUM_LIT:5>:<NUM_LIT:7>])<EOL>day = int(value[-<NUM_LIT:2>:])<EOL>value = datetime_.date(year, month, day)<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(value, numeric_types) and not coerce_value:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>if minimum and value and value < minimum:<EOL><INDENT>raise errors.MinimumValueError(<EOL>'<STR_LIT>' % (value.isoformat(),<EOL>minimum.isoformat())<EOL>)<EOL><DEDENT>if maximum and value and value > maximum:<EOL><INDENT>raise errors.MaximumValueError(<EOL>'<STR_LIT>' % (value.isoformat(),<EOL>maximum.isoformat())<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid date.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a
:class:`date <python:datetime.date>` if it is a timestamp value. If ``False``,
will not.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`date <python:datetime.date>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs before
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs after
``maximum``
|
f3771:m8
|
@disable_on_env<EOL>def datetime(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = True,<EOL>**kwargs):
|
<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>minimum = datetime(minimum, allow_empty = True, force_run = True) <EOL>maximum = datetime(maximum, allow_empty = True, force_run = True) <EOL>if not isinstance(value, datetime_types):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT>elif isinstance(value, timestamp_types) and coerce_value:<EOL><INDENT>try:<EOL><INDENT>value = datetime_.datetime.fromtimestamp(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT><DEDENT>elif isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value,<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value,<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value, '<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:T>' in value:<EOL><INDENT>value = datetime_.datetime.strptime(value,<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>value = datetime_.datetime.strptime(value,<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>if coerce_value:<EOL><INDENT>value = date(value)<EOL><DEDENT>else:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>elif isinstance(value, numeric_types) and not coerce_value:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT>if isinstance(value, datetime_.date) and not isinstance(value, datetime_.datetime):<EOL><INDENT>if coerce_value:<EOL><INDENT>value = datetime_.datetime(value.year, <EOL>value.month,<EOL>value.day,<EOL><NUM_LIT:0>,<EOL><NUM_LIT:0>,<EOL><NUM_LIT:0>,<EOL><NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT>if minimum and value and value < minimum:<EOL><INDENT>raise errors.MinimumValueError(<EOL>'<STR_LIT>' % (value.isoformat(),<EOL>minimum.isoformat())<EOL>)<EOL><DEDENT>if maximum and value and value > maximum:<EOL><INDENT>raise errors.MaximumValueError(<EOL>'<STR_LIT>' % (value.isoformat(),<EOL>maximum.isoformat())<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pass
validation. If it is not in an ISO 8601-format, validation will fail.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param coerce_value: If ``True``, will coerce dates to
:class:`datetime <python:datetime.datetime>` objects with times of 00:00:00. If ``False``, will error
if ``value`` is not an unambiguous timestamp. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`datetime <python:datetime.datetime>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`datetime <python:datetime.datetime>` value and is not
:obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum``
|
f3771:m9
|
@disable_on_env<EOL>def time(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = True,<EOL>**kwargs):
|
<EOL>if not value and not allow_empty:<EOL><INDENT>if isinstance(value, datetime_.time):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT><DEDENT>elif not value:<EOL><INDENT>if not isinstance(value, datetime_.time):<EOL><INDENT>return None<EOL><DEDENT><DEDENT>minimum = time(minimum, allow_empty = True, force_run = True) <EOL>maximum = time(maximum, allow_empty = True, force_run = True) <EOL>if not isinstance(value, time_types):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT>elif isinstance(value, datetime_.datetime) and not coerce_value:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT>elif isinstance(value, datetime_.datetime) and coerce_value:<EOL><INDENT>value = value.time()<EOL><DEDENT>elif isinstance(value, timestamp_types):<EOL><INDENT>try:<EOL><INDENT>datetime_value = datetime(value, force_run = True) <EOL>if coerce_value:<EOL><INDENT>value = datetime_value.time()<EOL><DEDENT>else:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT><DEDENT>elif isinstance(value, basestring):<EOL><INDENT>is_value_calculated = False<EOL>if len(value) > <NUM_LIT:10>:<EOL><INDENT>try:<EOL><INDENT>datetime_value = datetime(value, force_run = True) <EOL>if coerce_value:<EOL><INDENT>value = datetime_value.time()<EOL><DEDENT>else:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT>is_value_calculated = True<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not is_value_calculated:<EOL><INDENT>try:<EOL><INDENT>if '<STR_LIT:+>' in value:<EOL><INDENT>components = value.split('<STR_LIT:+>')<EOL>is_offset_positive = True<EOL><DEDENT>elif '<STR_LIT:->' in value:<EOL><INDENT>components = value.split('<STR_LIT:->')<EOL>is_offset_positive = False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError()<EOL><DEDENT>time_string = components[<NUM_LIT:0>]<EOL>if len(components) > <NUM_LIT:1>:<EOL><INDENT>utc_offset = components[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>utc_offset = None<EOL><DEDENT>time_components = time_string.split('<STR_LIT::>')<EOL>hour = int(time_components[<NUM_LIT:0>])<EOL>minutes = int(time_components[<NUM_LIT:1>])<EOL>seconds = time_components[<NUM_LIT:2>]<EOL>if '<STR_LIT:.>' in seconds:<EOL><INDENT>second_components = seconds.split('<STR_LIT:.>')<EOL>seconds = int(second_components[<NUM_LIT:0>])<EOL>microseconds = int(second_components[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>microseconds = <NUM_LIT:0><EOL><DEDENT>utc_offset = timezone(utc_offset, <EOL>allow_empty = True,<EOL>positive = is_offset_positive,<EOL>force_run = True)<EOL>value = datetime_.time(hour = hour,<EOL>minute = minutes,<EOL>second = seconds,<EOL>microsecond = microseconds,<EOL>tzinfo = utc_offset)<EOL><DEDENT>except (ValueError, TypeError, IndexError):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT><DEDENT>if value is not None:<EOL><INDENT>value = value.replace(tzinfo = None)<EOL><DEDENT><DEDENT>if minimum is not None and value and value < minimum:<EOL><INDENT>raise errors.MinimumValueError(<EOL>'<STR_LIT>' % (value.isoformat(),<EOL>minimum.isoformat())<EOL>)<EOL><DEDENT>if maximum is not None and value and value > maximum:<EOL><INDENT>raise errors.MaximumValueError(<EOL>'<STR_LIT>' % (value.isoformat(),<EOL>maximum.isoformat())<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (effectively
UTC). If ``value`` has a timezone / UTC offset applied, the validator will
coerce the value returned back to UTC.
:param value: The value to validate.
:type value: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce/extract a
:class:`time <python:datetime.time>` from ``value``. If ``False``, will only
respect direct representations of time. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` in UTC time / :obj:`None <python:None>`
:rtype: :class:`time <python:datetime.time>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`time <python:datetime.time>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum``
|
f3771:m10
|
@disable_on_env<EOL>def timezone(value,<EOL>allow_empty = False,<EOL>positive = True,<EOL>**kwargs):
|
<EOL>original_value = value<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, tzinfo_types):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>elif isinstance(value, datetime_.datetime):<EOL><INDENT>value = value.tzinfo<EOL><DEDENT>elif isinstance(value, datetime_.date):<EOL><INDENT>return None<EOL><DEDENT>elif isinstance(value, datetime_.time):<EOL><INDENT>return value.tzinfo<EOL><DEDENT>elif isinstance(value, timestamp_types):<EOL><INDENT>return None<EOL><DEDENT>elif isinstance(value, str):<EOL><INDENT>if '<STR_LIT:+>' not in value and '<STR_LIT:->' not in value:<EOL><INDENT>try:<EOL><INDENT>datetime_value = datetime(value, force_run = True) <EOL>return datetime_value.tzinfo<EOL><DEDENT>except TypeError:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT><DEDENT>elif '<STR_LIT:->' in value:<EOL><INDENT>try:<EOL><INDENT>datetime_value = datetime(value, force_run = True) <EOL>return datetime_value.tzinfo<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if '<STR_LIT:+>' in value and not positive:<EOL><INDENT>raise errors.NegativeOffsetMismatchError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>elif '<STR_LIT:->' in value and positive and len(value) == <NUM_LIT:6>:<EOL><INDENT>positive = False<EOL><DEDENT>elif '<STR_LIT:->' in value and positive:<EOL><INDENT>raise errors.PositiveOffsetMismatchError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if '<STR_LIT:+>' in value:<EOL><INDENT>value = value[value.find('<STR_LIT:+>'):]<EOL><DEDENT>elif '<STR_LIT:->' in value:<EOL><INDENT>value = value[value.rfind('<STR_LIT:->'):]<EOL><DEDENT>value = value[<NUM_LIT:1>:]<EOL>offset_components = value.split('<STR_LIT::>')<EOL>if len(offset_components) != <NUM_LIT:2>:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value))<EOL>)<EOL><DEDENT>hour = int(offset_components[<NUM_LIT:0>])<EOL>minutes = int(offset_components[<NUM_LIT:1>])<EOL>value = (hour * <NUM_LIT> * <NUM_LIT>) + (minutes * <NUM_LIT>)<EOL>if not positive:<EOL><INDENT>value = <NUM_LIT:0> - value<EOL><DEDENT><DEDENT>if isinstance(value, numeric_types):<EOL><INDENT>if value > <NUM_LIT:0>:<EOL><INDENT>positive = True<EOL><DEDENT>elif value < <NUM_LIT:0>:<EOL><INDENT>positive = False<EOL><DEDENT>elif value == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>offset = datetime_.timedelta(seconds = value)<EOL>if is_py2:<EOL><INDENT>value = TimeZone(offset = offset)<EOL><DEDENT>elif is_py3:<EOL><INDENT>try:<EOL><INDENT>value = TimeZone(offset)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.UTCOffsetError(<EOL>'<STR_LIT>' % original_value<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplementedError()<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** verify whether the value is a timezone that actually
exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``).
For that kind of functionality, we recommend you utilize:
`pytz <https://pypi.python.org/pypi/pytz>`_
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`tzinfo <python:datetime.tzinfo>`
/ numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param positive: Indicates whether the ``value`` is positive or negative
(only has meaning if ``value`` is a string). Defaults to ``True``.
:type positive: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`tzinfo <python:datetime.tzinfo>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to
:class:`tzinfo <python:datetime.tzinfo>` and is not :obj:`None <python:None>`
:raises PositiveOffsetMismatchError: if ``positive`` is ``True``, but the offset
indicated by ``value`` is actually negative
:raises NegativeOffsetMismatchError: if ``positive`` is ``False``, but the offset
indicated by ``value`` is actually positive
|
f3771:m11
|
@disable_on_env<EOL>def numeric(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
if maximum is None:<EOL><INDENT>maximum = POSITIVE_INFINITY<EOL><DEDENT>else:<EOL><INDENT>maximum = numeric(maximum)<EOL><DEDENT>if minimum is None:<EOL><INDENT>minimum = NEGATIVE_INFINITY<EOL><DEDENT>else:<EOL><INDENT>minimum = numeric(minimum)<EOL><DEDENT>if value is None and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif value is not None:<EOL><INDENT>if isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>value = float_(value)<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT>elif not isinstance(value, numeric_types):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % (value,<EOL>type(value))<EOL>)<EOL><DEDENT><DEDENT>if value is not None and value > maximum:<EOL><INDENT>raise errors.MaximumValueError(<EOL>'<STR_LIT>' % (value, maximum)<EOL>)<EOL><DEDENT>if value is not None and value < minimum:<EOL><INDENT>raise errors.MinimumValueError(<EOL>'<STR_LIT>' % (value, minimum)<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a numeric value.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises an
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form
|
f3771:m12
|
@disable_on_env<EOL>def integer(value,<EOL>allow_empty = False,<EOL>coerce_value = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>base = <NUM_LIT:10>,<EOL>**kwargs):
|
value = numeric(value, <EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>force_run = True)<EOL>if value is not None and hasattr(value, '<STR_LIT>'):<EOL><INDENT>if value.is_integer():<EOL><INDENT>return int(value)<EOL><DEDENT><DEDENT>if value is not None and coerce_value:<EOL><INDENT>float_value = math.ceil(value)<EOL>if is_py2:<EOL><INDENT>value = int(float_value) <EOL><DEDENT>elif is_py3:<EOL><INDENT>str_value = str(float_value)<EOL>value = int(str_value, base = base)<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>' % os.sys.version)<EOL><DEDENT><DEDENT>elif value is not None and not isinstance(value, integer_types):<EOL><INDENT>raise errors.NotAnIntegerError('<STR_LIT>'<EOL>'<STR_LIT>'% (value, type(value))<EOL>)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is an :class:`int <python:int>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will force any numeric ``value`` to an integer
(always rounding up). If ``False``, will raise an error if ``value`` is numeric
but not a whole number. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises NotAnIntegerError: if ``coerce_value`` is ``False``, and ``value``
is not an integer
:raises CannotCoerceError: if ``value`` cannot be coerced to an
:class:`int <python:int>`
|
f3771:m13
|
@disable_on_env<EOL>def float(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = _numeric_coercion(value,<EOL>coercion_function = float_,<EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum)<EOL><DEDENT>except (errors.EmptyValueError,<EOL>errors.CannotCoerceError,<EOL>errors.MinimumValueError,<EOL>errors.MaximumValueError) as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception as error:<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a :class:`float <python:float>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`float <python:float>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`float <python:float>`
|
f3771:m14
|
@disable_on_env<EOL>def fraction(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = _numeric_coercion(value,<EOL>coercion_function = fractions.Fraction,<EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum)<EOL><DEDENT>except (errors.EmptyValueError,<EOL>errors.CannotCoerceError,<EOL>errors.MinimumValueError,<EOL>errors.MaximumValueError) as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception as error:<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Fraction <python:fractions.Fraction>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Fraction <python:fractions.Fraction>`
|
f3771:m15
|
@disable_on_env<EOL>def decimal(value,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
if value is None and allow_empty:<EOL><INDENT>return None<EOL><DEDENT>elif value is None:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(value, str):<EOL><INDENT>try:<EOL><INDENT>value = decimal_.Decimal(value.strip())<EOL><DEDENT>except decimal_.InvalidOperation:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT>elif isinstance(value, fractions.Fraction):<EOL><INDENT>try:<EOL><INDENT>value = float(value, force_run = True) <EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT>value = numeric(value, <EOL>allow_empty = False,<EOL>maximum = maximum,<EOL>minimum = minimum,<EOL>force_run = True)<EOL>if not isinstance(value, decimal_.Decimal):<EOL><INDENT>value = decimal_.Decimal(value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Decimal <python:decimal.Decimal>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the
``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Decimal <python:decimal.Decimal>`
|
f3771:m16
|
def _numeric_coercion(value,<EOL>coercion_function = None,<EOL>allow_empty = False,<EOL>minimum = None,<EOL>maximum = None):
|
if coercion_function is None:<EOL><INDENT>raise errors.CoercionFunctionEmptyError('<STR_LIT>')<EOL><DEDENT>elif not hasattr(coercion_function, '<STR_LIT>'):<EOL><INDENT>raise errors.NotCallableError('<STR_LIT>')<EOL><DEDENT>value = numeric(value, <EOL>allow_empty = allow_empty,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>force_run = True)<EOL>if value is not None:<EOL><INDENT>try:<EOL><INDENT>value = coercion_function(value)<EOL><DEDENT>except (ValueError, TypeError, AttributeError, IndexError, SyntaxError):<EOL><INDENT>raise errors.CannotCoerceError(<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callable
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: the type returned by ``coercion_function``
:raises CoercionFunctionEmptyError: if ``coercion_function`` is empty
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises CannotCoerceError: if ``coercion_function`` raises an
:class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`,
:class:`AttributeError <python:AttributeError>`,
:class:`IndexError <python:IndexError>, or
:class:`SyntaxError <python:SyntaxError>`
|
f3771:m17
|
@disable_on_env<EOL>def bytesIO(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, io.BytesIO):<EOL><INDENT>raise errors.NotBytesIOError('<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value)))<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`BytesIO <python:io.BytesIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotBytesIOError: if ``value`` is not a :class:`BytesIO <python:io.BytesIO>`
object.
|
f3771:m18
|
@disable_on_env<EOL>def stringIO(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, io.StringIO):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % (value, type(value)))<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`StringIO <python:io.StringIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotStringIOError: if ``value`` is not a :class:`StringIO <python:io.StringIO>`
object
|
f3771:m19
|
@disable_on_env<EOL>def path(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if hasattr(os, '<STR_LIT>'):<EOL><INDENT>if not isinstance(value, (str, bytes, int, os.PathLike)): <EOL><INDENT>raise errors.NotPathlikeError('<STR_LIT>' % value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not isinstance(value, int):<EOL><INDENT>try:<EOL><INDENT>os.path.exists(value)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise errors.NotPathlikeError('<STR_LIT>' % value)<EOL><DEDENT><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid path-like object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The path represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
:raises NotPathlikeError: if ``value`` is not a valid path-like object
|
f3771:m20
|
@disable_on_env<EOL>def path_exists(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path(value, force_run = True) <EOL>if not os.path.exists(value):<EOL><INDENT>raise errors.PathExistsError('<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist
|
f3771:m21
|
@disable_on_env<EOL>def file_exists(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path_exists(value, force_run = True) <EOL>if not os.path.isfile(value):<EOL><INDENT>raise errors.NotAFileError('<STR_LIT>')<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid file that exists on the local filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
|
f3771:m22
|
@disable_on_env<EOL>def directory_exists(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path_exists(value, force_run = True) <EOL>if not os.path.isdir(value):<EOL><INDENT>raise errors.NotADirectoryError('<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid directory that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotADirectoryError: if ``value`` is not a valid directory
|
f3771:m23
|
@disable_on_env<EOL>def readable(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = file_exists(value, force_run = True) <EOL>try:<EOL><INDENT>with open(value, mode='<STR_LIT:r>'):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>except (OSError, IOError):<EOL><INDENT>raise errors.NotReadableError('<STR_LIT>'<EOL>'<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a path to a readable file.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the readability of a file *before* attempting to read it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The path to a file on the local filesystem whose readability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated path-like object or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
:raises NotReadableError: if ``value`` cannot be opened for reading
|
f3771:m24
|
@disable_on_env<EOL>def writeable(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = path(value, force_run = True)<EOL>if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>is_valid = os.access(value, mode = os.W_OK)<EOL>if not is_valid:<EOL><INDENT>raise errors.NotWriteableError('<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a path to a writeable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotWriteableError: if ``value`` cannot be opened for writing
|
f3771:m25
|
@disable_on_env<EOL>def executable(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>value = file_exists(value, force_run = True)<EOL>if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>is_valid = os.access(value, mode = os.X_OK)<EOL>if not is_valid:<EOL><INDENT>raise errors.NotExecutableError('<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a path to an executable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the executability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is executable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotAFileError: if ``value`` does not exist on the local file system
:raises NotExecutableError: if ``value`` cannot be executed
|
f3771:m26
|
@disable_on_env<EOL>def email(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' % type(value))<EOL><DEDENT>if '<STR_LIT:@>' not in value:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>' % value)<EOL><DEDENT>if '<STR_LIT:(>' in value and '<STR_LIT:)>' in value:<EOL><INDENT>open_parentheses = value.find('<STR_LIT:(>')<EOL>close_parentheses = value.find('<STR_LIT:)>') + <NUM_LIT:1><EOL>if close_parentheses < open_parentheses:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT>commented_value = value[open_parentheses:close_parentheses]<EOL>value = value.replace(commented_value, '<STR_LIT>')<EOL><DEDENT>elif '<STR_LIT:(>' in value:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>' % value)<EOL><DEDENT>elif '<STR_LIT:)>' in value:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>' % value)<EOL><DEDENT>if '<STR_LIT:<>' in value or '<STR_LIT:>>' in value:<EOL><INDENT>lt_position = value.find('<STR_LIT:<>')<EOL>gt_position = value.find('<STR_LIT:>>')<EOL>first_quote_position = -<NUM_LIT:1><EOL>second_quote_position = -<NUM_LIT:1><EOL>if lt_position >= <NUM_LIT:0>:<EOL><INDENT>first_quote_position = value.find('<STR_LIT:">', <NUM_LIT:0>, lt_position)<EOL><DEDENT>if gt_position >= <NUM_LIT:0>:<EOL><INDENT>second_quote_position = value.find('<STR_LIT:">', gt_position)<EOL><DEDENT>if first_quote_position < <NUM_LIT:0> or second_quote_position < <NUM_LIT:0>:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT><DEDENT>at_count = value.count('<STR_LIT:@>')<EOL>if at_count > <NUM_LIT:1>:<EOL><INDENT>last_at_position = <NUM_LIT:0><EOL>last_quote_position = <NUM_LIT:0><EOL>for x in range(<NUM_LIT:0>, at_count): <EOL><INDENT>at_position = value.find('<STR_LIT:@>', last_at_position + <NUM_LIT:1>)<EOL>if at_position >= <NUM_LIT:0>:<EOL><INDENT>first_quote_position = value.find('<STR_LIT:">',<EOL>last_quote_position,<EOL>at_position)<EOL>second_quote_position = value.find('<STR_LIT:">',<EOL>first_quote_position)<EOL>if first_quote_position < <NUM_LIT:0> or second_quote_position < <NUM_LIT:0>:<EOL><INDENT>raise errors.InvalidEmailError(<EOL>'<STR_LIT>' % value<EOL>)<EOL><DEDENT><DEDENT>last_at_position = at_position<EOL>last_quote_position = second_quote_position<EOL><DEDENT><DEDENT>split_values = value.split('<STR_LIT:@>')<EOL>if len(split_values) < <NUM_LIT:2>:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>' % value)<EOL><DEDENT>local_value = '<STR_LIT>'.join(split_values[:-<NUM_LIT:1>])<EOL>domain_value = split_values[-<NUM_LIT:1>]<EOL>is_domain = False<EOL>is_ip = False<EOL>try:<EOL><INDENT>if domain_value.startswith('<STR_LIT:[>') and domain_value.endswith('<STR_LIT:]>'):<EOL><INDENT>domain_value = domain_value[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>domain(domain_value)<EOL>is_domain = True<EOL><DEDENT>except ValueError:<EOL><INDENT>is_domain = False<EOL><DEDENT>if not is_domain:<EOL><INDENT>try:<EOL><INDENT>ip_address(domain_value, force_run = True) <EOL>is_ip = True<EOL><DEDENT>except ValueError:<EOL><INDENT>is_ip = False<EOL><DEDENT><DEDENT>if not is_domain and is_ip:<EOL><INDENT>try:<EOL><INDENT>email(local_value + '<STR_LIT>', force_run = True) <EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT>return value<EOL><DEDENT>if not is_domain:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>' % value)<EOL><DEDENT>else:<EOL><INDENT>is_valid = EMAIL_REGEX.search(value)<EOL>if not is_valid:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT>matched_string = is_valid.group(<NUM_LIT:0>)<EOL>position = value.find(matched_string)<EOL>if position > <NUM_LIT:0>:<EOL><INDENT>prefix = value[:position]<EOL>if prefix[<NUM_LIT:0>] in string_.punctuation:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT>if '<STR_LIT:..>' in prefix:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT><DEDENT>end_of_match = position + len(matched_string)<EOL>suffix = value[end_of_match:]<EOL>if suffix:<EOL><INDENT>raise errors.InvalidEmailError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid email address.
.. note::
Email address validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of
string parsing and regular expressions.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidEmailError: if ``value`` is not a valid email address or
empty with ``allow_empty`` set to ``True``
|
f3771:m27
|
@disable_on_env<EOL>def url(value,<EOL>allow_empty = False,<EOL>allow_special_ips = False,<EOL>**kwargs):
|
is_recursive = kwargs.pop('<STR_LIT>', False)<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' % type(value))<EOL><DEDENT>value = value.lower()<EOL>is_valid = False<EOL>stripped_value = None<EOL>for protocol in URL_PROTOCOLS:<EOL><INDENT>if protocol in value:<EOL><INDENT>stripped_value = value.replace(protocol, '<STR_LIT>')<EOL><DEDENT><DEDENT>for special_use_domain in SPECIAL_USE_DOMAIN_NAMES:<EOL><INDENT>if special_use_domain in value:<EOL><INDENT>if stripped_value:<EOL><INDENT>try:<EOL><INDENT>domain(stripped_value,<EOL>allow_empty = False,<EOL>is_recursive = is_recursive)<EOL>is_valid = True<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not is_valid and allow_special_ips:<EOL><INDENT>try:<EOL><INDENT>ip_address(stripped_value, allow_empty = False)<EOL>is_valid = True<EOL><DEDENT>except (ValueError, TypeError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not is_valid:<EOL><INDENT>is_valid = URL_REGEX.match(value)<EOL><DEDENT>if not is_valid and allow_special_ips:<EOL><INDENT>is_valid = URL_SPECIAL_IP_REGEX.match(value)<EOL><DEDENT>if not is_valid:<EOL><INDENT>raise errors.InvalidURLError('<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
`RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults
to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidURLError: if ``value`` is not a valid URL or
empty with ``allow_empty`` set to ``True``
|
f3771:m28
|
@disable_on_env<EOL>def domain(value,<EOL>allow_empty = False,<EOL>allow_ips = False,<EOL>**kwargs):
|
is_recursive = kwargs.pop('<STR_LIT>', False)<EOL>if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' % type(value))<EOL><DEDENT>if '<STR_LIT:/>' in value:<EOL><INDENT>raise errors.SlashInDomainError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:\\>' in value:<EOL><INDENT>raise errors.SlashInDomainError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:@>' in value:<EOL><INDENT>raise errors.AtInDomainError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT::>' in value:<EOL><INDENT>raise errors.ColonInDomainError('<STR_LIT>')<EOL><DEDENT>value = value.strip().lower()<EOL>for item in string_.whitespace:<EOL><INDENT>if item in value:<EOL><INDENT>raise errors.WhitespaceInDomainError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if value in SPECIAL_USE_DOMAIN_NAMES:<EOL><INDENT>return value<EOL><DEDENT>if allow_ips:<EOL><INDENT>try:<EOL><INDENT>ip_address(value, allow_empty = allow_empty)<EOL>is_valid = True<EOL><DEDENT>except (ValueError, TypeError, AttributeError):<EOL><INDENT>is_valid = False<EOL><DEDENT>if is_valid:<EOL><INDENT>return value<EOL><DEDENT><DEDENT>is_valid = DOMAIN_REGEX.match(value)<EOL>if not is_valid and not is_recursive:<EOL><INDENT>with_prefix = '<STR_LIT>' + value<EOL>try:<EOL><INDENT>url(with_prefix, force_run = True, is_recursive = True) <EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.InvalidDomainError('<STR_LIT>' % value)<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid domain name.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:password@domain.dev``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
.. hint::
Leading and trailing whitespace will be automatically stripped.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will raise a :class:`InvalidDomainError` if ``value`` is an IP
address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidDomainError: if ``value`` is not a valid domain name or
empty with ``allow_empty`` set to ``True``
:raises SlashInDomainError: if ``value`` contains a slash or backslash
:raises AtInDomainError: if ``value`` contains an ``@`` symbol
:raises ColonInDomainError: if ``value`` contains a ``:`` symbol
:raises WhitespaceInDomainError: if ``value`` contains whitespace
|
f3771:m29
|
@disable_on_env<EOL>def ip_address(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if is_py2 and value and isinstance(value, unicode):<EOL><INDENT>value = value.encode('<STR_LIT:utf-8>')<EOL><DEDENT>try:<EOL><INDENT>value = ipv6(value, force_run = True) <EOL>ipv6_failed = False<EOL><DEDENT>except ValueError:<EOL><INDENT>ipv6_failed = True<EOL><DEDENT>if ipv6_failed:<EOL><INDENT>try:<EOL><INDENT>value = ipv4(value, force_run = True) <EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>'<EOL>'<STR_LIT>' % value)<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid IP address.
.. note::
First, the validator will check if the address is a valid IPv6 address.
If that doesn't work, the validator will check if the address is a valid
IPv4 address.
If neither works, the validator will raise an error (as always).
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with
``allow_empty`` set to ``True``
|
f3771:m30
|
@disable_on_env<EOL>def ipv4(value, allow_empty = False):
|
if not value and allow_empty is False:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>components = value.split('<STR_LIT:.>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % value)<EOL><DEDENT>if len(components) != <NUM_LIT:4> or not all(x.isdigit() for x in components):<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % value)<EOL><DEDENT>for x in components:<EOL><INDENT>try:<EOL><INDENT>x = integer(x,<EOL>minimum = <NUM_LIT:0>,<EOL>maximum = <NUM_LIT:255>)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % value)<EOL><DEDENT><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid IP version 4 address.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or
empty with ``allow_empty`` set to ``True``
|
f3771:m31
|
@disable_on_env<EOL>def ipv6(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and allow_empty is False:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, str):<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % value)<EOL><DEDENT>value = value.lower().strip()<EOL>is_valid = IPV6_REGEX.match(value)<EOL>if not is_valid:<EOL><INDENT>raise errors.InvalidIPAddressError('<STR_LIT>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid IP address version 6.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or
empty with ``allow_empty`` is not set to ``True``
|
f3771:m32
|
@disable_on_env<EOL>def mac_address(value,<EOL>allow_empty = False,<EOL>**kwargs):
|
if not value and not allow_empty:<EOL><INDENT>raise errors.EmptyValueError('<STR_LIT>' % value)<EOL><DEDENT>elif not value:<EOL><INDENT>return None<EOL><DEDENT>if not isinstance(value, basestring):<EOL><INDENT>raise errors.CannotCoerceError('<STR_LIT>'<EOL>'<STR_LIT>' % type(value))<EOL><DEDENT>if '<STR_LIT:->' in value:<EOL><INDENT>value = value.replace('<STR_LIT:->', '<STR_LIT::>')<EOL><DEDENT>value = value.lower().strip()<EOL>is_valid = MAC_ADDRESS_REGEX.match(value)<EOL>if not is_valid:<EOL><INDENT>raise errors.InvalidMACAddressError('<STR_LIT>'<EOL>'<STR_LIT:address>' % value)<EOL><DEDENT>return value<EOL>
|
Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>`
or string-like object
:raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with
``allow_empty`` set to ``True``
|
f3771:m33
|
def disable_on_env(func):
|
@wraps(func)<EOL>def func_wrapper(*args, **kwargs):<EOL><INDENT>function_name = func.__name__<EOL>VALIDATORS_DISABLED = os.getenv('<STR_LIT>', '<STR_LIT>')<EOL>disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split('<STR_LIT:U+002C>')]<EOL>force_run = kwargs.get('<STR_LIT>', False)<EOL>try:<EOL><INDENT>value = args[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>raise ValidatorUsageError('<STR_LIT>')<EOL><DEDENT>if function_name in disabled_functions and not force_run:<EOL><INDENT>return value<EOL><DEDENT>else:<EOL><INDENT>updated_kwargs = {key : kwargs[key]<EOL>for key in kwargs<EOL>if key != '<STR_LIT>'}<EOL>return func(*args, **updated_kwargs)<EOL><DEDENT><DEDENT>return func_wrapper<EOL>
|
Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, the ``value`` (first positional argument) passed to
``func``. If enabled, the result of ``func``.
|
f3775:m0
|
def disable_checker_on_env(func):
|
@wraps(func)<EOL>def func_wrapper(*args, **kwargs):<EOL><INDENT>function_name = func.__name__<EOL>CHECKERS_DISABLED = os.getenv('<STR_LIT>', '<STR_LIT>')<EOL>disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split('<STR_LIT:U+002C>')]<EOL>force_run = kwargs.get('<STR_LIT>', False)<EOL>if function_name in disabled_functions and not force_run:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT>return func_wrapper<EOL>
|
Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, ``True``. If enabled, the result of ``func``.
|
f3775:m1
|
@disable_checker_on_env<EOL>def is_type(obj,<EOL>type_,<EOL>**kwargs):
|
if not is_iterable(type_):<EOL><INDENT>type_ = [type_]<EOL><DEDENT>return_value = False<EOL>for check_for_type in type_:<EOL><INDENT>if isinstance(check_for_type, type):<EOL><INDENT>return_value = isinstance(obj, check_for_type)<EOL><DEDENT>elif obj.__class__.__name__ == check_for_type:<EOL><INDENT>return_value = True<EOL><DEDENT>else:<EOL><INDENT>return_value = _check_base_classes(obj.__class__.__bases__,<EOL>check_for_type)<EOL><DEDENT>if return_value is True:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return return_value<EOL>
|
Indicate if ``obj`` is a type in ``type_``.
.. hint::
This checker is particularly useful when you want to evaluate whether
``obj`` is of a particular type, but importing that type directly to use
in :func:`isinstance() <python:isinstance>` would cause a circular import
error.
To use this checker in that kind of situation, you can instead pass the
*name* of the type you want to check as a string in ``type_``. The checker
will evaluate it and see whether ``obj`` is of a type or inherits from a
type whose name matches the string you passed.
:param obj: The object whose type should be checked.
:type obj: :class:`object <python:object>`
:param type_: The type(s) to check against.
:type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /
:class:`str <python:str>` with type name / iterable of :class:`str <python:str>`
with type name
:returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m0
|
def _check_base_classes(base_classes, check_for_type):
|
return_value = False<EOL>for base in base_classes:<EOL><INDENT>if base.__name__ == check_for_type:<EOL><INDENT>return_value = True<EOL>break<EOL><DEDENT>else:<EOL><INDENT>return_value = _check_base_classes(base.__bases__, check_for_type)<EOL>if return_value is True:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return return_value<EOL>
|
Indicate whether ``check_for_type`` exists in ``base_classes``.
|
f3776:m1
|
@disable_checker_on_env<EOL>def are_equivalent(*args, **kwargs):
|
if len(args) == <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>first_item = args[<NUM_LIT:0>]<EOL>for item in args[<NUM_LIT:1>:]:<EOL><INDENT>if type(item) != type(first_item): <EOL><INDENT>return False<EOL><DEDENT>if isinstance(item, dict):<EOL><INDENT>if not are_dicts_equivalent(item, first_item):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif hasattr(item, '<STR_LIT>') and not isinstance(item, (str, bytes, dict)):<EOL><INDENT>if len(item) != len(first_item):<EOL><INDENT>return False<EOL><DEDENT>for value in item:<EOL><INDENT>if value not in first_item:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>for value in first_item:<EOL><INDENT>if value not in item:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if item != first_item:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>
|
Indicate if arguments passed to this function are equivalent.
.. hint::
This checker operates recursively on the members contained within iterables
and :class:`dict <python:dict>` objects.
.. caution::
If you only pass one argument to this checker - even if it is an iterable -
the checker will *always* return ``True``.
To evaluate members of an iterable for equivalence, you should instead
unpack the iterable into the function like so:
.. code-block:: python
obj = [1, 1, 1, 2]
result = are_equivalent(*obj)
# Will return ``False`` by unpacking and evaluating the iterable's members
result = are_equivalent(obj)
# Will always return True
:param args: One or more values, passed as positional arguments.
:returns: ``True`` if ``args`` are equivalent, and ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m2
|
@disable_checker_on_env<EOL>def are_dicts_equivalent(*args, **kwargs):
|
<EOL>if not args:<EOL><INDENT>return False<EOL><DEDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>if not all(is_dict(x) for x in args):<EOL><INDENT>return False<EOL><DEDENT>first_item = args[<NUM_LIT:0>]<EOL>for item in args[<NUM_LIT:1>:]:<EOL><INDENT>if len(item) != len(first_item):<EOL><INDENT>return False<EOL><DEDENT>for key in item:<EOL><INDENT>if key not in first_item:<EOL><INDENT>return False<EOL><DEDENT>if not are_equivalent(item[key], first_item[key]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>for key in first_item:<EOL><INDENT>if key not in item:<EOL><INDENT>return False<EOL><DEDENT>if not are_equivalent(first_item[key], item[key]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>
|
Indicate if :ref:`dicts <python:dict>` passed to this function have identical
keys and values.
:param args: One or more values, passed as positional arguments.
:returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m3
|
@disable_checker_on_env<EOL>def is_between(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
if minimum is None and maximum is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if value is None:<EOL><INDENT>return False<EOL><DEDENT>if minimum is not None and maximum is None:<EOL><INDENT>return value >= minimum<EOL><DEDENT>elif minimum is None and maximum is not None:<EOL><INDENT>return value <= maximum<EOL><DEDENT>elif minimum is not None and maximum is not None:<EOL><INDENT>return value >= minimum and value <= maximum<EOL><DEDENT>
|
Indicate whether ``value`` is greater than or equal to a supplied ``minimum``
and/or less than or equal to ``maximum``.
.. note::
This function works on any ``value`` that support comparison operators,
whether they are numbers or not. Technically, this means that ``value``,
``minimum``, or ``maximum`` need to implement the Python magic methods
:func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`.
If ``value``, ``minimum``, or ``maximum`` do not support comparison
operators, they will raise :class:`NotImplemented <python:NotImplemented>`.
:param value: The ``value`` to check.
:type value: anything that supports comparison operators
:param minimum: If supplied, will return ``True`` if ``value`` is greater than or
equal to this value.
:type minimum: anything that supports comparison operators /
:obj:`None <python:None>`
:param maximum: If supplied, will return ``True`` if ``value`` is less than or
equal to this value.
:type maximum: anything that supports comparison operators /
:obj:`None <python:None>`
:returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum``
and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
:raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not
support comparison operators
:raises ValueError: if both ``minimum`` and ``maximum`` are
:obj:`None <python:None>`
|
f3776:m4
|
@disable_checker_on_env<EOL>def has_length(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
if minimum is None and maximum is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>length = len(value)<EOL>minimum = validators.numeric(minimum,<EOL>allow_empty = True)<EOL>maximum = validators.numeric(maximum,<EOL>allow_empty = True)<EOL>return is_between(length,<EOL>minimum = minimum,<EOL>maximum = maximum)<EOL>
|
Indicate whether ``value`` has a length greater than or equal to a
supplied ``minimum`` and/or less than or equal to ``maximum``.
.. note::
This function works on any ``value`` that supports the
:func:`len() <python:len>` operation. This means that ``value`` must implement
the :func:`__len__ <python:__len__>` magic method.
If ``value`` does not support length evaluation, the checker will raise
:class:`NotImplemented <python:NotImplemented>`.
:param value: The ``value`` to check.
:type value: anything that supports length evaluation
:param minimum: If supplied, will return ``True`` if ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will return ``True`` if ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` has length greater than or equal to a
supplied ``minimum`` and less than or equal to a supplied ``maximum``.
Otherwise, returns ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
:raises TypeError: if ``value`` does not support length evaluation
:raises ValueError: if both ``minimum`` and ``maximum`` are
:obj:`None <python:None>`
|
f3776:m5
|
@disable_checker_on_env<EOL>def is_dict(value, **kwargs):
|
if isinstance(value, dict):<EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>value = validators.dict(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid :class:`dict <python:dict>`
.. note::
This will return ``True`` even if ``value`` is an empty
:class:`dict <python:dict>`.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m6
|
@disable_checker_on_env<EOL>def is_json(value,<EOL>schema = None,<EOL>json_serializer = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.json(value,<EOL>schema = schema,<EOL>json_serializer = json_serializer,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid JSON object.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
:param value: The value to evaluate.
:param schema: An optional JSON schema against which ``value`` will be validated.
:type schema: :class:`dict <python:dict>` / :class:`str <python:str>` /
:obj:`None <python:None>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m7
|
@disable_checker_on_env<EOL>def is_string(value,<EOL>coerce_value = False,<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>whitespace_padding = False,<EOL>**kwargs):
|
if value is None:<EOL><INDENT>return False<EOL><DEDENT>minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs)<EOL>maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs)<EOL>if isinstance(value, basestring) and not value:<EOL><INDENT>if minimum_length and minimum_length > <NUM_LIT:0> and not whitespace_padding:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>try:<EOL><INDENT>value = validators.string(value,<EOL>coerce_value = coerce_value,<EOL>minimum_length = minimum_length,<EOL>maximum_length = maximum_length,<EOL>whitespace_padding = whitespace_padding,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a string.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will check whether ``value`` can be coerced
to a string if it is not already. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m8
|
@disable_checker_on_env<EOL>def is_iterable(obj,<EOL>forbid_literals = (str, bytes),<EOL>minimum_length = None,<EOL>maximum_length = None,<EOL>**kwargs):
|
if obj is None:<EOL><INDENT>return False<EOL><DEDENT>if obj in forbid_literals:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>obj = validators.iterable(obj,<EOL>allow_empty = True,<EOL>forbid_literals = forbid_literals,<EOL>minimum_length = minimum_length,<EOL>maximum_length = maximum_length,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``obj`` is iterable.
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to a :class:`tuple <python:tuple>`
containing :class:`str <python:str>` and :class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``True`` if ``obj`` is a valid iterable, ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m9
|
@disable_checker_on_env<EOL>def is_not_empty(value, **kwargs):
|
try:<EOL><INDENT>value = validators.not_empty(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is empty.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is empty, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m10
|
@disable_checker_on_env<EOL>def is_none(value, allow_empty = False, **kwargs):
|
try:<EOL><INDENT>validators.none(value, allow_empty = allow_empty, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is :obj:`None <python:None>`.
:param value: The value to evaluate.
:param allow_empty: If ``True``, accepts falsey values as equivalent to
:obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is :obj:`None <python:None>`, ``False``
if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m11
|
@disable_checker_on_env<EOL>def is_variable_name(value, **kwargs):
|
try:<EOL><INDENT>validators.variable_name(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid Python variable name.
.. caution::
This function does **NOT** check whether the variable exists. It only
checks that the ``value`` would work as a Python variable (or class, or
function, etc.) name.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m12
|
@disable_checker_on_env<EOL>def is_callable(value, **kwargs):
|
return hasattr(value, '<STR_LIT>')<EOL>
|
Indicate whether ``value`` is callable (like a function, method, or class).
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m13
|
@disable_checker_on_env<EOL>def is_uuid(value, **kwargs):
|
try:<EOL><INDENT>validators.uuid(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` contains a :class:`UUID <python:uuid.UUID>`
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m14
|
@disable_checker_on_env<EOL>def is_date(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = False,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.date(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>coerce_value = coerce_value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a :class:`date <python:datetime.date>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is on or after
this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param coerce_value: If ``True``, will return ``True`` if ``value`` can be
coerced to a :class:`date <python:datetime.date>`. If ``False``,
will only return ``True`` if ``value`` is a date value only. Defaults to
``False``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m15
|
@disable_checker_on_env<EOL>def is_datetime(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = False,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.datetime(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>coerce_value = coerce_value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a :class:`datetime <python:datetime.datetime>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is on or after
this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param coerce_value: If ``True``, will return ``True`` if ``value`` can be
coerced to a :class:`datetime <python:datetime.datetime>`. If ``False``,
will only return ``True`` if ``value`` is a complete timestamp. Defaults to
``False``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m16
|
@disable_checker_on_env<EOL>def is_time(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>coerce_value = False,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.time(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>coerce_value = coerce_value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a :class:`time <python:datetime.time>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param coerce_value: If ``True``, will return ``True`` if ``value`` can be
coerced to a :class:`time <python:datetime.time>`. If ``False``,
will only return ``True`` if ``value`` is a valid time. Defaults to
``False``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m17
|
@disable_checker_on_env<EOL>def is_timezone(value,<EOL>positive = True,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.timezone(value,<EOL>positive = positive,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** validate whether the value is a timezone that actually
exists, nor can it resolve timzone names (e.g. ``'Eastern'`` or ``'CET'``).
For that kind of functionality, we recommend you utilize:
`pytz <https://pypi.python.org/pypi/pytz>`_
:param value: The value to evaluate.
:param positive: Indicates whether the ``value`` is positive or negative
(only has meaning if ``value`` is a string). Defaults to ``True``.
:type positive: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m18
|
@disable_checker_on_env<EOL>def is_numeric(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.numeric(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a numeric value.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m19
|
@disable_checker_on_env<EOL>def is_integer(value,<EOL>coerce_value = False,<EOL>minimum = None,<EOL>maximum = None,<EOL>base = <NUM_LIT:10>,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.integer(value,<EOL>coerce_value = coerce_value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>base = base,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` contains a whole number.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced
to whole number. If ``False``, will only return ``True`` if ``value`` is already
a whole number (regardless of type). Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:type base: :class:`int <python:int>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m20
|
@disable_checker_on_env<EOL>def is_float(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.float(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a :class:`float <python:float>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m21
|
@disable_checker_on_env<EOL>def is_fraction(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.fraction(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m22
|
@disable_checker_on_env<EOL>def is_decimal(value,<EOL>minimum = None,<EOL>maximum = None,<EOL>**kwargs):
|
try:<EOL><INDENT>value = validators.decimal(value,<EOL>minimum = minimum,<EOL>maximum = maximum,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` contains a :class:`Decimal <python:decimal.Decimal>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m23
|
@disable_checker_on_env<EOL>def is_bytesIO(value, **kwargs):
|
return isinstance(value, io.BytesIO)<EOL>
|
Indicate whether ``value`` is a :class:`BytesIO <python:io.BytesIO>` object.
.. note::
This checker will return ``True`` even if ``value`` is empty, so long as
its type is a :class:`BytesIO <python:io.BytesIO>`.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m24
|
@disable_checker_on_env<EOL>def is_stringIO(value, **kwargs):
|
return isinstance(value, io.StringIO)<EOL>
|
Indicate whether ``value`` is a :class:`StringIO <python:io.StringIO>` object.
.. note::
This checker will return ``True`` even if ``value`` is empty, so long as
its type is a :class:`String <python:io.StringIO>`.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m25
|
@disable_checker_on_env<EOL>def is_pathlike(value, **kwargs):
|
try:<EOL><INDENT>value = validators.path(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a path-like object.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m26
|
@disable_checker_on_env<EOL>def is_on_filesystem(value, **kwargs):
|
try:<EOL><INDENT>value = validators.path_exists(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a file or directory that exists on the local
filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m27
|
@disable_checker_on_env<EOL>def is_file(value, **kwargs):
|
try:<EOL><INDENT>value = validators.file_exists(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a file that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m28
|
@disable_checker_on_env<EOL>def is_directory(value, **kwargs):
|
try:<EOL><INDENT>value = validators.directory_exists(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a directory that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m29
|
@disable_checker_on_env<EOL>def is_readable(value, **kwargs):
|
try:<EOL><INDENT>validators.readable(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a readable file.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the readability of a file *before* attempting to read it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m30
|
@disable_checker_on_env<EOL>def is_writeable(value,<EOL>**kwargs):
|
if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>validators.writeable(value,<EOL>allow_empty = False,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a writeable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises NotImplementedError: if called on a Windows system
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m31
|
@disable_checker_on_env<EOL>def is_executable(value,<EOL>**kwargs):
|
if sys.platform in ['<STR_LIT:win32>', '<STR_LIT>']:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>validators.executable(value,<EOL>**kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is an executable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The value to evaluate.
:type value: Path-like object
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises NotImplementedError: if called on a Windows system
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m32
|
@disable_checker_on_env<EOL>def is_email(value, **kwargs):
|
try:<EOL><INDENT>value = validators.email(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is an email address.
.. note::
Email address validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of
string parsing and regular expressions.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m33
|
@disable_checker_on_env<EOL>def is_url(value, **kwargs):
|
try:<EOL><INDENT>value = validators.url(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
`RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to evaluate.
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will fail if ``value`` is a special IP address. Defaults to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m34
|
@disable_checker_on_env<EOL>def is_domain(value, **kwargs):
|
try:<EOL><INDENT>value = validators.domain(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid domain.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:password@domain.dev``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
:param value: The value to evaluate.
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will fail if ``value`` is an IP address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m35
|
@disable_checker_on_env<EOL>def is_ip_address(value, **kwargs):
|
try:<EOL><INDENT>value = validators.ip_address(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid IP address (version 4 or version 6).
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m36
|
@disable_checker_on_env<EOL>def is_ipv4(value, **kwargs):
|
try:<EOL><INDENT>value = validators.ipv4(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid IP version 4 address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m37
|
@disable_checker_on_env<EOL>def is_ipv6(value, **kwargs):
|
try:<EOL><INDENT>value = validators.ipv6(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid IP version 6 address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m38
|
@disable_checker_on_env<EOL>def is_mac_address(value, **kwargs):
|
try:<EOL><INDENT>value = validators.mac_address(value, **kwargs)<EOL><DEDENT>except SyntaxError as error:<EOL><INDENT>raise error<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
Indicate whether ``value`` is a valid MAC address.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
|
f3776:m39
|
@command<EOL>def install_completion(<EOL>shell: arg(choices=('<STR_LIT>', '<STR_LIT>'), help='<STR_LIT>'),<EOL>to: arg(help='<STR_LIT>') = None,<EOL>overwrite: '<STR_LIT>' = False):
|
if shell == '<STR_LIT>':<EOL><INDENT>source = '<STR_LIT>'<EOL>to = to or '<STR_LIT>'<EOL><DEDENT>elif shell == '<STR_LIT>':<EOL><INDENT>source = '<STR_LIT>'<EOL>to = to or '<STR_LIT>'<EOL><DEDENT>source = asset_path(source)<EOL>destination = os.path.expanduser(to)<EOL>if os.path.isdir(destination):<EOL><INDENT>destination = os.path.join(destination, os.path.basename(source))<EOL><DEDENT>printer.info('<STR_LIT>', shell, '<STR_LIT>', destination)<EOL>if os.path.exists(destination):<EOL><INDENT>if overwrite:<EOL><INDENT>printer.info('<STR_LIT>'.format_map(locals()))<EOL><DEDENT>else:<EOL><INDENT>message = '<STR_LIT>'.format_map(locals())<EOL>overwrite = confirm(message, abort_on_unconfirmed=True)<EOL><DEDENT><DEDENT>copy_file(source, destination)<EOL>printer.info('<STR_LIT>'.format_map(locals()))<EOL>
|
Install command line completion script.
Currently, bash and fish are supported. The corresponding script
will be copied to an appropriate directory. If the script already
exists at that location, it will be overwritten by default.
|
f3779:m2
|
@command<EOL>def clean(verbose=False):
|
def rm(name):<EOL><INDENT>if os.path.isfile(name):<EOL><INDENT>os.remove(name)<EOL>if verbose:<EOL><INDENT>printer.info('<STR_LIT>', name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>printer.info('<STR_LIT>', name)<EOL><DEDENT><DEDENT><DEDENT>def rmdir(name):<EOL><INDENT>if os.path.isdir(name):<EOL><INDENT>shutil.rmtree(name)<EOL>if verbose:<EOL><INDENT>printer.info('<STR_LIT>', name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>printer.info('<STR_LIT>', name)<EOL><DEDENT><DEDENT><DEDENT>root = os.getcwd()<EOL>rmdir('<STR_LIT>')<EOL>rmdir('<STR_LIT>')<EOL>for path, dirs, files in os.walk(root):<EOL><INDENT>rel_path = os.path.relpath(path, root)<EOL>if rel_path == '<STR_LIT:.>':<EOL><INDENT>rel_path = '<STR_LIT>'<EOL><DEDENT>if rel_path.startswith('<STR_LIT:.>'):<EOL><INDENT>continue<EOL><DEDENT>for d in dirs:<EOL><INDENT>if d == '<STR_LIT>':<EOL><INDENT>rmdir(os.path.join(rel_path, d))<EOL><DEDENT><DEDENT>for f in files:<EOL><INDENT>if f.endswith('<STR_LIT>') or f.endswith('<STR_LIT>'):<EOL><INDENT>rm(os.path.join(rel_path, f))<EOL><DEDENT><DEDENT><DEDENT>
|
Clean up.
Removes:
- ./build/
- ./dist/
- **/__pycache__
- **/*.py[co]
Skips hidden directories.
|
f3779:m6
|
def parse_optional(self, string):
|
option_map = self.option_map<EOL>if string in option_map:<EOL><INDENT>return string, option_map[string], None<EOL><DEDENT>if '<STR_LIT:=>' in string:<EOL><INDENT>name, value = string.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>if name in option_map:<EOL><INDENT>return name, option_map[name], value<EOL><DEDENT><DEDENT>return None<EOL>
|
Parse string into name, option, and value (if possible).
If the string is a known option name, the string, the
corresponding option, and ``None`` will be returned.
If the string has the form ``--option=<value>`` or
``-o=<value>``, it will be split on equals into an option name
and value. If the option name is known, the option name, the
corresponding option, and the value will be returned.
In all other cases, ``None`` will be returned to indicate that
the string doesn't correspond to a known option.
|
f3786:c0:m7
|
def expand_short_options(self, argv):
|
new_argv = []<EOL>for arg in argv:<EOL><INDENT>result = self.parse_multi_short_option(arg)<EOL>new_argv.extend(result)<EOL><DEDENT>return new_argv<EOL>
|
Convert grouped short options like `-abc` to `-a, -b, -c`.
This is necessary because we set ``allow_abbrev=False`` on the
``ArgumentParser`` in :prop:`self.arg_parser`. The argparse docs
say ``allow_abbrev`` applies only to long options, but it also
affects whether short options grouped behind a single dash will
be parsed into multiple short options.
|
f3786:c0:m8
|
def find_arg(self, name):
|
name = self.normalize_name(name)<EOL>return self.args.get(name)<EOL>
|
Find arg by normalized arg name or parameter name.
|
f3786:c0:m11
|
def find_parameter(self, name):
|
name = self.normalize_name(name)<EOL>arg = self.args.get(name)<EOL>return None if arg is None else arg.parameter<EOL>
|
Find parameter by name or normalized arg name.
|
f3786:c0:m12
|
@cached_property<EOL><INDENT>def args(self):<DEDENT>
|
params = self.parameters<EOL>args = OrderedDict()<EOL>args['<STR_LIT>'] = HelpArg(command=self)<EOL>normalize_name = self.normalize_name<EOL>get_arg_config = self.get_arg_config<EOL>get_short_option = self.get_short_option_for_arg<EOL>get_long_option = self.get_long_option_for_arg<EOL>get_inverse_option = self.get_inverse_option_for_arg<EOL>names = {normalize_name(name) for name in params}<EOL>used_short_options = set()<EOL>for param in params.values():<EOL><INDENT>annotation = get_arg_config(param)<EOL>short_option = annotation.short_option<EOL>if short_option:<EOL><INDENT>used_short_options.add(short_option)<EOL><DEDENT><DEDENT>for name, param in params.items():<EOL><INDENT>name = normalize_name(name)<EOL>skip = (<EOL>name.startswith('<STR_LIT:_>') or<EOL>param.kind is param.VAR_KEYWORD or<EOL>param.kind is param.KEYWORD_ONLY)<EOL>if skip:<EOL><INDENT>continue<EOL><DEDENT>annotation = get_arg_config(param)<EOL>container = annotation.container<EOL>type = annotation.type<EOL>choices = annotation.choices<EOL>help = annotation.help<EOL>inverse_help = annotation.inverse_help<EOL>short_option = annotation.short_option<EOL>long_option = annotation.long_option<EOL>inverse_option = annotation.inverse_option<EOL>action = annotation.action<EOL>nargs = annotation.nargs<EOL>default = param.default<EOL>if default is not param.empty:<EOL><INDENT>if not short_option:<EOL><INDENT>short_option = get_short_option(name, names, used_short_options)<EOL>used_short_options.add(short_option)<EOL><DEDENT>if not long_option:<EOL><INDENT>long_option = get_long_option(name)<EOL><DEDENT>if not inverse_option:<EOL><INDENT>inverse_option = get_inverse_option(long_option)<EOL><DEDENT><DEDENT>args[name] = Arg(<EOL>command=self,<EOL>parameter=param,<EOL>name=name,<EOL>container=container,<EOL>type=type,<EOL>default=default,<EOL>choices=choices,<EOL>help=help,<EOL>inverse_help=inverse_help,<EOL>short_option=short_option,<EOL>long_option=long_option,<EOL>inverse_option=inverse_option,<EOL>action=action,<EOL>nargs=nargs,<EOL>)<EOL><DEDENT>option_map = OrderedDict()<EOL>for arg in args.values():<EOL><INDENT>for option in arg.options:<EOL><INDENT>option_map.setdefault(option, [])<EOL>option_map[option].append(arg)<EOL><DEDENT><DEDENT>for option, option_args in option_map.items():<EOL><INDENT>if len(option_args) > <NUM_LIT:1>:<EOL><INDENT>names = '<STR_LIT:U+002CU+0020>'.join(a.parameter.name for a in option_args)<EOL>message = (<EOL>'<STR_LIT>')<EOL>message = message.format_map(locals())<EOL>raise CommandError(message)<EOL><DEDENT><DEDENT>return args<EOL>
|
Create args from function parameters.
|
f3786:c0:m20
|
@cached_property<EOL><INDENT>def option_map(self):<DEDENT>
|
option_map = OrderedDict()<EOL>for arg in self.args.values():<EOL><INDENT>for option in arg.options:<EOL><INDENT>option_map[option] = arg<EOL><DEDENT><DEDENT>return option_map<EOL>
|
Map command-line options to args.
|
f3786:c0:m25
|
@command<EOL>def copy_file(source, destination, follow_symlinks=True,<EOL>template: arg(type=bool_or(str), choices=('<STR_LIT>', '<STR_LIT:string>')) = False,<EOL>context=None):
|
if not template:<EOL><INDENT>return shutil.copy(source, destination, follow_symlinks=follow_symlinks)<EOL><DEDENT>if os.path.isdir(destination):<EOL><INDENT>destination = os.path.join(destination, os.path.basename(source))<EOL><DEDENT>with open(source) as source:<EOL><INDENT>contents = source.read()<EOL><DEDENT>if template is True or template == '<STR_LIT>':<EOL><INDENT>contents = contents.format_map(context)<EOL><DEDENT>elif template == '<STR_LIT:string>':<EOL><INDENT>string_template = string.Template(contents)<EOL>contents = string_template.substitute(context)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % template)<EOL><DEDENT>with tempfile.NamedTemporaryFile('<STR_LIT:w>', delete=False) as temp_file:<EOL><INDENT>temp_file.write(contents)<EOL><DEDENT>path = shutil.copy(temp_file.name, destination)<EOL>os.remove(temp_file.name)<EOL>return path<EOL>
|
Copy source file to destination.
The destination may be a file path or a directory. When it's a
directory, the source file will be copied into the directory
using the file's base name.
When the source file is a template, ``context`` will be used as the
template context. The supported template types are 'format' and
'string'. The former uses ``str.format_map()`` and the latter uses
``string.Template()``.
.. note:: :func:`shutil.copy()` from the standard library is used to
do the copy operation.
|
f3787:m0
|
@command<EOL>def git_version(short: '<STR_LIT>' = True, show: '<STR_LIT>' = False):
|
result = local(<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>stdout='<STR_LIT>', stderr='<STR_LIT>', echo=False, raise_on_error=False)<EOL>if not result:<EOL><INDENT>return None<EOL><DEDENT>result = local(<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>stdout='<STR_LIT>', stderr='<STR_LIT>', echo=False, raise_on_error=False)<EOL>if result:<EOL><INDENT>return result.stdout<EOL><DEDENT>result = local(<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>' if short else None, '<STR_LIT>'],<EOL>stdout='<STR_LIT>', stderr='<STR_LIT>', echo=False, raise_on_error=False)<EOL>if result:<EOL><INDENT>version = result.stdout.strip()<EOL>if show:<EOL><INDENT>print(version)<EOL><DEDENT>return version<EOL><DEDENT>return None<EOL>
|
Get tag associated with HEAD; fall back to SHA1.
If HEAD is tagged, return the tag name; otherwise fall back to
HEAD's short SHA1 hash.
.. note:: Only annotated tags are considered.
.. note:: The output isn't shown by default. To show it, pass the
``--show`` flag.
|
f3787:m1
|
@command<EOL>def local(args: arg(container=list),<EOL>cd=None,<EOL>environ: arg(type=dict) = None,<EOL>replace_env=False,<EOL>paths=(),<EOL>shell: arg(type=bool) = None,<EOL>stdout: arg(type=StreamOptions) = None,<EOL>stderr: arg(type=StreamOptions) = None,<EOL>echo=False,<EOL>raise_on_error=True,<EOL>dry_run=False,<EOL>) -> Result:
|
if isinstance(args, str):<EOL><INDENT>if shell is None:<EOL><INDENT>shell = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>args = flatten_args(args, join=shell)<EOL><DEDENT>if cd:<EOL><INDENT>cd = abs_path(cd)<EOL>cd_passed = True<EOL><DEDENT>else:<EOL><INDENT>cd_passed = False<EOL><DEDENT>environ = {k: str(v) for k, v in (environ or {}).items()}<EOL>if replace_env:<EOL><INDENT>subprocess_env = environ.copy()<EOL><DEDENT>else:<EOL><INDENT>subprocess_env = os.environ.copy()<EOL>if environ:<EOL><INDENT>subprocess_env.update(environ)<EOL><DEDENT><DEDENT>if paths:<EOL><INDENT>paths = [paths] if isinstance(paths, str) else paths<EOL>paths = [abs_path(p) for p in paths]<EOL>current_path = subprocess_env.get('<STR_LIT>')<EOL>if current_path:<EOL><INDENT>paths.append(current_path)<EOL><DEDENT>path = '<STR_LIT::>'.join(paths)<EOL>subprocess_env['<STR_LIT>'] = path<EOL><DEDENT>if stdout:<EOL><INDENT>stdout = StreamOptions[stdout] if isinstance(stdout, str) else stdout<EOL>stdout = stdout.option<EOL><DEDENT>if stderr:<EOL><INDENT>stderr = StreamOptions[stderr] if isinstance(stderr, str) else stderr<EOL>stderr = stderr.option<EOL><DEDENT>kwargs = {<EOL>'<STR_LIT>': cd,<EOL>'<STR_LIT>': subprocess_env,<EOL>'<STR_LIT>': shell,<EOL>'<STR_LIT>': stdout,<EOL>'<STR_LIT>': stderr,<EOL>'<STR_LIT>': True,<EOL>}<EOL>display_str = args if shell else '<STR_LIT:U+0020>'.join(shlex.quote(a) for a in args)<EOL>if echo:<EOL><INDENT>if cd_passed:<EOL><INDENT>printer.echo('<STR_LIT>'.format_map(locals()), end='<STR_LIT:U+0020>')<EOL><DEDENT>if not dry_run:<EOL><INDENT>printer.echo(display_str)<EOL><DEDENT><DEDENT>if dry_run:<EOL><INDENT>printer.echo('<STR_LIT>', display_str)<EOL>result = Result(args, <NUM_LIT:0>, None, None)<EOL><DEDENT>else:<EOL><INDENT>result = subprocess.run(args, **kwargs)<EOL>result = Result.from_subprocess_result(result)<EOL><DEDENT>if result.return_code and raise_on_error:<EOL><INDENT>raise result<EOL><DEDENT>return result<EOL>
|
Run a local command via :func:`subprocess.run`.
Args:
args (list|str): A list of args or a shell command.
cd (str): Working directory to change to first.
environ (dict): Additional environment variables to pass to the
subprocess.
replace_env (bool): If set, only pass env variables from
``environ`` to the subprocess.
paths (list): A list of additional paths.
shell (bool): Run as a shell command? The default is to run in
shell mode if ``args`` is a string. This flag can be used to
force a list of args to be run as a shell command too.
stdout (StreamOptions): What to do with stdout (capture, hide,
or show).
stderr (StreamOptions): Same as ``stdout``.
echo (bool): Whether to echo the command before running it.
raise_on_error (bool): Whether to raise an exception when the
subprocess returns a non-zero exit code.
dry_run (bool): If set, print command instead of running it.
Returns:
Result
Raises:
Result: When the subprocess returns a non-zero exit code (and
``raise_on_error`` is set).
|
f3787:m2
|
@command<EOL>def remote(cmd: arg(container=list),<EOL>host,<EOL>user=None,<EOL>port=None,<EOL>sudo=False,<EOL>run_as=None,<EOL>shell='<STR_LIT>',<EOL>cd=None,<EOL>environ: arg(container=dict) = None,<EOL>paths=(),<EOL>stdout: arg(type=StreamOptions) = None,<EOL>stderr: arg(type=StreamOptions) = None,<EOL>echo=False,<EOL>raise_on_error=True,<EOL>dry_run=False,<EOL>) -> Result:
|
if not isinstance(cmd, str):<EOL><INDENT>cmd = flatten_args(cmd, join=True)<EOL><DEDENT>ssh_options = ['<STR_LIT>']<EOL>if isatty(sys.stdin):<EOL><INDENT>ssh_options.append('<STR_LIT>')<EOL><DEDENT>if port is not None:<EOL><INDENT>ssh_options.extend(('<STR_LIT>', port))<EOL><DEDENT>ssh_connection_str = '<STR_LIT>'.format_map(locals()) if user else host<EOL>remote_cmd = []<EOL>if sudo:<EOL><INDENT>remote_cmd.extend(('<STR_LIT>', '<STR_LIT>'))<EOL><DEDENT>elif run_as:<EOL><INDENT>remote_cmd.extend(('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', run_as))<EOL><DEDENT>remote_cmd.extend((shell, '<STR_LIT:-c>'))<EOL>inner_cmd = []<EOL>if cd:<EOL><INDENT>inner_cmd.append('<STR_LIT>'.format_map(locals()))<EOL><DEDENT>if environ:<EOL><INDENT>inner_cmd.extend('<STR_LIT>'.format_map(locals()) for k, v in environ.items())<EOL><DEDENT>if paths:<EOL><INDENT>inner_cmd.append('<STR_LIT>'.format(path='<STR_LIT::>'.join(paths)))<EOL><DEDENT>inner_cmd.append(cmd)<EOL>inner_cmd = '<STR_LIT>'.join(inner_cmd)<EOL>inner_cmd = '<STR_LIT>'.format_map(locals())<EOL>inner_cmd = shlex.quote(inner_cmd)<EOL>remote_cmd.append(inner_cmd)<EOL>remote_cmd = '<STR_LIT:U+0020>'.join(remote_cmd)<EOL>args = ('<STR_LIT>', ssh_options, ssh_connection_str, remote_cmd)<EOL>return local(<EOL>args, stdout=stdout, stderr=stderr, echo=echo, raise_on_error=raise_on_error,<EOL>dry_run=dry_run)<EOL>
|
Run a remote command via SSH.
Runs a remote shell command using ``ssh`` in a subprocess like so:
ssh -q [-t] [<user>@]<host> [sudo [-u <run_as>] -H] /bin/sh -c '
[cd <cd> &&]
[export XYZ="xyz" &&]
[export PATH="<path>" &&]
<cmd>
'
Args:
cmd (list|str): The command to run. If this is a list, it will
be flattened into a string.
host (str): Remote host to SSH into.
user (str): Remote user to log in as (defaults to current local
user).
port (int): SSH port on remote host.
sudo (bool): Run the remote command as root using ``sudo``.
run_as (str): Run the remote command as a different user using
``sudo -u <run_as>``.
shell (str): The remote user's default shell will be used to run
the remote command unless this is set to a different shell.
cd (str): Where to run the command on the remote host.
environ (dict): Extra environment variables to set on the remote
host.
paths (list): Additional paths to prepend to the remote
``$PATH``.
stdout: See :func:`local`.
stderr: See :func:`local`.
echo: See :func:`local`.
raise_on_error: See :func:`local`.
dry_run: See :func:`local`.
|
f3787:m3
|
@command<EOL>def sync(source,<EOL>destination,<EOL>host,<EOL>user=None,<EOL>sudo=False,<EOL>run_as=None,<EOL>options=('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'),<EOL>excludes=(),<EOL>exclude_from=None,<EOL>delete=False,<EOL>dry_run=False,<EOL>mode='<STR_LIT>',<EOL>quiet=True,<EOL>pull=False,<EOL>stdout: arg(type=StreamOptions) = None,<EOL>stderr: arg(type=StreamOptions) = None,<EOL>echo=False,<EOL>raise_on_error=True,<EOL>) -> Result:
|
source = abs_path(source, keep_slash=True)<EOL>destination = abs_path(destination, keep_slash=True)<EOL>connection_str = '<STR_LIT>'.format_map(locals()) if user else host<EOL>push = not pull<EOL>if sudo:<EOL><INDENT>rsync_path = ('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif run_as:<EOL><INDENT>rsync_path = ('<STR_LIT>', '<STR_LIT>'.format_map(locals()))<EOL><DEDENT>else:<EOL><INDENT>rsync_path = None<EOL><DEDENT>if push:<EOL><INDENT>destination = '<STR_LIT>'.format_map(locals())<EOL><DEDENT>else:<EOL><INDENT>source = '<STR_LIT>'.format_map(locals())<EOL><DEDENT>args = (<EOL>'<STR_LIT>',<EOL>rsync_path,<EOL>options,<EOL>('<STR_LIT>', mode) if mode else None,<EOL>tuple(('<STR_LIT>', exclude) for exclude in excludes),<EOL>('<STR_LIT>', exclude_from) if exclude_from else None,<EOL>'<STR_LIT>' if delete else None,<EOL>'<STR_LIT>' if dry_run else None,<EOL>'<STR_LIT>' if quiet else None,<EOL>source,<EOL>destination,<EOL>)<EOL>return local(args, stdout=stdout, stderr=stderr, echo=echo, raise_on_error=raise_on_error)<EOL>
|
Sync files using rsync.
By default, a local ``source`` is pushed to a remote
``destination``. To pull from a remote ``source`` to a local
``destination`` instead, pass ``pull=True``.
|
f3787:m4
|
def set_attrs(self, **attrs):
|
commands = tuple(self.values())<EOL>for name, value in attrs.items():<EOL><INDENT>for command in commands:<EOL><INDENT>setattr(command, name, value)<EOL><DEDENT><DEDENT>
|
Set the given attributes on *all* commands in collection.
|
f3788:c0:m3
|
def set_default_args(self, default_args):
|
for name, args in default_args.items():<EOL><INDENT>command = self[name]<EOL>command.default_args = default_args.get(command.name) or {}<EOL><DEDENT>
|
Set default args for commands in collection.
Default args are used when the corresponding args aren't passed
on the command line or in a direct call.
|
f3788:c0:m4
|
def abs_path(path, format_kwargs={}, relative_to=None, keep_slash=False):
|
if format_kwargs:<EOL><INDENT>path = path.format_map(format_kwargs)<EOL><DEDENT>has_slash = path.endswith(os.sep)<EOL>if os.path.isabs(path):<EOL><INDENT>path = os.path.normpath(path)<EOL><DEDENT>elif '<STR_LIT::>' in path:<EOL><INDENT>path = asset_path(path, keep_slash=False)<EOL><DEDENT>else:<EOL><INDENT>path = os.path.expanduser(path)<EOL>if relative_to:<EOL><INDENT>path = os.path.join(relative_to, path)<EOL><DEDENT>path = os.path.abspath(path)<EOL>path = os.path.normpath(path)<EOL><DEDENT>if has_slash and keep_slash:<EOL><INDENT>path = '<STR_LIT>'.format(path=path, slash=os.sep)<EOL><DEDENT>return path<EOL>
|
Get abs. path for ``path``.
``path`` may be a relative or absolute file system path or an asset
path. If ``path`` is already an abs. path, it will be returned as
is. Otherwise, it will be converted into a normalized abs. path.
If ``relative_to`` is passed *and* ``path`` is not absolute, the
path will be joined to the specified prefix before it's made
absolute.
If ``path`` ends with a slash, it will be stripped unless
``keep_slash`` is set (for use with ``rsync``, for example).
>>> file_path = os.path.normpath(__file__)
>>> dir_name = os.path.dirname(file_path)
>>> file_name = os.path.basename(file_path)
>>> os.chdir(dir_name)
>>>
>>> abs_path(file_name) == file_path
True
>>> abs_path('runcommands.util:') == dir_name
True
>>> abs_path('runcommands.util:path.py') == file_path
True
>>> abs_path('/{xyz}', format_kwargs={'xyz': 'abc'})
'/abc'
>>> abs_path('banana', relative_to='/usr')
'/usr/banana'
>>> abs_path('/usr/banana/')
'/usr/banana'
>>> abs_path('banana/', relative_to='/usr', keep_slash=True)
'/usr/banana/'
>>> abs_path('runcommands.util:banana/', keep_slash=True) == (dir_name + '/banana/')
True
|
f3790:m0
|
def asset_path(path, format_kwargs={}, keep_slash=False):
|
if format_kwargs:<EOL><INDENT>path = path.format_map(format_kwargs)<EOL><DEDENT>has_slash = path.endswith(os.sep)<EOL>if '<STR_LIT::>' in path:<EOL><INDENT>package_name, *rel_path = path.split('<STR_LIT::>', <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>package_name, rel_path = path, ()<EOL><DEDENT>try:<EOL><INDENT>package = importlib.import_module(package_name)<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>.format_map(locals()))<EOL><DEDENT>if not hasattr(package, '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>package_path = os.path.dirname(package.__file__)<EOL>path = os.path.join(package_path, *rel_path)<EOL>path = os.path.normpath(path)<EOL>if has_slash and keep_slash:<EOL><INDENT>path = '<STR_LIT>'.format(path=path, slash=os.sep)<EOL><DEDENT>return path<EOL>
|
Get absolute path to asset in package.
``path`` can be just a package name like 'package' or it can be
a package name and a relative file system path like 'package:util'.
If ``path`` ends with a slash, it will be stripped unless
``keep_slash`` is set (for use with ``rsync``, for example).
>>> file_path = os.path.normpath(__file__)
>>> dir_name = os.path.dirname(file_path)
>>> file_name = os.path.basename(file_path)
>>> os.chdir(dir_name)
>>>
>>> asset_path('runcommands.util') == dir_name
True
>>> asset_path('runcommands.util:path.py') == file_path
True
>>> asset_path('runcommands.util:{name}.py', format_kwargs={'name': 'path'}) == file_path
True
>>> asset_path('runcommands.util:dir/') == (dir_name + '/dir')
True
>>> asset_path('runcommands.util:dir/', keep_slash=True) == (dir_name + '/dir/')
True
|
f3790:m1
|
def paths_to_str(paths, format_kwargs={}, delimiter=os.pathsep, asset_paths=False,<EOL>check_paths=False):
|
if not paths:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if isinstance(paths, str):<EOL><INDENT>paths = paths.split(delimiter)<EOL><DEDENT>processed_paths = []<EOL>for path in paths:<EOL><INDENT>original = path<EOL>path = path.format_map(format_kwargs)<EOL>if not os.path.isabs(path):<EOL><INDENT>if asset_paths and '<STR_LIT::>' in path:<EOL><INDENT>try:<EOL><INDENT>path = asset_path(path)<EOL><DEDENT>except ValueError:<EOL><INDENT>path = None<EOL><DEDENT><DEDENT><DEDENT>if path is not None and os.path.isdir(path):<EOL><INDENT>processed_paths.append(path)<EOL><DEDENT>elif check_paths:<EOL><INDENT>f = locals()<EOL>printer.warning('<STR_LIT>'.format_map(f))<EOL><DEDENT><DEDENT>return delimiter.join(processed_paths)<EOL>
|
Convert ``paths`` to a single string.
Args:
paths (str|list): A string like "/a/path:/another/path" or
a list of paths; may include absolute paths and/or asset
paths; paths that are relative will be left relative
format_kwargs (dict): Will be injected into each path
delimiter (str): The string used to separate paths
asset_paths (bool): Whether paths that look like asset paths
will be converted to absolute paths
check_paths (bool): Whether paths should be checked to ensure
they exist
|
f3790:m2
|
def flatten_args(args: list, join=False, *, empty=(None, [], (), '<STR_LIT>')) -> list:
|
flat_args = []<EOL>non_empty_args = (arg for arg in args if arg not in empty)<EOL>for arg in non_empty_args:<EOL><INDENT>if isinstance(arg, (list, tuple)):<EOL><INDENT>flat_args.extend(flatten_args(arg))<EOL><DEDENT>else:<EOL><INDENT>flat_args.append(str(arg))<EOL><DEDENT><DEDENT>if join:<EOL><INDENT>join = '<STR_LIT:U+0020>' if join is True else join<EOL>flat_args = join.join(flat_args)<EOL><DEDENT>return flat_args<EOL>
|
Flatten args and remove empty items.
Args:
args: A list of items (typically but not necessarily strings),
which may contain sub-lists, that will be flattened into
a single list with empty items removed. Empty items include
``None`` and empty lists, tuples, and strings.
join: If ``True`` or a string, the final flattened list will be
joined into a single string. The default join string is
a space.
empty: Items that are considered empty.
Returns:
list|str: The list of args flattened with empty items removed
and the remaining items converted to strings. If ``join`` is
specified, the list of flattened args will be joined into
a single string.
Examples::
>>> flatten_args([])
[]
>>> flatten_args(())
[]
>>> flatten_args([(), (), [(), ()]])
[]
>>> flatten_args(['executable', '--flag' if True else None, ('--option', 'value'), [None]])
['executable', '--flag', '--option', 'value']
>>> flatten_args(['executable', '--option', 0])
['executable', '--option', '0']
|
f3791:m1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.