B
    lz]UW                 @   s  d dl mZmZmZ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 d dlmZmZ d d	lZejd  d
krd dlmZ d dlmZ d d	l Z d d	l!Z!d dl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' d d	l(Z(d dl)m*Z*m+Z+m,Z,m-Z- d d	l.Z.d dl/m0Z0m1Z1m2Z2 d dl3m4Z4m3Z3 ddl5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= d
dl>m?Z? d
dl@mAZA d
dlBmCZC d
dlDmEZE e'eFZGG dd de#ZHeCe(jIJdreHdZKne#dZKdJddZLG d d! d!eMZNG d"d# d#eNZOeO ZPG d$d% d%eZQedKd&d'ZRedLd(d)ZSedMd*d+ZTeeQjUeQjUfd,d-ZVed.d/ ZWed0d1 ZXed2d3 ZYedNd4d5ZZe&d	d6d	fd7d8Z[d9d: Z\G d;d< d<eMZ]G d=d> d>eMZ^G d?d@ d@e
Z_G dAdB dBe	Z`eZdCdD ZaG dEdF dFeNZbdGdH ZceFdIkrec  d	S )O    )absolute_importdivisionprint_functionunicode_literals)defaultdict)ProcessPoolExecutorThreadPoolExecutorExecutorFuture_baseas_completed)	_WorkItem)contextmanager)Enum)EPIPE	ESHUTDOWN)partialwrapsN   )BytesIO)cycle)CRITICAL	FormatterNOTSETStreamHandlerWARN	getLogger)dirnameisdirisfilejoin)EventThreadLock)sleeptime   )StringIO	iteritemson_winencode_environment)NULL)expand)memoizemethod)NullHandler)boolify)tqdmc                   s.   e Zd ZdZd fdd	Z fddZ  ZS )DeltaSecondsFormatteraw  
    Logging formatter with additional attributes for run time logging.

    Attributes:
      `delta_secs`:
        Elapsed seconds since last log/format call (or creation of logger).
      `relative_created_secs`:
        Like `relativeCreated`, time relative to the initialization of the
        `logging` module but conveniently scaled to seconds as a `float` value.
    Nc                s    t  | _tt| j||d d S )N)fmtdatefmt)r%   	prev_timesuperr1   __init__)selfr2   r3   )	__class__ .lib/python3.7/site-packages/conda/common/io.pyr6   1   s    zDeltaSecondsFormatter.__init__c                s@   t  }| j}t| j|| _|| |_|jd |_tt| |S )Ni  )	r%   r4   maxZ
delta_secsZrelativeCreatedZrelative_created_secsr5   r1   format)r7   recordZnowr4   )r8   r9   r:   r<   5   s    
zDeltaSecondsFormatter.format)NN)__name__
__module____qualname____doc__r6   r<   __classcell__r9   r9   )r8   r:   r1   &   s   
r1   ZCONDA_TIMED_LOGGINGzm%(relative_created_secs) 7.2f %(delta_secs) 7.2f %(levelname)s %(name)s:%(funcName)s(%(lineno)d): %(message)sz<%(levelname)s %(name)s:%(funcName)s(%(lineno)d): %(message)sc                s   d  fdd| D S )N c             3   s&   | ]}d d   d t | V  qdS )
 z- N)str).0x)indentr9   r:   	<genexpr>J   s    zdashlist.<locals>.<genexpr>)r    )iterablerI   r9   )rI   r:   dashlistI   s    rL   c               @   s   e Zd ZdZdd ZdS )ContextDecoratorzyBase class for a context manager class (implementing __enter__() and __exit__()) that also
    makes it a decorator.
    c                s   t   fdd}|S )Nc           	      s     | |S Q R X d S )Nr9   )argskwds)fr7   r9   r:   	decoratedU   s    z,ContextDecorator.__call__.<locals>.decorated)r   )r7   rP   rQ   r9   )rP   r7   r:   __call__T   s    zContextDecorator.__call__N)r>   r?   r@   rA   rR   r9   r9   r9   r:   rM   M   s   rM   c               @   s   e Zd Zdd Zdd ZdS )SwallowBrokenPipec             C   s   d S )Nr9   )r7   r9   r9   r:   	__enter__`   s    zSwallowBrokenPipe.__enter__c             C   s0   |r,t |tr,t|dd r,|jttfkr,dS d S )NerrnoT)
isinstanceEnvironmentErrorgetattrrU   r   r   )r7   exc_typeexc_valexc_tbr9   r9   r:   __exit__c   s
    
zSwallowBrokenPipe.__exit__N)r>   r?   r@   rT   r\   r9   r9   r9   r:   rS   \   s   rS   c               @   s   e Zd ZdZdZdZdS )CaptureTargetzConstants used for contextmanager captured.

    Used similarly like the constants PIPE, STDOUT for stdlib's subprocess.Popen.
    N)r>   r?   r@   rA   STRINGSTDOUTr9   r9   r9   r:   r]   n   s   r]   c          
   c   s   | d kri } t | }i }x0t|D ]$\}}tj|t||< |tj|< q"W z |rV|  |rb|d d V  W d x0t|D ]$\}}|tkrtj|= qv|tj|< qvW |r|  |r|d X d S )NTF)r*   r(   osenvirongetr+   )Zvar_mapcallbackstack_callbackZnew_var_mapZ
saved_varsnamevaluer9   r9   r:   env_varsw   s*    

ri   c          	   c   s,   | |i}t |||d}|V  W d Q R X d S )N)re   rf   )ri   )rg   rh   re   rf   desr9   r9   r:   env_var   s    rl   c          	   c   s    t | d}|V  W d Q R X d S )N)re   )ri   )re   rk   r9   r9   r:   env_unmodified   s    rm   c       	   	   c   s@  dd }G dd dt }tjtj }}| tjkrRt }|j|_t	|||_|t_n| }|dk	rd|t_|tjkrt }|j|_t	|||_|t_n(|tj
kr| t_}n|}|dk	r|t_| }td z
|V  W d| tjkr| |_n||_|tjkr| |_n|tj
krd|_n||_|| t_t_td X dS )a  Capture outputs of sys.stdout and sys.stderr.

    If stdout is STRING, capture sys.stdout as a string,
    if stdout is None, do not capture sys.stdout, leaving it untouched,
    otherwise redirect sys.stdout to the file-like object given by stdout.

    Behave correspondingly for stderr with the exception that if stderr is STDOUT,
    redirect sys.stderr to stdout target and set stderr attribute of yielded object to None.

    Args:
        stdout: capture target for sys.stdout, one of STRING, None, or file-like object
        stderr: capture target for sys.stderr, one of STRING, STDOUT, None, or file-like object

    Yields:
        CapturedText: has attributes stdout, stderr which are either strings, None or the
            corresponding file-like function argument.
    c             S   s   t | drd| jkrt}n6tjd dkr8t| tr8t}ntjd dkrLt}nt}t||st |drz|	d}| 
| qt |dr|d}| 
| n
| 
| d S )	Nmodebr      r   decodezutf-8encode)hasattrrn   bytessysversion_inforV   r   ZunicoderF   rq   	old_writerr   )r7   Zto_writeZwantedZdecodedro   r9   r9   r:   write_wrapper   s    




zcaptured.<locals>.write_wrapperc               @   s   e Zd ZdS )zcaptured.<locals>.CapturedTextN)r>   r?   r@   r9   r9   r9   r:   CapturedText   s   ry   Nzovertaking stderr and stdoutzstderr and stdout yielding back)objectru   stdoutstderrr]   r`   r'   writerw   r   ra   loginfogetvalue)	r{   r|   rx   ry   Zsaved_stdoutZsaved_stderrZoutfileZerrfilecr9   r9   r:   captured   sF    "





r   c             c   s$   t j}| t _z
d V  W d |t _X d S )N)ru   argv)Z	args_listZ
saved_argsr9   r9   r:   r     s
    
r   c               c   s"   t   z
d V  W d t   X d S )N)loggingZ_acquireLockZ_releaseLockr9   r9   r9   r:   _logger_lock  s    
r   c             c   s   t | }|j|j|j  }}}t }t * || |td  d\|_|_W d Q R X z
d V  W d t $ |	| || |_|_||_W d Q R X X d S )Nr&   )TF)
r   leveldisabled	propagater.   r   
addHandlersetLevelr   removeHandler)logger_namelogr_lvl_dsbld_prpgtZnull_handlerr9   r9   r:   disable_logger  s    


r   c             c   s   t |}|j|j|j|jf\}}}}ttj}d|_|	|  |
t t : |	|  g dd  |_|_|_|| |	|  W d Q R X z
d V  W d t " |||  |_|_|_||_W d Q R X X d S )Nr|   F)r   handlersr   r   r   r   ru   r|   rg   r   setFormatter
_FORMATTERr   r   )r   r   r   Z_hndlrsr   r   r   handlerr9   r9   r:   stderr_log_level-  s     





r   Fc          	   C   s   t |}tdd |jD d }ttj}d|_|t |	|pBt
 t . |r\|| || ||  ||_W d Q R X d S )Nc             s   s   | ]}|j d kr|V  qdS )r|   N)rg   )rG   r   r9   r9   r:   rJ   E  s    z(attach_stderr_handler.<locals>.<genexpr>r|   )r   nextr   r   ru   r|   rg   r   r   r   r   r   r   r   r   )r   r   r   Z	formatterr   Zold_stderr_handlerZnew_stderr_handlerr9   r9   r:   attach_stderr_handlerB  s    




r   c          	      s   | dd}tr2y
|||S  tk
r.   |S X nfG dd dt  fdd}ttj| t|  y|||}td |S   tfk
r   |S X dS )z[Enforce a maximum time for a callable to complete.
    Not yet implemented on Windows.
    default_returnNc               @   s   e Zd ZdS )z!timeout.<locals>.TimeoutExceptionN)r>   r?   r@   r9   r9   r9   r:   TimeoutExceptiond  s   r   c                s
     d S )Nr9   )Zsignumframe)r   r9   r:   	interruptg  s    ztimeout.<locals>.interruptr   )popr)   KeyboardInterrupt	ExceptionsignalSIGALRMalarm)Ztimeout_secsfuncrN   kwargsr   r   Zretr9   )r   r:   timeoutW  s     



r   c               @   sN   e Zd ZdZedZdddZdd	 Zd
d Zdd Z	e
dd Zdd ZdS )Spinnera  
    Args:
        message (str):
            A message to prefix the spinner with. The string ': ' is automatically appended.
        enabled (bool):
            If False, usage is a no-op.
        json (bool):
           If True, will not output non-json to stdout.

    z/-\|TFfailed
c             C   sp   || _ || _|| _t | _t| jd| _tt	| j
d | _tj| _|ob| obt| jdob| j | _|| _d S )N)targetr&   isatty)messageenabledjsonr!   _stop_runningr"   _start_spinning_spinner_threadlenr   spinner_cycle_indicator_lengthru   r{   fhrs   r   	show_spinfail_message)r7   r   r   r   r   r9   r9   r:   r6     s    "zSpinner.__init__c             C   s2   | j r| j  n| js.| jd | j  d S )Nz...working... )r   r   startr   r   r}   flush)r7   r9   r9   r:   r     s
    zSpinner.startc             C   s$   | j r | j  | j  d| _ d S )NF)r   r   setr   r    )r7   r9   r9   r:   stop  s    

zSpinner.stopc          
   C   s   yNxH| j  sJ| jt| jd  | j  td | jd| j  qW W n< t	k
r } z|j
ttfkrx|   n W d d }~X Y nX d S )NrE   g?)r   Zis_setr   r}   r   r   r   r$   r   rW   rU   r   r   r   )r7   er9   r9   r:   r     s    

zSpinner._start_spinningc             C   s.   | j s"tjd| j  tj  |   d S )Nz%s: )r   ru   r{   r}   r   r   r   )r7   r9   r9   r:   rT     s    
zSpinner.__enter__c          	   C   sP   |    | jsLt4 |s|r,tj| j ntjd tj  W d Q R X d S )Nzdone
)r   r   swallow_broken_piperu   r{   r}   r   r   )r7   rY   rZ   r[   r9   r9   r:   r\     s    zSpinner.__exit__N)TFr   )r>   r?   r@   rA   r   r   r6   r   r   r   r   rT   r\   r9   r9   r9   r:   r   u  s   

r   c               @   s2   e Zd ZdddZdd Zdd Zed	d
 ZdS )ProgressBarTFc          
   C   sz   || _ || _|| _|rn^|rvd}yt||ddtjd| _W n: tk
rt } z|jt	t
fkrbd| _n W dd}~X Y nX dS )a  
        Args:
            description (str):
                The name of the progress bar, shown on left side of output.
            enabled (bool):
                If False, usage is a no-op.
            json (bool):
                If true, outputs json progress to stdout rather than a progress bar.
                Currently, the json format assumes this is only used for "fetch", which
                maintains backward compatibility with conda 4.3 and earlier behavior.
        z!{desc}{bar} | {percentage:3.0f}% Tr&   )Zdesc
bar_formatasciiZtotalfileFN)descriptionr   r   r0   ru   r{   pbarrW   rU   r   r   )r7   r   r   r   r   r   r9   r9   r:   r6     s    
zProgressBar.__init__c          
   C   s   yB| j r&| jr&tjd| j|f  n| jr@| j|| jj  W n: t	k
r| } z|j
ttfkrjd| _n W d d }~X Y nX d S )Nz:{"fetch":"%s","finished":false,"maxval":1,"progress":%f}
 F)r   r   ru   r{   r}   r   r   updatenrW   rU   r   r   )r7   Zfractionr   r9   r9   r:   	update_to  s    zProgressBar.update_toc             C   s   |  d d S )Nr&   )r   )r7   r9   r9   r:   finish  s    zProgressBar.finishc             C   s>   | j r*| jr*tjd| j  tj  n| j r:| j  d S )Nz8{"fetch":"%s","finished":true,"maxval":1,"progress":1}
 )	r   r   ru   r{   r}   r   r   r   close)r7   r9   r9   r:   r     s    
zProgressBar.closeN)TF)r>   r?   r@   r6   r   r   r   r   r9   r9   r9   r:   r     s   
r   c               @   s.   e Zd Zdd Zdd Zdd Zddd	Zd
S )DummyExecutorc             C   s   d| _ t | _d S )NF)	_shutdownr#   _shutdownLock)r7   r9   r9   r:   r6     s    zDummyExecutor.__init__c             O   sp   | j ` | jrtdt }y|||}W n, tk
rV } z|| W d d }~X Y nX || |S Q R X d S )Nz*cannot schedule new futures after shutdown)r   r   RuntimeErrorr
   BaseExceptionZset_exceptionZ
set_result)r7   fnrN   r   rP   resultr   r9   r9   r:   submit  s    
zDummyExecutor.submitc             g   s*   x$|D ]}x|D ]}||V  qW qW d S )Nr9   )r7   r   	iterablesrK   thingr9   r9   r:   map
  s    

zDummyExecutor.mapTc          	   C   s   | j  d| _W d Q R X d S )NT)r   r   )r7   waitr9   r9   r:   shutdown  s    zDummyExecutor.shutdownN)T)r>   r?   r@   r6   r   r   r   r9   r9   r9   r:   r     s   r   c                   s&   e Zd Zd fdd	Zdd Z  ZS )ThreadLimitedThreadPoolExecutor
   c                s   t t| | d S )N)r5   r   r6   )r7   Zmax_workers)r8   r9   r:   r6     s    z(ThreadLimitedThreadPoolExecutor.__init__c          	   O   sz   | j j | jrtdt }t||||}| j| y|   W n& tk
rj   t	| j
dkrdn Y nX |S Q R X dS )a  
        This is an exact reimplementation of the `submit()` method on the parent class, except
        with an added `try/except` around `self._adjust_thread_count()`.  So long as there is at
        least one living thread, this thread pool will not throw an exception if threads cannot
        be expanded to `max_workers`.

        In the implementation, we use "protected" attributes from concurrent.futures (`_base`
        and `_WorkItem`). Consider vendoring the whole concurrent.futures library
        as an alternative to these protected imports.

        https://github.com/agronholm/pythonfutures/blob/3.2.0/concurrent/futures/thread.py#L121-L131  # NOQA
        https://github.com/python/cpython/blob/v3.6.4/Lib/concurrent/futures/thread.py#L114-L124
        z*cannot schedule new futures after shutdownr   N)Z_shutdown_lockr   r   r   r
   r   Z_work_queueZputZ_adjust_thread_countr   Z_threads)r7   r   rN   r   rP   wr9   r9   r:   r     s    z&ThreadLimitedThreadPoolExecutor.submit)r   )r>   r?   r@   r6   r   rB   r9   r9   )r8   r:   r     s   r   c              C   s   t ddd} ttjd| S )N~z.condazinstrumentation-record.csvZ!CONDA_INSTRUMENTATION_RECORD_FILE)r    r,   rb   rc   rd   )Zdefault_record_filer9   r9   r:   get_instrumentation_record_file?  s    r   c                   sp   e Zd Ze ZdZeeZee	Z
dddZdd Z fddZdd	 Zd
d Zedd Zedd Z  ZS )time_recorderNc             C   s   || _ || _d S )N)
entry_namemodule_name)r7   r   r   r9   r9   r:   r6   J  s    ztime_recorder.__init__c             C   sF   | j d krBt|dr|j}n
d|j }| jr<d| j|f}|| _ d S )Nr@   :.)r   rs   r@   r>   r   r    )r7   rP   r   r9   r9   r:   _set_entry_nameN  s    


ztime_recorder._set_entry_namec                s   |  | tt| |S )N)r   r5   r   rR   )r7   rP   )r8   r9   r:   rR   X  s    
ztime_recorder.__call__c             C   s$   t jd}|r t|r t | _| S )NCONDA_INSTRUMENTATION_ENABLED)rb   rc   rd   r/   r%   
start_time)r7   r   r9   r9   r:   rT   \  s    ztime_recorder.__enter__c          	   C   sv   | j rr| j}t }|| j  }| j|  d7  < | j|  |7  < |   t| jd}|d||f  W d Q R X d S )Nr&   az%s,%f
)	r   r   r%   total_call_numtotal_run_time_ensure_diropenrecord_filer}   )r7   rY   rZ   r[   r   Zend_timeZrun_timer   r9   r9   r:   r\   b  s    
ztime_recorder.__exit__c             C   s^   t jd}|rt|sd S td x2t| j D ] }td| j| | j	| | q6W d S )Nr   z*=== time_recorder total time and calls ===zTOTAL %9.3f % 9d %s)
rb   rc   rd   r/   r~   r   sortedr   keysr   )clsr   r   r9   r9   r:   
log_totalsp  s    
ztime_recorder.log_totalsc             C   s"   t t| jstt| j d S )N)r   r   r   rb   makedirs)r7   r9   r9   r:   r   ~  s    ztime_recorder._ensure_dir)NN)r>   r?   r@   r   r   r   r   intr   floatr   r6   r   rR   rT   r\   classmethodr   r-   r   rB   r9   r9   )r8   r:   r   D  s   

r   c        
   	   C   s   t  } tt}i }t| sd S t| 8}x0|D ](}| d\}}|| t| q.W W d Q R X x@t	|D ]4}|| }t
|}t|}|| }	|||	d||< qnW ttj|dddd d S )N,)counts
total_timeaverage_timeTr   )r   z: )Z	sort_keysrI   Z
separators)r   r   listr   r   stripsplitappendr   r   r   sumprintr   dumps)
r   Zgrouped_dataZ
final_datar   liner   r   Z	all_timesr   r   r9   r9   r:   print_instrumentation_data  s$    

 r   __main__)r   )NNN)NN)N)N)dZ
__future__r   r   r   r   collectionsr   Zconcurrent.futuresr   r   r	   r
   r   r   Zconcurrent.futures.threadr   
contextlibr   enumr   rU   r   r   	functoolsr   r   ru   rv   ior   	itertoolsr   r   r   r   r   r   r   r   r   rb   os.pathr   r   r   r    r   Z	threadingr!   r"   r#   r%   r$   compatr'   r(   r)   r*   Z	constantsr+   pathr,   Z_vendor.auxlib.decoratorsr-   Z_vendor.auxlib.logzr.   Z_vendor.auxlib.type_coercionr/   Z_vendor.tqdmr0   r>   r~   r1   rc   rd   r   rL   rz   rM   rS   r   r]   ri   rl   rm   r`   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r9   r9   r9   r:   <module>   s~     
		d
	G:)@
