a
    õ£BeÀ£  ã                   @  s”  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ddl	Z	ddl
ZddlmZmZ ddl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mZmZmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 d 7¡ Z8d 7¡ Z9e:e	dƒ�sTdge	_;dZ<ej= >dd¡Z?e? @¡ dv �rzdZAn e? @¡ dv �rŽdZAneBde? ƒ‚e	jC�o¬e	jC Dd¡ZEejFdejGdejHf d �ZIejJejKejLf ZMej#eNejHf ZOejPej&eN  ZQej&ejRe  ZSddd!œd"d#„ZTG d$d%„ d%eUƒZVG d&d'„ d'ejWƒZXG d(d)„ d)eƒZYeYjZZ[eYj\Z]d4d*d*d*d*d+d,œd-d.„Z^d/d0œd1d2„Z_e`d3k�r�eY a¡  dS )5z,A base class for a configurable application.é    )ÚannotationsN)ÚOrderedDictÚdefaultdict)Úsuppress)Údeepcopy)Ú
dictConfig)Údedent)ÚConfigurableÚSingletonConfigurable)ÚArgumentErrorÚConfigÚConfigFileNotFoundÚJSONFileConfigLoaderÚKVArgParseConfigLoaderÚPyFileConfigLoader)
ÚBoolÚDictÚEnumÚInstanceÚListÚ
TraitErrorÚUnicodeÚdefaultÚobserveÚobserve_compat)ÚBunch)Únested_update)ÚindentÚwrap_paragraphsé   ©Úcast_unicode)Úimport_itemzÜ
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
    <cmd> --help-all
zþ
The command-line option below sets the respective configurable class-parameter:
    --Class.parameter=value
This line is evaluated in Python, so simple expressions are allowed.
For instance, to set `C.a=[0,1,2]`, you may type this:
    --C.a='range(3)'
ÚargvÚ zp
Subcommands are launched as `{app} cmd [args]`. For information on using
subcommand 'cmd', do: `{app} cmd -h`.
Ú-TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR>   ÚtrueÚ1T>   r$   Ú0ÚfalseFz�Unsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of  {'0', '1', 'false', 'true', ''}.zpythonw.exeÚT.)Úbound)ÚmethodÚreturnc                   s.   t  ˆ ¡dddddœ‡ fdd„ƒ}t t|¡S )a  Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

    On a TraitError (generally caused by bad config), this will print the trait's
    message, and exit the app.

    For use on init methods, to prevent invoking excepthook on invalid input.
    ÚApplicationút.Any)ÚappÚargsÚkwargsr-   c              
     sn   zˆ | g|¢R i |¤ŽW S  t tfyh } z4| j d|¡ | j d| j¡ |  d¡ W Y d }~n
d }~0 0 d S )Nz0Bad config encountered during initialization: %szConfig at the time: %sé   )r   r   ÚlogÚfatalÚdebugÚconfigÚexit)r0   r1   r2   Úe©r,   © ú_/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/traitlets/config/application.pyÚinnerr   s    z!catch_config_error.<locals>.inner)Ú	functoolsÚwrapsÚtÚcastr*   )r,   r=   r;   r:   r<   Úcatch_config_errori   s    	rB   c                   @  s   e Zd ZdS )ÚApplicationErrorN)Ú__name__Ú
__module__Ú__qualname__r;   r;   r;   r<   rC   ~   s   rC   c                      s2   e Zd ZdZejZdZdddœ‡ fdd„Z‡  Z	S )ÚLevelFormattera  Formatter with additional `highlevel` record

    This field is empty if log level is less than highlevel_limit,
    otherwise it is formatted with self.highlevel_format.

    Useful for adding 'WARNING' to warning messages,
    without adding 'INFO' to info, etc.
    z %(levelname)s |zlogging.LogRecordÚstr)Úrecordr-   c                   s.   |j | jkr| j|j |_nd|_tƒ  |¡S )Nr$   )ÚlevelnoÚhighlevel_limitÚhighlevel_formatÚ__dict__Z	highlevelÚsuperÚformat)ÚselfrI   ©Ú	__class__r;   r<   rO   �   s    zLevelFormatter.format)
rD   rE   rF   Ú__doc__ÚloggingÚWARNrK   rL   rO   Ú__classcell__r;   r;   rQ   r<   rG   ‚   s   	rG   c                      sæ  e Zd ZU dZedƒZded< edƒZded< eeƒZded< ee	ƒZ	ded< ee
ƒZ
ded	< eZeZeƒ Zded
< g Zded< d´dddœdd„ZedƒZded< eƒ Zded< eeƒZedejdd�jdd�ZeZeddd�jdd�Zedd d�jdd�Z d!d"œd#d$„Z!e"d%d&d'd(ƒd)d*d+œd,d-„ƒZ#e"d.d/d0�d)d*d+œd1d2„ƒZ$d*d"œd3d4„Z%e&d.ƒd5d"œd6d7„ƒZ'e(d8d�jdd�Z)d9d:iZ*d!ed;< d d'ej+iid<fd d=diid>fd d?diid@fdAœZ,d!edB< e(ƒ Z-dCedD< e.dEddF�Z/eeƒ ƒZ0e.e1dGi dHd�Z2eƒ Z3dIedJ< edKd�jdd�Z4edLd�jdd�Z5e"d?ƒd)d*d+œdMdN„ƒZ6e"d=ƒd)d*d+œdOdP„ƒZ7dQd*dRœdSdT„Z8e"dUƒe9d)d*d+œ‡ fdVdW„ƒƒZ:e;dµdXd*dYœdZd[„ƒZ<d*d"œd\d]„Z=d*d"œd^d_„Z>d*d"œd`da„Z?dbd"œdcdd„Z@d*d"œdedf„ZAdbd"œdgdh„ZBd*d"œdidj„ZCdbd"œdkdl„ZDd*d"œdmdn„ZEdbd"œdodp„ZFdqdbdœdrds„ZGd¶dqd*dœdudv„ZHd·dqdbdœdwdx„ZIdyd"œdzd{„ZJd*d"œd|d}„ZKdbd"œd~d„ZLd*d"œd€d�„ZMdbd"œd‚dƒ„ZNd*d"œd„d…„ZOe;d¸dydXd*d†œd‡dˆ„ƒZPd‰d"œdŠd‹„ZQdŒd!d!dd�dŽœd�d�„ZReSd¹dqd‘d’œd“d”„ƒZTeSd*d"œd•d–„ƒZUe;dºdXd*dYœd—d˜„ƒZVeSd»dyd™dšdqd›dœœd�dž„ƒZWeXd‘d"œdŸd „ƒZYe;d¼dyd™d*d¡œd¢d£„ƒZZd½dddœd¤d¥„Z[d¾ddydœd¦d§„Z\d*d"œd¨d©„Z]d¿d«d*d¬œd­d®„Z^d*d"œd¯d°„Z_eSdÀdXdQd*d±œd²d³„ƒZ`‡  ZaS )Ár.   z8A singleton application with full configuration support.Zapplicationzstr | Unicode[str, str | bytes]ÚnamezThis is an application.ÚdescriptionÚoption_descriptionÚkeyvalue_descriptionÚsubcommand_descriptionÚexamplesÚClassesTypeÚclassesNzClassesType | Nonez+t.Generator[type[Configurable], None, None])r^   r-   c                 c  sV   |du r| j }tƒ }|D ]8}t| ¡ ƒD ]&}t|tƒr(||vr(| |¡ |V  q(qdS )a  Iterate through configurable classes, including configurable parents

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Children should always be after parents, and each class should only be
        yielded once.
        N)r^   ÚsetÚreversedÚmroÚ
issubclassr	   Úadd)rP   r^   ÚseenÚcÚparentr;   r;   r<   Ú_classes_inc_parents°   s    
z Application._classes_inc_parentsz0.0Úversionzlist[str] | List[str]r#   )r   é
   é   é   é(   é2   ÚDEBUGÚINFOrU   ÚERRORÚCRITICALz#Set the log level by value or name.)Údefault_valueÚhelpT©r7   z%Y-%m-%d %H:%M:%Sz:The date format used by logging formatters for %(asctime)s)rs   z#[%(name)s]%(highlevel)s %(message)szThe Logging format templateÚStrDict©r-   c                 C  sl   ddddt  | j¡ddœid| jj› d| jj› �| j| jdœi| jjddgd	œid
dœ}t	rh|d= |d= |S )a‡  Return the base logging configuration.

        The default is to log to stderr using a StreamHandler, if no default
        handler already exists.

        The log handler level starts at logging.WARN, but this can be adjusted
        by setting the ``log_level`` attribute.

        The ``logging_config`` trait is merged into this allowing for finer
        control of logging.

        r3   Úconsolezlogging.StreamHandlerzext://sys.stderr)ÚclassÚ	formatterÚlevelÚstreamÚ.)rx   rO   Údatefmtrn   )rz   ÚhandlersF)rh   r~   Ú
formattersÚloggersÚdisable_existing_loggersr~   r€   )
rT   ÚgetLevelNameÚ	log_levelÚ_log_formatter_clsrE   rD   Ú
log_formatÚlog_datefmtrR   Ú
IS_PYTHONW©rP   r7   r;   r;   r<   Úget_default_logging_configá   s6    
üÿ	
ÿúÿþÿæz&Application.get_default_logging_configr†   r…   rƒ   Úlogging_configr   ÚNone)Úchanger-   c                 C  s0   | j }t|tƒr$t ttt|ƒ¡| _ |  ¡  d S ©N)	rƒ   Ú
isinstancerH   r@   rA   ÚintÚgetattrrT   Ú_configure_logging)rP   rŒ   rƒ   r;   r;   r<   Ú_observe_logging_change  s    
z#Application._observe_logging_changer4   r   )Útypec                 C  s   |   ¡  d S r�   )r‘   ©rP   rŒ   r;   r;   r<   Ú_observe_logging_default  s    z$Application._observe_logging_defaultc                 C  s*   |   ¡ }t|| jpi ƒ t|ƒ d| _d S )NT)r‰   r   rŠ   r   Ú_logging_configuredrˆ   r;   r;   r<   r‘      s    zApplication._configure_loggingÚ	AnyLoggerc                 C  s@   t  | jj¡}d|_|}|dur<|jr*|S |js4q<q|j}q|S )z#Start logging for this application.FN)rT   Ú	getLoggerrR   rD   Ú	propagater~   rf   )rP   r4   Ú_logr;   r;   r<   Ú_log_default'  s    zApplication._log_defaulta!  
            Configure additional log handlers.

            The default stderr logs handler is configured by the
            log_level, log_datefmt and log_format settings.

            This configuration can be used to configure additional handlers
            (e.g. to output the log to a file) or for finer control over the
            default handlers.

            If provided this should be a logging configuration dictionary, for
            more information see:
            https://docs.python.org/3/library/logging.config.html#logging-config-dictschema

            This dictionary is merged with the base logging configuration which
            defines the following:

            * A logging formatter intended for interactive use called
              ``console``.
            * A logging handler that writes to stderr called
              ``console`` which uses the formatter ``console``.
            * A logger with the name of this application set to ``DEBUG``
              level.

            This example adds a new handler that writes to a file:

            .. code-block:: python

               c.Application.logging_config = {
                   "handlers": {
                       "file": {
                           "class": "logging.FileHandler",
                           "level": "DEBUG",
                           "filename": "<path/to/file>",
                       }
                   },
                   "loggers": {
                       "<application-name>": {
                           "level": "DEBUG",
                           # NOTE: if you don't list the default "console"
                           # handler here then it will be disabled
                           "handlers": ["console", "file"],
                       },
                   },
               }

        z	log-levelzApplication.log_levelÚaliasesz5Set log-level to debug, for the most verbose logging.Úshow_configz<Show the application's configuration (human-readable format)Úshow_config_jsonz2Show the application's configuration (json format))r6   zshow-configzshow-config-jsonÚflagsz#dict[str, t.Any] | Dict[str, t.Any]Úsubcommandsz(traitlets.config.application.Application)Ú
allow_noner;   zÁThe subset of our configuration that came from the command-line

        We re-load this configuration after loading config files,
        to ensure that it maintains highest priority.
        z	List[str]Ú_loaded_config_fileszAInstead of starting the Application, dump configuration to stdoutzKInstead of starting the Application, dump configuration to stdout (as JSON)c                 C  s   |j | _d S r�   )Únewr�   r”   r;   r;   r<   Ú_show_config_json_changed¯  s    z%Application._show_config_json_changedc                 C  s   |j r| j| _| j| _d S r�   )r£   ÚstartZ_save_startÚstart_show_configr”   r;   r;   r<   Ú_show_config_changed³  s    z Application._show_config_changedr/   )r2   r-   c                 K  sR   t j| fi |¤Ž | j}|| jvrN| j|ju r>|g| j¢| _n| j d| j¡ d S )Nr   )r
   Ú__init__rR   r^   Úinsert)rP   r2   Úclsr;   r;   r<   r¨   ¹  s    
zApplication.__init__r7   c                   s    t ƒ  |¡ | j d|j¡ d S )NzConfig changed: %r)rN   Ú_config_changedr4   r6   r£   r”   rQ   r;   r<   r«   Å  s    zApplication._config_changedÚArgvType)r#   r-   c                 C  s   |   |¡ dS )zMDo the basic steps to configure me.

        Override in subclasses.
        N)Úparse_command_line)rP   r#   r;   r;   r<   Ú
initializeË  s    zApplication.initializec                 C  s(   | j dur$t| j tƒsJ ‚| j  ¡ S dS )zAStart the app mainloop.

        Override in subclasses.
        N)ÚsubapprŽ   r.   r¥   ©rP   r;   r;   r<   r¥   Ó  s    
zApplication.startc           
   
   C  s
  | j  ¡ }| j ¡ D ]0}|j|v r||j }| dd¡ | dd¡ q| jrrtj|t	j
ddtd� t	j
 d¡ dS | jržtdƒ | jD ]}td	| ƒ q†tƒ  t|ƒD ]^}|| }|s¸q¦t|ƒ td
dd�}t|ƒD ].}|| }	td|› dtj|	fi |¤Ž› �ƒ qÔq¦dS )z,start function used when show_config is Truer�   Nrž   r3   T)r   Ú	sort_keysr   Ú
zLoaded config files:z  é   )r   Úcompactz  .z = )r7   ÚcopyrR   ra   rD   Úpoprž   ÚjsonÚdumpÚsysÚstdoutÚreprÚwriter¢   ÚprintÚsortedÚdictÚpprintÚpformat)
rP   r7   rª   Z
cls_configÚfÚ	classnameZclass_configZpformat_kwargsÚ	traitnameÚvaluer;   r;   r<   r¦   Ü  s0    



zApplication.start_show_configc                 C  s   t d |  ¡ ¡ƒ dS )z"Print the alias parts of the help.r²   N)r½   ÚjoinÚemit_alias_helpr°   r;   r;   r<   Úprint_alias_helpý  s    zApplication.print_alias_helpzt.Generator[str, None, None]c                 c  sd  | j s
dS i }| jD ]2}| ¡ dd… D ]}t tjt |¡||j< q(q| j  ¡ D �]
\}}zÈt	|t
ƒrr|\}}nd}| d¡dd… \}}|d | }|| }|jdd�| }	|j|	|d� ¡ }
t	|t
ƒsÒ|f}t|td�}d	 d
d„ |D ƒ¡}|
d  d| |¡|
d< |
E dH  td| ƒV  W qR t�y\ } z| j d||¡ ‚ W Y d}~qRd}~0 0 qRdS )z+Yield the lines for alias part of the help.Néýÿÿÿr|   éþÿÿÿTrt   )Zhelptext©Úkeyú, c                 s  s&   | ]}t |ƒd krdnd| V  qdS ©r3   z--%sz-%sN©Úlen©Ú.0Úmr;   r;   r<   Ú	<genexpr>  ó    z.Application.emit_alias_help.<locals>.<genexpr>r   ú--zEquivalent to: [--%s]z7Failed collecting help-message for alias %r, due to: %s)rœ   r^   ra   r@   rA   ÚTyper	   rD   ÚitemsrŽ   ÚtupleÚsplitZclass_traitsZclass_get_trait_helpÚ
splitlinesr¾   rÐ   rÆ   Úreplacer   Ú	Exceptionr4   Úerror)rP   Ú	classdictrª   re   ÚaliasÚlongnameÚfhelprÃ   rÄ   ÚtraitZfhelp_linesÚexr;   r;   r<   rÇ     s4    




zApplication.emit_alias_helpc                 C  s   t d |  ¡ ¡ƒ dS )z Print the flag part of the help.r²   N)r½   rÆ   Úemit_flag_helpr°   r;   r;   r<   Úprint_flag_help'  s    zApplication.print_flag_helpc                 c  sØ   | j s
dS | j  ¡ D ]¾\}\}}zzt|tƒs2|f}t|td�}d dd„ |D ƒ¡}|V  tt| 	¡ ƒƒV  d dd„ | ¡ D ƒ¡}d| }tt|ƒƒV  W q t
yÐ } z| j d	||¡ ‚ W Y d}~qd}~0 0 qdS )
z.Yield the lines for the flag part of the help.NrË   rÍ   c                 s  s&   | ]}t |ƒd krdnd| V  qdS rÎ   rÏ   rÑ   r;   r;   r<   rÔ   5  rÕ   z-Application.emit_flag_help.<locals>.<genexpr>ú c                 s  s:   | ]2\}}|  ¡ D ] \}}d |› d|› d|› �V  qqdS )rÖ   r|   ú=N)rØ   )rÒ   ZclnameZ
props_dictÚpropÚvalr;   r;   r<   rÔ   8  s   þzEquivalent to: [%s]z6Failed collecting help-message for flag %r, due to: %s)rŸ   rØ   rŽ   rÙ   r¾   rÐ   rÆ   r   r   ÚstriprÝ   r4   rÞ   )rP   rŸ   Úcfgrâ   Zcfg_listZcfg_txträ   r;   r;   r<   rå   +  s$    

þzApplication.emit_flag_helpc                 C  s   t d |  ¡ ¡ƒ dS )z#Print the options part of the help.r²   N)r½   rÆ   Úemit_options_helpr°   r;   r;   r<   Úprint_optionsC  s    zApplication.print_optionsc                 c  sj   | j s| jsdS d}|V  dt|ƒ V  t| jƒD ]}|V  dV  q2|  ¡ E dH  |  ¡ E dH  dV  dS )z1Yield the lines for the options part of the help.NÚOptionsrè   r$   )rŸ   rœ   rÐ   r   rY   rå   rÇ   )rP   ÚheaderÚpr;   r;   r<   rí   G  s    zApplication.emit_options_helpc                 C  s   t d |  ¡ ¡ƒ dS )z&Print the subcommand part of the help.r²   N)r½   rÆ   Úemit_subcommands_helpr°   r;   r;   r<   Úprint_subcommandsV  s    zApplication.print_subcommandsc                 c  s†   | j s
dS d}|V  dt|ƒ V  t| jj| jd�ƒD ]}|V  dV  q6| j  ¡ D ](\}\}}|V  |rRtt| 	¡ ƒƒV  qRdV  dS )z4Yield the lines for the subcommand part of the help.NZSubcommandsrè   )r0   r$   )
r    rÐ   r   r[   rO   rW   rØ   r   r   rë   )rP   rð   rñ   ÚsubcÚ_rs   r;   r;   r<   rò   Z  s    z!Application.emit_subcommands_helpÚboolc                 c  s   |sdV  dV  dS )zzYield the very bottom lines of the help message.

        If classes=False (the default), print `--help-all` msg.
        z5To see all available configurables, use `--help-all`.r$   Nr;   ©rP   r^   r;   r;   r<   Úemit_help_epiloguek  s    zApplication.emit_help_epilogueFc                 C  s   t d | j|d�¡ƒ dS )z‘Print the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        r²   ©r^   N)r½   rÆ   Ú	emit_helpr÷   r;   r;   r<   Ú
print_helpt  s    zApplication.print_helpc                 c  s¢   |   ¡ E dH  |  ¡ E dH  |  ¡ E dH  |r€|  ¡ }|durfdV  dV  t| jƒD ]}|V  dV  qT|D ]}| ¡ V  dV  qj|  ¡ E dH  |  |¡E dH  dS )z—Yield the help-lines for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        NzClass optionsz=============r$   )	Úemit_descriptionrò   rí   Ú_classes_with_config_traitsr   rZ   Zclass_get_helpÚemit_examplesrø   )rP   r^   Zhelp_classesrñ   rª   r;   r;   r<   rú   {  s     
zApplication.emit_helprH   c                 C  s   d  dd„ |  ¡ D ƒ¡S )zwGenerate rST format documentation for the config options this application

        Returns a multiline string.
        r²   c                 s  s   | ]}|  ¡ V  qd S r�   )Zclass_config_rst_doc)rÒ   re   r;   r;   r<   rÔ   ™  rÕ   z6Application.document_config_options.<locals>.<genexpr>)rÆ   rg   r°   r;   r;   r<   Údocument_config_options”  s    z#Application.document_config_optionsc                 C  s   t d |  ¡ ¡ƒ dS )z"Print the application description.r²   N)r½   rÆ   rü   r°   r;   r;   r<   Úprint_description›  s    zApplication.print_descriptionc                 c  s*   t | jp| jpdƒD ]}|V  dV  qdS )z-Yield lines with the application description.r$   N)r   rX   rS   )rP   rñ   r;   r;   r<   rü   Ÿ  s    zApplication.emit_descriptionc                 C  s   t d |  ¡ ¡ƒ dS )z1Print usage and examples (see `emit_examples()`).r²   N)r½   rÆ   rþ   r°   r;   r;   r<   Úprint_examples¥  s    zApplication.print_examplesc                 c  s6   | j r2dV  dV  dV  tt| j  ¡ ƒƒV  dV  dS )z¼Yield lines with the usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        ZExamplesz--------r$   N)r\   r   r   rë   r°   r;   r;   r<   rþ   ©  s    zApplication.emit_examplesc                 C  s   t | jƒ dS )zPrint the version string.N)r½   rh   r°   r;   r;   r<   Úprint_version¶  s    zApplication.print_version)rô   r#   r-   c                 C  s�   | j  |¡}|dusJ ‚|\}}t|tƒr2t|ƒ}t|tƒr`t|tƒr`| j 	¡  |j
| d�| _n t|ƒrt|| ƒ| _ntd| ƒ‚| j |¡ dS )z"Initialize a subcommand with argv.N)rf   z%Invalid mappings for subcommand '%s'!)r    ÚgetrŽ   rH   r"   r“   rb   r.   rR   Zclear_instanceÚinstancer¯   ÚcallableÚAssertionErrorr®   )rP   rô   r#   rê   r¯   rõ   r;   r;   r<   Úinitialize_subcommandº  s    

z!Application.initialize_subcommandz)tuple[dict[str, t.Any], dict[str, t.Any]]c                 C  sf  t tƒ}| jD ]0}|j}| ¡ dd… D ]}||j  |¡ q(qi }| j ¡ D ]r\}}t|t	ƒrh|\}}| 
dd¡\}}	|| }
t|
ƒdkr”|
d }t|t	ƒs¤|f}|D ]}d ||	g¡||< q¨qNi }| j ¡ D ]Œ\}\}}i }| ¡ D ]H\}}|| }
t|
ƒdk�r|
d }||v �r(||  |¡ qè|||< qèt|t	ƒ�sD|f}|D ]}||f||< �qHqÐ||fS )aä  Flatten flags and aliases for loaders, so cl-args override as expected.

        This prevents issues such as an alias pointing to InteractiveShell,
        but a config file setting the same trait in TerminalInteraciveShell
        getting inappropriate priority over the command-line arg.
        Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items.

        Only aliases with exactly one descendent in the class list
        will be promoted.

        r3   rÉ   r|   r   )r   Úlistr^   rD   ra   Úappendrœ   rØ   rŽ   rÙ   rÚ   rÐ   rÆ   rŸ   Úupdate)rP   Zmro_treerª   Úclsnamerf   rœ   rà   rá   rõ   rã   ÚchildrenÚalrŸ   rÌ   Zflagdictrs   ZnewflagZsubdictÚkr;   r;   r<   Úflatten_flagsÓ  s@    




zApplication.flatten_flagszlist[str] | Noner   )r#   rœ   rŸ   r^   r-   c                 C  s   t ||||| j| jd�S )N)r^   r4   r    )r   r4   r    )rP   r#   rœ   rŸ   r^   r;   r;   r<   Ú_create_loader  s    ÿzApplication._create_loaderz	list[str])Úcheck_argcompleter-   c              	   C  sP   |rJdt jv rJz$ddlm} |ƒ }|dus.J ‚|W S  ttfyH   Y n0 tjS )a  Get `sys.argv` or equivalent from `argcomplete`

        `argcomplete`'s strategy is to call the python script with no arguments,
        so ``len(sys.argv) == 1``, and run until the `ArgumentParser` is constructed
        and determine what completions are available.

        On the other hand, `traitlet`'s subcommand-handling strategy is to check
        ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically
        load the subcommand app and initialize it with ``sys.argv[1:]``.

        This helper method helps to take the current tokens for `argcomplete` and pass
        them through as `argv`.
        Ú_ARGCOMPLETEr   )Úget_argcomplete_cwordsN)ÚosÚenvironÚ#traitlets.config.argcomplete_configr  ÚImportErrorÚModuleNotFoundErrorr¹   r#   )rª   r  r  Úcwordsr;   r;   r<   Ú_get_sys_argv  s    zApplication._get_sys_argvc              	   C  s@   dt jvrdS zddlm} |ƒ  W n ttfy:   Y n0 dS )aß  Helper for `argcomplete` to recognize `traitlets` subcommands

        `argcomplete` does not know that `traitlets` has already consumed subcommands,
        as it only "sees" the final `argparse.ArgumentParser` that is constructed.
        (Indeed `KVArgParseConfigLoader` does not get passed subcommands at all currently.)
        We explicitly manipulate the environment variables used internally by `argcomplete`
        to get it to skip over the subcommand tokens.
        r  Nr   )Úincrement_argcomplete_index)r  r  r  r  r  r  )rª   r  r;   r;   r<   Ú"_handle_argcomplete_for_subcommand3  s    


z.Application._handle_argcomplete_for_subcommandc                   s¤  t |tƒrJ ‚|du r0| jt| jƒd�dd… }dd„ |D ƒ| _|rb|d dkrb|dd… dg }| jr´t|ƒdkr´|d |dd…  }}t d	|¡r´|| jv r´|  	¡  |  
||¡S z|d| d
¡… ‰ W n tyà   |‰ Y n0 t‡ fdd„dD ƒƒ�r|  dˆ v ¡ |  d¡ dˆ v �s&dˆ v �r8|  ¡  |  d¡ |  ¡ \}}t|  ¡ ƒ}| j||||d�}zt| ¡ ƒ| _W n t�yŠ   ‚ Y n0 |  | j¡ |j| _dS )z!Parse the command line arguments.N)r  r3   c                 S  s   g | ]}t |ƒ‘qS r;   r    )rÒ   Úargr;   r;   r<   Ú
<listcomp>M  rÕ   z2Application.parse_command_line.<locals>.<listcomp>r   rs   ú-hz^\w(\-?\w)*$rÖ   c                 3  s   | ]}|ˆ v V  qd S r�   r;   )rÒ   Úx©Zinterpreted_argvr;   r<   rÔ   d  rÕ   z1Application.parse_command_line.<locals>.<genexpr>)r  ú
--help-allz--helpr"  z	--versionz-Vrù   )rŽ   rH   r  rö   r    r#   rÐ   ÚreÚmatchr  r  ÚindexÚ
ValueErrorÚanyrû   r8   r  r  r  rý   r  r   Úload_configÚ
cli_configÚ
SystemExitÚupdate_configÚ
extra_args)rP   r#   rô   ZsubargvrŸ   rœ   r^   Úloaderr;   r!  r<   r­   G  s<    


zApplication.parse_command_linez#str | t.Sequence[str | None] | NonezAnyLogger | Nonezt.Generator[t.Any, None, None])ÚbasefilenameÚpathr4   Úraise_config_file_errorsr-   c                 c  sZ  t |tƒs|du r|g}t|ƒD �]2}| j|d ||d�}|rT| d||pPt ¡ ¡ | j|d ||d�}g }g }	||fD ]Ú}
d}z|
 ¡ }W nF t	yž   Y nH t
yÒ   |
jp²|}|rº‚ |rÎ|jd|dd� Y n0 |ræ| d	|
j¡ |rxt|	|ƒD ]:\}}| |¡}|rô|rô| d
 ||
jtj|dd�¡¡ qô||
jfV  | |¡ |	 |
j¡ qxq dS )zeLoad config files (py,json) by filename and path.

        yield each config object in turn.
        Nz.py)r/  r4   zLooking for %s in %sz.jsonz&Exception while loading config file %sT)Úexc_infozLoaded config file: %szMCollisions detected in {0} and {1} config files. {1} has higher priority: {2}r   )r   )rŽ   rH   r`   Úpython_config_loader_classr6   r  ÚgetcwdÚjson_config_loader_classr(  r   rÝ   Zfull_filenamerÞ   ÚzipÚ
collisionsÚwarningrO   r·   Údumpsr	  )rª   r.  r/  r4   r0  ÚcurrentZpyloaderZ
jsonloaderZloadedÚ	filenamesr-  r7   ÚfilenameZearlier_configr6  r;   r;   r<   Ú_load_config_filesz  sJ    

üÿ
zApplication._load_config_filesc                 C  s   | j dd… S )z$Currently loaded configuration filesN)r¢   r°   r;   r;   r<   Úloaded_config_files²  s    zApplication.loaded_config_files)r;  r/  r-   c                 C  sp   t j |¡\}}tƒ }| j||| j| jd�D ](\}}| |¡ || jvr,| j 	|¡ q,| | j
¡ |  |¡ dS )z'Load config files by filename and path.)r/  r4   r0  N)r  r/  Úsplitextr   r<  r4   r0  Úmerger¢   r	  r)  r+  )rP   r;  r/  ÚextZ
new_configr7   Úfnamer;   r;   r<   Úload_config_file·  s    ü
ÿzApplication.load_config_filec                 #  sˆ   |du r| j }tdd„ |  |¡D ƒƒ‰ dddœ‡ fdd„‰ˆ  ¡ }t‡fd	d„ˆ  ¡ D ƒƒ‰ ˆ |kr:qhq:ˆ  ¡ D ]\}}|rp|V  qpdS )
aË  
        Yields only classes with configurable traits, and their subclasses.

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Thus, produced sample config-file will contain all classes
        on which a trait-value may be overridden:

        - either on the class owning the trait,
        - or on its subclasses, even if those subclasses do not define
          any traits themselves.
        Nc                 s  s"   | ]}|t |jd d�ƒfV  qdS )Trt   N)rö   Zclass_own_traits)rÒ   rª   r;   r;   r<   rÔ   à  s   ÿz:Application._classes_with_config_traits.<locals>.<genexpr>r/   rö   )rª   r-   c                   s   t ‡ fdd„| jD ƒƒS )Nc                 3  s   | ]}|ˆ v oˆ | V  qd S r�   r;   )rÒ   Úb©Úcls_to_configr;   r<   rÔ   æ  rÕ   zZApplication._classes_with_config_traits.<locals>.is_any_parent_included.<locals>.<genexpr>)r'  Ú	__bases__)rª   rD  r;   r<   Úis_any_parent_includedå  s    zGApplication._classes_with_config_traits.<locals>.is_any_parent_includedc                 3  s"   | ]\}}||pˆ |ƒfV  qd S r�   r;   )rÒ   rª   Úinc_yes)rG  r;   r<   rÔ   í  s   ÿ)r^   r   rg   rµ   rØ   )rP   r^   Zto_incl_origÚclrH  r;   )rE  rG  r<   rý   Í  s    þþz'Application._classes_with_config_traitsc                 C  sn   d| j  g}| d¡ | d¡ | d¡ |du r8| jn|}t|  |¡ƒ}|D ]}| | |¡¡ qNd |¡S )z/generate default config file from Configurablesz# Configuration file for %s.r$   zc = get_config()  #noqaNr²   )rW   r	  r^   r  rý   Zclass_config_sectionrÆ   )rP   r^   ÚlinesZconfig_classesrª   r;   r;   r<   Úgenerate_config_file÷  s    


z Application.generate_config_filec              	   C  sT   t | ddƒrP| jjD ]4}ttƒ� | ¡  W d   ƒ q1 s>0    Y  qd| _d S )Nr–   F)r�   r4   r~   r   rÝ   Úcloser–   )rP   Úhandlerr;   r;   r<   Úclose_handlers  s
    
(zApplication.close_handlersr   zint | str | None)Úexit_statusr-   c                 C  s(   | j  d| j ¡ |  ¡  t |¡ d S )NzExiting application: %s)r4   r6   rW   rN  r¹   r8   )rP   rO  r;   r;   r<   r8     s    zApplication.exitc                 C  s   |   ¡  d S r�   )rN  r°   r;   r;   r<   Ú__del__  s    zApplication.__del__)r#   r2   r-   c                 K  s&   | j f i |¤Ž}| |¡ | ¡  dS )z„Launch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        N)r  r®   r¥   )rª   r#   r2   r0   r;   r;   r<   Úlaunch_instance  s    
zApplication.launch_instance)N)N)F)F)N)F)N)NF)N)N)N)r   )N)brD   rE   rF   rS   r   rW   Ú__annotations__rX   rY   rZ   r[   r   r2  r   r4  r\   r^   rg   rh   r   r#   r   r%   r0  r   rT   rU   Útagrƒ   rG   r„   r†   r…   r‰   r   r’   r•   r‘   r   r›   r   rŠ   rœ   rn   rŸ   r    r   r¯   r,  r   r)  r¢   r�   rž   r¤   r§   r¨   r   r«   rB   r®   r¥   r¦   rÈ   rÇ   ræ   rå   rî   rí   ró   rò   rø   rû   rú   rÿ   r   rü   r  rþ   r  r  r  r  Úclassmethodr  r  r­   r<  Úpropertyr=  rB  rý   rK  rN  r8   rP  rQ  rV   r;   r;   rQ   r<   r.   —   s  
 ÿýüÿþþý3
ÿ0Ð7	ÿÿú
ÿÿú
ÿÿúï 
üÿþÿþ	!&	;2  û7 ÿ ÿ*
r.   rH   ru   )rW   ÚconfigurableÚset_helpÚ
unset_helpr-   c                 C  sV   |p
d| }|pd| }|  d¡\}}||dii}||dii}| ||fd|  ||fiS )aû  Helper for building basic --trait, --no-trait flags.

    Parameters
    ----------
    name : str
        The name of the flag.
    configurable : str
        The 'Class.trait' string of the trait to be set/unset with the flag
    set_help : unicode
        help string for --name flag
    unset_help : unicode
        help string for --no-name flag

    Returns
    -------
    cfg : dict
        A dict with two keys: 'name', and 'no-name', for setting and unsetting
        the trait, respectively.
    zset %s=Truezset %s=Falser|   TFzno-)rÚ   )rW   rV  rW  rX  rª   rã   ÚsetterZunsetterr;   r;   r<   Úboolean_flag(  s    rZ  r   rv   c                   C  s   t  ¡ rt  ¡ jS tƒ S dS )z|Get the config object for the global Application instance, if there is one

    otherwise return an empty config object
    N)r.   Zinitializedr  r7   r   r;   r;   r;   r<   Ú
get_configG  s    
r[  Ú__main__)r$   r$   )brS   Ú
__future__r   r>   r·   rT   r  rÀ   r#  r¹   Útypingr@   Úcollectionsr   r   Ú
contextlibr   rµ   r   Úlogging.configr   Útextwrapr   Ztraitlets.config.configurabler	   r
   Ztraitlets.config.loaderr   r   r   r   r   r   Ztraitlets.traitletsr   r   r   r   r   r   r   r   r   r   Ztraitlets.utils.bunchr   Ztraitlets.utils.nested_updater   Ztraitlets.utils.textr   r   Úutilsr!   Zutils.importstringr"   rë   rY   rZ   Úhasattrr#   r[   r  r  Z_envvarÚlowerr%   r&  Ú
executableÚendswithr‡   ÚTypeVarÚCallableÚAnyr*   ÚUnionÚLoggerÚLoggerAdapterr—   rH   ru   ÚOptionalr¬   r×   r]   rB   rÝ   rC   Ú	FormatterrG   r.   rœ   Zdefault_aliasesrŸ   Zdefault_flagsrZ  r[  rD   rQ  r;   r;   r;   r<   Ú<module>   sx    0
ÿÿ       
