3
sdE                 @   s*  d Z ddlZddlZddlmZm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 ejdkZejZeedZdZd+ddZd,ddZd-ddZedfddZdedfddZdd Zdd Zd.ddZd	e_dd Zd/ddZ d0d d!Z!d"d# Z"d1d%d&Z#d	e#_d2d'd(Z$d	e$_d)d* Z%dS )3a`   Test package information in various install settings

The routines here install the package from source directories, zips or eggs, and
check these installations by running tests, checking version information,
looking for files that were not copied over.

The typical use for this module is as a Makefile target.  For example, here are
the Makefile targets from nibabel::

    # Check for files not installed
    check-files:
        $(PYTHON) -c 'from nisext.testers import check_files; check_files("nibabel")'

    # Print out info for possible install methods
    check-version-info:
        $(PYTHON) -c 'from nisext.testers import info_from_here; info_from_here("nibabel")'

    # Run tests from installed code
    installed-tests:
        $(PYTHON) -c 'from nisext.testers import tests_installed; tests_installed("nibabel")'

    # Run tests from installed code
    sdist-tests:
        $(PYTHON) -c 'from nisext.testers import sdist_tests; sdist_tests("nibabel")'

    # Run tests from binary egg
    bdist-egg-tests:
        $(PYTHON) -c 'from nisext.testers import bdist_egg_tests; bdist_egg_tests("nibabel")'

    N)joinabspath)glob)PopenPIPEntputenvZpylibFTc             C   s   t | tttd}|j \}}|j}|dkr>|j  t| d |dkrVt| d|  |j }|rl|jd}|st|S |j }|r|jd}||fS )a   Run command `cmd`, return stdout, or stdout, stderr if `ret_err`

    Roughly equivalent to ``check_output`` in Python 2.7

    Parameters
    ----------
    cmd : str
        command to execute
    ret_err : bool, optional
        If True, return stderr in addition to stdout.  If False, just return
        stdout
    as_str : bool, optional
        Whether to decode outputs to unicode string on exit.

    Returns
    -------
    out : str or tuple
        If `ret_err` is False, return stripped string containing stdout from
        `cmd`.  If `ret_err` is True, return tuple of (stdout, stderr) where
        ``stdout`` is the stripped stdout, and ``stderr`` is the stripped
        stderr.

    Raises
    ------
    RuntimeError
        if command returns non-zero exit code.
    )stdoutstderrshellNz process did not terminater   z process returned code %dzlatin-1)	r   r   NEEDS_SHELLcommunicate
returncode	terminateRuntimeErrorstripdecode)cmdret_errZas_strprocouterrretcode r   1/tmp/pip-build-7vycvbft/nibabel/nisext/testers.py	back_tick1   s"    

r   c             C   s   |dkrd}nt stddjf t }|r:d|  d}nd}tj }tj }zJtj| t	dd}	|	j
d	jf t  W dQ R X tt d
dd}
W dtj| tj| X |
S )a   Run command in own process in anonymous path

    Parameters
    ----------
    mod_name : str
        Name of module to import - e.g. 'nibabel'
    pkg_path : str
        directory containing `mod_name` package.  Typically that will be the
        directory containing the e.g. 'nibabel' directory.
    cmd : str
        Python command to execute
    script_dir : None or str, optional
        script directory to prepend to PATH
    print_location : bool, optional
        Whether to print the location of the imported `mod_name`

    Returns
    -------
    stdout : str
        stdout as str
    stderr : str
        stderr as str
    N z#We cannot set environment variablesa  
os.environ['PATH'] = r'"{script_dir}"' + os.path.pathsep + os.environ['PATH']
PYTHONPATH = os.environ.get('PYTHONPATH')
if PYTHONPATH is None:
    os.environ['PYTHONPATH'] = r'"{pkg_path}"'
else:
    os.environ['PYTHONPATH'] = r'"{pkg_path}"' + os.path.pathsep + PYTHONPATH
zprint(z.__file__);z	script.pywtzc
import os
import sys
sys.path.insert(0, r"{pkg_path}")
{paths_add}
import {mod_name}
{p_loc}
{cmd}z
 script.pyT)r   )HAVE_PUTENVr   formatlocalsosgetcwdtempfilemkdtempchdiropenwriter   PYTHONshutilrmtree)mod_nameZpkg_pathr   Z
script_dirZprint_locationZ	paths_addZp_loccwdZtmpdirZfobjresr   r   r   run_mod_cmd`   s&    

r.   c             C   s@   t j| }|j }dd |D }x|D ]}|j||d q&W dS )z Extract all members from zipfile

    Deals with situation where the directory is stored in the zipfile as a name,
    as well as files that have to go into this directory.
    c             S   s   g | ]}|j d s|qS )/)endswith).0mr   r   r   
<listcomp>   s    z#zip_extract_all.<locals>.<listcomp>N)zipfileZipFilenamelistextract)fnamepathzfmemberszipinfor   r   r   zip_extract_all   s
    

r=   binc             C   sj   t jj||}d| d| }t jjt j }t d| d| }zt j|  t| W dt j| X dS )a   Install package in `from_dir` to standard location in `to_dir`

    Parameters
    ----------
    from_dir : str
        path containing files to install with ``python setup.py ...``
    to_dir : str
        prefix path to which files will be installed, as in ``python setup.py
        install --prefix=to_dir``
    py_lib_sdir : str, optional
        subdirectory within `to_dir` to which library code will be installed
    bin_sdir : str, optional
        subdirectory within `to_dir` to which scripts will be installed
    z --install-purelib=z --install-platlib=z# setup.py --quiet install --prefix= N)r!   r9   r   r   r"   r(   r%   r   )Zfrom_dirZto_dirpy_lib_sdirZbin_sdirsite_pkgs_pathZpy_lib_locspwdr   r   r   r   install_from_to   s    
rC   c             C   sL   t j }z2t| | |dkr"|}n||}t|||| W dtj| X dS )a   Install package from zip file `zip_fname`

    Parameters
    ----------
    zip_fname : str
        filename of zip file containing package code
    install_path : str
        output prefix at which to install package
    pkg_finder : None or callable, optional
        If None, assume zip contains ``setup.py`` at the top level.  Otherwise,
        find directory containing ``setup.py`` with ``pth =
        pkg_finder(unzip_path)`` where ``unzip_path`` is the path to which we
        have unzipped the zip file contents.
    py_lib_sdir : str, optional
        subdirectory to which to write the library code from the package.  Thus
        if package called ``nibabel``, the written code will be in
        ``<install_path>/<py_lib_sdir>/nibabel
    script_sdir : str, optional
        subdirectory to which we write the installed scripts.  Thus scripts will
        be written to ``<install_path>/<script_sdir>
    N)r#   r$   r=   rC   r)   r*   )	zip_fnameinstall_pathZ
pkg_finderr@   Zscript_sdirZ
unzip_path	from_pathr   r   r   install_from_zip   s    
rG   c             C   s   t jj|t}t jjt j }t|d}zt j| td| d W dt j| X t	||d d|  d}t
t| ||d  t||t t
t| ||d  t
t| ||d  dS )ap   Print result of get_info from different installation routes

    Runs installation from:

    * git archive zip file
    * with setup.py install from repository directory
    * just running code from repository directory

    and prints out result of get_info in each case.  There will be many files
    written into `install_path` that you may want to clean up somehow.

    Parameters
    ----------
    mod_name : str
       package name that will be installed, and tested
    repo_path : str
       path to location of git repository
    install_path : str
       path into which to install temporary installations
    ztest.zipzgit archive --format zip -o z HEADNzprint(z.get_info())r   )r!   r9   r   PY_LIB_SDIRr   r"   pjoinr%   r   rG   printr.   rC   )r+   	repo_pathrE   rA   rB   Z	out_fnameZcmd_strr   r   r   contexts_print_info   s    

rL   c             C   s:   t jjt j }tj }zt| || W dtj| X dS )a   Run info context checks starting in working directory

    Runs checks from current working directory, installing temporary
    installations into a new temporary directory

    Parameters
    ----------
    mod_name : str
       package name that will be installed, and tested
    N)	r!   r9   r   r"   r#   r$   rL   r)   r*   )r+   rK   rE   r   r   r   info_from_here  s
    rM   c             C   s~   |dkrt jjt j }tj }t|t}t|d}z(t||td t	| || d |\}}W dt
j| X t| t| dS )a   Install from `source_path` into temporary directory; run tests

    Parameters
    ----------
    mod_name : str
        name of module - e.g. 'nibabel'
    source_path : None or str
        Path from which to install.  If None, defaults to working directory
    Nr>   z.test())r!   r9   r   r"   r#   r$   rI   rH   rC   r.   r)   r*   rJ   )r+   source_pathrE   rA   scripts_pathr	   r
   r   r   r   tests_installed.  s    


rP   c             C   s   t | |ddS )ao   Check files in `repo_mod_path` are installed at `install_mod_path`

    At the moment, all this does is check that all the ``*.py`` files in
    `repo_mod_path` are installed at `install_mod_path`.

    Parameters
    ----------
    repo_mod_path : str
        repository path containing package files, e.g. <nibabel-repo>/nibabel>
    install_mod_path : str
        path at which package has been installed.  This is the path where the
        root package ``__init__.py`` lives.

    Return
    ------
    uninstalled : list
        list of files that should have been installed, but have not been
        installed
    z\.py$)filter)missing_from)repo_mod_pathZinstall_mod_pathr   r   r   check_installed_filesL  s    rT   c       
      C   s   |dk	rt j|}g }xttj| D ]f\}}}|j| |}xN|D ]F}|dk	rZ|j|dkrZq>tjj||}	tjj|	s>|j	t
|| q>W q"W |S )a1   Return filenames present in `path0` but not in `path1`

    Parameters
    ----------
    path0 : str
        path which contains all files of interest
    path1 : str
        path which should contain all files of interest
    filter : None or str or regexp, optional
        A successful result from ``filter.search(fname)`` means the file is of
        interest.  None means all files are of interest

    Returns
    -------
    path1_missing : list
        list of all files missing from `path1` that are in `path0` at the same
        relative path.
    N)recompiler!   walkreplacesearchr9   r   isfileappendrI   )
Zpath0path1rQ   uninstalleddirpathdirnames	filenamesZout_dirpathr8   Zequiv_fnamer   r   r   rR   c  s    

rR   c             C   s   |dkrt tj }tj }t|| }t|t| }t|d}t|d}z@t||dd}t| }	t	|||	t| t
||d}
t
||}W dtj| X |
rtddj|
 ntd |rtd	dj| ntd
 t|
dkpt|dkS )zA Print library and script files not picked up during install
    Nr>   zsdist --formats=zipz*.zipz\.py$zMissed library files: z, zYou got all the library fileszMissed script files: zYou got all the script filesr   )r   r!   r"   r#   r$   rI   rH   	make_distget_sdist_finderrG   rR   r)   r*   rJ   r   len)r+   rK   Zscripts_sdirrE   rS   Zinstalled_mod_pathZrepo_binZinstalled_binrD   pfZ
lib_missesZscript_missesr   r   r   check_files  s0    


re   c                s    fdd}|S )zC Return function finding sdist source directory for `mod_name`
    c                s.   t t|  d }t|dkr&td|d S )Nz-*   z*There must be one and only one package dirr   )r   rI   rc   OSError)pthZpkg_dirs)r+   r   r   rd     s    zget_sdist_finder.<locals>.pfr   )r+   rd   r   )r+   r   rb     s    rb   fastc             C   s   |dkrt tj }tj }zft||dd}t| }t|||td t	|t}t	|d}|  d| d| d}	t
| ||	|\}
}W dtj| X t|
 t| dS )z0 Make sdist zip, install from it, and run tests Nzsdist --formats=zipz*.zipr>   z.test(label='z', doctests=))r   r!   r"   r#   r$   ra   rb   rG   rH   rI   r.   r)   r*   rJ   )r+   rK   labeldoctestsrE   rD   rd   rA   Zscript_pathr   r	   r
   r   r   r   sdist_tests  s(    

rm   c       
      C   s   |dkrt tj }tj }t|d}zDt||dd}t|| |  d| d| d}t| |||\}}	W dt	j
| X t| t|	 dS )a   Make bdist_egg, unzip it, and run tests from result

    We've got a problem here, because the egg does not contain the scripts, and
    so, if we are testing the scripts with ``mod.test()``, we won't pick up the
    scripts from the repository we are testing.

    So, you might need to add a label to the script tests, and use the `label`
    parameter to indicate these should be skipped. As in:

        bdist_egg_tests('nibabel', None, label='not script_test')
    Nr>   	bdist_eggz*.eggz.test(label='z', doctests=rj   )r   r!   r"   r#   r$   rI   ra   r=   r.   r)   r*   rJ   )
r+   rK   rk   rl   rE   rO   rD   r   r	   r
   r   r   r   bdist_egg_tests  s$    

ro   c             C   s   t jjt j }z\t j|  tt d| d|  tt||}t	|dkrjt
d| ddj| dW dt j| X |d	 S )
a   Create distutils distribution file

    Parameters
    ----------
    repo_path : str
        path to repository containing code and ``setup.py``
    out_dir : str
        path to which to write new distribution file
    setup_params: str
        parameters to pass to ``setup.py`` to create distribution.
    zipglob : str
        glob identifying expected output file.

    Returns
    -------
    out_fname : str
        filename of generated distribution file

    Examples
    --------
    Make, return a zipped sdist::

      make_dist('/path/to/repo', '/tmp/path', 'sdist --formats=zip', '*.zip')

    Make, return a binary egg::

      make_dist('/path/to/repo', '/tmp/path', 'bdist_egg', '*.egg')
    z
 setup.py z --dist-dir=rf   zThere must be one and only one z file, but I found "z: "Nr   )r!   r9   r   r"   r%   r   r(   r   rI   rc   rg   r   )rK   Zout_dirZsetup_paramsZzipglobrB   Zzipsr   r   r   ra     s    
 ra   )FT)NT)N)N)N)Nr>   )Nri   T)Nri   T)&__doc__r!   sysos.pathr   rI   r   r   r)   r#   r4   rU   
subprocessr   r   namer   
executabler(   hasattrr   rH   r   r.   r=   rC   rG   rL   rM   rP   Z__test__rT   rR   re   rb   rm   ro   ra   r   r   r   r   <module>   sB   


/
D
#)

"
 

 