o
    i,                     @   s   d Z ddlm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ZddlmZ ddlmZ ddlmZ dd	lmZmZ 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dS )z9
Utilities for file-based Contents/Checkpoints managers.
    )contextmanagerN)	HTTPError)to_api_path
to_os_path)str_to_unicode)Configurable)Bool)encodebytesdecodebytesc                 C   sJ   t tdrt| | dS tjdkrtj|rt| t| | dS )zh replace dst with src

    switches between os.replace or os.rename based on python 2.7 or python 3
    replacentN)hasattrosr   namepathexistsremoverename)srcdst r   \/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/notebook/services/contents/fileio.pyreplace_file   s
   

r   c                 C   sN   t | | z	t | | W dS  ty&   |r#|jd|dd Y dS Y dS w )zZcopy src to dst

    like shutil.copy2, but log errors in copystat instead of raising
    zcopystat on %s failedT)exc_infoN)shutilcopyfilecopystatOSErrordebug)r   r   logr   r   r   
copy2_safe*   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   r   splitjoinr   dirnamebasenamer   r   r   path_to_intermediate6   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_invalid=   s   r(   Tutf-8c                 k   s    t j| rt jt j| t | } t| }t j| r&t| ||d |r:|	dd t
| dfd|i|}n	t
| dfi |}z|V  W n   |  t||   |  t |  |  t j|rrt | 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`.
    r   newline
wencodingwbN)r   r   islinkr#   r%   readlinkr'   isfiler    
setdefaultopencloser   flushfsyncfilenor   )r   textr.   r   kwargstmp_pathfileobjr   r   r   atomic_writingB   s,   

r=   c                 k   s    t j| rt jt j| t | } |r)|dd t| dfd|i|}n	t| dfi |}z|V  W n   |   |  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.   r/   N)	r   r   r0   r#   r%   r1   r3   r4   r5   )r   r9   r.   r   r:   r<   r   r   r   _simple_writing   s   
r>   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 both notebooks and
    generic files.

    Shared by FileContentsManager and FileCheckpoints.

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

    root_dir : unicode
        A directory 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helpc              	   o   s~    |  |/ t|g|R i |}|V  W d   n1 s w   Y  W d   dS W d   dS 1 s8w   Y  dS )z<wrapper around io.open that turns permission errors into 403N)perm_to_403r4   selfos_pathargsr:   fr   r   r   r4      s   "zFileManagerMixin.openc              	   o   s    |  |_ | jr,t|g|R d| ji|}|V  W d   n1 s&w   Y  n)t|g|R d| ji|}|V  W d   n1 sHw   Y  W d   dS W d   dS W d   dS 1 shw   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)rB   use_atomic_writingr=   r   r>   rC   r   r   r   r=      s    "zFileManagerMixin.atomic_writing c              
   c   sn    zdV  W dS  t y6 } z#|jtjtjhv r1|s!t|jpd}t|| jd}tdd| | d}~ww )z7context manager for turning permission errors into 403.Nzunknown file)rooti  zPermission denied: )	r   errnoEPERMEACCESr   filenamer   root_dirr   )rD   rE   er   r   r   r   rB      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   )rD   r   destr   r   r   _copy   s   zFileManagerMixin._copyc                 C   sF   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# is outside root contents directory)r   r   abspathrO   r   sep
startswithr   )rD   r   rJ   rE   r   r   r   _get_os_path   s
   
zFileManagerMixin._get_os_path   c                 C   s   | j |dddX}ztj||dW W  d   S  ty, } z|}W Y d}~nd}~ww t|}| jr:tj|sEt	dd| d|t
|}t|| t|| | ||W  d   S 1 scw   Y  dS )	z Read a notebook from an os path.rr)   r.   )
as_versionN  zUnreadable Notebook:  )r4   nbformatread	Exceptionr'   rH   r   r   r   r   r(   r   _read_notebook)rD   rE   rZ   rG   rP   e_origr;   invalid_filer   r   r   r`     s&   


$zFileManagerMixin._read_notebookc                 C   sF   | j |dd}tj||tjd W d   dS 1 sw   Y  dS )zSave a notebook to an os_path.r)   rY   )versionN)r=   r]   write
NO_CONVERT)rD   rE   nbrG   r   r   r   _save_notebook  s   "zFileManagerMixin._save_notebookc              
   C   s   t j|stdd| | |d}| }W d   n1 s#w   Y  |du s0|dkrZz|ddfW S  tyY } z|dkrOtd| ddd	|W Y d}~nd}~ww 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 rbNr9   utf8z is not UTF-8 encodedz
bad format)reasonasciibase64)	r   r   r2   r   r4   r^   decodeUnicodeErrorr	   )rD   rE   formatrG   bcontentrP   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 n ty6 } zt dd| d| |d	}~ww | j|d
d}|| W d	   d	S 1 sOw   Y  d	S )zSave content of a generic file.>   r9   rl   r[   z:Must specify format of file contents as 'text' or 'base64'r9   ri   rk   zEncoding error saving z: NF)r9   )r   encoder
   r_   r=   rd   )rD   rE   contentro   rp   	b64_bytesrP   rG   r   r   r   
_save_fileA  s,   
"zFileManagerMixin._save_fileN)rI   )rW   )__name__
__module____qualname____doc__r   rH   r   r4   r=   rB   rR   rV   r`   rg   rq   ru   r   r   r   r   r?      s"    


r?   )N)Tr)   N)ry   
contextlibr   rK   r   r   tornado.webr   notebook.utilsr   r   r]   ipython_genutils.py3compatr   traitlets.configr   	traitletsr   rl   r	   r
   r   r    r'   r(   r=   r>   r?   r   r   r   r   <module>   s*    
<+