a
    m b&;                     @   s  d 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 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 dd
lmZ ddlmZ ddlmZ dd Zdd Zd#ddZd$ddZdd Zdd Ze	d%ddZe	d&ddZG dd  d eZ G d!d" d"e Z!dS )'z9
Utilities for file-based Contents/Checkpoints managers.
    N)decodebytes)encodebytes)contextmanager)partial)run_sync)	HTTPError)Bool)Configurable)to_api_path)
to_os_pathc                 C   s   t | | dS )zreplace dst with srcN)osreplacesrcdst r   Flib/python3.9/site-packages/jupyter_server/services/contents/fileio.pyreplace_file   s    r   c                    s   t tj| |I dH  dS )z#replace dst with src asynchronouslyN)r   r   r   r   r   r   r   async_replace_file   s    r   c                 C   sH   t | | zt | | W n& tyB   |r>|jd|dd Y n0 dS )zZcopy src to dst

    like shutil.copy2, but log errors in copystat instead of raising
    copystat on %s failedTexc_infoN)shutilcopyfilecopystatOSErrordebugr   r   logr   r   r   
copy2_safe#   s    r   c                    sX   t tj| |I dH  zt tj| |I dH  W n& tyR   |rN|jd|dd Y n0 dS )zicopy src to dst asynchronously

    like shutil.copy2, but log errors in copystat instead of raising
    Nr   Tr   )r   r   r   r   r   r   r   r   r   r   async_copy2_safe0   s    r    c                 C   s"   t j| \}}t j|d| S )ztName of the intermediate file used in atomic writes.

    The .~ prefix will make Dropbox ignore the temporary file.z.~r   pathsplitjoinr"   dirnamebasenamer   r   r   path_to_intermediate=   s    r(   c                 C   s"   t j| \}}t j||d S )zEName of invalid file after a failed atomic write and subsequent read.z.invalidr!   r%   r   r   r   path_to_invalidE   s    r)   Tutf-8c                 k   s   t j| r(t jt j| t | } t| }t j| rJt| ||d |rt|	dd t
j| dfd|i|}nt
j| dfi |}z
|V  W n    |  t||   Y n0 |  t |  |  t j|rt | 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`.
    r   newline
wencodingwbN)r   r"   islinkr$   r&   readlinkr(   isfiler   
setdefaultioopencloser   flushfsyncfilenoremove)r"   textr/   r   kwargstmp_pathfileobjr   r   r   atomic_writingK   s(    

r@   c                 k   s   t j| r(t jt j| t | } |rR|dd tj| dfd|i|}ntj| dfi |}z
|V  W n   |	   Y n0 |	  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`.
    r,   r-   r.   r/   r0   N)
r   r"   r1   r$   r&   r2   r4   r5   r6   r7   )r"   r<   r/   r   r=   r?   r   r   r   _simple_writing   s    
rA   c                   @   sv   e Zd ZdZeddddZedd Zedd Zedd
dZ	dd Z
dd ZdddZdd Zdd Zd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 succefully written, it replaces the old ones.
      This procedure, namely 'atomic_writing', causes some bugs on file system whitout 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 ))Zconfighelpc              	   o   sl   |  |N tj|g|R i |}|V  W d   n1 s@0    Y  W d   n1 s^0    Y  dS )z<wrapper around io.open that turns permission errors into 403N)perm_to_403r5   r6   selfos_pathargsr=   fr   r   r   r6      s    zFileManagerMixin.openc              	   o   s   |  | | jrVt|g|R d| ji|}|V  W d   q1 sJ0    Y  nBt|g|R d| ji|}|V  W d   n1 s0    Y  W d   n1 s0    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)rD   use_atomic_writingr@   r   rA   rE   r   r   r   r@      s    &zFileManagerMixin.atomic_writing c              
   c   sz   z
dV  W nj t tfyt } zN|jtjtjhv r^|s>|jp<d}t|| jd}tdd| |n W Y d}~n
d}~0 0 dS )z7context manager for turning permission errors into 403.Nzunknown file)rooti  zPermission denied: %s)	r   IOErrorerrnoEPERMZEACCESfilenamer
   root_dirr   )rF   rG   er"   r   r   r   rD      s    

zFileManagerMixin.perm_to_403c                 C   s   t ||| jd dS zPcopy src to dest

        like shutil.copy2, but log errors in copystat
        r+   N)r   r   rF   r   destr   r   r   _copy   s    zFileManagerMixin._copyc                 C   sD   t j| j}t||}t j|t jj |s@tdd| |S )aY  Given an API path, return its file system path.

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

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

        Raises
        ------
        404: if path is outside root
        i  z%%s is outside root contents directory)r   r"   abspathrQ   r   sep
startswithr   )rF   r"   rL   rG   r   r   r   _get_os_path   s
    
zFileManagerMixin._get_os_path   c                 C   s   | j |ddd}ztj||dW W  d   S  tyX } z|}W Y d}~n
d}~0 0 t|}| jrttj|st	dd||f t
|}t|| t|| | ||W  d   S 1 s0    Y  dS z Read a notebook from an os path.rr*   r/   )
as_versionN  zUnreadable Notebook: %s %r)r6   nbformatread	Exceptionr(   rJ   r   r"   existsr   r)   r   _read_notebookrF   rG   r_   rI   rR   Ze_origr>   Zinvalid_filer   r   r   re     s    


zFileManagerMixin._read_notebookc                 C   sD   | j |dd"}tj||tjd W d   n1 s60    Y  dS zSave a notebook to an os_path.r*   r^   )versionN)r@   ra   write
NO_CONVERTrF   rG   nbrI   r   r   r   _save_notebook!  s    zFileManagerMixin._save_notebookc              
   C   s   t j|stdd| | |d}| }W d   n1 sD0    Y  |du s^|dkrz|ddfW S  ty } z(|dkrtdd| dd	|W Y d}~n
d}~0 0 t|d
dfS a*  Read a non-notebook file.

        os_path: The path to be read.
        format:
          If 'text', the contents will be decoded as UTF-8.
          If 'base64', the raw bytes contents will be encoded as base64.
          If not specified, try to decode as UTF-8, and fall back to base64
        r`   zCannot read non-file %srbNr<   utf8z%s is not UTF-8 encodedz
bad format)reasonasciibase64)	r   r"   r3   r   r6   rb   decodeUnicodeErrorr   rF   rG   formatrI   bcontentrR   r   r   r   
_read_file&  s"    	&zFileManagerMixin._read_filec              
   C   s   |dvrt ddz*|dkr(|d}n|d}t|}W n8 tyt } z t dd||f |W Y d}~n
d}~0 0 | j|d	d
}|| W d   n1 s0    Y  dS zSave content of a generic file.>   r<   rs   r`   z:Must specify format of file contents as 'text' or 'base64'r<   rp   rr   zEncoding error saving %s: %sNF)r<   )r   encoder   rc   r@   ri   rF   rG   Zcontentrw   rx   Z	b64_bytesrR   rI   r   r   r   
_save_fileC  s    
*zFileManagerMixin._save_fileN)rK   )r[   )__name__
__module____qualname____doc__r   rJ   r   r6   r@   rD   rV   rZ   re   rm   ry   r}   r   r   r   r   rB      s$   


rB   c                   @   s:   e Zd ZdZdd ZdddZdd Zd	d
 Zdd ZdS )AsyncFileManagerMixinzY
    Mixin for ContentsAPI classes that interact with the filesystem asynchronously.
    c                    s   t ||| jdI dH  dS rS   )r    r   rT   r   r   r   rV   \  s    zAsyncFileManagerMixin._copyr[   c                    s   | j |ddd}z*tttj|d|I dH W W  d   S  tyd } z|}W Y d}~n
d}~0 0 t|}| jrtj	
|stdd||f t|}t||I dH  t||I dH  | ||I dH W  d   S 1 s0    Y  dS r\   )r6   r   r   ra   rb   rc   r(   rJ   r   r"   rd   r   r)   r   re   rf   r   r   r   re   c  s    *
z$AsyncFileManagerMixin._read_notebookc                    sP   | j |dd.}tttjtjd||I dH  W d   n1 sB0    Y  dS rg   )r@   r   r   ra   ri   rj   rk   r   r   r   rm   |  s    z$AsyncFileManagerMixin._save_notebookc              
      s   t j|stdd| | |d }t|jI dH }W d   n1 sL0    Y  |du sf|dkrz|ddfW S  ty } z(|dkrtdd| dd	|W Y d}~n
d}~0 0 t	|d
dfS rn   )
r   r"   r3   r   r6   r   rb   rt   ru   r   rv   r   r   r   ry     s"    	.z AsyncFileManagerMixin._read_filec              
      s   |dvrt ddz*|dkr(|d}n|d}t|}W n8 tyt } z t dd||f |W Y d}~n
d}~0 0 | j|d	d
"}t|j|I dH  W d   n1 s0    Y  dS rz   )r   r{   r   rc   r@   r   ri   r|   r   r   r   r}     s    
*z AsyncFileManagerMixin._save_fileN)r[   )	r~   r   r   r   rV   re   rm   ry   r}   r   r   r   r   r   W  s   
r   )N)N)Tr*   N)Tr*   N)"r   rN   r5   r   r   rs   r   r   
contextlibr   	functoolsr   ra   Zanyio.to_threadr   Ztornado.webr   Z	traitletsr   Ztraitlets.configr	   Zjupyter_server.utilsr
   r   r   r   r   r    r(   r)   r@   rA   rB   r   r   r   r   r   <module>   s8   

8& -