
    KiI                     T   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j\                  d ej^                  ej`                        ddejb                        Z2ee3d<    ej\                  d ej^                  ejh                        ddejb                        Z5ee3d<    G d de      Z6 G 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!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"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(Z=y)*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                        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ZddededefdZdee   fdZdefdZ xZS )FilePathSanitizerNmax_lenfs_encodingplatformnull_value_handlerreserved_name_handleradditional_reserved_names	normalizevalidate_after_sanitize	validatorreturnc
           
      p   |	r|	}
nt        t        ||d||      }
t        |   |||
|||||       | j	                         | _        t        | j                  ||||| j                  |      | _	        || _
        | j                  d      rt        j                  | _        y t        j                  | _        y )NTmin_lenr(   r)   check_reservedr-   r*   )r(   r)   r0   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/   r0   fpath_validator	__class__s              b/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/pathvalidate/_filepath.pyr:   zFilePathSanitizer.__init__   s     'O/''#*C!O 	#%1"7&?$; 	 		
 !% 9 9 ;!2LL#1"7&?]]$;"
 %d3!'!2!2D!*!5!5D    valuereplacement_textc                    	 t        || j                  d              t        |      }| j                  |      \  }}| j                  j                  ||      }| j                  r!|rt        j                  j!                  |      }|}g }|r|j#                  |       |j%                  dd      j'                  d      D ]l  }|t(        v r|j#                  | d        t+        | j,                  j/                  ||            }	|	s|s|j#                  d       \|j#                  |	       n | j1                         j3                  |      }	 | j4                  j7                  |       | j8                  r| j4                  j7                  |       t        |t              rt;        |      S |S # t        $ rJ}|j                  t        j
                  k(  r't        |t              r | j                  |      cY d }~S  d }~ww xY w# t        $ r8}|j                  t        j
                  k(  r| j                  |      }Y d }~d }~ww xY w)	NTr6   allow_whitespaces\/_)rJ    )r   r?   r   reasonr   	NULL_NAME
isinstancer   _null_value_handlerr   rB   r<   subr>   ospathnormpathappendreplacesplitr   strr=   sanitize&_FilePathSanitizer__get_path_separatorjoin
_validatorvalidate_validate_after_sanitizer   )
rD   rI   rJ   eunicode_filepathdrivesanitized_pathsanitized_entriesentrysanitized_entrys
             rG   r^   zFilePathSanitizer.sanitizeR   s   	e4;K;K^b;K;c7cd "%="&"4"45E"F00445EGWX 0!ww//0@A)')$$U+#++D#6<<SA 	6E11!((E7!5!&&//HX/YO #(%,,R0$$_5	6 22499:KL	=OO$$^4
 ((OO$$^4eX&'']  	xx;000eX.//22	H  	=xx;000!%!9!9!!<	=s;   F. H .	H7>G<5H;G<<H	I.I  Ic                 >    | j                  d      rt        S t        S )NTr6   )r?   r%   r$   rD   s    rG   r;   z&FilePathSanitizer._get_sanitize_regexp   s    d3''rH   c                 &    | j                         ryy)NrN   rO   )r?   rl   s    rG   __get_path_separatorz&FilePathSanitizer.__get_path_separator   s    rH   )	NNNNNTFN)rQ   )__name__
__module____qualname__intr   r]   r   r    r   boolr   r:   r   r^   r   r;   r_   __classcell__rF   s   @rG   r'   r'      s     %)+/?CBF=A(-151616 c]16 <(	16
 %%;<16  ((>?16 $,HSM#:16 16 "&16 -.16 
16f1h 1# 1x 1f gcl  c rH   r'   c                   F    e Zd ZU  ej                  dj                  d eD              ej                        Ze	e
d<   dZe	e
d<   edeedf   f f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Zdedd
fdZdedd
fdZdedd
fdZdedd
fdZ xZS )r8   |c              #   N   K   | ]  }d t        j                  |       d  yw)z^/$N)reescape).0patterns     rG   	<genexpr>zFilePathValidator.<genexpr>   s#     U2bii()+Us   #%_RE_NTFS_RESERVED)rO   :_MACOS_RESERVED_FILE_PATHSr1   .c                     t         |   }t        | j                         | j	                         | j                         g      r|| j                  z   S | j                         r|dz   S |S )N)rO   )r9   reserved_keywordsany_is_universal	_is_posix	_is_macosr   	_is_linux)rD   common_keywordsrF   s     rG   r   z#FilePathValidator.reserved_keywords   s_    '3""$dnn&68HIJ"T%D%DDD>>"V++rH   ro   NTr4   r(   r)   r*   r5   r-   c                     t         |   ||||||       t        || j                  ||||      | _        | j                  d      rt        j                  | _        y t        j                  | _        y )Nr3   Tr6   )
r9   r:   r   r(   #_FilePathValidator__fname_validatorr?   r@   rA   _FilePathValidator__split_driverC   )rD   r4   r(   r)   r*   r5   r-   rF   s          rG   r:   zFilePathValidator.__init__   s}     	#)&? 	 	
 "3LL#)&?"
 d3!'!2!2D!*!5!5DrH   rI   c           
         t        || j                  d              | j                  |       | j                  |      \  }}|sy t	        |      }t        |j                  | j                              }t        j                  t        j                  t        j                  | j                  t        j                  | j                  t        j                  |t        j                   |i}|| j"                  kD  r t%        d| j"                  dd|ddgfi ||| j&                  k  r't%        dj)                  | j&                  |      gfi || j+                  |       |j-                  d	d
      }|j/                  d
      D ]$  }|r|dv r
| j0                  j3                  |       & | j                  d      r| j5                  |       y | j7                  |       y )NTr6   rL   z!file path is too long: expected<=dz bytes, actual=z bytesz?file path is too short: expected>={:d} bytes, actual={:d} bytesrN   rO   ).z..)r   r?   validate_abspathr   r   lenencode_fs_encodingr   REASONr   INVALID_LENGTHPLATFORMr*   FS_ENCODING
BYTE_COUNTVALUEr(   r   r4   format_validate_reserved_keywordsr[   r\   r   rb   )_FilePathValidator__validate_win_filepath*_FilePathValidator__validate_unix_filepath)rD   rI   _drivetailre   byte_ct
err_kwargsri   s           rG   rb   zFilePathValidator.validate   s   %t7G7GZ^7G7_3_`e$))%0!$<&--d.?.?@A!;!;!!4==$$d&7&7##W 0

 T\\!!7Q7GW^_`Vaagh 	  T\\!!U\\g   	(()9:+33D#>%++C0 	3EE[0""++E2		3 d3(()9:))*:;rH   c                 Z   t        j                  |      }t        t        |            }t	        | j                         xr || j                         xr |g      ry | j                         r3t	        ||g      r&t        d| j                  t        j                         t        d|d| j                  j                   ddz   dz   | j                  t        j                        }| j                  d	
      r|r|| j                         s t        j                  |      \  }}|r|r|y y y )Nz8platform-independent absolute file path is not supported)r*   rR   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*   rR   Tr6   )rC   isabsr   r   r   r?   r   r   r   r*   r   MALFORMED_ABS_PATHrI   r@   rA   )rD   rI   is_posix_abs	is_nt_abs
err_objectrf   _tails          rG   r   z"FilePathValidator.validate_abspath   s    u-!&-0	  "0y$..2B2S|TUCL(A$BJ"55 %1%:Nt}}ObObNccefYZ/0 ]]11

 d3!!,,U3LE5   #u "rH   re   c                     t         j                  |      }|r*t        t        j                  t        |            |      y )Ninvalid)rI   )r$   findallr   r   r   r   )rD   re   matchs      rG   __validate_unix_filepathz*FilePathValidator.__validate_unix_filepath  s>     (()9:")009NO&  rH   c                 f   t         j                  |      }|r9t        t        j                  t        |            t        j                  |      | j                  |      \  }}|rK| j                  j                  |      }|r-|j                         }t        d| dd|| j                        y y )Nr   )r*   rI   'z' is a reserved nameF)reusable_namereserved_namer*   )r%   r   r   r   r   r   r   WINDOWSr   r   searchgroupr   r*   )rD   re   r   r   rI   match_reservedr   s          rG   __validate_win_filepathz)FilePathValidator.__validate_win_filepath  s    $,,-=>")009NO!))&  **+;<!33::5AN . 4 4 6'&:;"'"/!]]	   rH   )rp   rq   rr   r{   compiler`   r   
IGNORECASEr   r   __annotations__r   propertytupler]   r   r   rs   r   r   rt   r   r:   r   rb   r   r   r   ru   rv   s   @rG   r8   r8      s!   )rzzU;TUU
 u  )32	5c? 	 	 '%)+/#=A66 6 c]	6
 <(6 6 $,HSM#:6 
6@.<h .<4 .<`!h !4 !@    rH   r8   T	file_pathr*   r4   r(   r)   r5   r-   r1   c                 L    t        |||dn||||      j                  |        y)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>`__
    Nro   r*   r4   r(   r)   r5   r-   )r8   rb   r   r*   r4   r(   r)   r5   r-   s          rG   validate_filepathr   3  s1    r o7%"; hyrH   c                 J    t        |||dn||||      j                  |       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()`
    ro   r   )r8   is_validr   s          rG   is_valid_filepathr   v  s5    0 o7%"; hyrH   rJ   r+   r,   r.   r/   c           
          |.t        j                  dt               |du rt        j                  }t        ||dn|||	||||
      j                  | |      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`
    zD'check_reserved' is deprecated. Use 'reserved_name_handler' instead.Fro   )r*   r(   r)   r.   r+   r,   r-   r/   )warningswarnDeprecationWarningr   as_isr'   r^   )r   rJ   r*   r(   r)   r5   r+   r,   r-   r.   r/   s              rG   sanitize_filepathr     sm    t !R	

 U"$7$=$=!o7-3"; 7	 hy*+	,rH   )
rQ   NNNNNNNTF)>__doc__r@   os.pathrW   rC   r{   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   r|   _INVALID_PATH_CHARSUNICODEr$   r   _INVALID_WIN_PATH_CHARSr%   r'   r8   rs   r]   rt   r   r   r    rH   rG   <module>r      s      	  $ "  " P P M M c c ; * b b @ %"**q83O3O)PQR(SST%UWYWaWab % b(bjj			(223A6a8"** e 
q) qh^ ^F (,"!!%9=@@|$@ @ c]	@
 #@ @  (6@ 
@J (,"!!%9=|$  c]	
 #   (6 
H '+!!%%);?>B9=$)l,l,l, |$l, c]	l,
 #l, TNl, !!78l, $$:;l,  (6l, l, "l, l,rH   