"""Request utilities.""" from __future__ import annotations from enum import Enum from typing import Optional, overload class BooleanFilter(Enum): """Boolean Filter Enum.""" __FALSY = {'0', 'f', 'false', 'n', 'no', 'off'} __TRUTHY = {'1', 'on', 't', 'true', 'y', 'yes'} __ALL = {'*', 'all'} FALSE = 'false' TRUE = 'true' ALL = 'all' @overload @classmethod def parse(cls, value: str | bool, default: None = ...) -> BooleanFilter: ... @overload @classmethod def parse( cls, value: Optional[str | bool], default: BooleanFilter = ... ) -> BooleanFilter: ... @overload @classmethod def parse(cls, value: None, default: None = ...) -> None: ... @classmethod def parse( cls, value: Optional[str | bool], default: Optional[BooleanFilter] = None ) -> Optional[BooleanFilter]: """Parse a string value into a BooleanFilter.""" # If no value is provided, return the default. if value is None: return default # If boolean provided if isinstance(value, bool): return cls.TRUE if value else cls.FALSE # Normalize the value to lowercase and strip whitespaces. v = value.strip().lower() # Check against known values. if v in cls.__TRUTHY: return cls.TRUE if v in cls.__FALSY: return cls.FALSE if v in cls.__ALL: return cls.ALL # If the value does not match any known value, raise an error. raise ValueError(f'Invalid boolean value: {value!r}') def _serialize(self) -> Optional[bool]: return self.to_bool() def to_bool(self) -> Optional[bool]: """Convert this filter to bool or None for ALL.""" if self is BooleanFilter.TRUE: return True if self is BooleanFilter.FALSE: return False return None