B
    6d;                 @   s  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ZddlZddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ dd Zdd Z dd Z!dd Z"dd Z#dd Z$dd Z%dBddZ&dCddZ'dd Z(d d! Z)d"d# Z*ej+d$kr.e)Z,ne*Z,d%d& Z-d'd( Z.d)d* Z/d+d, Z0d-d. Z1d/d0 Z2d1d2 Z3e
dDd4d5Z4dEd6d7Z5dFd8d9Z6d:d; Z7dGd<d=Z8d>d? Z9d@dA Z:dS )HzNotebook related utilities    N)contextmanager)urljoin)SplitResultquoteunquoteurlparseurlsplit
urlunsplit)pathname2url)_NamespacePath)Version)AsyncHTTPClient
HTTPClientHTTPRequest)Resolverc              G   sf   | d  d}| d d}dd | D }ddd |D }|rJd| }|rV|d }|dkrbd}|S )	zJoin components of url into a relative url

    Use to prevent double slash when joining subpath. This will leave the
    initial and final / in place
    r   /c             S   s   g | ]}| d qS )r   )strip).0s r   a/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/jupyter_server/utils.py
<listcomp>   s    z!url_path_join.<locals>.<listcomp>c             s   s   | ]}|r|V  qd S )Nr   )r   r   r   r   r   	<genexpr>   s    z url_path_join.<locals>.<genexpr>z//)
startswithendswithjoin)piecesinitialfinalstrippedresultr   r   r   url_path_join   s    r"   c             C   s   t | jdS )z)Determine whether a given URL is absoluter   )r   pathr   )urlr   r   r   url_is_absolute)   s    r%   c             C   s6   dd |  tjD }|d dkr*d|d< t| }|S )z"Convert a local file path to a URLc             S   s   g | ]}t |qS r   )r   )r   pr   r   r   r   0   s    zpath2url.<locals>.<listcomp>r    r   )splitossepr"   )r#   r   r$   r   r   r   path2url.   s
    r+   c             C   s$   dd |  dD }tjj| }|S )z"Convert a URL to a local file pathc             S   s   g | ]}t |qS r   )r   )r   r&   r   r   r   r   :   s    zurl2path.<locals>.<listcomp>r   )r(   r)   r#   r   )r$   r   r#   r   r   r   url2path8   s    r,   c             C   s   |  d}ddd |D S )zVEscape special characters in a URL path

    Turns '/foo bar/' into '/foo%20bar/'
    r   c             S   s   g | ]}t |qS r   )r   )r   r&   r   r   r   r   E   s    zurl_escape.<locals>.<listcomp>)r(   r   )r#   partsr   r   r   
url_escape?   s    
r.   c             C   s   d dd | dD S )zXUnescape special characters in a URL path

    Turns '/foo%20bar/' into '/foo bar/'
    r   c             S   s   g | ]}t |qS r   )r   )r   r&   r   r   r   r   M   s    z url_unescape.<locals>.<listcomp>)r   r(   )r#   r   r   r   url_unescapeH   s    r/   c             C   s,   t | }t |}|  | ko*||kS )af  
    Fill in for os.path.samefile when it is unavailable (Windows+py2).

    Do a case-insensitive string comparison in this case
    plus comparing the full stat result (including times)
    because Windows + py2 doesn't support the stat fields
    needed for identifying if it's the same file (st_ino, st_dev).

    Only to be used if os.path.samefile is not available.

    Parameters
    ----------
    path : String representing a path to a file
    other_path : String representing a path to another file

    Returns
    -------
    same:   Boolean that is True if both path and other path are the same
    )r)   statlower)r#   
other_pathZ	path_statZother_path_statr   r   r   samefile_simpleP   s    

r3   r'   c             C   s<   |  dd}dd |D }tjj|f| } tj| S )zConvert an API path to a filesystem path

    If given, root will be prepended to the path.
    root must be a filesystem path already.
    r   c             S   s   g | ]}|d kr|qS )r'   r   )r   r&   r   r   r   r   p   s    zto_os_path.<locals>.<listcomp>)r   r(   r)   r#   r   normpath)r#   rootr-   r   r   r   
to_os_pathi   s    r6   c             C   sN   |  |r| t|d } | tjjtjj}dd |D }d|}|S )zConvert a filesystem path to an API path

    If given, root will be removed from the path.
    root must be a filesystem path already.
    Nc             S   s   g | ]}|d kr|qS )r'   r   )r   r&   r   r   r   r   ~   s    zto_api_path.<locals>.<listcomp>r   )r   lenr   r)   r#   r*   r(   r   )Zos_pathr5   r-   r#   r   r   r   to_api_pathu   s    

r8   c             C   s*   yt | t |kS  tk
r$   dS X dS )zcheck version string v >= check

    If dev/prerelease tags result in TypeError for string-number comparison,
    it is assumed that the dependency is satisfied.
    Users on dev branches are responsible for keeping their own packages up to date.
    TN)r   	TypeError)vcheckr   r   r   check_version   s    r<   c             C   s   dd l }t|jjdd| S )Nr      )ctypesboolwindllkernel32ZOpenProcess)pidr>   r   r   r   _check_pid_win32   s    rC   c          
   C   s^   yt | d W nD tk
rT } z&|jtjkr2dS |jtjkrBdS  W dd}~X Y nX dS dS )z'Copy of IPython.utils.process.check_pidr   FTN)r)   killOSErrorerrnoZESRCHEPERM)rB   errr   r   r   _check_pid_posix   s    rI   win32c          
      sV   t | rRy| I dH }W n4 tk
rL } zt|dkr:| S  W dd}~X Y nX |S | S )zmConvert a non-awaitable object to a coroutine if needed,
    and await it if it was not already awaited.
    Nz&cannot reuse already awaited coroutine)inspectisawaitableRuntimeErrorstr)objr!   er   r   r   ensure_async   s    
rQ   c                s    t  s S  fdd}| S )a  If async, runs maybe_async and blocks until it has executed,
    possibly creating an event loop.
    If not async, just returns maybe_async as it is the result of something
    that has already executed.

    Parameters
    ----------
    maybe_async : async or non-async object
        The object to be executed, if it is async.

    Returns
    -------
    result
        Whatever the async object returns, or the object itself.
    c           
      s   d} yt  }W n tk
r(   d} Y nX | r6d} | rLt  }t | y| }W n> tk
r } z t|dkrt  }n|W d d }~X Y nX |S )NFTz"This event loop is already running)	asyncioget_event_looprM   	is_closednew_event_loopset_event_looprun_until_completerN   ensure_future)Zcreate_new_event_looploopr!   rP   )maybe_asyncr   r   wrapped   s"    

zrun_sync.<locals>.wrapped)rK   rL   )rZ   r[   r   )rZ   r   run_sync   s    
r\   c                s   t | s| S | I dH S )a  Runs a function synchronously whether it is an async function or not.

    If async, runs maybe_async and blocks until it has executed.

    If not async, just returns maybe_async as it is the result of something
    that has already executed.

    Parameters
    ----------
    maybe_async : async or non-async object
        The object to be executed, if it is async.

    Returns
    -------
    result
        Whatever the async object returns, or the object itself.
    N)rK   rL   )rZ   r   r   r   run_sync_in_loop   s    
r]   c             C   s   |  ddS )zREncodes a UNIX socket path string from a socket path for the `http+unix` URI form.r   z%2F)replace)socket_pathr   r   r   urlencode_unix_socket_path  s    r`   c             C   s   |  ddS )zWDecodes a UNIX sock path string from an encoded sock path for the `http+unix` URI form.z%2Fr   )r^   )r_   r   r   r   urldecode_unix_socket_path  s    ra   c             C   s   dt |  S )zJEncodes a UNIX socket URL from a socket path for the `http+unix` URI form.zhttp+unix://%s)r`   )r_   r   r   r   urlencode_unix_socket  s    rb   c             C   s\   t j| sdS z<yttjtj}||  W n tk
rD   dS X dS W d|  X dS )zSChecks whether a UNIX socket path on disk is in use by attempting to connect to it.FTN)	r)   r#   existssocketAF_UNIXSOCK_STREAMconnectrE   close)r_   sockr   r   r   unix_socket_in_use  s    rj   GETc       	      c   s   t | }|jdkrnX|jdkrdtd|j|j|j|jd}G dd dt}|t d}tj	d|d nt
d	t|}t||||d
}|V  dS )aN  A utility that provides a context that handles
    HTTP, HTTPS, and HTTP+UNIX request.
    Creates a tornado HTTPRequest object with a URL
    that tornado's HTTPClients can accept.
    If the request is made to a unix socket, temporarily
    configure the AsyncHTTPClient to resolve the URL
    and connect to the proper socket.
    )httphttpsz	http+unixrl   )schemenetlocr#   queryfragmentc               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	z7_request_for_tornado_client.<locals>.UnixSocketResolvera>  A resolver that routes HTTP requests to unix sockets
            in tornado HTTP clients.
            Due to constraints in Tornados' API, the scheme of the
            must be `http` (not `http+unix`). Applications should replace
            the scheme in URLS before making a request to the HTTP client.
            c             S   s
   || _ d S )N)resolver)selfrr   r   r   r   
initializeD  s    zB_request_for_tornado_client.<locals>.UnixSocketResolver.initializec             S   s   | j   d S )N)rr   rh   )rs   r   r   r   rh   G  s    z=_request_for_tornado_client.<locals>.UnixSocketResolver.closec                s   t jt|fgS )N)rd   re   ra   )rs   hostportargskwargsr   r   r   resolveJ  s    z?_request_for_tornado_client.<locals>.UnixSocketResolver.resolveN)__name__
__module____qualname____doc__rt   rh   ry   r   r   r   r   UnixSocketResolver<  s   r~   )rr   NzUnknown URL scheme.)methodbodyheaders)r   rn   r   ro   r#   rp   rq   r   r   	configure	Exceptionr	   r   )		urlstringr   r   r   r-   r~   rr   r$   requestr   r   r   _request_for_tornado_client%  s"    



r   c          	   C   s.   t | |||d}tt|}W dQ R X |S )zo
    Send a HTTP, HTTPS, or HTTP+UNIX request
    to a Tornado Web Server. Returns a tornado HTTPResponse.
    )r   r   r   N)r   r   r   fetch)r   r   r   r   r   responser   r   r   r   X  s
    r   c          	      s4   t | |||d}t||I dH }W dQ R X |S )z}
    Send an asynchronous HTTP, HTTPS, or HTTP+UNIX request
    to a Tornado Web Server. Returns a tornado HTTPResponse.
    )r   r   r   N)r   r   r   )r   r   r   r   Zio_loopr   r   r   r   r   async_fetchd  s
    r   c             C   s:   yt j| }W n tk
r$   dS X |s.dS t|jtS )zIs the provided namespace a Python Namespace Package (PEP420).

    https://www.python.org/dev/peps/pep-0420/#specification

    Returns `None` if module is not importable.

    N)	importlibutil	find_spec
ValueError
isinstancesubmodule_search_locationsr   )	namespacespecr   r   r   is_namespace_packagep  s    	r   c             C   s   |  d d} tj| r,tj| r,| S |dkr:d}nt|trJ|f}xF|D ]>}|dkrdt }ttj	|| }tj|rPtj
|S qPW td| d|dS )a  Find a file by looking through a sequence of paths.
    This iterates through a sequence of paths looking for a file and returns
    the full, absolute path of the first occurence of the file.  If no set of
    path dirs is given, the filename is tested as is, after running through
    :func:`expandvars` and :func:`expanduser`.  Thus a simple call::
        filefind('myfile.txt')
    will find the file in the current working dir, but::
        filefind('~/myfile.txt')
    Will find the file in the users home directory.  This function does not
    automatically try any paths, such as the cwd or the user's home directory.
    Parameters
    ----------
    filename : str
        The filename to look for.
    path_dirs : str, None or sequence of str
        The sequence of paths to look for the file in.  If None, the filename
        need to be absolute or be in the cwd.  If a string, the string is
        put into a sequence and the searched.  If a sequence, walk through
        each element and join with ``filename``, calling :func:`expandvars`
        and :func:`expanduser` before testing for existence.
    Returns
    -------
    Raises :exc:`IOError` or returns absolute path to file.
    "'N)r'   .zFile z, does not exist in any of the search paths: )r   r)   r#   isabsisfiler   rN   getcwdexpand_pathr   abspathrE   )filenameZ	path_dirsr#   Ztestnamer   r   r   filefind  s    

r   c             C   sD   t jdkr| dd} t jt j| } t jdkr@| dd} | S )zExpand $VARS and ~names in a string, like a shell
    :Examples:
       In [2]: os.environ['FOO']='test'
       In [3]: expand_path('variable FOO is $FOO')
       Out[3]: 'variable FOO is test'
    ntz$\ZIPYTHON_TEMP)r)   namer^   r#   
expandvars
expanduser)r   r   r   r   r     s    

r   c             C   sr   |  dd}t|dkrb|\}}t||gd}yt||}W n  tk
r\   td| Y nX |S t|d S dS )a  Import and return ``bar`` given the string ``foo.bar``.
    Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
    executing the code ``from foo import bar``.
    Parameters
    ----------
    name : string
      The fully qualified name of the module/package being imported.
    Returns
    -------
    mod : module object
       The module that was imported.
    r   r=      )fromlistzNo module named %sr   N)rsplitr7   
__import__getattrAttributeErrorImportError)r   r-   packagerO   moduleZpakr   r   r   import_item  s    r   )r'   )r'   )rk   NN)rk   NN)rk   NNN)N);r}   rR   rF   importlib.utilr   rK   r)   rd   sys
contextlibr   urllib.parser   r   r   r   r   r   r	   urllib.requestr
   _frozen_importlib_externalr   Zpackaging.versionr   Ztornado.httpclientr   r   r   Ztornado.netutilr   r"   r%   r+   r,   r.   r/   r3   r6   r8   r<   rC   rI   platformZ	check_pidrQ   r\   r]   r`   ra   rb   rj   r   r   r   r   r   r   r   r   r   r   r   <module>   sZ    
	

.2


/