3
d"+                 @   s~   d Z ddlZddlmZ ddlmZ ddd	Zd
d ZdddZdd Z	dd Z
dddZdgfddZdddZdd ZdS )zUtilities to pull in documentation from command-line tools.

Examples
--------

# Instantiate bet object
from nipype.interfaces import fsl
from nipype.utils import docparse
better = fsl.Bet()
docstring = docparse.get_doc(better.cmd, better.opt_map)

    N   )CommandLine   )is_containerTc             C   sL   t j| t jt jdd}|j \}}|r@|jr@d| |f }t||rH|S |S )a  Run cmd without args and grab documentation.

    Parameters
    ----------
    cmd : string
        Command line string
    trap_error : boolean
        Ensure that returncode is 0

    Returns
    -------
    doc : string
        The command line documentation
    T)stdoutstderrshellz(Attempting to run %s. Returned Error: %s)
subprocessPopenPIPEcommunicate
returncodeIOError)cmd
trap_errorprocr   r   msg r   7/tmp/pip-build-7vycvbft/nipype/nipype/utils/docparse.pygrab_doc   s    
r   c             C   sR   i }xHt | j D ]8\}}t|r*|d }|dkr|dk	r|||j d < qW |S )at  Reverse the key/value pairs of the option map in the interface classes.

    Parameters
    ----------
    opt_map : dict
        Dictionary mapping the attribute name to a command line flag.
        Each interface class defines these for the command it wraps.

    Returns
    -------
    rev_opt_map : dict
       Dictionary mapping the flags to the attribute name.
    r   flagsN)listitemsr   split)opt_mapZrevdictkeyvaluer   r   r   reverse_opt_map6   s    r   c             C   s   d}d}| j d| | j d| dj| }g }dj|}|rd}d}|j d| |j d| |j dd dj|}dj||g}|S )a  Format the parameters according to the nipy style conventions.

    Since the external programs do not conform to any conventions, the
    resulting docstrings are not ideal.  But at a minimum the
    Parameters section is reasonably close.

    Parameters
    ----------
    paramlist : list
        List of strings where each list item matches exactly one
        parameter and it's description.  These items will go into the
        'Parameters' section of the docstring.
    otherlist : list
        List of strings, similar to paramlist above.  These items will
        go into the 'Other Parameters' section of the docstring.

    Returns
    -------
    doc : string
        The formatted docstring.
    Z
Parametersz
----------r   
 zOthers Parametersz-----------------)insertjoin)Z	paramlistZ	otherlisthdrdelimparamsZotherparamsdocr   r   r   format_paramsU   s     


r&   c             C   sl   | j d}|dd }|j| |j|dd  g }x |D ]}|j| |jd q<W |jd dj|S )a  Insert ``new_items`` into the beginning of the ``doc``

    Docstrings in ``new_items`` will be inserted right after the
    *Parameters* header but before the existing docs.

    Parameters
    ----------
    doc : str
        The existing docstring we're inserting docmentation into.
    new_items : list
        List of strings to be inserted in the ``doc``.

    Examples
    --------
    >>> from nipype.utils.docparse import insert_doc
    >>> doc = '''Parameters
    ... ----------
    ... outline :
    ...     something about an outline'''

    >>> new_items = ['infile : str', '    The name of the input file']
    >>> new_items.extend(['outfile : str', '    The name of the output file'])
    >>> newdoc = insert_doc(doc, new_items)
    >>> print(newdoc)
    Parameters
    ----------
    infile : str
        The name of the input file
    outfile : str
        The name of the output file
    outline :
        something about an outline

    r   Nr   r   r   )r   extendappendpopr!   )r%   Z	new_itemsdoclistZtmpdocnewdocliner   r   r   
insert_doc~   s    %




r.   c       
      C   s   | j d}g }g }x|D ]}|j  }|s*qd|d krJ|d j dd }n|d }|j|}|dk	rdt| |d< dj|}	|j|	 q|d j r|j| qW t||S )a  Build docstring from doc and options

    Parameters
    ----------
    rep_doc : string
        Documentation string
    opts : dict
        Dictionary of option attributes and keys.  Use reverse_opt_map
        to reverse flags and attrs from opt_map class attribute.

    Returns
    -------
    newdoc : string
        The docstring with flags replaced with attribute names and
        formated to match nipy standards (as best we can).

    r   ,r   Nz	%s :
     )r   getstrr!   r)   isspacer&   )
r%   optsr+   r,   Z	flags_docr-   linelistflagattrnewliner   r   r   	build_doc   s$    



r9   c             C   sx   t d| jdd  dddj }|jjj }|dkrJtd| jdd  |r\dj| |f} t| |}t	|}t
||S )	a  Get the docstring from our command and options map.

    Parameters
    ----------
    cmd : string
        The command whose documentation we are fetching
    opt_map : dict
        Dictionary of flags and option attributes.
    help_flag : string
        Provide additional help flag. e.g., -h
    trap_error : boolean
        Override if underlying command returns a non-zero returncode

    Returns
    -------
    doc : string
        The formated docstring

    zwhich %sr0   r   F	allatonce)resource_monitorterminal_outputr   zCommand %s not found)r   r   runruntimer   strip	Exceptionr!   r   r   r9   )r   r   	help_flagr   rescmd_pathr%   r4   r   r   r   get_doc   s    
rD   --c       
         s   | j d}i }tttfr"gx|D ]}|j  }fddt|D   r(t dkr| fddD jd} d  nXg }x8 D ]0}x*tD ]\}}	|j|	r|j| P qW qW  |jt	|  t	|}d  | j | d < q(W |S )	zParses a help doc for inputs

    Parameters
    ----------
    doc : string
        Documentation string
    style : string default ['--']
        The help command style (--, -)

    Returns
    -------
    optmap : dict of input parameters
    r   c                s>   g | ]6\} |d k rt  fddD rt dkr qS )r   c                s   g | ]} j |qS r   )
startswith).0s)itemr   r   
<listcomp>%  s    z)_parse_doc.<locals>.<listcomp>.<listcomp>r   )anylen)rG   i)style)rI   r   rJ   #  s   z_parse_doc.<locals>.<listcomp>r   c                s   g | ]} d  j |qS )r   )rF   )rG   rH   )r6   r   r   rJ   )  s    Tr   z%s %%s)
r   
isinstancer2   bytes	enumeraterL   indexrF   r)   min)
r%   rN   r+   Zoptmapr-   r5   Z	style_idxfrM   rH   r   )r6   rN   r   
_parse_doc  s,    







rU   c             C   sp   t d| jdd  dddj }|jjj }|dkrJtd| jdd  |r\dj| |f} t| |}t	||S )	a9  Auto-generate option map from command line help

    Parameters
    ----------
    cmd : string
        The command whose documentation we are fetching
    style : string default ['--']
        The help command style (--, -). Multiple styles can be provided in a
        list e.g. ['--','-'].
    help_flag : string
        Provide additional help flag. e.g., -h
    trap_error : boolean
        Override if underlying command returns a non-zero returncode

    Returns
    -------
    optmap : dict
        Contains a mapping from input to command line variables

    zwhich %sr0   r   Fr:   )r;   r<   r   zCommand %s not found)
r   r   r=   r>   r   r?   r@   r!   r   rU   )r   rN   rA   r   rB   rC   r%   r   r   r   get_params_from_doc8  s    
rV   c             C   s*   x$t |j D ]\}}| j||} qW | S )am  Replace flags with parameter names.

    This is a simple operation where we replace the command line flags
    with the attribute names.

    Parameters
    ----------
    rep_doc : string
        Documentation string
    opts : dict
        Dictionary of option attributes and keys.  Use reverse_opt_map
        to reverse flags and attrs from opt_map class attribute.

    Returns
    -------
    rep_doc : string
        New docstring with flags replaces with attribute names.

    Examples
    --------
    doc = grab_doc('bet')
    opts = reverse_opt_map(fsl.Bet.opt_map)
    rep_doc = replace_opts(doc, opts)

    )r   r   replace)Zrep_docr4   r   valr   r   r   replace_opts[  s    rY   )T)N)NT)rE   NT)__doc__r	   Zinterfaces.baser   Zmiscr   r   r   r&   r.   r9   rD   rU   rV   rY   r   r   r   r   <module>   s   
!
)55
#-
#