
    Mh	                    r   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 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/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 d8                                Z9d8                                Z: e;e	d          sdge	_<        dZ=ej>        ?                    dd          Z@e@A                                dv rdZBn'e@A                                dv rdZBn eCde@z            e	jD        oe	jD        E                    d          ZF ejG        dejH        dejI        f                    ZJejK        ejL        d!f         ZMej$        eNejI        f         ZOejP        ej'        eN                  ZQej'        ejR        e                  ZSd5d$ZT G d% d&eU          ZV G d' d(ejW                  ZX G d) d*e          ZYeYjZ        Z[eYj\        Z]d6d7d1Z^d8d3Z_e`d4k    reYa                                 dS dS )9z,A base class for a configurable application.    )annotationsN)OrderedDictdefaultdict)suppress)deepcopy)
dictConfig)dedent)ConfigurableSingletonConfigurable)ArgumentErrorConfigConfigFileNotFoundDeferredConfigString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>   1trueT>   r&   0falseFzUnsupported 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.)boundzlogging.LoggerAdapter[t.Any]methodreturnc                x     t          j                   d fd            }t          j        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.
    appApplicationargst.Anykwargsr/   c                    	  | g|R i |S # t           t          f$ r[}| j                            d|           | j                            d| j                   |                     d           Y d }~d S d }~ww xY w)Nz0Bad config encountered during initialization: %szConfig at the time: %s   )r   r   logfataldebugconfigexit)r1   r3   r5   er.   s       \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/traitlets/config/application.pyinnerz!catch_config_error.<locals>.inners   s    	6#///////M* 	 	 	GMMLaPPPGMM2CJ???HHQKKKKKKKKK	s    A;AA66A;)r1   r2   r3   r4   r5   r4   r/   r4   )	functoolswrapstcastr,   )r.   r?   s   ` r>   catch_config_errorrD   j   sL     _V      6!U    c                      e Zd ZdS )ApplicationErrorN)__name__
__module____qualname__ rE   r>   rG   rG      s        DrE   rG   c                  6     e Zd ZdZej        ZdZd fdZ x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 |recordlogging.LogRecordr/   strc                    |j         | j        k    r| j        |j        z  |_        nd|_        t                                          |          S )Nr&   )levelnohighlevel_limithighlevel_format__dict__	highlevelsuperformat)selfrN   	__class__s     r>   rX   zLevelFormatter.format   sF    >T111#4vFF!Fww~~f%%%rE   )rN   rO   r/   rP   )
rH   rI   rJ   __doc__loggingWARNrS   rT   rX   __classcell__rZ   s   @r>   rM   rM      sV          lO)& & & & & & & & & &rE   rM   c                      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<   	 dddZ ed          Zded<    e            Zded<    ee          Z edej        d                              d          ZeZ edd                              d          Z edd                              d          Z dd!Z! e"d"d#d$d%          dd)            Z# e"d*d+,          dd-            Z$dd.Z% e&d*          dd0            Z' e(d1                              d          Z)d2d3iZ*d ed4<   d d$ej+        iid5fd d6diid7fd d8diid9fd:Z,d ed;<    e(            Z-d<ed=<    e.d>d?          Z/ e e                      Z0 e.e1d@i dA          Z2 e            Z3dBedC<    edD                              d          Z4 edE                              d          Z5 e"d8          ddF            Z6 e"d6          ddG            Z7ddJZ8 e"dK          e9d fdL                        Z:e;dddN            Z<ddOZ=ddPZ>ddQZ?ddSZ@ddTZAddUZBddVZCddWZDddXZEddYZFdd[ZGddd]ZHddd^ZIdd`ZJddaZKddbZLddcZMdddZNddeZOe;dddg            ZPddiZQddlZReSdddo            ZTeSddp            ZUe;dddq            ZVeS	 	 dddx            ZWeXddy            ZYe;	 ddd{            ZZe;dd|            Z[	 ddd}Z\ddd~Z]ddZ^dddZ_ddZ`eSddd            Za xZbS )r2   z8A singleton application with full configuration support.applicationzstr | Unicode[str, str | bytes]namezThis is an application.descriptionoption_descriptionkeyvalue_descriptionsubcommand_descriptionexamplesClassesTypeclassesNClassesType | Noner/   +t.Generator[type[Configurable], None, None]c              #     K   || j         }t                      }|D ]X}t          |                                          D ]4}t	          |t
                    r||vr|                    |           |V  5Yd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)ri   setreversedmro
issubclassr
   add)rY   ri   seencparents        r>   _classes_inc_parentsz Application._classes_inc_parents   s       ?lGuu 	! 	!A"15577++ ! !fl33 !t9K9KHHV$$$ LLL!	! 	!rE   z0.0versionzlist[str] | List[str]r%   )r   
         (   2   DEBUGINFOr]   ERRORCRITICALz#Set the log level by value or name.)default_valuehelpTr;   z%Y-%m-%d %H:%M:%Sz:The date format used by logging formatters for %(asctime)s)r   z#[%(name)s]%(highlevel)s %(message)szThe Logging format templateStrDictc                    ddddt          j        | j                  ddid| j        j         d| j        j         | j        | j        di| j        j        ddgd	id
d}t          r|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.

        r7   consolezlogging.StreamHandlerzext://sys.stderr)class	formatterlevelstream.)r   rX   datefmtr|   )r   handlersF)rv   r   
formattersloggersdisable_existing_loggersr   r   )
r\   getLevelName	log_level_log_formatter_clsrI   rH   
log_formatlog_datefmtrZ   
IS_PYTHONWrY   r;   s     r>   get_default_logging_configz&Application.get_default_logging_config   s     4!*$1$.AA0	  2= ? ? 3<? ? #o#/ 	 '$!** * ).5
 
:  	" z"y!rE   r   r   r   logging_configchanger   Nonec                    | j         }t          |t                    r2t          j        t
          t          t          |                    | _         |                                  d S N)	r   
isinstancerP   rB   rC   intgetattrr\   _configure_logging)rY   r   r   s      r>   _observe_logging_changez#Application._observe_logging_change  sS     N	i%% 	FVC))D)DEEDN!!!!!rE   r8   r   )typec                .    |                                   d S r   )r   rY   r   s     r>   _observe_logging_defaultz$Application._observe_logging_default  s    !!!!!rE   c                    |                                  }t          || j        pi            t          |           d| _        d S )NT)r   r   r   r   _logging_configuredr   s     r>   r   zApplication._configure_logging!  sG    0022fd17R8886#'   rE   	AnyLoggerc                    t          j        | j        j                  }d|_        |}||j        r|S |j        sn	|j        }||S )z#Start logging for this application.F)r\   	getLoggerrZ   rH   	propagater   rt   )rY   r8   _logs      r>   _log_defaultzApplication._log_default(  s]      788} 
> ;D  
rE   a!  
            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))r:   zshow-configzshow-config-jsonflagsz#dict[str, t.Any] | Dict[str, t.Any]subcommandsz(traitlets.config.application.Application)
allow_nonerK   zThe 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                    |j         | _        d S r   )newr   r   s     r>   _show_config_json_changedz%Application._show_config_json_changed  s    !:rE   c                H    |j         r| j        | _        | j        | _        d S d S r   )r   start_save_startstart_show_configr   s     r>   _show_config_changedz Application._show_config_changed  s.    : 	0#zD/DJJJ	0 	0rE   r5   r4   c                    t          j        | fi | | j        }|| j        vrA| j        |j        u r|g| j        | _        d S | j                            d| j                   d S d S )Nr   )r   __init__rZ   ri   insert)rY   r5   clss      r>   r   zApplication.__init__  s}    &t66v666 ndl""|s{** #3dl3##At~66666 #"rE   r;   c                    t                                          |           | j                            d|j                   d S )NzConfig changed: %r)rW   _config_changedr8   r:   r   )rY   r   rZ   s     r>   r   zApplication._config_changed  s<     	'''+VZ88888rE   ArgvTypec                0    |                      |           dS )zMDo the basic steps to configure me.

        Override in subclasses.
        N)parse_command_line)rY   r%   s     r>   
initializezApplication.initialize  s     	%%%%%rE   c                ~    | j         5t          | j         t                    sJ | j                                         S dS )zAStart the app mainloop.

        Override in subclasses.
        N)subappr   r2   r   rY   s    r>   r   zApplication.start  s@    
 ;"dk;77777;$$&&& #"rE   c                   | j                                         }| j                                        D ]D}|j        |v r9||j                 }|                    dd           |                    dd           E| j        rIt          j        |t          j
        ddt                     t          j
                            d           dS | j        r9t          d           | j        D ]}t          d	|z              t                       t          |          D ]l}||         }|st          |           t!          d
d          }t          |          D ]/}||         }	t          d| dt#          j        |	fi |            0mdS )z,start function used when show_config is Truer   Nr   r7   T)r   	sort_keysr   
zLoaded config files:z     )r   compactz  .z = )r;   copyrZ   ro   rH   popr   jsondumpsysstdoutreprwriter   printsorteddictpprintpformat)
rY   r;   r   
cls_configf	classnameclass_configpformat_kwargs	traitnamevalues
             r>   r   zApplication.start_show_config  s   !!##>%%'' 	9 	9C|v%%#CL1
}d33314888  	IfcjdDQQQQJT"""F$ 	())).    dQhGGG 		U 		UI!),L )&*!T&B&B&BN#L11 U U	$Y/SISS&.*Q*Q.*Q*QSSTTTTU		U 		UrE   c                n    t          d                    |                                                      dS )z"Print the alias parts of the help.r   N)r   joinemit_alias_helpr   s    r>   print_alias_helpzApplication.print_alias_help  s.    dii,,..//00000rE   t.Generator[str, None, None]c              #    K   | j         sdS i }| j        D ]S}|                                dd         D ]4}t          j        t          j        t                   |          ||j        <   5T| j                                         D ]S\  }}	 t          |t                    r|\  }}nd}|                    d          dd         \  }}|dz   |z   }||         }|                    d          |         }	|                    |	|                                          }
t          |t                    s|f}t          |t                     }d	                    d
 |D                       }|
d                             d|z   |          |
d<   |
E d{V  t'          d|z            V  &# t(          $ r"}| j                            d||            d}~ww xY wdS )z+Yield the lines for alias part of the help.Nr   Tr   )helptextkey, c              3  J   K   | ]}t          |          d k    rdnd|z  V  dS r7   z--%sz-%sNlen.0ms     r>   	<genexpr>z.Application.emit_alias_help.<locals>.<genexpr>  9      !W!WASVVaZZ66Ua"G!W!W!W!W!W!WrE   r   --zEquivalent to: [--%s]z7Failed collecting help-message for alias %r, due to: %s)r   ri   ro   rB   rC   Typer
   rH   itemsr   tuplesplitclass_traitsclass_get_trait_help
splitlinesr   r   r   replacer   	Exceptionr8   error)rY   	classdictr   rs   aliaslongnamefhelpr   r   traitfhelp_linesexs               r>   r   zApplication.emit_alias_help  s!     | 	F35	< 	H 	HCWWYYss^ H H()qvl/CQ(G(G	!*%%H  $|1133 	 	OE8h.. !&.OHee E'/~~c':':233'?$	9$s?Y6	*(((55i@!66uu6MMXXZZ!%// %"HEu#...		!W!WQV!W!W!WWW "-Q!7!7x!O!OA&&&&&&&&4x?@@@@@@   XZ_acddd-	 	s   	DF((
G2GGc                n    t          d                    |                                                      dS )z Print the flag part of the help.r   N)r   r   emit_flag_helpr   s    r>   print_flag_helpzApplication.print_flag_help'  s.    dii++--../////rE   c              #  l  K   | j         sdS | j                                         D ]\  }\  }}	 t          |t                    s|f}t	          |t
                    }d                    d |D                       }|V  t          t          |	                                                    V  d                    d |                                D                       }d|z  }t          t          |                    V  # t          $ r"}| j                            d||            d}~ww xY wdS )	z.Yield the lines for the flag part of the help.Nr   r   c              3  J   K   | ]}t          |          d k    rdnd|z  V  dS r   r   r   s     r>   r   z-Application.emit_flag_help.<locals>.<genexpr>5  r   rE    c              3  f   K   | ],\  }}|                                 D ]\  }}d | d| d| V  -dS )r   r   =N)r   )r   clname
props_dictpropvals        r>   r   z-Application.emit_flag_help.<locals>.<genexpr>8  sy       $ $*
%/%5%5%7%7$ $ "c /..$....$ $ $ $ $ $ $rE   zEquivalent to: [%s]z6Failed collecting help-message for flag %r, due to: %s)r   r   r   r   r   r   r   r   r	   stripr  r8   r  )rY   r   cfgr  cfg_listcfg_txtr	  s          r>   r  zApplication.emit_flag_help+  s`     z 	F#':#3#3#5#5 	 	E<C!%// %"HEu#...		!W!WQV!W!W!WWWVEKKMM223333388 $ $.1iikk$ $ $  
 0(:VG__------   WY^`bccc	 	s   CD
D1D,,D1c                n    t          d                    |                                                      dS )z#Print the options part of the help.r   N)r   r   emit_options_helpr   s    r>   print_optionszApplication.print_optionsC  s.    dii..001122222rE   c              #    K   | j         s	| j        sdS d}|V  dt          |          z  V  t          | j                  D ]
}|V  dV  |                                 E d{V  |                                 E d{V  dV  dS )z1Yield the lines for the options part of the help.NOptionsr  r&   )r   r   r   r    rd   r  r   )rY   headerps      r>   r  zApplication.emit_options_helpG  s      z 	$, 	FCKK !899 	 	AGGGHHHH&&((((((((('')))))))))rE   c                n    t          d                    |                                                      dS )z&Print the subcommand part of the help.r   N)r   r   emit_subcommands_helpr   s    r>   print_subcommandszApplication.print_subcommandsV  s.    dii22445566666rE   c              #  x  K   | j         sdS d}|V  dt          |          z  V  t          | j                            | j                            D ]
}|V  dV  | j                                         D ]>\  }\  }}|V  |r0t          t          |	                                                    V  ?dV  dS )z4Yield the lines for the subcommand part of the help.NSubcommandsr  )r1   r&   )
r   r   r    rf   rX   rb   r   r   r	   r  )rY   r  r   subc_r   s         r>   r"  z!Application.emit_subcommands_helpZ  s       	FCKK !<!C!C	!C!R!RSS 	 	AGGGHHHH#/5577 	3 	3OD)1dJJJ 3VDJJLL1122222rE   boolc              #  "   K   |s
dV  dV  dS 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&   NrK   rY   ri   s     r>   emit_help_epiloguezApplication.emit_help_epiloguek  s3      
  	IIIIHHHHH	 	rE   Fc                r    t          d                    |                     |                               dS )zPrint the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        r   ri   N)r   r   	emit_helpr*  s     r>   
print_helpzApplication.print_helpt  s2    
 	diiw778899999rE   c              #    K   |                                  E d{V  |                                 E d{V  |                                 E d{V  |r\|                                 }|'dV  dV  t	          | j                  D ]
}|V  dV  |D ]}|                                V  dV  |                                 E d{V  |                     |          E d{V  dS )zYield 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    re   class_get_helpemit_examplesr+  )rY   ri   help_classesr   r   s        r>   r.  zApplication.emit_help{  s[     
 ((*********--/////////))+++++++++ 	;;==L'%%%%%%%%()BCC  AGGGHHHH#  ((*****%%'''''''''**733333333333rE   rP   c                d    d                     d |                                 D                       S )zwGenerate rST format documentation for the config options this application

        Returns a multiline string.
        r   c              3  >   K   | ]}|                                 V  d S r   )class_config_rst_doc)r   rs   s     r>   r   z6Application.document_config_options.<locals>.<genexpr>  s.      WWa//11WWWWWWrE   )r   ru   r   s    r>   document_config_optionsz#Application.document_config_options  s1    
 yyWW4;T;T;V;VWWWWWWrE   c                n    t          d                    |                                                      dS )z"Print the application description.r   N)r   r   r1  r   s    r>   print_descriptionzApplication.print_description  s.    dii--//0011111rE   c              #  Z   K   t          | j        p| j        pd          D ]
}|V  dV  dS )z-Yield lines with the application description.r&   N)r    rc   r[   )rY   r   s     r>   r1  zApplication.emit_description  sJ       !1!GT\!GRHH 	 	AGGGHHHH	 	rE   c                n    t          d                    |                                                      dS )z1Print usage and examples (see `emit_examples()`).r   N)r   r   r4  r   s    r>   print_exampleszApplication.print_examples  s.    dii**,,--.....rE   c              #     K   | j         rGdV  dV  dV  t          t          | j                                                             V  dV  dS dS )zYield 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.
        Examplesz--------r&   N)rg   r   r	   r  r   s    r>   r4  zApplication.emit_examples  st       = 	HHH 3 3 5 56677777HHHHH	 	rE   c                .    t          | j                   dS )zPrint the version string.N)r   rv   r   s    r>   print_versionzApplication.print_version  s    dlrE   r&  c                   | j                             |          }|J |\  }}t          |t                    rt	          |          }t          |t
                    rJt          |t                    r5| j        	                                 |
                    |           | _        n2t          |          r ||           | _        nt          d|z            | j                            |           dS )z"Initialize a subcommand with argv.N)rt   z%Invalid mappings for subcommand '%s'!)r   getr   rP   r$   r   rp   r2   rZ   clear_instanceinstancer   callableAssertionErrorr   )rY   r&  r%   r  r   r'  s         r>   initialize_subcommandz!Application.initialize_subcommand  s     ""4((	fc"" 	) ((F fd## 		Q
6;(G(G 		QN))+++ ///66DKKf 	Q &,,DKK !H4!OPPP 	t$$$$$rE   )tuple[dict[str, t.Any], dict[str, t.Any]]c                   t          t                    }| j        D ]H}|j        }|                                dd         D ]"}||j                                     |           #Ii }| j                                        D ]\  }}t          |t                    r|\  }}|
                    dd          \  }}	||         }
t          |
          dk    r|
d         }t          |t                    s|f}|D ]}d                    ||	g          ||<   i }| j                                        D ]\  }\  }}i }|                                D ]M\  }}||         }
t          |
          dk    r|
d         }||v r||                             |           H|||<   Nt          |t                    s|f}|D ]	}||f||<   
||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.

        r7   r   r   r   )r   listri   rH   ro   appendr   r   r   r   r   r   r   r   update)rY   mro_treer   clsnamert   r   r  r  r'  r  childrenalr   r   flagdictr   newflagsubdictks                      r>   flatten_flagszApplication.flatten_flags  s    t$$< 	: 	:ClG''))AbD/ : :)009999:
 #%#|1133 	5 	5OE8(E** '&!!Q//JC}H8}}!!qkgu-- ! 5 5!hhU|445
 %)Z%5%5%7%7 	+ 	+!C!(D*,G ( 0 0 	+ 	+W#C=x==A%%"1+C'>>CL''0000#*GCLLc5)) f + +#T?a+g~rE   list[str] | Noner   c                @    t          ||||| j        | j                  S )N)ri   r8   r   )r   r8   r   )rY   r%   r   r   ri   s        r>   _create_loaderzApplication._create_loader  s-     &'5'txTM]
 
 
 	
rE   check_argcomplete	list[str]c                    |r<dt           j        v r.	 ddlm}  |            }|J |S # t          t
          f$ r Y nw xY w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_cwords)osenviron#traitlets.config.argcomplete_configr_  ImportErrorModuleNotFoundErrorr   r%   )r   r[  r_  cwordss       r>   _get_sys_argvzApplication._get_sys_argv  s{      	2:!=!=VVVVVV//11)))!45   xs   ( <<c                x    dt           j        vrdS 	 ddlm}  |             dS # t          t
          f$ r Y dS w xY w)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`  ra  rb  rh  rc  rd  )r   rh  s     r>   "_handle_argcomplete_for_subcommandz.Application._handle_argcomplete_for_subcommand3  sj     ++F	WWWWWW'')))))01 	 	 	DD	s   $ 99c                   t          |t                    rJ |0|                     t          | j                            dd         }d |D             | _        |r|d         dk    r|dd         dgz   }| j        rmt          |          dk    rZ|d         |dd         }}t          j        d|          r3|| j        v r*| 	                                 | 
                    ||          S 	 |d|                    d	                   n# t          $ r |Y nw xY wt          fd
dD                       r,|                     dv            |                     d           dv sdv r)|                                  |                     d           |                                 \  }}t%          |                                           }|                     ||||          }	 t+          |                                          | _        n# t0          $ r  w xY w|                     | j                   |j        | _        dS )z!Parse the command line arguments.N)r[  r7   c                ,    g | ]}t          |          S rK   r"   )r   args     r>   
<listcomp>z2Application.parse_command_line.<locals>.<listcomp>M  s     7773\#&&777rE   r   r   -hz^\w(\-?\w)*$r   c              3      K   | ]}|v V  	d S r   rK   )r   xinterpreted_argvs     r>   r   z1Application.parse_command_line.<locals>.<genexpr>d  s)      MMq$$MMMMMMrE   )rn  
--help-allz--helprr  z	--versionz-Vr-  )r   rP   rf  r(  r   r%   r   rematchri  rI  index
ValueErroranyr/  r<   rB  rW  rL  r2  rZ  r   load_config
cli_config
SystemExitupdate_config
extra_args)	rY   r%   r&  subargvr   r   ri   loaderrq  s	           @r>   r   zApplication.parse_command_lineG  s    dC(((((<%%T=M8N8N%OOPQPRPRSD77$777	 	%DGv%%8tf$D 	AD		A GT!""X'Dx.. A44;K3K3K7799911$@@@	$#$6djj&6&6$67 	$ 	$ 	$#	$ MMMM.LMMMMM 	OOL,<<===IIaLLL***d6F.F.F   IIaLLL ++--wt7799::$$T7E7$KK	&v'9'9';';<<DOO 	 	 	 	 	4?+++ +s   -D DD'&H Hbasefilenamepath#str | t.Sequence[str | None] | NoneAnyLogger | Noneraise_config_file_errorst.Generator[t.Any, None, None]c              #    K   t          |t                    s||g}t          |          D ]}|                     |dz   ||          }|r*|                    d||pt          j                               |                     |dz   ||          }g }g }	||fD ]'}
d}	 |
                                }|r|                    d|
j	                   nA# t          $ r Y n5t          $ r) |
j	        p|}|r |r|                    d|d	           Y nw xY w|rt          |	|          D ]a\  }}|                    |          }|rE|rC|                    d
                    ||
j	        t#          j        |d                               b||
j	        fV  |                    |           |	                    |
j	                   )dS )zeLoad config files (py,json) by filename and path.

        yield each config object in turn.
        Nz.py)r  r8   zLooking for %s in %sz.jsonzLoaded config file: %sz&Exception while loading config file %sT)exc_infozMCollisions detected in {0} and {1} config files. {1} has higher priority: {2}r!   )r   )r   rP   rn   python_config_loader_classr:   r`  getcwdjson_config_loader_classrx  full_filenamer   r  r  zip
collisionswarningrX   r   dumpsrM  )r   r  r  r8   r  currentpyloader
jsonloaderloaded	filenamesr~  r;   filenameearlier_configr  s                  r>   _load_config_fileszApplication._load_config_filesz  s_      dC   	DL6D~~ (	; (	;G55lU6JQX^a5bbH X		0,@V29;;WWW55lW6LSZ`c5ddJ"$F#%I#Z0  ;  ;R#//11F  R		":F<PQQQ *   D  e e e  &3C|H/  e		"JH_c	ddde  ;47	64J4J 
 
0.%3%>%>v%F%F
% # KK!@@F$,$*$8$(Jz!$D$D$DA" A"   "6#78888MM&)))$$V%9:::A ;(	; (	;s   C
D/DDc                     | j         dd         S )z$Currently loaded configuration filesN)r   r   s    r>   loaded_config_fileszApplication.loaded_config_files  s     (++rE   r  c                   t           j                            |          \  }}t                      }|                     ||| j        | j                  D ]=\  }}|                    |           || j        vr| j        	                    |           >|                    | j
                   |                     |           dS )z'Load config files by filename and path.)r  r8   r  N)r`  r  splitextr   r  r8   r  merger   rM  ry  r{  )rY   r  r  ext
new_configr;   fnames          r>   load_config_filezApplication.load_config_file  s    
 ((22#XX
!44%)%B	 5 
 
 
	8 
	8MFE V$$$T666)00777))):&&&&&rE   c                F   | j                                                             dd          }t                      }| j                            d|           t          j                                        D ]|\  }}|	                    |          rb| j                            d||           |
                    d          ^}}}|}|D ]
}	||	         }t          ||t          |                     }|                    | j                   |                     |           dS )z!Load config files by environment.-r'  z1Looping through config variables with prefix "%s"zSeeing environ "%s"="%s"__N)rb   upperr   r   r8   r:   r`  ra  r   
startswithr   setattrr   r  ry  r{  )
rY   PREFIXr  rV  vr'  r  r   sectionr   s
             r>   load_config_environzApplication.load_config_environ  s    ""**344XX
JFSSSJ$$&& 		? 		?DAq||F## ?91a@@@ !"D#$ ) )A%ajGG&:1&=&=>>>))):&&&&&rE   c              #  X  K   || j         }t          d |                     |          D                       d
fd	                                 }t          fd	                                D                       |k    rnI                                D ]\  }}|r|V  d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              3  `   K   | ])}|t          |                    d                     fV  *dS )Tr   N)r(  class_own_traits)r   r   s     r>   r   z:Application._classes_with_config_traits.<locals>.<genexpr>  sT       $
 $
 $s++4+8899:$
 $
 $
 $
 $
 $
rE   r   r4   r/   r(  c                D    t          fd| j        D                       S )Nc              3  0   K   | ]}|v o|         V  d S r   rK   )r   bcls_to_configs     r>   r   zZApplication._classes_with_config_traits.<locals>.is_any_parent_included.<locals>.<genexpr>  s2      VV1qM)>mA.>VVVVVVrE   )rw  	__bases__)r   r  s    r>   is_any_parent_includedzGApplication._classes_with_config_traits.<locals>.is_any_parent_included  s(    VVVVVVVVVVrE   Tc              3  <   K   | ]\  }}||p
 |          fV  d S r   rK   )r   r   inc_yesr  s      r>   r   z:Application._classes_with_config_traits.<locals>.<genexpr>  sQ       ( ( C g<!7!7!<!<=( ( ( ( ( (rE   )r   r4   r/   r(  )ri   r   ru   r   r   )rY   ri   to_incl_origclr  r  r  s        @@r>   r2  z'Application._classes_with_config_traits  s       ?lG# $
 $
0099$
 $
 $
 
 

	W 	W 	W 	W 	W 	W	(--//L' ( ( ( ($1$7$7$9$9( ( (  M ,,	 )..00 	 	KB 	 	rE   c                t   d| j         z  g}|                    d           |                    d           |                    d           || j        n|}t          |                     |                    }|D ]*}|                    |                    |                     +d                    |          S )z/generate default config file from Configurablesz# Configuration file for %s.r&   zc = get_config()  #noqaNr   )rb   rM  ri   rL  r2  class_config_sectionr   )rY   ri   linesconfig_classesr   s        r>   generate_config_filez Application.generate_config_file  s    /$);<R3444R")/$,,wd>>wGGHH! 	C 	CCLL11.AABBBByyrE   c                    t          | dd          rX| j        j        D ]B}t          t                    5  |                                 d d d            n# 1 swxY w Y   Cd| _        d S d S )Nr   F)r   r8   r   r   r  closer   )rY   handlers     r>   close_handlerszApplication.close_handlers  s    4.66 	-  8, $ $i(( $ $MMOOO$ $ $ $ $ $ $ $ $ $ $ $ $ $ $',D$$$	- 	-s   AA	A	r   exit_statusint | str | Nonec                    | j                             d| j                   |                                  t	          j        |           d S )NzExiting application: %s)r8   r:   rb   r  r   r<   )rY   r  s     r>   r<   zApplication.exit#  sC    0$)<<<rE   c                .    |                                   d S r   )r  r   s    r>   __del__zApplication.__del__(  s    rE   c                r     | j         di |}|                    |           |                                 dS )zLaunch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        NrK   )rF  r   r   )r   r%   r5   r1   s       r>   launch_instancezApplication.launch_instance+  s>     cl$$V$$t		rE   r   )ri   rj   r/   rk   )r/   r   )r   r   r/   r   )r/   r   )r/   r   )r5   r4   r/   r   )r%   r   r/   r   )r/   r   )ri   r(  r/   r   )F)ri   r(  r/   r   )r/   rP   )r&  rP   r%   r   r/   r   )r/   rJ  )
r%   rX  r   r   r   r   ri   rj   r/   r   )r[  r(  r/   r\  )NF)
r  rP   r  r  r8   r  r  r(  r/   r  )r/   r\  )r  rP   r  r  r/   r   )ri   rj   r/   rP   )r   )r  r  r/   r   )r%   r   r5   r4   r/   r   )crH   rI   rJ   r[   r   rb   __annotations__rc   rd   re   rf   r   r  r   r  rg   ri   ru   rv   r   r%   r   r'   r  r   r\   r]   tagr   rM   r   r   r   r   r   r   r   r   r   r   r   r   r   r|   r   r   r   r   r|  r   ry  r   r   r   r   r   r   r   r   rD   r   r   r   r   r   r  r  r  r  r#  r"  r+  r/  r.  r9  r;  r1  r>  r4  rB  rI  rW  rZ  classmethodrf  ri  r   r  propertyr  r  r  r2  r  r  r<   r  r  r^   r_   s   @r>   r2   r2      s        BB -4GM,B,BDBBBB 4;7;T3U3UKUUUU:A'BT:U:UUUUU<CGDX<Y<YYYYY>EgF\>]>]]]]]!33 18		H9999 G -1! ! ! ! !. 07wu~~G==== #'$&&D((((  $t$QRR Ml2   
cc	  ('"^  	cc  -*   
cc 
1 1 1 1f W]L+7GHH" " " IH" WU###" " " $#"( ( ( ( WU^^   ^ T.0 0 0` 
cca n $%<=G====  
 D
 !4 
 K
 & 
 A
# E    @ 8<tvvK====X@TRRRF ggiiJ

		 	 	J '+dff,,,,$P  	cc  tZ  	cc  W  & & & ! & W]0 0 0 0

7 
7 
7 
7 WX9 9 9 9 9 ^ 9 & & & & &' ' ' 'U U U UB1 1 1 1$ $ $ $L0 0 0 0   03 3 3 3   7 7 7 7   "   : : : : :4 4 4 4 42X X X X2 2 2 2   / / / /       % % % % %09 9 9 9v	
 	
 	
 	
     [2    [& 0, 0, 0, 0, 0,d 
 !%).5; 5; 5; 5; [5;n , , , X, IM' ' ' ' '* ' ' ' ', -1( ( ( ( (T
  
  
  
  
 - - - -    
        [    rE   r2   rb   rP   configurableset_help
unset_helpr   c                    |pd|z  }|pd|z  }|                     d          \  }}||dii}||dii}| ||fd| z   ||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   )rb   r  r  r  r   r  setterunsetters           r>   boolean_flagr  >  sr    * 7=<7H<~<J##C((JCE4=!FeU^$H68$edlXz4JKKrE   r   c                     t                                           rt                                           j        S t	                      S )z|Get the config object for the global Application instance, if there is one

    otherwise return an empty config object
    )r2   initializedrF  r;   r   rK   rE   r>   
get_configr  ]  s6    
    ##%%,,xxrE   __main__)r.   r,   r/   r,   )r&   r&   )
rb   rP   r  rP   r  rP   r  rP   r/   r   )r/   r   )br[   
__future__r   r@   r   r\   r`  r   rs  r   typingrB   collectionsr   r   
contextlibr   r   r   logging.configr   textwrapr	   traitlets.config.configurabler
   r   traitlets.config.loaderr   r   r   r   r   r   r   traitlets.traitletsr   r   r   r   r   r   r   r   r   r   traitlets.utils.bunchr   traitlets.utils.nested_updater   traitlets.utils.textr   r    utilsr#   utils.importstringr$   r  rd   re   hasattrr%   rf   ra  rD  _envvarlowerr'   rv  
executableendswithr   TypeVarCallableAnyr,   UnionLoggerr   rP   r   Optionalr   r   rh   rD   r  rG   	FormatterrM   r2   r   default_aliasesr   default_flagsr  r  rH   r  rK   rE   r>   <module>r     sy   2 2 # " " " " "       				  				 



     0 0 0 0 0 0 0 0             % % % % % %       M M M M M M M M                                         ( ' ' ' ' ' 7 7 7 7 7 7 8 8 8 8 8 8 8 8             , , , , , ,
 
EGG  
EGG  wsF tCH  *..H"
M
M
==??m##4811]]__***4911
* 	h
	   ^F 7 7 F F
AIcCJ/000GGN$BBC	
&ae
:afSk"fQVL)*   *	 	 	 	 	y 	 	 	& & & & &W& & & &*[ [ [ [ [' [ [ [D %!L L L L L>    z!!!!! rE   