Source code for cli_interview_kit.validators
"""Answer validators: functions that return the value or raise ``ValueError``."""
from __future__ import annotations
import re
from collections.abc import Callable
Validator = Callable[[str], str]
"""``(value) -> value``, raising ``ValueError`` with a user-facing message."""
_BYTE_SIZE = re.compile(r"\d+[kmgt]?b?")
[docs]
def non_empty(value: str) -> str:
"""Reject a blank answer.
Parameters
----------
value
The answer as typed.
Returns
-------
The answer, unchanged.
Raises
------
ValueError
The answer is blank.
"""
if not value.strip():
raise ValueError("A value is required.")
return value
def whole_number(value: str) -> str:
"""Accept a whole number, or a blank answer.
Parameters
----------
value
The answer as typed.
Returns
-------
The answer, unchanged.
Raises
------
ValueError
The answer is neither blank nor a whole number.
"""
stripped = value.strip()
if stripped and not stripped.removeprefix("-").isdigit():
raise ValueError("Enter a whole number, or leave it blank.")
return value
def byte_size(value: str) -> str:
"""Accept a size such as ``512m`` or ``1g``, or a blank answer.
Parameters
----------
value
The answer as typed.
Returns
-------
The answer, unchanged.
Raises
------
ValueError
The answer is neither blank nor a size.
"""
stripped = value.strip()
if stripped and not _BYTE_SIZE.fullmatch(stripped.lower()):
raise ValueError("Enter a size such as 512m or 1g, or leave it blank.")
return value
def all_of(*validators: Validator | None) -> Validator:
"""Return a validator applying each given one in order, skipping ``None``.
Parameters
----------
validators
The validators, any of which may be ``None``.
Returns
-------
One validator that runs them all and returns the value.
"""
def _validate(value: str) -> str:
"""Run each validator on the value."""
for validator in validators:
if validator is not None:
_ = validator(value)
return value
return _validate