
    ~f	                       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jq                         Z9djq                         Z: e;e	d      sdge	_<        dZ=ej|                  j                  dd      Z@e@j                         dv rdZBn e@j                         dv rdZBn eCde@z        e	j                  xr e	j                  j                  d      ZF ej                  dej                  dej                  f          ZJej                  ej                  d!f   ZMejH                  eNej                  f   ZOej                  ejN                  eN      ZQejN                  ej                  e      ZSd,d"ZT G d# d$eU      ZV G d% d&ej                        ZX G d' d(e      ZYeYj                  Z[eYj                  Z]d-d.d)Z^d/d*Z_e`d+k(  reYj                          yy)0z,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]c                t     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.
    c                    	  | g|i |S # t         t        f$ r]}| j                  j                  d|       | j                  j	                  d| j
                         | j                  d       Y d }~y d }~ww xY w)Nz0Bad config encountered during initialization: %szConfig at the time: %s   )r   r   logfataldebugconfigexit)appargskwargsemethods       W/var/www/cvtools/html/venv/lib/python3.12/site-packages/traitlets/config/application.pyinnerz!catch_config_error.<locals>.inners   si    	#////M* 	GGMMLaPGGMM2CJJ?HHQKK	s    A;AA66A;)r5   Applicationr6   t.Anyr7   r=   returnr=   )	functoolswrapstcastr+   )r9   r;   s   ` r:   catch_config_errorrC   j   s3     __V  66!U    c                      e Zd Zy)ApplicationErrorN)__name__
__module____qualname__ rD   r:   rF   rF      s    rD   rF   c                  @     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 |c                    |j                   | j                  k\  r| j                  |j                  z  |_        nd|_        t
        |   |      S )Nr%   )levelnohighlevel_limithighlevel_format__dict__	highlevelsuperformat)selfrecord	__class__s     r:   rT   zLevelFormatter.format   sC    >>T111#44vFF!Fw~f%%rD   )rV   zlogging.LogRecordr>   str)
rG   rH   rI   __doc__loggingWARNrO   rP   rT   __classcell__rW   s   @r:   rL   rL      s#     llO)& &rD   rL   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<   	 dg	 	 	 dhdZ ed      Zded<    e       Zded<    ee      Z edej4                  d      j7                  d      ZeZ edd      j7                  d      Z edd      j7                  d      Z didZ! e"ddd d!      djd"       Z# e"d#d$%      djd&       Z$dkd'Z% e&d#      dld(       Z' e(d)      j7                  d      Z)d*d+iZ*ded,<   d d ejV                  iid-fd d.diid/fd d0diid1fd2Z,ded3<    e(       Z-d4ed5<    e.d6d7      Z/ e e             Z0 e.e1d8i d9      Z2 e       Z3d:ed;<    ed<      j7                  d      Z4 ed=      j7                  d      Z5 e"d0      djd>       Z6 e"d.      djd?       Z7dmd@Z8 e"dA      e9dj fdB              Z:e;dgdndC       Z<dkdDZ=dkdEZ>dkdFZ?dodGZ@dkdHZAdodIZBdkdJZCdodKZDdkdLZEdodMZFdpdNZGdqdrdOZHdqdpdPZIdsdQZJdkdRZKdodSZLdkdTZMdodUZNdkdVZOe;dgdtdW       ZPdudXZQ	 	 	 	 	 	 	 	 	 	 dvdYZReSdqdwdZ       ZTeSdkd[       ZUe;dgdnd\       ZVeS	 	 dx	 	 	 	 	 	 	 	 	 dyd]       ZWeXdzd^       ZYe;	 dg	 	 	 	 	 d{d_       ZZe;dkd`       Z[	 dg	 	 	 dhdaZ\dgd|dbZ]dkdcZ^d}d~ddZ_dkdeZ`eSdgddf       Za xZbS )r<   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classesc              #     K   || j                   }t               }|D ]K  }t        |j                               D ]-  }t	        |t
              s||vs|j                  |       | / M yw)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)rg   setreversedmro
issubclassr
   add)rU   rg   seencparents        r:   _classes_inc_parentsz Application._classes_inc_parents   sh      ?llGu 	!A"1557+ !fl3t9KHHV$ L!	!s   A
A,A,A,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r3   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                8   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.

        r/   consolezlogging.StreamHandlerzext://sys.stderr)class	formatterlevelstream.)r   rT   datefmtrx   )r   handlersF)rr   r   
formattersloggersdisable_existing_loggersr   r   )
rZ   getLevelName	log_level_log_formatter_clsrH   rG   
log_formatlog_datefmtrW   
IS_PYTHONWrU   r3   s     r:   get_default_logging_configz&Application.get_default_logging_config   s     4!*$11$..A0	 22==>D33<<=? #oo#//	 ''$!** ).5
:  z"y!rD   r   r   r   logging_configc                    | j                   }t        |t              r-t        j                  t
        t        t        |            | _         | j                          y N)	r   
isinstancerX   rA   rB   intgetattrrZ   _configure_logging)rU   changer   s      r:   _observe_logging_changez#Application._observe_logging_change  s<     NN	i%VVC))DEDN!rD   r0   r   )typec                $    | j                          y r   )r   rU   r   s     r:   _observe_logging_defaultz$Application._observe_logging_default  s    !rD   c                |    | j                         }t        || j                  xs i        t        |       d| _        y )NT)r   r   r   r   _logging_configuredr   s     r:   r   zApplication._configure_logging!  s5    002fd117R86#' rD   c                    t        j                  | j                  j                        }d|_        |}|,|j
                  r|S |j                  s	 |S |j                  }|,|S )z#Start logging for this application.F)rZ   	getLoggerrW   rG   	propagater   rp   )rU   r0   _logs      r:   _log_defaultzApplication._log_default(  se      7 78}}
>>
 ;;D  
rD   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))r2   zshow-configzshow-config-jsonflagsz#dict[str, t.Any] | Dict[str, t.Any]subcommandsz(traitlets.config.application.Application)
allow_nonerJ   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                   | _        y r   )newr   r   s     r:   _show_config_json_changedz%Application._show_config_json_changed  s    !::rD   c                b    |j                   r#| j                  | _        | j                  | _        y y r   )r   start_save_startstart_show_configr   s     r:   _show_config_changedz Application._show_config_changed  s'    ::#zzD//DJ rD   c                   t        j                  | fi | | j                  }|| j                  vrT| j                  |j                  u r|g| j                  | _        y | j                  j	                  d| j                         y y )Nr   )r   __init__rW   rg   insert)rU   r7   clss      r:   r   zApplication.__init__  sl    &&t6v6 nndll"||s{{* #3dll3##At~~6 #rD   r3   c                p    t         |   |       | j                  j                  d|j                         y )NzConfig changed: %r)rS   _config_changedr0   r2   r   )rU   r   rW   s     r:   r   zApplication._config_changed  s)     	'+VZZ8rD   c                &    | j                  |       y)zMDo the basic steps to configure me.

        Override in subclasses.
        N)parse_command_line)rU   r$   s     r:   
initializezApplication.initialize  s     	%rD   c                    | j                   6t        | j                   t              sJ | j                   j                         S y)zAStart the app mainloop.

        Override in subclasses.
        N)subappr   r<   r   rU   s    r:   r   zApplication.start  s:    
 ;;"dkk;777;;$$&& #rD   c                   | j                   j                         }| j                  j                         D ]D  }|j                  |v s||j                     }|j                  dd       |j                  dd       F | j                  rLt        j                  |t        j                  ddt               t        j                  j                  d       y| j                  r4t        d       | j                  D ]  }t        d	|z           t                t        |      D ]\  }||   }|st        |       t!        d
d      }t        |      D ],  }||   }	t        d| dt#        j$                  |	fi |        . ^ y)z,start function used when show_config is Truer   Nr   r/   T)r   	sort_keysr   
zLoaded config files:z     )r   compactz  .z = )r3   copyrW   rk   rG   popr   jsondumpsysstdoutreprwriter   printsorteddictpprintpformat)
rU   r3   r   
cls_configf	classnameclass_configpformat_kwargs	traitnamevalues
             r:   r   zApplication.start_show_config  sS   !!#>>%%' 	9C||v%#CLL1
}d3148		9   IIfcjjdDQJJT"$$()..  dQh G 		UI!),L)&*!T&BN#L1 U	$Y/I;c&..*Q.*Q)RSTU		UrD   c                T    t        dj                  | j                                      y)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,,./0rD   c              #  Z  K   | j                   syi }| j                  D ]R  }|j                         dd D ]:  }t        j                  t        j
                  t           |      ||j                  <   < T | j                   j                         D ]  \  }}	 t        |t              r|\  }}nd}|j                  d      dd \  }}|dz   |z   }||   }|j                  d      |   }	|j                  |	|      j                         }
t        |t              s|f}t        |t               }d	j#                  d
 |D              }|
d   j%                  d|z   |      |
d<   |
E d{    t'        d|z          y7 # t(        $ r#}| j*                  j-                  d||        d}~ww xY ww)z+Yield the lines for alias part of the help.Nr   Tr~   )helptextkey, c              3  F   K   | ]  }t        |      d kD  rdnd|z    ywr/   z--%sz-%sNlen.0ms     r:   	<genexpr>z.Application.emit_alias_help.<locals>.<genexpr>  !     !WASVaZ6Ua"G!W   !r   --zEquivalent to: [--%s]z7Failed collecting help-message for alias %r, due to: %s)r   rg   rk   rA   rB   Typer
   rG   itemsr   tuplesplitclass_traitsclass_get_trait_help
splitlinesr   r   r   replacer   	Exceptionr0   error)rU   	classdictr   ro   aliaslongnamefhelpr   r   traitfhelp_linesexs               r:   r   zApplication.emit_alias_help  s    ||35	<< 	HCWWYs^ H()qvvl/CQ(G	!**%H	H  $||113 	OE8h.&.OHe E'/~~c':23'?$	9$s?Y6	*(((5i@!66uu6MXXZ!%/"HEu#.		!WQV!WW "-Q!7!7x!OA&&&4x?@@+	( ' XZ_acds=   BF+CE<"E:#E<7F+:E<<	F(F##F((F+c                T    t        dj                  | j                                      y)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++-./rD   c              #    K   | j                   sy| j                   j                         D ]  \  }\  }}	 t        |t              s|f}t	        |t
              }dj                  d |D              }| t        t        |j                                      dj                  d |j                         D              }d|z  }t        t        |              y# t        $ r#}| j                  j                  d||        d}~ww xY ww)	z.Yield the lines for the flag part of the help.Nr   r   c              3  F   K   | ]  }t        |      d kD  rdnd|z    ywr   r   r   s     r:   r   z-Application.emit_flag_help.<locals>.<genexpr>5  r   r    c              3  h   K   | ]*  \  }}|j                         D ]  \  }}d | d| d|   , yw)r   r   =N)r   )r   clname
props_dictpropvals        r:   r   z-Application.emit_flag_help.<locals>.<genexpr>8  sQ      $*
%/%5%5%7$ "c $q.$.$s   02zEquivalent to: [%s]z6Failed collecting help-message for flag %r, due to: %s)r   r   r   r   r   r   r   r   r	   stripr   r0   r   )rU   r   cfgr   cfg_listcfg_txtr  s          r:   r  zApplication.emit_flag_help+  s     zz#'::#3#3#5 	E<C!%/"HEu#.		!WQV!WWVEKKM23388 $.1iik$ 
 0(:VG_--	  WY^`bcs)   1DB%CD	D%DDDc                T    t        dj                  | j                                      y)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12rD   c              #    K   | j                   s| j                  syd}| dt        |      z   t        | j                        D ]
  }| d  | j                         E d{    | j                         E d{    d y7 !7 w)z1Yield the lines for the options part of the help.NOptionsr
  r%   )r   r   r   r    rb   r  r   )rU   headerps      r:   r  zApplication.emit_options_helpG  s     zz$,,CK !8!89 	AGH	 &&(((''))) 	))s$   A%B'B	(B?B 
BBc                T    t        dj                  | j                                      y)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56rD   c              #  r  K   | j                   syd}| dt        |      z   t        | j                  j	                  | j
                              D ]
  }| d  | j                   j                         D ]3  \  }\  }}| |st        t        |j                                      5 d yw)z4Yield the lines for the subcommand part of the help.NSubcommandsr
  )r5   r%   )
r   r   r    rd   rT   r`   r   r   r	   r  )rU   r  r  subc_r}   s         r:   r  z!Application.emit_subcommands_helpZ  s     CK !<!<!C!C		!C!RS 	AGH	  $//557 	3OD)1dJVDJJL122	3 s   B	B7+B7c              #  "   K   |s	d d yyw)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%   NrJ   rU   rg   s     r:   emit_help_epiloguezApplication.emit_help_epiloguek  s     
 IIH s   c                X    t        dj                  | j                  |                   y)zPrint the help for each Configurable class in self.classes.

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

        Returns a multiline string.
        r   c              3  <   K   | ]  }|j                           y wr   )class_config_rst_doc)r   ro   s     r:   r   z6Application.document_config_options.<locals>.<genexpr>  s     Wa//1Ws   )r   rq   r   s    r:   document_config_optionsz#Application.document_config_options  s"    
 yyW4;T;T;VWWWrD   c                T    t        dj                  | j                                      y)z"Print the application description.r   N)r   r   r)  r   s    r:   print_descriptionzApplication.print_description  s    dii--/01rD   c              #  t   K   t        | j                  xs | j                  xs d      D ]
  }| d  yw)z-Yield lines with the application description.r%   N)r    ra   rY   )rU   r  s     r:   r)  zApplication.emit_description  s8      !1!1!GT\\!GRH 	AGH	s   68c                T    t        dj                  | j                                      y)z1Print usage and examples (see `emit_examples()`).r   N)r   r   r,  r   s    r:   print_exampleszApplication.print_examples  s    dii**,-.rD   c              #     K   | j                   r?d d d t        t        | j                   j                                      d yyw)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)re   r   r	   r  r   s    r:   r,  zApplication.emit_examples  sG      ==H 3 3 5677H s   AAc                .    t        | j                         y)zPrint the version string.N)r   rr   r   s    r:   print_versionzApplication.print_version  s    dllrD   c                   | j                   j                  |      }|J |\  }}t        |t              rt	        |      }t        |t
              rBt        |t              r2| j                  j                          |j                  |       | _        n't        |      r ||       | _        nt        d|z        | j                  j                  |       y)z"Initialize a subcommand with argv.N)rp   z%Invalid mappings for subcommand '%s'!)r   getr   rX   r#   r   rl   r<   rW   clear_instanceinstancer   callableAssertionErrorr   )rU   r  r$   r  r   r   s         r:   initialize_subcommandz!Application.initialize_subcommand  s     ""4(	fc" (F fd#
6;(GNN))+ ///6DKf ,DK !H4!OPP 	t$rD   c                *   t        t              }| j                  D ]D  }|j                  }|j	                         dd D ]   }||j                     j                  |       " F i }| j                  j                         D ]w  \  }}t        |t              r|\  }}|j                  dd      \  }}	||   }
t        |
      dk(  r|
d   }t        |t              s|f}|D ]  }dj                  ||	g      ||<    y i }| j                  j                         D ]y  \  }\  }}i }|j                         D ];  \  }}||   }
t        |
      dk(  r|
d   }||v r||   j                  |       7|||<   = t        |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.

        r/   r   r   r   )r   listrg   rG   rk   appendr   r   r   r   r   r   r   r   update)rU   mro_treer   clsnamerp   r   r   r   r   r   childrenalr   r   flagdictr}   newflagsubdictks                      r:   flatten_flagszApplication.flatten_flags  s    t$<< 	:CllG'')Ab/ :)009:	: #%#||113 	5OE8(E*&!!Q/JC}H8}!qkgu- 5!hhU|45	5 %)ZZ%5%5%7 	+!C!(D*,G ( 0 	+W#C=x=A%"1+C'>CL''0#*GCL	+ c5)f +#T?a+	+" g~rD   c                L    t        ||||| j                  | j                        S )N)rg   r0   r   )r   r0   r   )rU   r$   r   r   rg   s        r:   _create_loaderzApplication._create_loader  s(     &'5'txxTM]M]
 	
rD   c                    |r&dt         j                  v r	 ddlm}  |       }|J |S t        j                  S # t        t
        f$ r Y t        j                  S w xY w)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_configrS  ImportErrorModuleNotFoundErrorr   r$   )r   check_argcompleterS  cwordss       r:   _get_sys_argvzApplication._get_sys_argv  sa     2::!=V/1))) xx  !45 xxs   9 AAc                p    dt         j                  vry	 ddlm}  |        y# t        t
        f$ r Y y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.
        rR  Nr   )increment_argcomplete_index)rT  rU  rV  r]  rW  rX  )r   r]  s     r:   "_handle_argcomplete_for_subcommandz.Application._handle_argcomplete_for_subcommand3  s9     +	W')01 		s   # 55c                  	 t        |t              rJ |(| j                  t        | j                              dd }|D cg c]  }t        |       c}| _        |r|d   dk(  r	|dd dgz   }| j                  r^t        |      dkD  rP|d   |dd }}t        j                  d|      r0|| j                  v r"| j                          | j                  ||      S 	 |d|j                  d       	t        	fd	d
D              r$| j                  d	v        | j!                  d       d	v sd	v r!| j#                          | j!                  d       | j%                         \  }}t'        | j)                               }| j+                  ||||      }	 t-        |j/                               | _        | j5                  | j0                         |j6                  | _        yc c}w # t        $ r |	Y w xY w# t2        $ r  w xY w)z!Parse the command line arguments.N)rY  r/   r   r}   -hz^\w(\-?\w)*$r   c              3  &   K   | ]  }|v  
 y wr   rJ   )r   xinterpreted_argvs     r:   r   z1Application.parse_command_line.<locals>.<genexpr>d  s     Mq$$Ms   )r`  
--help-allz--helprd  z	--versionz-Vr%  )r   rX   r[  boolr   r"   r$   r   rematchr^  rA  index
ValueErroranyr'  r4   r:  rN  rC  r*  rP  r   load_config
cli_config
SystemExitupdate_config
extra_args)
rU   r$   argr  subargvr   r   rg   loaderrc  s
            @r:   r   zApplication.parse_command_lineG  s    dC(((<%%T=M=M8N%OPQPRSD2673\#&7	DGv%8tf$DD	A GT!"X'Dxx.44;K;K3K77911$@@	$#$6djj&67 M.LMMOOL,<<=IIaL**d6F.F IIaL ++-wt779:$$T7E7$K	&v'9'9';<DO
 	4??+ ++W 8(  	$#	$"  	 	s$   GG! G3 !G0/G03G>c              #  d  K   t        |t              s||g}t        |      D ]F  }| j                  |dz   ||      }|r)|j	                  d||xs t        j                                | j                  |dz   ||      }g }g }	||fD ]  }
d}	 |
j                         }|r|j	                  d|
j                         	 |s8t        |	|      D ]]  \  }}|j                  |      }|s|s|j                  d
j!                  ||
j                  t#        j$                  |d                   _ ||
j                  f |j'                  |       |	j'                  |
j                          I y# t        $ r Y t        $ r, |
j                  xs |}|r |r|j                  d|d	       Y w xY ww)zeLoad config files (py,json) by filename and path.

        yield each config object in turn.
        Nz.py)pathr0   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   rX   rj   python_config_loader_classr2   rT  getcwdjson_config_loader_classrk  full_filenamer   r   r   zip
collisionswarningrT   r   dumpsrD  )r   basefilenamert  r0   raise_config_file_errorscurrentpyloader
jsonloaderloaded	filenamesrr  r3   filenameearlier_configr{  s                  r:   _load_config_fileszApplication._load_config_filesz  s     dC DL6D~ (	;G55lU6JQX^a5bH		0,@V299;W55lW6LSZ`c5dJ"$F#%I#Z0  ;R#//1F 		":F<P<PQ47	64J 
0.%3%>%>v%F
%#KK!@@F$,$*$8$8$(JJz!$DA"
 "6#7#788MM&)$$V%9%9:A ;(	; *   e  &33C|H/		"JH_c	desI   BF0E.!F0 %F0&F0)BF0.	F-7F091F-*F0,F--F0c                     | j                   dd S )z$Currently loaded configuration filesN)r   r   s    r:   loaded_config_fileszApplication.loaded_config_files  s     ((++rD   c                   t         j                  j                  |      \  }}t               }| j	                  ||| j
                  | j                        D ]@  \  }}|j                  |       || j                  vs&| j                  j                  |       B |j                  | j                         | j                  |       y)z'Load config files by filename and path.)rt  r0   r  N)rT  rt  splitextr   r  r0   r  merger   rD  rl  rn  )rU   r  rt  ext
new_configr3   fnames          r:   load_config_filezApplication.load_config_file  s    
 ((2#X
!44%)%B%B	 5 
 
	8MFE V$T666))007
	8 	):&rD   c                   | j                   j                         j                  dd      }t               }| j                  j                  d|       t        j                  j                         D ]m  \  }}|j                  |      s| j                  j                  d||       |j                  d      ^}}}|}|D ]  }	||	   }	 t        ||t        |             o |j                  | j                         | j                  |       y)z!Load config files by environment.-r   z1Looping through config variables with prefix "%s"zSeeing environ "%s"="%s"__N)r`   upperr   r   r0   r2   rT  rU  r   
startswithr   setattrr   r  rl  rn  )
rU   PREFIXr  rM  vr   rt  r   sectionr  s
             r:   load_config_environzApplication.load_config_environ  s     "**34X
JFSJJ$$& 		?DAq||F#91a@ !"D#$ )A%ajG)&:1&=>		? 	):&rD   c              #  ,  K   || j                   }t        d | j                  |      D              dfd	 j                         }t        fdj	                         D              |k(  rn9j	                         D ]  \  }}|s	|  yw)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  V   K   | ]!  }|t        |j                  d             f # yw)Tr~   N)re  class_own_traits)r   r   s     r:   r   z:Application._classes_with_config_traits.<locals>.<genexpr>  s0      $
 $s++4+89:$
s   ')c                @    t        fd| j                  D              S )Nc              3  4   K   | ]  }|v xr |     y wr   rJ   )r   bcls_to_configs     r:   r   zZApplication._classes_with_config_traits.<locals>.is_any_parent_included.<locals>.<genexpr>  s#     V1qM)>mA.>>Vs   )rj  	__bases__)r   r  s    r:   is_any_parent_includedzGApplication._classes_with_config_traits.<locals>.is_any_parent_included  s    VVVVrD   c              3  @   K   | ]  \  }}||xs  |      f  y wr   rJ   )r   r   inc_yesr  s      r:   r   z:Application._classes_with_config_traits.<locals>.<genexpr>  s-      ( C g<!7!<=(s   )r   r=   r>   re  )rg   r   rq   r   r   )rU   rg   to_incl_origclr  r  r  s        @@r:   r*  z'Application._classes_with_config_traits  s       ?llG# $
009$
 

	W (--/L' ($1$7$7$9( M ,  )..0 	KB	s   BBBc                L   d| j                   z  g}|j                  d       |j                  d       |j                  d       || j                  n|}t        | j	                  |            }|D ]"  }|j                  |j                  |             $ dj                  |      S )z/generate default config file from Configurablesz# Configuration file for %s.r%   zc = get_config()  #noqar   )r`   rD  rg   rC  r*  class_config_sectionr   )rU   rg   linesconfig_classesr   s        r:   generate_config_filez Application.generate_config_file  s    /$));<R34R")/$,,wd>>wGH! 	CCLL11.AB	CyyrD   c                    t        | dd      rK| j                  j                  D ]*  }t        t              5  |j                          d d d        , d| _        y y # 1 sw Y   ?xY w)Nr   F)r   r0   r   r   r   closer   )rU   handlers     r:   close_handlerszApplication.close_handlers  sd    4.6  88,, $i( $MMO$ $$ (-D$ 7
$ $s   AA#	c                    | j                   j                  d| j                         | j                          t	        j
                  |       y )NzExiting application: %s)r0   r2   r`   r  r   r4   )rU   exit_statuss     r:   r4   zApplication.exit#  s1    0$))<rD   c                $    | j                          y r   )r  r   s    r:   __del__zApplication.__del__(  s    rD   c                j     | j                   di |}|j                  |       |j                          y)zLaunch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        NrJ   )r>  r   r   )r   r$   r7   r5   s       r:   launch_instancezApplication.launch_instance+  s,     cll$V$t		rD   r   )rg   ClassesType | Noner>   z+t.Generator[type[Configurable], None, None])r>   r   )r   r   r>   None)r>   r  )r>   	AnyLogger)r7   r=   r>   r  )r$   ArgvTyper>   r  )r>   t.Generator[str, None, None])rg   re  r>   r  )F)rg   re  r>   r  )r>   rX   )r  rX   r$   r  r>   r  )r>   z)tuple[dict[str, t.Any], dict[str, t.Any]])
r$   zlist[str] | Noner   r   r   r   rg   r  r>   r   )rY  re  r>   	list[str])NF)
r~  rX   rt  #str | t.Sequence[str | None] | Noner0   zAnyLogger | Noner  re  r>   zt.Generator[t.Any, None, None])r>   r  )r  rX   rt  r  r>   r  )rg   r  r>   rX   )r   )r  zint | str | Noner>   r  )r$   r  r7   r=   r>   r  )crG   rH   rI   rY   r   r`   __annotations__ra   rb   rc   rd   r   rv  r   rx  re   rg   rq   rr   r   r$   r   r&   r  r   rZ   r[   tagr   rL   r   r   r   r   r   r   r   r   r   r   r   r   r   rx   r   r   r   r   ro  r   rl  r   r   r   r   r   r   r   r   rC   r   r   r   r   r   r  r  r  r  r  r  r#  r'  r&  r1  r3  r)  r6  r,  r:  rA  rN  rP  classmethodr[  r^  r   r  propertyr  r  r  r*  r  r  r4   r  r  r\   r]   s   @r:   r<   r<      s   B -4M,BD
)B 4;;T3UK0U:ABT:U7U<CDX<Y9Y>EF\>];]!33 18	H-9 G[ -1!)!	4!. 07u~G,= #'&D
(  $$QR Mll2 
cc	  ("^	cc  -* 
cc 
1f ]L+7GH" I" U#" $"( U^  .0` 
cca n $%<=GW=  
 D
 !4 
 K
 & 
 A
#E7 @ 8<vK4=@TRF giJ

		J '+f),P	cc  Z	cc   & !& ]0 0

7 X9  9 & &'UB1$L0037":42X2/ % %09v	
	
 	
 		

 $	
 
 	
  2  & 0, 0,d 
 !%).5;5; 25; 	5;
 #'5; 
(5; 5;n , , IM''#F'	' '* ' ', -1()(	4(T
 -
  rD   r<   c                    |xs d|z  }|xs d|z  }|j                  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   )r`   configurableset_help
unset_helpr   r   setterunsetters           r:   boolean_flagr  >  so    * 7=<7H<~<J##C(JCE4=!FeU^$H68$edlXz4JKKrD   c                 z    t         j                         rt         j                         j                  S t	               S )z|Get the config object for the global Application instance, if there is one

    otherwise return an empty config object
    )r<   initializedr>  r3   r   rJ   rD   r:   
get_configr  ]  s,    
  ##%,,,xrD   __main__)r9   r+   r>   r+   )r%   r%   )
r`   rX   r  rX   r  rX   r  rX   r>   r   )r>   r   )brY   
__future__r   r?   r   rZ   rT  r   rf  r   typingrA   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  rb   rc   hasattrr$   rd   rU  r<  _envvarlowerr&   ri  
executableendswithr   TypeVarCallableAnyr+   UnionLoggerr  rX   r   Optionalr  r   rf   rC   r   rF   	FormatterrL   r<   r   default_aliasesr   default_flagsr  r  rG   r  rJ   rD   r:   <module>r     s   2 #    	  	 
  0   %  M     ( 7 8   ,
 
EG  
EG  sFtCH  **..H"
M
==?m#481]]_**491
 	h
	  ^^F 7 7 F
AIIcCJ/0GGGNN$BBC	
&&aee
::affSk"ffQVVL)**	y 	&W&& &*[' [D %%!!L> z! rD   