ó
ù2¢\c           @   s]  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 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 y d d	 l m Z m Z Wn' e k
 rë d d
 l m Z m Z n Xd „  Z d d „ Z d „  Z d „  Z e e d d d „ ƒ Z e e d d d „ ƒ Z  d e f d „  ƒ  YZ! d S(   s9   
Utilities for file-based Contents/Checkpoints managers.
iÿÿÿÿ(   t   contextmanagerN(   t	   HTTPError(   t   to_api_patht
   to_os_path(   t   str_to_unicode(   t   Configurable(   t   Bool(   t   encodebytest   decodebytes(   t   encodestringt   decodestringc         C   sg   t  t d ƒ r" t j |  | ƒ nA t j d k rS t j j | ƒ rS t j | ƒ n  t j |  | ƒ d S(   sh    replace dst with src

    switches between os.replace or os.rename based on python 2.7 or python 3
    t   replacet   ntN(   t   hasattrt   osR   t   namet   patht   existst   removet   rename(   t   srct   dst(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   replace_file!   s
    !c         C   s[   t  j |  | ƒ y t  j |  | ƒ Wn0 t k
 rV | rW | j d | d t ƒqW n Xd S(   sZ   copy src to dst

    like shutil.copy2, but log errors in copystat instead of raising
    s   copystat on %s failedt   exc_infoN(   t   shutilt   copyfilet   copystatt   OSErrort   debugt   True(   R   R   t   log(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt
   copy2_safe.   s    c         C   s/   t  j j |  ƒ \ } } t  j j | d | ƒ S(   st   Name of the intermediate file used in atomic writes.

    The .~ prefix will make Dropbox ignore the temporary file.s   .~(   R   R   t   splitt   join(   R   t   dirnamet   basename(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   path_to_intermediate:   s    c         C   s/   t  j j |  ƒ \ } } t  j j | | d ƒ S(   sE   Name of invalid file after a failed atomic write and subsequent read.s   .invalid(   R   R   R    R!   (   R   R"   R#   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   path_to_invalidA   s    s   utf-8c         k   s6  t  j j |  ƒ r? t  j j t  j j |  ƒ t  j |  ƒ ƒ }  n  t |  ƒ } t  j j |  ƒ rs t |  | d | ƒn  | r§ | j	 d d ƒ t
 j |  d d | | } n t
 j |  d |  } y	 | VWn! | j ƒ  t | |  ƒ ‚  n X| j ƒ  t  j | j ƒ  ƒ | j ƒ  t  j j | ƒ r2t  j | ƒ n  d S(   sÊ  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   t   newlines   
t   wt   encodingt   wbN(   R   R   t   islinkR!   R"   t   readlinkR$   t   isfileR   t
   setdefaultt   iot   opent   closeR   t   flusht   fsynct   filenoR   (   R   t   textR(   R   t   kwargst   tmp_patht   fileobj(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   atomic_writingF   s(    -	


c         k   s¶   t  j j |  ƒ r? t  j j t  j j |  ƒ t  j |  ƒ ƒ }  n  | rs | j d d ƒ t j |  d d | | } n t j |  d |  } y	 | VWn | j	 ƒ  ‚  n X| j	 ƒ  d S(   sÄ  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&   s   
R'   R(   R)   N(
   R   R   R*   R!   R"   R+   R-   R.   R/   R0   (   R   R4   R(   R   R5   R7   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   _simple_writingƒ   s    -	
t   FileManagerMixinc           B   s   e  Z d  Z e e d e d d ƒZ e d „  ƒ Z e d „  ƒ Z e d d „ ƒ Z	 d „  Z
 d	 „  Z d
 d „ Z d „  Z d „  Z d „  Z RS(   sº  
    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 against which API-style paths are to be resolved.

    log : logging.Logger
    t   configt   helps}  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 )c      	   o   s=   |  j  | ƒ ( t j | | | Ž  } | VWd QXWd QXd S(   s<   wrapper around io.open that turns permission errors into 403N(   t   perm_to_403R.   R/   (   t   selft   os_patht   argsR5   t   f(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyR/   Ç   s    c      
   o   sx   |  j  | ƒ c |  j rE t | d |  j | | Ž } | VWd QXn) t | d |  j | | Ž } | VWd QXWd QXd S(   sá   wrapper 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=   t   use_atomic_writingR8   R   R9   (   R>   R?   R@   R5   RA   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyR8   Î   s    	t    c         c   s   y	 d VWn€ t  t f k
 r‹ } | j t j t j h k r… | sZ t | j pQ d ƒ } n  t | d |  j ƒ} t	 d d | ƒ ‚ qŒ ‚  n Xd S(   s7   context manager for turning permission errors into 403.Ns   unknown filet   rooti“  u   Permission denied: %s(
   R   t   IOErrort   errnot   EPERMt   EACCESR   t   filenameR   t   root_dirR   (   R>   R?   t   eR   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyR=   Û   s    	c         C   s   t  | | d |  j ƒd S(   sP   copy src to dest

        like shutil.copy2, but log errors in copystat
        R   N(   R   R   (   R>   R   t   dest(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   _copyì   s    c         C   sc   t  j j |  j ƒ } t | | ƒ } t  j j | ƒ t  j j j | ƒ s_ t d d | ƒ ‚ n  | S(   sY  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”  s%   %s is outside root contents directory(   R   R   t   abspathRJ   R   t   sept
   startswithR   (   R>   R   RD   R?   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   _get_os_pathó   s
    %i   c      	   C   sÓ   |  j  | d d d ƒµ } y t j | d | ƒSWn t k
 rM } | } n Xt | ƒ } |  j sw t j j | ƒ r“ t	 d d | | f ƒ ‚ n  t
 | ƒ } t | | ƒ t | | ƒ |  j | | ƒ SWd QXd S(   s    Read a notebook from an os path.t   rR(   s   utf-8t
   as_versioni  u   Unreadable Notebook: %s %rN(   R/   t   nbformatt   readt	   ExceptionR$   RB   R   R   R   R   R%   R   t   _read_notebook(   R>   R?   RS   RA   RK   t   e_origR6   t   invalid_file(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyRW   
  s    
c      	   C   s;   |  j  | d d ƒ  } t j | | d t j ƒWd QXd S(   s   Save a notebook to an os_path.R(   s   utf-8t   versionN(   R8   RT   t   writet
   NO_CONVERT(   R>   R?   t   nbRA   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   _save_notebook#  s    c         C   sÖ   t  j j | ƒ s( t d d | ƒ ‚ n  |  j | d ƒ  } | j ƒ  } Wd QX| d k sg | d k r½ y | j d ƒ d f SWq½ t k
 r¹ | d k rº t d d | d d	 ƒ‚ qº q½ Xn  t	 | ƒ j d
 ƒ d f S(   s*  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
        i  s   Cannot read non-file %st   rbNR4   t   utf8s   %s is not UTF-8 encodedt   reasons
   bad formatt   asciit   base64(
   R   R   R,   R   R/   RU   t   Nonet   decodet   UnicodeErrorR   (   R>   R?   t   formatRA   t   bcontent(    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt
   _read_file(  s    	
c         C   s¿   | d d h k r$ t  d d ƒ ‚ n  y= | d k rE | j d ƒ } n | j d ƒ } t | ƒ } Wn, t k
 r } t  d d | | f ƒ ‚ n X|  j | d t ƒ } | j | ƒ Wd QXd S(	   s   Save content of a generic file.R4   Rc   i  s:   Must specify format of file contents as 'text' or 'base64'R`   Rb   u   Encoding error saving %s: %sN(   R   t   encodeR   RV   R8   t   FalseR[   (   R>   R?   t   contentRg   Rh   t	   b64_bytesRK   RA   (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt
   _save_fileE  s    (   t   __name__t
   __module__t   __doc__R   R   RB   R    R/   R8   R=   RM   RQ   RW   R^   Ri   Rn   (    (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyR:   ¯   s   					("   Rq   t
   contextlibR    RF   R.   R   R   t   tornado.webR   t   notebook.utilsR   R   RT   t   ipython_genutils.py3compatR   t   traitlets.configR   t	   traitletsR   Rc   R   R   t   ImportErrorR	   R
   R   Rd   R   R$   R%   R   R8   R9   R:   (    (    (    s@   lib/python2.7/site-packages/notebook/services/contents/fileio.pyt   <module>   s0   			<+