o
    iI                     @   sv  U d Z ddlZddlZddlZddlZddlZddlmZ ddl	m
Z
mZ ddlmZ ddlmZmZ ddlmZmZmZmZ dd	lmZmZmZmZ dd
lmZmZmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z- e.de/ej0ddej1Z2ee3d< e.de/ej4ddej1Z5ee3d< G dd deZ6G dd deZ7deddddfde#dee$ de8dee8 dee9 de:deee9  d dfd!d"Z;deddddfde#dee$ de8dee8 dee9 de:deee9  d e:fd#d$Z<	%									&d.de#d'e9dee$ dee8 dee9 dee: d(ee- d)ee- deee9  d*e:d+e:d e#fd,d-Z=dS )/zA
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
    N)Sequence)PathPurePath)Pattern)FinalOptional   )AbstractSanitizerAbstractValidatorBaseFileBaseValidator)findall_to_stris_nt_abspathto_strvalidate_pathtype)_NTFS_RESERVED_FILE_NAMESDEFAULT_MIN_LENINVALID_CHAR_ERR_MSG_TMPLPlatform)FileNameSanitizerFileNameValidator)PathTypePlatformType)ErrorAttrKeyErrorReasonInvalidCharErrorReservedNameErrorValidationError)ReservedNameHandlerValidationErrorHandler[s]_RE_INVALID_PATH_RE_INVALID_WIN_PATHc                       s   e Zd Z									ddedee dee dee d	ee d
eee  de	de	dee
 ddf fddZddededefddZdee fddZdefddZ  ZS )FilePathSanitizerNTFmax_lenfs_encodingplatformnull_value_handlerreserved_name_handleradditional_reserved_names	normalizevalidate_after_sanitize	validatorreturnc
              
      s   |	r|	}
n
t t||d||d}
t j|||
|||||d |  | _t| j||||| j|d| _	|| _
| jddr?tj| _d S tj| _d S )NTmin_lenr'   r(   check_reservedr,   r)   )r'   r(   r/   r*   r+   r,   r)   r.   )r'   r(   r*   r+   r,   r)   r.   include_universal)FilePathValidatorr   super__init___get_sanitize_regexp_sanitize_regexpr   r'   r)   #_FilePathSanitizer__fname_sanitizer_FilePathSanitizer__normalize_is_windowsntpath
splitdrive_FilePathSanitizer__split_drive	posixpath)selfr'   r(   r)   r*   r+   r,   r-   r.   r/   fpath_validator	__class__ \/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pathvalidate/_filepath.pyr8      sD   
	zFilePathSanitizer.__init__ valuereplacement_textc           
   
   C   s  zt || jdd d W n$ ty1 } z|jtjkr,t|tr! | |W  Y d }~S  d }~ww t	|}| 
|\}}| j||}| jrO|rOtj|}|}g }|rZ|| |dddD ](}|tv rr|| d qct| jj||d}	|	s|s|d qc||	 qc|  |}z| j| W n ty } z|jtjkr| |}W Y d }~nd }~ww | jr| j| t|trt|S |S )	NTr4   allow_whitespaces\/_)rJ   rH   )r   r=   r   reasonr   	NULL_NAME
isinstancer   _null_value_handlerr   r@   r:   subr<   ospathnormpathappendreplacesplitr   strr;   sanitize&_FilePathSanitizer__get_path_separatorjoin
_validatorvalidate_validate_after_sanitizer   )
rB   rI   rJ   eunicode_filepathdrivesanitized_pathsanitized_entriesentrysanitized_entryrF   rF   rG   r\   R   sX   





zFilePathSanitizer.sanitizec                 C   s   | j ddrtS tS )NTr4   )r=   r$   r#   rB   rF   rF   rG   r9      s   z&FilePathSanitizer._get_sanitize_regexpc                 C   s   |   rdS dS )NrM   rN   )r=   ri   rF   rF   rG   __get_path_separator   s   z&FilePathSanitizer.__get_path_separator)	r&   NNNNNTFN)rH   )__name__
__module____qualname__intr   r[   r   r   r   boolr
   r8   r   r\   r   r9   r]   __classcell__rF   rF   rD   rG   r%      sD    
	
33r%   c                       s   e Zd ZU eddd eD ejZe	e
d< dZe	e
d< edeedf f fd	d
Zedddddfdededee dee dedeee  ddf fddZdeddfddZdeddfddZdeddfddZdeddfddZ  ZS ) r6   |c                 c   s"    | ]}d t | dV  qdS )z^/$N)reescape).0patternrF   rF   rG   	<genexpr>   s     zFilePathValidator.<genexpr>_RE_NTFS_RESERVED)rN   :_MACOS_RESERVED_FILE_PATHSr0   .c                    s@   t  j}t|  |  |  gr|| j S |  r|d S |S )N)rN   )r7   reserved_keywordsany_is_universal	_is_posix	_is_macosrz   	_is_linux)rB   common_keywordsrD   rF   rG   r{      s   
z#FilePathValidator.reserved_keywordsr&   NTr2   r'   r(   r)   r3   r,   c                    sT   t  j||||||d t|| j||||d| _| jddr$tj| _d S t	j| _d S )Nr1   Tr4   )
r7   r8   r   r'   #_FilePathValidator__fname_validatorr=   r>   r?   _FilePathValidator__split_driverA   )rB   r2   r'   r(   r)   r3   r,   rD   rF   rG   r8      s&   			zFilePathValidator.__init__rI   c              
   C   s4  t || jdd d | | | |\}}|sd S t|}t|| j}tj	t
jtj| jtj| jtj|tj|i}|| jkrStd| jdd|ddgfi ||| jk rftd| j|gfi || | |d	d
}|d
D ]}|r~|dv rqv| j| qv| jddr| | d S | | d S )NTr4   rK   z!file path is too long: expected<=dz bytes, actual=z bytesz?file path is too short: expected>={:d} bytes, actual={:d} bytesrM   rN   ).z..)r   r=   validate_abspathr   r   lenencode_fs_encodingr   REASONr   INVALID_LENGTHPLATFORMr)   FS_ENCODING
BYTE_COUNTVALUEr'   r   r2   format_validate_reserved_keywordsrY   rZ   r   r`   )_FilePathValidator__validate_win_filepath*_FilePathValidator__validate_unix_filepath)rB   rI   _drivetailrc   byte_ct
err_kwargsrg   rF   rF   rG   r`      sL   



	zFilePathValidator.validatec                 C   s   t |}tt|}t|  o||  o|grd S |  r.t||gr.td| j	t
jd td|d| j	j dd d | j	t
jd}| jd	d
rN|rN||  s_t|\}}|ra|rc|d S d S d S )Nz8platform-independent absolute file path is not supported)r)   rP   zan invalid absolute file path (z) for the platform (z).zE to avoid the error, specify an appropriate platform corresponding toz the path format or 'auto'.)descriptionr)   rP   Tr4   )rA   isabsr   r   r|   r=   r~   r}   r   r)   r   MALFORMED_ABS_PATHrI   r>   r?   )rB   rI   is_posix_abs	is_nt_abs
err_objectrd   _tailrF   rF   rG   r      s6   

z"FilePathValidator.validate_abspathrc   c                 C   s*   t |}|rttjt|d|dd S )Ninvalid)rI   )r#   findallr   r   r   r   )rB   rc   matchrF   rF   rG   __validate_unix_filepath  s   
z*FilePathValidator.__validate_unix_filepathc                 C   sv   t |}|rttjt|dtj|d| |\}}|r7| j	
|}|r9| }td| dd|| jdd S d S )Nr   )r)   rI   'z' is a reserved nameF)reusable_namereserved_namer)   )r$   r   r   r   r   r   r   WINDOWSr   rx   searchgroupr   r)   )rB   rc   r   r   rI   match_reservedr   rF   rF   rG   __validate_win_filepath  s(   

z)FilePathValidator.__validate_win_filepath)rk   rl   rm   rs   compiler^   r   
IGNORECASErx   r   __annotations__rz   propertytupler[   r{   r   rn   r   r   ro   r   r8   r   r`   r   r   r   rp   rF   rF   rD   rG   r6      sB   
 
 0 r6   T	file_pathr)   r2   r'   r(   r3   r,   r0   c                 C   s*   t |||du r	dn||||d|  dS )a  Verifying whether the ``file_path`` is a valid file path or not.

    Args:
        file_path (PathType):
            File path to be validated.
        platform (Optional[PlatformType], optional):
            Target platform name of the file path.

            .. include:: platform.txt
        min_len (int, optional):
            Minimum byte length of the ``file_path``. The value must be greater or equal to one.
            Defaults to ``1``.
        max_len (Optional[int], optional):
            Maximum byte length of the ``file_path``. If the value is |None| or minus,
            automatically determined by the ``platform``:

                - ``Linux``: 4096
                - ``macOS``: 1024
                - ``Windows``: 260
                - ``universal``: 260
        fs_encoding (Optional[str], optional):
            Filesystem encoding that is used to calculate the byte length of the file path.
            If |None|, get the encoding from the execution environment.
        check_reserved (bool, optional):
            If |True|, check the reserved names of the ``platform``.
            Defaults to |True|.
        additional_reserved_names (Optional[Sequence[str]], optional):
            Additional reserved names to check.

    Raises:
        ValidationError (ErrorReason.INVALID_CHARACTER):
            If the ``file_path`` includes invalid char(s):
            |invalid_file_path_chars|.
            The following characters are also invalid for Windows platforms:
            |invalid_win_file_path_chars|
        ValidationError (ErrorReason.INVALID_LENGTH):
            If the ``file_path`` is longer than ``max_len`` characters.
        ValidationError:
            If ``file_path`` includes invalid values.

    Example:
        :ref:`example-validate-file-path`

    See Also:
        `Naming Files, Paths, and Namespaces - Win32 apps | Microsoft Docs
        <https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file>`__
    Nr&   r)   r2   r'   r(   r3   r,   )r6   r`   r   r)   r2   r'   r(   r3   r,   rF   rF   rG   validate_filepath3  s   9r   c                 C   s&   t |||du r	dn||||d| S )a3  Check whether the ``file_path`` is a valid name or not.

    Args:
        file_path:
            A filepath to be checked.
        platform:
            Target platform name of the file path.

    Example:
        :ref:`example-is-valid-filepath`

    See Also:
        :py:func:`.validate_filepath()`
    Nr&   r   )r6   is_validr   rF   rF   rG   is_valid_filepathv  s   r   rH   FrJ   r*   r+   r-   r.   c              
   C   sN   |durt dt |du rtj}t||du rdn|||	||||
d| |S )a  Make a valid file path from a string.

    To make a valid file path, the function does the following:

        - Replace invalid characters for a file path within the ``file_path``
          with the ``replacement_text``. Invalid characters are as follows:

            - unprintable characters
            - |invalid_file_path_chars|
            - for Windows (or universal) only: |invalid_win_file_path_chars|

        - Replace a value if a sanitized value is a reserved name by operating systems
          with a specified handler by ``reserved_name_handler``.

    Args:
        file_path:
            File path to sanitize.
        replacement_text:
            Replacement text for invalid characters.
            Defaults to ``""``.
        platform:
            Target platform name of the file path.

            .. include:: platform.txt
        max_len:
            Maximum byte length of the file path.
            Truncate the path if the value length exceeds the `max_len`.
            If the value is |None| or minus, ``max_len`` will automatically determined by the ``platform``:

                - ``Linux``: 4096
                - ``macOS``: 1024
                - ``Windows``: 260
                - ``universal``: 260
        fs_encoding:
            Filesystem encoding that is used to calculate the byte length of the file path.
            If |None|, get the encoding from the execution environment.
        check_reserved:
            [Deprecated] Use 'reserved_name_handler' instead.
        null_value_handler:
            Function called when a value after sanitization is an empty string.
            You can specify predefined handlers:

                - :py:func:`.handler.NullValueHandler.return_null_string`
                - :py:func:`.handler.NullValueHandler.return_timestamp`
                - :py:func:`.handler.raise_error`

            Defaults to :py:func:`.handler.NullValueHandler.return_null_string` that just return ``""``.
        reserved_name_handler:
            Function called when a value after sanitization is one of the reserved names.
            You can specify predefined handlers:

                - :py:meth:`~.handler.ReservedNameHandler.add_leading_underscore`
                - :py:meth:`~.handler.ReservedNameHandler.add_trailing_underscore`
                - :py:meth:`~.handler.ReservedNameHandler.as_is`
                - :py:func:`~.handler.raise_error`

            Defaults to :py:func:`.handler.add_trailing_underscore`.
        additional_reserved_names:
            Additional reserved names to sanitize.
            Case insensitive.
        normalize:
            If |True|, normalize the the file path.
        validate_after_sanitize:
            Execute validation after sanitization to the file path.

    Returns:
        Same type as the argument (str or PathLike object):
            Sanitized filepath.

    Raises:
        ValueError:
            If the ``file_path`` is an invalid file path.

    Example:
        :ref:`example-sanitize-file-path`
    NzD'check_reserved' is deprecated. Use 'reserved_name_handler' instead.Fr&   )r)   r'   r(   r-   r*   r+   r,   r.   )warningswarnDeprecationWarningr   as_isr%   r\   )r   rJ   r)   r'   r(   r3   r*   r+   r,   r-   r.   rF   rF   rG   sanitize_filepath  s&   Z	r   )
rH   NNNNNNNTF)>__doc__r>   os.pathrU   rA   rs   r   collections.abcr   pathlibr   r   r   typingr   r   _baser	   r
   r   r   _commonr   r   r   r   _constr   r   r   r   	_filenamer   r   _typesr   r   errorr   r   r   r   r   handlerr   r   r   rt   _INVALID_PATH_CHARSUNICODEr#   r   _INVALID_WIN_PATH_CHARSr$   r%   r6   rn   r[   ro   r   r   r   rF   rF   rF   rG   <module>   s    (t $

E

$
	
