
    Mh*R                    L   d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	 ddl
mZ ddlmZ ddlZddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZmZmZ d Zd ZddZ ddZ!d Z"d Z#edd            Z$edd            Z% G d dee          Z& G d de&          Z'dS )z9
Utilities for file-based Contents/Checkpoints managers.
    )annotationsN)decodebytesencodebytes)contextmanager)partial)run_sync)	HTTPError)BoolEnum)Configurable)LoggingConfigurable)ApiPathto_api_path
to_os_pathc                0    t          j        | |           dS )zreplace dst with srcN)osreplacesrcdsts     g/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_server/services/contents/fileio.pyreplace_filer      s    JsC    c                L   K   t          t          j        | |           d{V  dS )z#replace dst with src asynchronouslyN)r   r   r   r   s     r   async_replace_filer       s2      
2:sC
(
((((((((((r   c                d   t          j        | t           j                  s7|r|                    d| d           t	          t
          j        d|            t          j        | |           	 t          j	        | |           dS # t          $ r! |r|                    d|d           Y dS Y dS w xY w)zZcopy src to dst

    like shutil.copy2, but log errors in copystat instead of raising
     Source file, %s, is not writableTexc_infoFile is not writable: copystat on %s failedN)r   accessW_OKdebugPermissionErrorerrnoEACCESshutilcopyfilecopystatOSErrorr   r   logs      r   
copy2_safer.   %   s     9S"'"" L 	NII8#IMMMel,JS,J,JKKK
OCCS!!!!! C C C 	CII-sTIBBBBBB	C 	C 	CCs   -B $B/.B/c                  K   t          j        | t           j                  s7|r|                    d| d           t	          t
          j        d|            t          t          j	        | |           d{V  	 t          t          j
        | |           d{V  dS # t          $ r! |r|                    d|d           Y dS Y dS w xY w)zicopy src to dst asynchronously

    like shutil.copy2, but log errors in copystat instead of raising
    r   Tr   r    Nr!   )r   r"   r#   r$   r%   r&   r'   r   r(   r)   r*   r+   r,   s      r   async_copy2_safer0   8   s     
 9S"'"" L 	NII8#IMMMel,JS,J,JKKK
6?C
-
--------CvS11111111111 C C C 	CII-sTIBBBBBB	C 	C 	CCs   ;!B $C	C	c                    t           j                            |           \  }}t           j                            |d|z             S )ztName of the intermediate file used in atomic writes.

    The .~ prefix will make Dropbox ignore the temporary file.z.~r   pathsplitjoinr3   dirnamebasenames      r   path_to_intermediater9   J   s6     d++GX7<<111r   c                    t           j                            |           \  }}t           j                            ||dz             S )zEName of invalid file after a failed atomic write and subsequent read.z.invalidr2   r6   s      r   path_to_invalidr;   R   s5    d++GX7<<J!6777r   Tutf-8c              +  "  K   t           j                            |           rOt           j                            t           j                            |           t          j        |                     } t           j                            |           pt          j                    }t           j                            |           rt          j        |t           j	                  s{t          j        | t           j	                  r\|rdnd}|rt          | |fd|i|}nt          | |fi |}	 |V  |                                 n# |                                 w xY wdS t          |           }t           j                            |           rt          | ||           |r'|                    dd           t          | dfd|i|}nt          | dfi |}	 |V  n3# t          $ r& |                                 t!          ||             w xY w|                                 t          j        |                                           |                                 t           j                            |          rt          j        |           dS dS )a  Context manager to write to a file only if the entire write is successful.

    This works by copying the previous file contents to a temporary file in the
    same directory, and renaming that file back to the target if the context
    exits with an error. If the context is successful, the new data is synced to
    disk and the temporary file is removed.

    Parameters
    ----------
    path : str
        The target file to write to.
    text : bool, optional
        Whether to open the file in text mode (i.e. to write unicode). Default is
        True.
    encoding : str, optional
        The encoding to use for files opened in text mode. Default is UTF-8.
    **kwargs
        Passed to :func:`io.open`.
    wwbencodingNr-   newline
)r   r3   islinkr5   r7   readlinkgetcwdisfiler"   r#   opencloser9   r.   
setdefaultBaseExceptionr   flushfsyncfilenoremove)	r3   textr@   r-   kwargsdirpathmodefileobjtmp_paths	            r   atomic_writingrV   X   sq     0 
w~~d Fw||BGOOD112;t3D3DEE good##2ry{{G	w~~d BIgrw$?$? BIdTVT[D\D\ $ss 	14CCCFCCGG40000G	MMMMMOOOOGMMOOOO#D))H	w~~d ,4s++++ -)T***tS>>8>v>>tT,,V,,   Xt$$$	 MMOOOHW^^MMOOO 
w~~h 
	( s   (E EG 0H	c              +    K   t           j                            |           rOt           j                            t           j                            |           t          j        |                     } |r'|                    dd           t          | dfd|i|}nt          | dfi |}	 |V  n## t          $ r |	                                  w xY w|	                                 dS )a  Context manager to write file without doing atomic writing
    (for weird filesystem eg: nfs).

    Parameters
    ----------
    path : str
        The target file to write to.
    text : bool, optional
        Whether to open the file in text mode (i.e. to write unicode). Default is
        True.
    encoding : str, optional
        The encoding to use for files opened in text mode. Default is UTF-8.
    **kwargs
        Passed to :func:`io.open`.
    rB   rC   r>   r@   r?   N)
r   r3   rD   r5   r7   rE   rJ   rH   rK   rI   )r3   rP   r@   r-   rQ   rT   s         r   _simple_writingrX      s      ( 
w~~d Fw||BGOOD112;t3D3DEE -)T***tS>>8>v>>tT,,V,,    MMOOOOOs   )B. . Cc                      e Zd ZdZ eddd          Z eej        ddd          Z	e
d             Ze
d	             Ze
d!d            Zd Zd Z	 d"d#dZd$dZd%dZ	 d&d'dZd  ZdS )(FileManagerMixina  
    Mixin for ContentsAPI classes that interact with the filesystem.

    Provides facilities for reading, writing, and copying files.

    Shared by FileContentsManager and FileCheckpoints.

    Note
    ----
    Classes using this mixin must provide the following attributes:

    root_dir : unicode
        A directory against against which API-style paths are to be resolved.

    log : logging.Logger
    Ta  By default notebooks are saved on disk on a temporary file and then if successfully written, it replaces the old ones.
      This procedure, namely 'atomic_writing', causes some bugs on file system without operation order enforcement (like some networked fs).
      If set to False, the new notebook is written directly on the old one which could fail (eg: full filesystem or quota ))confighelpsha256z:Hash algorithm to use for file content, support by hashlib)default_valuer[   r\   c              /     K   |                      |          5  t          |g|R i |5 }|V  ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )z<wrapper around io.open that turns permission errors into 403N)perm_to_403rH   selfos_pathargsrQ   fs        r   rH   zFileManagerMixin.open   s       g&& 	 	W(Ft(F(F(Fv(F(F 	!GGG	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s.   A:A>	A>	AAAc              /  :  K   |                      |          5  | j        |d<   | j        r-t          |g|R i |5 }|V  ddd           n# 1 swxY w Y   n,t	          |g|R i |5 }|V  ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )zwrapper around atomic_writing that turns permission errors to 403.
        Depending on flag 'use_atomic_writing', the wrapper perform an actual atomic writing or
        simply writes the file (whatever an old exists or not)r-   N)r`   r-   use_atomic_writingrV   rX   ra   s        r   rV   zFileManagerMixin.atomic_writing   s     
 g&& 	 	 HF5M& #G=d===f== GGG               %W>t>>>v>> !GGG              	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	sW   "BABA	BA	B'A8,B8A<	<B?A<	 BBB c              #     K   	 dV  dS # t           $ rZ}|j        t          j        t          j        hv r5|s	|j        pd}t          || j                  }t          dd|z            | d}~ww xY w)z7context manager for turning permission errors into 403.Nzunknown file)rooti  zPermission denied: %s)r+   r&   EPERMr'   filenamer   root_dirr	   )rb   rc   er3   s       r   r`   zFileManagerMixin.perm_to_403   s      	EEEEE 
	 
	 
	w5;555  ;j:NG"7???%<t%CDD!K
	s   
 
A.AA))A.c                4    t          ||| j                   dS zPcopy src to dest

        like shutil.copy2, but log errors in copystat
        rA   N)r.   r-   rb   r   dests      r   _copyzFileManagerMixin._copy  s!    
 	3$(++++++r   c                ,   t           j                            | j                  }t           j                            |          d         rt          dd|z            t          t          |          |          }	 t          j        |           n-# t          $ r Y n!t          $ r t          d| d          dw xY wt           j                            |          t           j        j        z                       |          st          dd|z            |S )aS  Given an API path, return its file system path.

        Parameters
        ----------
        path : str
            The relative API path to the named file.

        Returns
        -------
        path : str
            Native, absolute OS path to for a file.

        Raises
        ------
        404: if path is outside root
        r   i  z%s is not a relative API pathz is not a valid pathNz%%s is outside root contents directory)r   r3   abspathrm   
splitdriver	   r   r   lstatr+   
ValueErrorsep
startswith)rb   r3   rj   rc   s       r   _get_os_pathzFileManagerMixin._get_os_path  s   & wt}--7d##A& 	IC!@4!GHHHWT]]D11	JHW 	 	 	 D 	J 	J 	JCD!>!>!>??TI	J ((27;6BB4HH 	QC!H4!OPPPs   ;B 
B:B:   NFrawboolc                   |                      |d|          }	 t          j        |d         ||          }|r
||d         fn|S # t          $ r}|}Y d}~nd}~ww xY wt	          |          }	| j        rt          j                            |	          st          dd| d	|          t          |          }
t          ||
           t          |	|           |                     ||||
          S ) Read a notebook from an os path.rP   )r}   r   
as_versioncapture_validation_error   N  Unreadable Notebook:  r   r}   )
_read_filenbformatreads	Exceptionr9   rg   r   r3   existsr	   r;   r   _read_notebookrb   rc   r   r   r}   answernbrn   e_origrU   invalid_files              r   r   zFileManagerMixin._read_notebook;  s8    &c::		q	%)A  B '*1Bq	??r1 	 	 	FFFFFF	 (00& 	bgnnX.F.F 	<<<&<<   'w//Wl+++Xw'''""Z:RX[ # 
 
 	
s   *A 
AAAc                    |                      |d          5 }t          j        ||t          j        |           ddd           dS # 1 swxY w Y   dS zSave a notebook to an os_path.r<   )r@   )versionr   N)rV   r   write
NO_CONVERTrb   rc   r   r   re   s        r   _save_notebookzFileManagerMixin._save_notebook_  s      7 ;; 	qN +)A	   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   #AAAbyte_contentbytesreturndict[str, str]c                    | j         }t          j        |          }|                    |           |                                |dS )a^  Compute the hash hexdigest for the provided bytes.

        The hash algorithm is provided by the `hash_algorithm` attribute.

        Parameters
        ----------
        byte_content : bytes
            The bytes to hash

        Returns
        -------
        A dictionary to be appended to a model {"hash": str, "hash_algorithm": str}.
        )hashhash_algorithm)r   hashlibnewupdate	hexdigest)rb   r   	algorithmhs       r   	_get_hashzFileManagerMixin._get_hashi  sC     '	K	""	CCCr   rc   strformat
str | None8tuple[str | bytes, str] | tuple[str | bytes, str, bytes]c                |   t           j                            |          st          dd|z            |                     |d          5 }|                                }ddd           n# 1 swxY w Y   |dk    r|r|d|fn|dfS ||dk    re	 |r|                    d          d|fn|                    d          dfS # t          $ r&}|dk    rt          dd|z  d	
          |Y d}~nd}~ww xY w|r%t          |                              d          d|fn#t          |                              d          dfS a  Read a non-notebook file.

        Parameters
        ----------
        os_path: str
            The path to be read.
        format: str
            If 'text', the contents will be decoded as UTF-8.
            If 'base64', the raw bytes contents will be encoded as base64.
            If 'byte', the raw bytes contents will be returned.
            If not specified, try to decode as UTF-8, and fall back to base64
        raw: bool
            [Optional] If True, will return as third argument the raw bytes content

        Returns
        -------
        (content, format, byte_content) It returns the content in the given format
        as well as the raw byte content.
        r   zCannot read non-file %srbNbyterP   utf8z%s is not UTF-8 encodedz
bad format)reasonasciibase64)	r   r3   rG   r	   rH   readdecodeUnicodeErrorr   rb   rc   r   r}   re   bcontentrn   s          r   r   zFileManagerMixin._read_file|  s   , w~~g&& 	FC!:W!DEEEYYw%% 	 vvxxH	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  V36NHfh//Xv<NN>Vv-- X__V,,fh?? !//     V###1G;+   	 $#### [""))'22HhGG H%%,,W55	
s*   	A**A.1A.0C   
C0
C++C0c                   |dvrt          dd          	 |dk    r|                    d          }n$|                    d          }t          |          }n)# t          $ r}t          dd| d|           |d	}~ww xY w|                     |d
          5 }|                    |           d	d	d	           d	S # 1 swxY w Y   d	S zSave content of a generic file.>   rP   r   r   z:Must specify format of file contents as 'text' or 'base64'rP   r   r   zEncoding error saving z: NF)rP   )r	   encoder   r   rV   r   rb   rc   contentr   r   	b64_bytesrn   re   s           r   
_save_filezFileManagerMixin._save_file  s=   +++L  	Q">>&11#NN733	&y11 	Q 	Q 	QC!H'!H!HQ!H!HIIqP	Q   u 55 	GGH	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s*   A A 
A=!A88A=B::B>B>)rh   r|   NFr}   r~   N)r   r   r   r   Frc   r   r   r   r}   r~   r   r   )__name__
__module____qualname____doc__r
   rg   r   r   algorithms_availabler   r   rH   rV   r`   rs   r{   r   r   r   r   r    r   r   rZ   rZ      s[        "    T$I	  N   ^
   ^    ^ , , ,% % %P QV"
 "
 "
 "
 "
H   D D D D( =B:
 :
 :
 :
 :
x    r   rZ   c                  >    e Zd ZdZd Z	 dddZdd	Z	 dddZd ZdS )AsyncFileManagerMixinzY
    Mixin for ContentsAPI classes that interact with the filesystem asynchronously.
    c                D   K   t          ||| j                   d{V  dS rp   )r0   r-   rq   s      r   rs   zAsyncFileManagerMixin._copy  s7      
 sDdh777777777777r   r|   NFr}   r~   c                J  K   |                      |d|           d{V }	 t          t          t          j        ||          |d                    d{V }|r
||d         fn|S # t
          $ r}|}Y d}~nd}~ww xY wt          |          }	| j        rt          j	        
                    |	          st          dd| d|          t          |          }
t          ||
           d{V  t          |	|           d{V  |                     ||||	           d{V }|S )
r   rP   Nr   r   r   r   r   r   r   )r   r   r   r   r   r   r9   rg   r   r3   r   r	   r;   r   r   r   s              r   r   z$AsyncFileManagerMixin._read_notebook  s      w<<<<<<<<	N)-E  
 q	       B '*1Bq	??r1 	 	 	FFFFFF	 (00& 	bgnnX.F.F 	<<<&<<   'w// ,777777777 7333333333**Z:RX[ + 
 
 
 
 
 
 
 
 s   AA% %
A;/A66A;c                   K   |                      |d          5 }t          t          t          j        t          j        |          ||           d{V  ddd           dS # 1 swxY w Y   dS r   )rV   r   r   r   r   r   r   s        r   r   z$AsyncFileManagerMixin._save_notebook   s        7 ;; 		qN$/-E  
         		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		s   <A##A'*A'rc   r   r   r   r   r   c                  K   t           j                            |          st          dd|z            |                     |d          5 }t          |j                   d{V }ddd           n# 1 swxY w Y   |dk    r|r|d|fn|dfS ||dk    re	 |r|                    d          d|fn|                    d          dfS # t          $ r&}|dk    rt          dd|z  d	
          |Y d}~nd}~ww xY w|r%t          |                              d          d|fn#t          |                              d          dfS r   )
r   r3   rG   r	   rH   r   r   r   r   r   r   s          r   r   z AsyncFileManagerMixin._read_file  s     , w~~g&& 	FC!:W!DEEEYYw%% 	.%af--------H	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. V36NHfh//Xv<NN>Vv-- X__V,,fh?? !//     V###1G;+   	 $#### C[""))'22HhGGh''..w77B	
s*   A22A69A60C 
C8C33C8c                  K   |dvrt          dd          	 |dk    r|                    d          }n$|                    d          }t          |          }n)# t          $ r}t          dd| d|           |d	}~ww xY w|                     |d
          5 }t          |j        |           d	{V  d	d	d	           d	S # 1 swxY w Y   d	S r   )r	   r   r   r   rV   r   r   r   s           r   r   z AsyncFileManagerMixin._save_fileF  sS     +++L  	Q">>&11#NN733	&y11 	Q 	Q 	QC!H'!H!HQ!H!HIIqP	Q   u 55 	.17H---------	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.s*   A A 
A?#A::A?CC	Cr   r   r   r   r   )	r   r   r   r   rs   r   r   r   r   r   r   r   r   r     s         8 8 8 QV& & & & &P    =B7
 7
 7
 7
 7
r. . . . .r   r   r   )Tr<   N)(r   
__future__r   r&   r   r   r(   r   r   r   
contextlibr   	functoolsr   r   anyio.to_threadr   tornado.webr	   	traitletsr
   r   traitlets.configr   traitlets.config.configurabler   jupyter_server.utilsr   r   r   r   r   r.   r0   r9   r;   rV   rX   rZ   r   r   r   r   <module>r      s1    # " " " " "   				  + + + + + + + + % % % % % %        $ $ $ $ $ $ ! ! ! ! ! !                 ) ) ) ) ) ) = = = = = = A A A A A A A A A A  
) ) )
C C C C&C C C C$2 2 28 8 8 D D D DN # # # #LB B B B B*L B B BJK. K. K. K. K., K. K. K. K. K.r   