U
    ldX                     @   sx   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 G dd dee j	Z
G dd dee j	ZG dd	 d	ee jZdS )
    N)BaseCommandMixin)CONFIGc                       sZ   e Zd ZdZejjjejjjejjjdZ	 fddZ
edd Zdd Zd	d
 Z  ZS )RootCommandzAThis class defers to either the PluginCommand or the builtin cmds)infotoolsdevc                    s  dd l }dd l}ddddddg}|d}g }g }|jD ]R t fd	d
|D r\|  | }	|	d k	r8|	 \}
| d|
 f q8|s|r|rdd| }t	j
td|dd |rddd
 |D }d| }t	j
td|dd |d t j|| d | _d S )Nr   u   ‘u   ’u   “u   ”u   —u   –z--m-(\S+)-categoryc                 3   s   | ]}| kV  qd S N ).0xZcommandr	   Flib/python3.8/site-packages/q2cli-2023.5.0-py3.8.egg/q2cli/commands.py	<genexpr>%   s     z'RootCommand.__init__.<locals>.<genexpr>z--m-%s-columnzdError: Detected invalid character in: %s
Verify the correct quotes or dashes (ASCII) are being used., errorTerr
c                 s   s   | ]\}}d ||f V  qdS )zInstead of %s, trying using %sNr	   )r
   oldnewr	   r	   r   r   5   s   z|Error: The following options no longer exist because metadata *categories* are now called metadata *columns* in QIIME 2.

%s)resyscompileargvanyappend	fullmatchgroupsjoinclickechor   	cfg_styleexitsuper__init___plugins)selfargskwargsr   r   ZunicodesZcategory_regexZinvalid_charsZ
categoriesmatchZ
param_namemsgZold_to_new_names	__class__r   r   r%      s<    






zRootCommand.__init__c                 C   s\   dd l }| jd kr(dd l}|jjjj| _i }| j D ] \}}|d r6|||j	|< q6|S )Nr   actions)

q2cli.utilr&   Zq2cli.core.cachecorecacheZCACHEpluginsitemsutilto_cli_name)r'   q2cliZname_mapnamepluginr	   r	   r   _plugin_lookupD   s    
zRootCommand._plugin_lookupc                 C   s$   dd l }| j}t| j}|||S )Nr   )	itertools_builtin_commandssortedr9   chain)r'   ctxr:   builtinsr2   r	   r	   r   list_commandsU   s    
zRootCommand.list_commandsc              	   C   s   || j kr| j | S z| j| }W n tk
r   ddlm} ||| j}t|dkrdd|d  }n|rxdd| }nd}tjt	
dd	| | d
d |d Y nX t||S )Nr   get_close_matches     Did you mean %r?  (Possible commands: %s)r    r   z.Error: QIIME 2 has no plugin/command named %r.Tr      )r;   r9   KeyErrorr/   rB   lenr   r    r!   r   r"   r#   PluginCommand)r'   r>   r7   r8   rB   possibilitieshintr	   r	   r   get_command_   s,    

zRootCommand.get_command)__name__
__module____qualname____doc__r6   Zbuiltinr   r   r   r;   r%   propertyr9   r@   rM   __classcell__r	   r	   r,   r   r      s   )

r   c                       sH   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Zdd Z	  Z
S )rJ   z2Provides ActionCommands based on available Actionsc           
         s   dd l  || _ fdd|d  D | _d|d  }d|d  }d	|d
  }d|||g}tjdddd| jdd j	| j
 j| jg}	t j|f||d ||	d| d S )Nr   c                    s   i | ]\}} j ||qS r	   )r4   r5   )r
   idar6   r	   r   
<dictcomp>   s     
 z*PluginCommand.__init__.<locals>.<dictcomp>r.   zGetting user support: %sZuser_support_textzPlugin website: %swebsitezDescription: %sdescription

)z	--versionTFzShow the version and exit.)is_flagZexpose_valueZis_eagercallbackhelpZshort_description)
short_helpr]   params)r/   _pluginr3   _action_lookupr   r    Option_get_versionr4   example_data_option_get_plugincitations_option_get_citation_recordsr$   r%   )
r'   r8   r7   r(   r)   ZsupportrX   rY   help_r_   r,   rV   r   r%   {   s.    


  zPluginCommand.__init__c           	      C   s   |r
|j rd S dd l}|j }|j D ]$}| jd |jkr*|j}|j	} qXq*d }}t
d| jd | jd ||f  |  d S )Nr   r7   z	[UNKNOWN]z=QIIME 2 Plugin '%s' version %s (from package '%s' version %s)version)Zresilient_parsingr/   r4   get_plugin_managerr2   valuesr`   r7   Zproject_nameri   r    r!   r#   )	r'   r>   Zparamvaluer6   pmr8   pkg_nameZpkg_versionr	   r	   r   rc      s&    

 zPluginCommand._get_versionc                 C   s$   dd l }|j }|j| jd  jS Nr   r7   )r/   r4   rj   r2   r`   	citationsr'   r6   rm   r	   r	   r   rg      s    
z#PluginCommand._get_citation_recordsc                 C   s"   dd l }|j }|j| jd  S ro   )r/   r4   rj   r2   r`   rq   r	   r	   r   re      s    
zPluginCommand._get_pluginc                 C   s
   t | jS r   )r<   ra   r'   r>   r	   r	   r   r@      s    zPluginCommand.list_commandsc              
   C   s   z| j | }W n tk
r   ddlm} ||| j }t|dkrPd|d  }n|rddd| }nd}tjt	dd	| j
d
 |f | dd |d Y nX t|| j
|S )Nr   rA   rC   rD   rE   r   rF   r   z*Error: QIIME 2 plugin %r has no action %r.r7   Tr   rG   )ra   rH   r/   rB   rI   r   r    r!   r   r"   r`   r#   ActionCommand)r'   r>   r7   actionrB   rK   rL   r	   r	   r   rM      s(    zPluginCommand.get_command)rN   rO   rP   rQ   r%   rc   rg   re   r@   rM   rS   r	   r	   r,   r   rJ   y   s   rJ   c                       s`   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Z  ZS )rs   zGA click manifestation of a QIIME 2 API Action (Method/Visualizer)

    c                    sx  dd l }dd l}|| _|| _|  \| _| _| _tj	dg|jj
 ddtj	dgd dddg| _|  }|j
d	kr| jtj	d
gdtddtj	dgddddtj	dgddddtj	dgdtjdddddtj	dgdtjdddddg | j|j| j| jd |j| jg | j| j| j| j}|d g}| jd rT|tdd t j||| |d d|d  d S )!Nr   z--output-dirz)Output unspecified results to a directory)typer]   z--verbose / --quietFzDisplay verbose output to stdout and/or stderr during execution of this action. Or silence output if execution is successful (silence is golden).)defaultrequiredr]   pipelinez--recycle-poolaw  Use a cache pool for pipeline resumption. QIIME 2 will cache your results in this pool for reuse by future invocations. These pool are retained until deleted by the user. If not provided, QIIME 2 will create a pool which is automatically reused by invocations of the same action and removed if the action is successful. Note: these pools are local to the cache you are using.)rw   ru   r]   z--no-recycleTzrDo not recycle results from a previous failed pipeline run or save the results from this run for future recycling.)r[   rw   r]   z
--parallelzQExecute your action in parallel. This flag will use your default parallel config.z--parallel-config)existsZdir_okayzEExecute your action in parallel using a config at the indicated path.z--use-cache)ry   Z	file_okayaL  Specify the cache to be used for the intermediate work of this pipeline. If not provided, the default cache under $TMP/qiime2/<uname> will be used. IMPORTANT FOR HPC USERS: If you are on an HPC system and are using parallel execution it is important to set this to a location that is globally accessible to all nodes in the cluster.rT   rY   
deprecatedwarningz\WARNING:

This command is deprecated and will be removed in a future version of this plugin.r7   rZ   )r_   r\   r^   r]   )r/   Zq2cli.click.typer8   rt   _build_generated_options_inputs_params_outputsr    rb   ru   Z
OutDirType_misc_get_actionextendstrPathr4   rd   re   rf   rg   r   r   r"   r$   r%   r   )r'   r7   r8   rt   r6   Z
action_objZoptionsrh   r,   r	   r   r%      sl    




$ 
  zActionCommand.__init__c           	      C   s   dd l }g }g }g }| jd D ]\}| }|d}|dkrB|}n|dkrP|}n|}|jjjf d|d i|}|| q|||fS )Nr   	signatureru   inputZ	parameterprefix)Zq2cli.click.optionrt   copypopr    ZoptionZGeneratedOptionr   )	r'   r6   Zinputsr_   outputsitemru   ZstorageZoptr	   r	   r   r|     s    
z&ActionCommand._build_generated_optionsc                 C   s"   | j | j| j| j| |g dS )N)ZInputsZ
ParametersZOutputsZMiscellaneous)r}   r~   r   r   Zget_help_optionrr   r	   r	   r   get_opt_groups3  s
    zActionCommand.get_opt_groupsc                 C   s
   |   jS r   )r   rp   )r'   r	   r	   r   rg   ;  s    z#ActionCommand._get_citation_recordsc                 C   s"   dd l }|j }|j| jd  S ro   )r/   r4   rj   r2   r8   rq   r	   r	   r   re   >  s    
zActionCommand._get_pluginc                 C   s   |   }|j| jd  S )NrT   )re   r.   rt   )r'   r8   r	   r	   r   r   C  s    zActionCommand._get_actionc           ,   
      s  ddl }ddl}ddl}ddlm}m}m} ddlm} ddl	m
}	 |d}
|
r|
ddd }|r|j|r||rtd	|
 d
|dd}|dd}|dk	r|rtd|dd}|dk	r||std| d|dd}|dd}|dk	r ddlm} d}|| |d}|dkr>d}d}n|rJd}nd}||d i }i }| D ]$\}}|d^}}d|}|dkr|dkr|j|
|}|||< n|dkr|||dtd  < n|dkr|dk	r|}t|tr fdd|D }njt|ts(t||	r@ fdd | D }n:t|trdt fd!d|D }n|dk	rz j|}|||< n|||< qh| |}|  }||j d|j  }|s|j!d"kr|dkr|}|dk	r||kr| " krd#| jf }|#t$%d$| d}|s>ddl&} | j'd%d&dd'd(}|j(rtd)t)j*+| j,d* | j-f }|#t$%d$| d}!zzz|j*j0||d+` |r|j1}|dkr|f |}"|"2 }"n0 j3|dd,}#|# |f |}"|"2 }"W 5 Q R X W 5 Q R X W nV t4k
rJ }$ z6d-t)j*+| j,d*  }%|r(d.}t)j*j5|$|%|d/ W 5 d}$~$X Y nX d}!W 5 |r|!r|j|j-r|.  |/|j- X |
dk	r|6|
 t7|"|D ]\}&}'t|'t8rt|'dkr|'d }'||'r(|
dkr(||'\}(}||( t|&|	r 9|&| |'})n |&| |'})n
|&|'})|s||'r\d0|&j! d1|( d2| }*n<t|&|	rd3t|&: d j! d4n|&j!}+d5|+ d6|) }*|#t$%d7|* q||kr /| dS )8zACalled when user hits return, **kwargs are Dict[click_names, Obj]r   N)output_in_cache_get_cache_path_and_keyget_default_recycle_pool)Cache)ResultCollection
output_dir:rC   zThe given output dir 'zL' appears to be a cache:key combo. Cache keys cannot be used as output dirs.recycle_pool
no_recycleFzICannot set a pool to be used for recycling and no recycle simultaneously.Z	use_cachez
The path 'zK' is not a valid cache, please supply a path to a valid pre-existing cache.parallelZparallel_config)setup_parallelTverbose)path_omZ_fileic                    s   g | ]} j |qS r	   process_poolsaver
   vr1   r	   r   
<listcomp>  s     z*ActionCommand.__call__.<locals>.<listcomp>c                    s   i | ]\}}| j |qS r	   r   )r
   kr   r   r	   r   rW     s    z*ActionCommand.__call__.<locals>.<dictcomp>c                    s   g | ]} j |qS r	   r   r   r   r	   r   r     s     rx   zFThe pool '%s' does not exist on the cache at '%s'. It will be created.r{   zqiime2-q2cli-err-z.logw)r   suffixdeletemodezaPlugin warning from %s:

%s is deprecated and will be removed in a future version of this plugin.r7   )stdoutstderr)keyZreusezPlugin error from %s:r   )header	tracebackzAdded z to cache: z as: zCollection[]zSaved z to: Zsuccess);osr    Zqiime2.utilr/   r   r   r   Zqiime2.core.cacher   Z
qiime2.sdkr   r   rsplitr   ry   Zis_cache
ValueErrorZqiime2.sdk.parallel_configr   r3   splitr   rI   
isinstancelistdictsetr   r   _order_outputsr   Z	plugin_idrT   ru   Z	get_poolsr!   r   r"   tempfileZNamedTemporaryFilerz   r6   r4   r5   r8   r7   closeremoveZredirected_stdior   Z_resultZcreate_pool	ExceptionZexit_with_errormakedirsziptupleZsave_collectionrk   ),r'   r)   r   r    Zqiime2r   r   r   r   r   r   Zpotential_cacher   r   Z
used_cacher   Zparallel_config_fpr   r   quietZ	argumentsZinit_outputsr   rl   r   partsZvalue_r   rt   Zdefault_poolr+   logr   Zcleanup_logfileZresultsZpooler   resultoutput
cache_pathr   messageru   r	   r   r   __call__G  s   














 



 $




zActionCommand.__call__c                 C   s6   g }| j d D ]"}|d dkr|||d   q|S )Nr   ru   r   r7   )rt   r   )r'   r   Zorderedr   r	   r	   r   r     s
    zActionCommand._order_outputsc              	   C   sb   | j d r^|tjddd: | j d D ](}|d|j  || |d q*W 5 Q R X d S )NZepilogZExamplesT)Zbold r   )rt   Zsectionr    ZstylewriteZcurrent_indent)r'   r>   Z	formatterliner	   r	   r   format_epilog  s    

zActionCommand.format_epilog)rN   rO   rP   rQ   r%   r|   r   rg   re   r   r   r   r   rS   r	   r	   r,   r   rs      s   K Rrs   )r    Zq2cli.builtin.devr6   Zq2cli.builtin.infoZq2cli.builtin.toolsZq2cli.click.commandr   Zq2cli.core.configr   ZMultiCommandr   rJ   ZCommandrs   r	   r	   r	   r   <module>	   s   fT