a
    sDfG                     @   s  d dl mZmZmZ ddl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Zd dlZdd Zd9d	d
Zd:d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Zd dlZzd dlZW n ey   dZY n0 ejZdZdZdZdZ dZ!g dZ"dZ#dZ$dZ%dZ&G dd de'Z(ddde!e ddfddZ)ej*efddZ+G dd  d e'Z,d!d" Z-d#d$ Z.d;d%d&Z/d<d)d*Z0d+d, Z1d-d. Z2d/d0 Z3d=d1d2Z4d3d4 Z5d>d5d6Z6d7d8 Z7dS )?    )print_functionabsolute_importdivision   )__version__)reportNc                 C   sh   t jtt| }t j|dt j|ddg}|D ]}t j|r:|  S q:t	d| |f d S )Nexamplesz..z+Could not find examples for %s at any of %s)
ospathdirnameinspectgetfile	importlibimport_modulejoinexists
ValueError)namemodule_path
candidates	candidate r   U/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/pyct/cmd.py_find_examples   s    
r   Fc                 C   s$   t | ||| t| |d||d dS )z
    Copy examples and fetch data (if any) to the supplied path.
    See copy-examples and fetch-data for more flexibility.

    NOTE: force operates both on example and data over-writing
    pre-existing files.
    F)require_datasetsuse_test_dataforceN)copy_examples
fetch_data)r   r
   verboser   r   r   r   r   r      s    r   c                 C   sb   t | }tj|}tj|r0|s0td| |r@td|  tjj	|||d td|  dS )z#Copy examples to the supplied path.zSPath %s already exists; please move it away, choose a different path, or use force.zCopying examples from %s)r   zCopied examples to %sN)
r   r	   r
   abspathr   r   print	distutilsdir_util	copy_tree)r   r
   r   r   sourcer   r   r   r   *   s    r   )OrderedDictz%s[%s%s] %i/%i - %sz%s %s %i/%i.# )|/-\	   dataz.data_stubsc                   @   sN   e Zd Zdd Zdd Zdddeeddfd	d
ZdddZdd Z	dd Z
dS )Barc                 C   s   | S Nr   selfr   r   r   	__enter__r   s    zBar.__enter__c                 C   s   |    dS )NF)done)r3   exc_typeexc_valexc_tbr   r   r   __exit__u   s    zBar.__exit__     Nr   c                 C   s   || _ || _|| _|du rDzt  | _W n tyB   d| _Y n0 || _|| _|| _|| _	t

 | _g | _d| _t

 | _| | j| _d| _| jr| d dS )z3Bar is a class for printing the status of downloadsNTr   )labelwidthhideSTREAMisattyAttributeError
empty_charfilled_charexpected_sizeeverytimestartittimesetaetadeltaformat_timeetadisplast_progressshow)r3   r<   r=   r>   rB   rC   rD   rE   r   r   r   __init__y   s(    

zBar.__init__c              	   C   s  |d ur|| _ | j d u r td|| _t | j tkrt | _| jt d  | jt   |d  g | _t	| jt
t| j | j |  | _| | j| _t| j| | j  }| js|| j dks|| j krtt| j| j| | j| j|  || j | jf  t  d S )Nzexpected_size not initializedr   r   )rD   	ExceptionrM   rF   rJ   ETA_INTERVALrH   ETA_SMA_WINDOWrG   sumfloatlenrI   rK   rL   intr=   r>   rE   r?   writeBAR_TEMPLATEr<   rC   rB   flush)r3   progresscountxr   r   r   rN      s6    

zBar.showc              	   C   sf   t   | j | _| | j}| jsbtt| j| j	| j
 | jd | j| j|f  td t  d S )Nr   
)rF   rG   elapsedrK   r>   r?   rW   rX   r<   rC   r=   rB   rM   rD   rY   )r3   Zelapsed_dispr   r   r   r5      s    
zBar.donec                 C   s   t dt |S )Nz%H:%M:%S)rF   strftimegmtime)r3   secondsr   r   r   rK      s    zBar.format_time)N)__name__
__module____qualname__r4   r9   BAR_EMPTY_CHARBAR_FILLED_CHARrO   rN   r5   rK   r   r   r   r   r0   q   s   

r0   r:   r;   c              	   c   st   |du rt | n|}t|||tt||d6}	t| D ]\}
}|V  |	|
d  q4W d   n1 sf0    Y  dS )z/Progress iterator. Wrap your iterables with it.N)r<   r=   r>   rB   rC   rD   rE   r   )rU   r0   re   rf   	enumeraterN   )itr<   r=   r>   rB   rC   rD   rE   r[   bariitemr   r   r   ri      s    
ri   c                    s:   G dd d|} fdd}| tjjj| t| |S )Nc                   @   s   e Zd ZdS )z#ordered_load.<locals>.OrderedLoaderN)rb   rc   rd   r   r   r   r   OrderedLoader   s   rl   c                    s   |  |  | |S r1   )Zflatten_mappingZconstruct_pairs)loadernodeobject_pairs_hookr   r   construct_mapping   s    
z'ordered_load.<locals>.construct_mapping)Zadd_constructoryamlresolverBaseResolverZDEFAULT_MAPPING_TAGload)streamLoaderrp   rl   rq   r   ro   r   ordered_load   s    rx   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	DirectoryContextz2
    Context Manager for changing directories
    c                 C   s   t  | _|| _d S r1   )r	   getcwdold_dirnew_dir)r3   r
   r   r   r   rO      s    
zDirectoryContext.__init__c                 C   s   t | j d S r1   )r	   chdirr|   r2   r   r   r   r4      s    zDirectoryContext.__enter__c                 G   s   t | j d S r1   )r	   r}   r{   )r3   argsr   r   r   r9      s    zDirectoryContext.__exit__N)rb   rc   rd   __doc__rO   r4   r9   r   r   r   r   ry      s   ry   c                 C   s   t d| tj| dd}zxt|dZ}t|jd}t|jdd|d d d	d
D ]}|rX|	| |
  qXW d   n1 s0    Y  W n$   tj|rt|  Y n0 dS )zGiven a url, output_path and title,
    write the contents of a requests get operation to
    the url in binary mode and print the title of operationzDownloading {0}T)rv   wbzcontent-lengthi   )
chunk_sizer   i  )rD   rE   N)r!   formatrequestsgetopenrV   headersri   iter_contentrW   rY   r	   r
   r   remove)urloutput_pathtitlerespftotal_lengthchunkr   r   r   _url_to_binary_write   s    "
,
r   c                 C   s.  |  drJt| d}|  W d   n1 s40    Y  t|  n|  drt| d}|  W d   n1 s~0    Y  t|  n|  drt| d}|  W d   n1 s0    Y  t|  nL|  dr*t| d	}|  W d   n1 s0    Y  t|  dS )
zEExtract a local archive, e.g. zip or tar, then
    delete the archiveztar.gzzr:gzNtarzr:ztar.bz2zr:bz2zipr)endswithtarfiler   
extractallr	   r   zipfileZipFile)r   r   Zzipfr   r   r   _extract_downloaded_archive   s     
&
&
&(r   c                    sL  t j|st | t| d}| dg D ]}t j|s2d} qLq2|du rz|sztd| d  W d   dS | d | d d }d	rԇfd
d| d D } fdd| d D }	dd |	D }
n6g}t j	d g}	| d }
t
|
ttfs
|
g}
t||	|
}t|D ]\}\}}||d t|}|du r~t|slt j|ddr~td| qt j|t|}|rt j|rt j||}td|| t|| qn"|rt j|std| t|| t| qW d   n1 s"0    Y  tdu rHtd td dS )ay  Process each download spec in datasets.yml

    Typically each dataset list entry in the yml has
    "files" and "url" and "title" keys/values to show
    local files that must be present / extracted from
    a decompression of contents downloaded from the url.

    If a url endswith '/', then all files given
    are assumed to be added to the url pattern at the
    end
    FfilesTzSkipping {0}r   Nr   z	 {} of {}r+   c                    s   g | ]} | qS r   r   ).0r   )r   r   r   
<listcomp>)      z$_process_dataset.<locals>.<listcomp>c                    s   g | ]}t j t|qS r   )r	   r
   r   DATA_DIR)r   fname)herer   r   r   *  s   c              	   S   s6   g | ].}d  |d d|dr$dnd d qS )r'   Ngz*)r   splitr   )r   r   r   r   r   r   -  s   r   r   r:   z%Copying test data file '{0}' to '{1}'z6No test file found for: {}. Using regular file insteadzIthis download script requires the requests module: conda install requests)r	   r
   r   makedirsry   r   r!   r   r   r   
isinstancetuplelistr   rg   rU   globreplacer   DATA_STUBS_DIRshutilcopyfiler   r   r   sysexit)Zdataset
output_dirr   r   r   Zrequires_downloadr   Z	title_fmturlsZoutput_pathsunpackedZzippedidxr   unpackZrunning_titletesttargetr   )r   r   r   _process_dataset  sZ    


,,
r   datasets.ymlTc              
   C   s   t j|}t j||}t j|s8t jt| |}t j|sX|du rXtd dS td|t j|tf  t|X}t	|
 }| D ]2\}	}
t j||	}|
D ]}t|||||d qqW d   n1 s0    Y  dS )zFetch sample datasets as defined by path/datasets if it exists or else module's own examples/datasets otherwise.

    Datasets are placed in path/data
    FzNo datasets to downloadNz-Fetching data defined in %s and placing in %s)r   r   )r	   r
   r    r   r   r   r!   r   r   rx   readitemsr   )r   r
   Zdatasetsr   r   r   Z	info_filer   infoZtopicZ	downloadsr   dr   r   r   r   M  s    
r   c           	      C   s   t j|}t j|s t| }t j|t}t j|t}t j|rZtt 	|dkrft
d dS t 	|D ]}t j||}t j|st
d| qpt j||}t j|rpt j|}t j|}||krt
d| t | qpt
d|| qpdS )z=Remove up any data files that are copied from test files
    r   zNo test files foundNz!Test file was not copied to data:zRemoving copied test file:z?Size of test file {:.2e} did not match size of data file {:.2e})r	   r
   r    r   r   r   r   r   rU   listdirr!   isfilegetsizer   r   )	r   r
   data_dirZtest_dirr   Z	data_fileZ	test_fileZdata_sZtest_sr   r   r   
clean_datad  s.    

r   c                 G   s>   d|v r| j ddddd d|v r:| j dtdd|d	 d S )
N-vz	--verboser[   r   )actiondefault--pathzwhere to place outputz{}-examples)typehelpr   )add_argumentstrr   )parserr   r~   r   r   r   _add_common_args  s    r   c                    s   | j  fddd d S )Nc                    s"   fi  fddt  D S )Nc                    s    i | ]}|d kr|t  |qS func)getattr)r   kr~   r   r   
<dictcomp>  r   z3_set_defaults.<locals>.<lambda>.<locals>.<dictcomp>)varsr   fnr   r   r   <lambda>  r   z_set_defaults.<locals>.<lambda>r   )set_defaults)r   r   r   r   r   r   _set_defaults  s    r   c                 C   sN  |du rg d}d|v rV| j dttd}|jdddd t||d	d
 t||t d|v r| j dttd}|jdtddd |jdddd |jdddd t||d
 t||t d|v r| j dtt	d}|jdddd |jdddd t||d	d
 t||t	 d|v rJ| j dtt
d}t||d
 t||t
 dS )zF
    Add all commands in pyct.cmd unless specific cmds are listed
    N)r   copy-examples
fetch-data
clean-datar   r   z--force
store_truezQif PATH already exists, force overwrite existing files if older than source files)r   r   r   r   r   z
--datasetsr   z^*name* of datasets file; must exist either in path specified by --path or in package/examples/)r   r   r   z,Force any existing data files to be replacedz--use-test-datazUse data's test files, if any, instead of fetching full data. If test file not in '.data_stubs', fall back to fetching full data.r   zif PATH already exists, force overwrite existing examples if older than source examples. ALSO force any existing data files to be replacedr   )
add_parserr   getdocr   r   r   r   r   r   r   r   )r   r   cmdsr~   Z	eg_parserZd_parserZ
egd_parserZ	cd_parserr   r   r   add_commands  sD    


r   c                 C   s$   t |}| jddd|j d d S )N	--versionversion	%(prog)s r   r   )r   r   r   r   )r   r   modr   r   r   add_version  s    
r   c                 C   s^   t jd|  d}|jdd}t|| || t||  | }t|drP||n|d dS )z_
    If module has no other commands, use this function to add all of the ones in pyct.cmd
    z%s commandsdescriptionavailable commandsr   r   must supply command to runN)	argparseArgumentParseradd_subparsersr   r   
parse_argshasattrr   error)r   r   r~   r   
subparsersr   r   r   substitute_main  s    
r   c                  C   s   t jdd} | jdddt d | jdd}|jd	ttd
}|j	td |jddt
ddd |  }t|dr|j|j  n
| d d S )NzCommands relating to versioningr   r   r   r   r   r   r   r   r   r   packagespackage+zname of package)metavarr   nargsr   r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   Zreport_parserr~   r   r   r   main  s    
r   )FFF)FF)FF)r   TFF)NN)NN)8
__future__r   r   r   r:   r   r   r	   r   r   r   distutils.dir_utilr"   r   r   r   r   collectionsr&   r   r   r   rF   r   rr   r   ImportErrorstderrr?   rX   ZMILL_TEMPLATEZ	DOTS_CHARrf   re   Z
MILL_CHARSrQ   rR   r   r   objectr0   ri   rw   rx   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sd   

 
J

@

,
