
    AHjI                    B   d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	m
Z
 ddlmZmZmZ ddlmZ ddlZe	 G d d	             Ze	 G d
 d             Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)z

This module provides a number of classes for validating input.

See [Validating Input](/widgets/input/#validating-input) for details.

    )annotationsN)ABCabstractmethod)	dataclassfield)CallablePatternSequence)urlparsec                      e Zd ZU dZ ee      Zded<   	 edd       Z	edd       Z
edd       Zedd       Zedd	       Zy
)ValidationResultz4The result of calling a `Validator.validate` method.)default_factorySequence[Failure]failuresc                    t        d | D              }| D cg c]  }|j                  D ]  }|  }}}|rt        j                         S t        j	                  |      S c c}}w )zMerge multiple ValidationResult objects into one.

        Args:
            results: List of ValidationResult objects to merge.

        Returns:
            Merged ValidationResult object.
        c              3  4   K   | ]  }|j                     y wN)is_valid).0results     J/root/tools/cai/cai_env/lib/python3.12/site-packages/textual/validation.py	<genexpr>z)ValidationResult.merge.<locals>.<genexpr>&   s     =6v=s   )allr   r   successfailure)resultsr   r   r   r   s        r   mergezValidationResult.merge   s`     =W==*1QQgGQGQQ#++--#++H55	 Rs   A c                     t               S )znConstruct a successful ValidationResult.

        Returns:
            A successful ValidationResult.
        r        r   r   zValidationResult.success-   s      !!r!   c                    t        |       S )zConstruct a failure ValidationResult.

        Args:
            failures: The failures.

        Returns:
            A failure ValidationResult.
        r   r   s    r   r   zValidationResult.failure6   s      ))r!   c                l    | j                   D cg c]  }|j                  |j                   c}S c c}w )a  Utility for extracting failure descriptions as strings.

        Useful if you don't care about the additional metadata included in the `Failure` objects.

        Returns:
            A list of the string descriptions explaining the failing validations.
        )r   descriptionselfr   s     r   failure_descriptionsz%ValidationResult.failure_descriptionsB   s:      ==
"". 
 	
 
s   1c                2    t        | j                        dk(  S )z&True if the validation was successful.r   )lenr   r'   s    r   r   zValidationResult.is_validQ   s     4==!Q&&r!   N)r   zSequence['ValidationResult']returnz'ValidationResult'r,   r   )r   r   r,   r   )r,   z	list[str])r,   bool)__name__
__module____qualname____doc__r   listr   __annotations__staticmethodr   r   r   propertyr(   r   r    r!   r   r   r      sz    >"'"=H=J6 6  " " 	* 	* 
 
 ' 'r!   r   c                  N    e Zd ZU dZded<   	 dZded<   	 dZded<   	 d
dZdd	Zy)Failurez'Information about a validation failure.	Validator	validatorN
str | Nonevaluer%   c                    | j                   S| j                  j                  | j                  j                  | _         y | j                  j                  |       | _         y y r   )r%   r:   failure_descriptiondescribe_failurer+   s    r   __post_init__zFailure.__post_init__b   sL    #~~11=#'>>#E#E #'>>#B#B4#H 	 $r!   c              #  `   K   | j                    | j                   | j                   y wr   )r<   r:   r%   r+   s    r   __rich_repr__zFailure.__rich_repr__j   s&     jjnns   ,.)r,   None)r,   zrich.repr.Result)	r/   r0   r1   r2   r4   r<   r%   r@   rB   r    r!   r   r8   r8   W   s3    13E:9"K"tIr!   r8   c                  Z    e Zd ZdZdd	dZed
d       ZddZddZ	 	 	 d	 	 	 	 	 	 	 ddZ	y)r9   aa  Base class for the validation of string values.

    Commonly used in conjunction with the `Input` widget, which accepts a
    list of validators via its constructor. This validation framework can also be used to validate any 'stringly-typed'
    values (for example raw command line input from `sys.args`).

    To implement your own `Validator`, subclass this class.

    Example:
        ```python
        def is_palindrome(value: str) -> bool:
            """Check has string has the same code points left to right, as right to left."""
            return value == value[::-1]

        class Palindrome(Validator):
            def validate(self, value: str) -> ValidationResult:
                if is_palindrome(value):
                    return self.success()
                else:
                    return self.failure("Not a palindrome!")
        ```
    Nc                    || _         y r   r>   )r'   r>   s     r   __init__zValidator.__init__   s    #6 	r!   c                     y)a  Validate the value and return a ValidationResult describing the outcome of the validation.

        Implement this method when defining custom validators.

        Args:
            value: The value to validate.

        Returns:
            The result of the validation ([`self.success()`][textual.validation.Validator.success) or [`self.failure(...)`][textual.validation.Validator.failure]).
        Nr    r'   r<   s     r   validatezValidator.validate   s    r!   c                    | j                   S )a  Return a string description of the Failure.

        Used to provide a more fine-grained description of the failure. A Validator could fail for multiple
        reasons, so this method could be used to provide a different reason for different types of failure.

        !!! warning

            This method is only called if no other description has been supplied. If you supply a description
            inside a call to `self.failure(description="...")`, or pass a description into the constructor of
            the validator, those will take priority, and this method won't be called.

        Args:
            failure: Information about why the validation failed.

        Returns:
            A string description of the failure.
        rF   r&   s     r   r?   zValidator.describe_failure   s    $ '''r!   c                    t               S )a  Shorthand for `ValidationResult(True)`.

        Return `self.success()` from [`validate()`][textual.validation.Validator.validate] to indicated that validation *succeeded*.

        Returns:
            A ValidationResult indicating validation succeeded.
        r   r+   s    r   r   zValidator.success   s      !!r!   c                d    t        |t              r|g}t        |xs t        | ||      g      }|S )aq  Shorthand for signaling validation failure.

        Return `self.failure(...)` from [`validate()`][textual.validation.Validator.validate] to indicated that validation *failed*.

        Args:
            description: The failure description that will be used. When used in conjunction with the Input widget,
                this is the description that will ultimately be available inside the handler for `Input.Changed`. If not
                supplied, the `failure_description` from the `Validator` will be used. If that is not supplied either,
                then the `describe_failure` method on `Validator` will be called.
            value: The value that was considered invalid. This is optional, and only needs to be supplied if required
                in your `Input.Changed` handler.
            failures: The reasons the validator failed. If not supplied, a generic `Failure` will be included in the
                ValidationResult returned from this function.

        Returns:
            A ValidationResult representing failed validation, and containing the metadata supplied
                to this function.
        )r:   r<   r%   )
isinstancer8   r   )r'   r%   r<   r   r   s        r   r   zValidator.failure   s:    0 h( zH!W4u+VW
 r!   r   )r>   r;   r,   rC   r<   strr,   r   r   r8   r,   r;   r-   NNN)r%   r;   r<   r;   r   z"Failure | Sequence[Failure] | Noner,   r   )
r/   r0   r1   r2   rG   r   rJ   r?   r   r   r    r!   r   r9   r9   p   s`    . 
 
((" #' 7;	  5	
 
r!   r9   c                  ^     e Zd ZdZ	 	 d	 	 	 	 	 	 	 d fdZ G d de      Zd	dZd
dZ xZ	S )RegexzGA validator that checks the value matches a regex (via `re.fullmatch`).c                D    t         |   |       || _        	 || _        y NrF   )superrG   regexflags)r'   rX   rY   r>   	__class__s       r   rG   zRegex.__init__   s*     	-@A
E
2r!   c                      e Zd ZdZy)Regex.NoResultszYIndicates validation failed because the regex could not be found within the value string.Nr/   r0   r1   r2   r    r!   r   	NoResultsr\      s    gr!   r^   c                    | j                   }t        j                  ||| j                        du}|s)t        j                  | |      g}| j                  |      S | j                         S )zEnsure that the value matches the regex.

        Args:
            value: The value that should match the regex.

        Returns:
            The result of the validation.
        )rY   Nr#   )rX   re	fullmatchrY   rT   r^   r   r   )r'   r<   rX   	has_matchr   s        r   rJ   zRegex.validate   s[     

LLTZZ@L	e45H<<<22||~r!   c                <    d| j                   d| j                   dS )Describes why the validator failed.

        Args:
            failure: Information about why the validation failed.

        Returns:
            A string description of the failure.
        zMust match regular expression z (flags=z).)rX   rY   r&   s     r   r?   zRegex.describe_failure   s"     0

~Xdjj\QSTTr!   )r   N)rX   zstr | Pattern[str]rY   zint | re.RegexFlagr>   r;   r,   rC   rO   rQ   )
r/   r0   r1   r2   rG   r8   r^   rJ   r?   __classcell__rZ   s   @r   rT   rT      sR    Q
 %&*.	
3!
3 "
3 (	
3
 

3hG h 	Ur!   rT   c                  ~     e Zd ZdZ	 	 	 d
	 	 	 	 	 	 	 d fdZ G d de      Z G d de      ZddZddZ	dd	Z
 xZS )NumberzKValidator that ensures the value is a number, with an optional range check.c                D    t         |   |       || _        	 || _        y rV   rW   rG   minimummaximumr'   rk   rl   r>   rZ   s       r   rG   zNumber.__init__  s*     	-@A^^r!   c                      e Zd ZdZy)Number.NotANumberziIndicates a failure due to the value not being a valid number (decimal/integer, inc. scientific notation)Nr]   r    r!   r   
NotANumberro     s    wr!   rp   c                      e Zd ZdZy)Number.NotInRangezTIndicates a failure due to the number not being within the range [minimum, maximum].Nr]   r    r!   r   
NotInRangerr     s    br!   rs   c                   	 t        |      }t        j                  |      st        j                  |      r*t        j                  t        j                  | |      g      S | j                  |      s*t        j                  t        j                  | |      g      S | j                         S # t        $ r- t        j                  t        j                  | |      g      cY S w xY w)zEnsure that `value` is a valid number, optionally within a range.

        Args:
            value: The value to validate.

        Returns:
            The result of the validation.
        )float
ValueErrorr   r   rh   rp   mathisnanisinf_validate_rangers   r   )r'   r<   float_values      r   rJ   zNumber.validate!  s    	N,K ::k"djj&=#++V->->tU-K,LMM##K0#++""4/0  ||~  	N#++V->->tU-K,LMM	Ns   B, ,3C"!C"c                t    | j                   || j                   k  ry| j                  || j                  kD  ryy)z_Return a boolean indicating whether the number is within the range specified in the attributes.FT)rk   rl   rI   s     r   rz   zNumber._validate_range8  s5    <<#(<<<#(<r!   c                H   t        |t        j                        ryt        |t        j                        rm| j                  | j
                  d| j
                   dS | j                  | j
                  d| j                   dS d| j                   d| j
                   dS y)rd   zMust be a valid number.NMust be less than or equal to .!Must be greater than or equal to Must be between  and )rN   rh   rp   rs   rk   rl   r&   s     r   r?   zNumber.describe_failure@  s     gv001,!2!23||#(@7~QGG)dll.B:4<<.JJ)$,,uT\\N!LLr!   rR   )rk   float | Nonerl   r   r>   r;   r,   rC   rO   )r<   ru   r,   r.   rQ   )r/   r0   r1   r2   rG   r8   rp   rs   rJ   rz   r?   re   rf   s   @r   rh   rh     sl    U !% $*.	
_
_ 
_ (	
_
 

_xW xcW c.r!   rh   c                  B     e Zd ZdZ G d de      Zd fdZddZ xZS )IntegerzKValidator which ensures the value is an integer which falls within a range.c                      e Zd ZdZy)Integer.NotAnIntegerz?Indicates a failure due to the value not being a valid integer.Nr]   r    r!   r   NotAnIntegerr   Y  s    Mr!   r   c                    t         |   |      }|j                  s|S 	 t        |      }| j                         S # t        $ r- t
        j                  t        j                  | |      g      cY S w xY w)zEnsure that `value` is an integer, optionally within a range.

        Args:
            value: The value to validate.

        Returns:
            The result of the validation.
        )
rW   rJ   r   intrv   r   r   r   r   r   )r'   r<   number_validation_result	int_valuerZ   s       r   rJ   zInteger.validate\  su     $)7#3E#: '00++	QE
I ||~  	Q#++W-A-A$-N,OPP	Qs   ; 3A10A1c                h   t        |t        j                  t        j                  f      ryt        |t        j                        rm| j
                  | j                  d| j                   dS | j
                  | j                  d| j
                   dS d| j
                   d| j                   dS y)rd   zMust be a valid integer.Nr~   r   r   r   r   )rN   r   rp   r   rs   rk   rl   r&   s     r   r?   zInteger.describe_failureq  s     g 2 2G4H4HIJ-!3!34||#(@7~QGG)dll.B:4<<.JJ)$,,uT\\N!LLr!   rO   rQ   )	r/   r0   r1   r2   r8   r   rJ   r?   re   rf   s   @r   r   r   V  s    UNw N*r!   r   c                  `     e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 d fdZ G d de      Zd	dZd
dZ xZ	S )Lengthz5Validate that a string is within a range (inclusive).c                D    t         |   |       || _        	 || _        y rV   rj   rm   s       r   rG   zLength.__init__  s*     	-@ANNr!   c                      e Zd ZdZy)Length.IncorrectzKIndicates a failure due to the length of the value being outside the range.Nr]   r    r!   r   	Incorrectr     s    Yr!   r   c                   | j                   duxr t        |      | j                   k  }| j                  duxr t        |      | j                  kD  }|s|r*t        j	                  t
        j                  | |      g      S | j                         S )zEnsure that value falls within the maximum and minimum length constraints.

        Args:
            value: The value to validate.

        Returns:
            The result of the validation.
        N)rk   r*   rl   r   r   r   r   r   )r'   r<   	too_shorttoo_longs       r   rJ   zLength.validate  sv     LL,JUdll1J	<<t+IE
T\\0I#++V-=-=dE-J,KLL||~r!   c                   t        |t        j                        rm| j                  | j                  d| j                   dS | j                  | j                  d| j                   dS d| j                   d| j                   dS y)rd   NzMust be shorter than z characters.zMust be longer than r   r   )rN   r   r   rk   rl   r&   s     r   r?   zLength.describe_failure  s     gv//0||#(@.t||nLII)dll.B-dll^<HH)$,,uT\\N,WWr!   rR   )rk   
int | Nonerl   r   r>   r;   r,   rC   rO   rQ   )
r/   r0   r1   r2   rG   r8   r   rJ   r?   re   rf   s   @r   r   r     sY    ? #"*.	
O
O 
O (	
O
 

OZG Zr!   r   c                  X     e Zd ZdZ	 d	 	 	 	 	 d fdZ G d de      Zd	dZd
dZ xZ	S )FunctionzIA flexible validator which allows you to provide custom validation logic.c                4    t         |   |       || _        y rV   )rW   rG   function)r'   r   r>   rZ   s      r   rG   zFunction.__init__  s     
 	-@A hr!   c                      e Zd ZdZy)Function.ReturnedFalsezIIndicates validation failed because the supplied function returned False.Nr]   r    r!   r   ReturnedFalser     s    Wr!   r   c                    | j                  |      }|r| j                         S | j                  t        j	                  | |            S )a'  Validate that the supplied function returns True.

        Args:
            value: The value to pass into the supplied function.

        Returns:
            A ValidationResult indicating success if the function returned True,
                and failure if the function return False.
        r#   )r   r   r   r   r   )r'   r<   r   s      r   rJ   zFunction.validate  s?     =='<<>!||X%;%;D%%H|IIr!   c                    | j                   S )rd   rF   r&   s     r   r?   zFunction.describe_failure  s     '''r!   r   )r   zCallable[[str], bool]r>   r;   r,   rC   rO   rQ   )
r/   r0   r1   r2   rG   r8   r   rJ   r?   re   rf   s   @r   r   r     sI    S
 +/i'i (i 
	iX XJ	(r!   r   c                  6    e Zd ZdZ G d de      ZddZddZy)	URLzGValidator that checks if a URL is valid (ensuring a scheme is present).c                      e Zd ZdZy)URL.InvalidURLz$Indicates that the URL is not valid.Nr]   r    r!   r   
InvalidURLr     s    2r!   r   c                    t         j                  t        j                  | |      g      }	 t	        |      }t        |j                  |j                  g      s|S 	 | j                         S # t        $ r |cY S w xY w)zValidates that `value` is a valid URL (contains a scheme).

        Args:
            value: The value to validate.

        Returns:
            The result of the validation.
        )
r   r   r   r   r   r   schemenetlocrv   r   )r'   r<   invalid_url
parsed_urls       r   rJ   zURL.validate  sy     '..tU0K/LM	!%J
)):+<+<=>"" ?
 ||~  		s   -A+ +A98A9c                     y)rd   zMust be a valid URL.r    r&   s     r   r?   zURL.describe_failure  s     &r!   NrO   rQ   )r/   r0   r1   r2   r8   r   rJ   r?   r    r!   r   r   r     s    Q3W 3&	&r!   r   )r2   
__future__r   rw   r`   abcr   r   dataclassesr   r   typingr   r	   r
   urllib.parser   	rich.reprrichr   r8   r9   rT   rh   r   r   r   r   r    r!   r   <module>r      s    #  	 # ( . . !  >' >' >'B   0k k\+UI +U\GY GT.f .b1Y 1h'(y '(T"&) "&r!   