o
    찓i                    @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
mZmZmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddl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*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZEmFZFmGZG ddlmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQ ddlDmRZRmSZSmTZTmUZUmVZVmWZWmXZX ddlYmZZZ e!rddl[m\Z\ G dd deZ]G d d! d!e/Z^G d"d# d#e/Z_e'd$Z`e"e`dB eOf Zae"e`eNf Zbe'd%ecd&Zde"edeMf Zee"edeLf Zfe"edePf Zge"edeKf ZheZie"e`eif Zje"ekel e0g d'eQeIf ZmG d(d) d)eZe$e` ZndS )*z'Command-line interface settings source.    )annotationsN)SUPPRESSArgumentParserBooleanOptionalAction	NamespaceRawDescriptionHelpFormatter_SubParsersAction)defaultdict)CallableMappingSequence)Enum)cached_property)chain)dedent)SimpleNamespace)TYPE_CHECKING	AnnotatedAnyGenericLiteralNoReturnTypeVarcastget_args
get_originoverload)AliasChoices	AliasPath	BaseModelFieldPrivateAttrTypeAdapterValidationError)Representation)is_model_class)is_pydantic_dataclass)	FieldInfo)PydanticUndefined)typing_objects)is_union_origin   SettingsError)_lenient_issubclass_typing_base_WithArgsTypes   )
ForceDecodeNoDecodePydanticModel_CliDualFlag_CliExplicitFlag_CliImplicitFlag_CliPositionalArg_CliSubCommand_CliToggleFlag_CliUnknownArgs)_annotation_contains_types_annotation_enum_val_to_name_get_alias_names_get_model_fields_is_function_strip_annotatedparse_env_vars   )EnvSettingsSource)BaseSettingsc                      s.   e Zd Zdd fdd	Zd fddZ  ZS )_CliInternalArgParserTcli_exit_on_errorboolkwargsr   returnNonec                   s   t  jdi | || _d S )N )super__init___cli_exit_on_error)selfrG   rI   	__class__rL   [/home/ubuntu/.local/lib/python3.10/site-packages/pydantic_settings/sources/providers/cli.pyrN   O   s   
z_CliInternalArgParser.__init__messagestrr   c                   s$   | j s
td| t | d S )Nzerror parsing CLI: )rO   r-   rM   error)rP   rT   rQ   rL   rS   rV   S   s   z_CliInternalArgParser.error)T)rG   rH   rI   r   rJ   rK   )rT   rU   rJ   r   )__name__
__module____qualname__rN   rV   __classcell__rL   rL   rQ   rS   rF   N   s    rF   c                   @  s   e Zd ZdS )CliMutuallyExclusiveGroupN)rW   rX   rY   rL   rL   rL   rS   r[   Y   s    r[   c                      s  e Zd ZU ded< ded< ded< ded< ded< ded	< d
ed< ded< ded< g Zded< i Zded< edZded< ei Zded< edZ	ded< e Z
ded< dJ fd#d$ZedKd&d'ZedLd*d+ZdMd.d/ZedNd0d1ZedOd3d4ZedPd5d6ZedPd7d8ZedQd:d;ZedRd<d=ZedSd>d?ZedPd@dAZedTdBdCZedTdDdEZedTdFdGZedTdHdIZ  ZS )U_CliArgr   modelparserrU   
field_name
arg_prefixrH   case_sensitivehide_none_type(bool | Literal['all', 'no_enums'] | None
kebab_casebool | Noneenable_decodingintenv_prefix_len	list[str]argsdict[str, Any]rI   rL   tuple[str, ...]_alias_namesdict[str, int | None]_alias_pathsF_is_alias_path_onlyr'   _field_info
field_info
parser_mapOdefaultdict[str | FieldInfo, dict[int | None | str | type[BaseModel], _CliArg]]valuesrJ   rK   c           	        s0  t  jdi | | _t j j j jd\ _ _	 fdd j
 D } jr] jD ]-} |} jg i dd| j |< | j | | j |< | j | | j |< q.n j|vru | j d < | j d  | j d < |
 D ]\}} jg i dd|| |< || | | j |< qyd S )N)alias_path_argsra   c                   s    i | ]\}} j  | |qS rL   r`   ).0nameindexrP   rL   rS   
<dictcomp>{        z$_CliArg.__init__.<locals>.<dictcomp>rj   rI   )updaterL   )rM   rN   rq   r>   r_   rr   ro   ra   rm   rp   itemssubcommand_dest
sub_modelssubcommand_alias
model_copydest)	rP   rr   rs   ru   alias_path_dests	sub_modelr   alias_path_destrz   rQ   r{   rS   rN   o   s(   


z_CliArg.__init__ry   c                 C  s   |dvr
| ddS |S )NNF_-)replace)clsry   rd   rL   rL   rS   get_kebab_case   s   z_CliArg.get_kebab_case
annotation	type[Any]c                   s^   d}t |}t|D ]
}| |7 }q
|r-t|tr-|t fdd|j D 7 }|S )NrL   c                 3  s     | ]}  |d kV  qdS )allN)r   rx   ry   r   rd   rL   rS   	<genexpr>   s    z)_CliArg.get_enum_names.<locals>.<genexpr>)rA   r   get_enum_namesr.   r   tuple__members__keys)r   r   rd   
enum_namestype_rL   r   rS   r      s   "z_CliArg.get_enum_namesr   type[BaseModel]c                 C  s*   |  t| jdkr|j| jS | j| jS NrC   )r   lenr   rW   preferred_aliasrd   )rP   r   rL   rL   rS   r      s
   z_CliArg.subcommand_aliasc                 C     | j S N)rq   r{   rL   rL   rS   rr         z_CliArg.field_info
str | Nonec                 C  s   t | jjv r| j dS d S )N:subcommand)r9   rr   metadatar`   r{   rL   rL   rS   r      s   z_CliArg.subcommand_destc                 C  sH   | j s| jr| jjd ur| js| j | j | jd  S | j | j S r   )r   r`   rr   validation_aliasis_parser_submodelr   rh   r{   rL   rL   rS   r      s   z_CliArg.destc                 C  s"   | j r| jd ddS | jd S )Nr   r   r   )rd   rj   r   r{   rL   rL   rS   preferred_arg_name   s   "z_CliArg.preferred_arg_namelist[type[BaseModel]]c                 C  s   t | jjs| jjfnt | jj}| jrtdd |D }g }|D ]?}t|tfddr8td| jj	 d| j
 t|tfddrMtd| jj	 d| j
 tt|sYtt|r`|t| q!|S )Nc                 S     g | ]
}|t d ur|qS r   typerx   r   rL   rL   rS   
<listcomp>       z&_CliArg.sub_models.<locals>.<listcomp>F)is_include_originz.CliSubCommand is not outermost annotation for .z1CliPositionalArg is not outermost annotation for )r   rr   r   rb   r   r<   r9   r-   r]   rW   r_   r8   r%   rA   r&   append)rP   field_typesr   r   rL   rL   rS   r      s(   

z_CliArg.sub_modelsc                 C  r   r   rm   r{   rL   rL   rS   alias_names   r   z_CliArg.alias_namesc                 C  r   r   )ro   r{   rL   rL   rS   alias_paths   r   z_CliArg.alias_pathsc                 C  s
   | j d S )Nr   r   r{   rL   rL   rS   r      s   
z_CliArg.preferred_aliasc                 C  r   r   )rp   r{   rL   rL   rS   is_alias_path_only   r   z_CliArg.is_alias_path_onlyc                 C  s$   | j  ot| jjtttttfddS )NTis_strip_annotated)	r   r<   rr   r   listsetdictr   r   r{   rL   rL   rS   is_append_action   s   
z_CliArg.is_append_actionc                 C  s   | j  ot| jo| j S r   )r   rH   r   r   r{   rL   rL   rS   r      s   z_CliArg.is_parser_submodelc                 C  s,   | j d uot| j jv p| jdu ot| j jvS r   )rr   r3   r   rf   r2   r{   rL   rL   rS   is_no_decode   s   
z_CliArg.is_no_decode)rr   r'   rs   rt   ru   r   rJ   rK   )ry   rU   rd   rc   rJ   rU   )r   r   rd   rc   rJ   rl   )r   r   rJ   rU   )rJ   r'   )rJ   r   )rJ   rU   )rJ   r   )rJ   rl   )rJ   rn   )rJ   rH   )rW   rX   rY   __annotations__rj   rI   r!   rm   ro   rp   rq   rN   classmethodr   r   r   r   rr   r   r   r   r   r   r   r   r   r   r   r   rZ   rL   rL   rQ   rS   r\   ]   s\   
 
r\   T_CliBoolFlag)bound)defaultc                      sB  e Zd ZdZdddddddddddddddddejejejej	ej
efd fd'd(Zedd*d+Zedd/d+Zedd2d+Zddd3dƇ fd7d+Zedd9d:Zedd;d:Zdd<dd>d:ZddAdBZddGdHZddKdLZddNdOZddPdQZddTdUZddVdWZddZd[Zdd`daZddcddZeddfdgZddldmZddndoZejejejej	ej
efddpdqZddrdsZdti dfdddZ dddZ!dddZ"dddZ#dddZ$dddZ%dddZ&dddZ'ddddZ(dddZ)dddZ*dddZ+dddZ,dddZ-		ddddZ.e/dddZ0			t	tddddZ1  Z2S )CliSettingsSourcea  
    Source class for loading settings values from CLI.

    Note:
        A `CliSettingsSource` connects with a `root_parser` object by using the parser methods to add
        `settings_cls` fields as command line arguments. The `CliSettingsSource` internal parser representation
        is based upon the `argparse` parsing library, and therefore, requires the parser methods to support
        the same attributes as their `argparse` library counterparts.

    Args:
        cli_prog_name: The CLI program name to display in help text. Defaults to `None` if cli_parse_args is `None`.
            Otherwise, defaults to sys.argv[0].
        cli_parse_args: The list of CLI arguments to parse. Defaults to None.
            If set to `True`, defaults to sys.argv[1:].
        cli_parse_none_str: The CLI string value that should be parsed (e.g. "null", "void", "None", etc.) into `None`
            type(None). Defaults to "null" if cli_avoid_json is `False`, and "None" if cli_avoid_json is `True`.
        cli_hide_none_type: Hide `None` values in CLI help text. Defaults to `False`.
        cli_avoid_json: Avoid complex JSON objects in CLI help text. Defaults to `False`.
        cli_enforce_required: Enforce required fields at the CLI. Defaults to `False`.
        cli_use_class_docs_for_groups: Use class docstrings in CLI group help text instead of field descriptions.
            Defaults to `False`.
        cli_exit_on_error: Determines whether or not the internal parser exits with error info when an error occurs.
            Defaults to `True`.
        cli_prefix: Prefix for command line arguments added under the root parser. Defaults to "".
        cli_flag_prefix_char: The flag prefix character to use for CLI optional arguments. Defaults to '-'.
        cli_implicit_flags: Controls how `bool` fields are exposed as CLI flags.

            - False (default): no implicit flags are generated; booleans must be set explicitly (e.g. --flag=true).
            - True / 'dual': optional boolean fields generate both positive and negative forms (--flag and --no-flag).
            - 'toggle': required boolean fields remain in 'dual' mode, while optional boolean fields generate a single
              flag aligned with the default value (if default=False, expose --flag; if default=True, expose --no-flag).
        cli_ignore_unknown_args: Whether to ignore unknown CLI args and parse only known ones. Defaults to `False`.
        cli_kebab_case: CLI args use kebab case. Defaults to `False`.
        cli_shortcuts: Mapping of target field name to alias names. Defaults to `None`.
        case_sensitive: Whether CLI "--arg" names should be read with case-sensitivity. Defaults to `True`.
            Note: Case-insensitive matching is only supported on the internal root parser and does not apply to CLI
            subcommands.
        root_parser: The root parser object.
        parse_args_method: The root parser parse args method. Defaults to `argparse.ArgumentParser.parse_args`.
        add_argument_method: The root parser add argument method. Defaults to `argparse.ArgumentParser.add_argument`.
        add_argument_group_method: The root parser add argument group method.
            Defaults to `argparse.ArgumentParser.add_argument_group`.
        add_parser_method: The root parser add new parser (sub-command) method.
            Defaults to `argparse._SubParsersAction.add_parser`.
        add_subparsers_method: The root parser add subparsers (sub-commands) method.
            Defaults to `argparse.ArgumentParser.add_subparsers`.
        format_help_method: The root parser format help method. Defaults to `argparse.ArgumentParser.format_help`.
        formatter_class: A class for customizing the root parser help text. Defaults to `argparse.RawDescriptionHelpFormatter`.
    NTsettings_clstype[BaseSettings]cli_prog_namer   cli_parse_args)bool | list[str] | tuple[str, ...] | Nonecli_parse_none_strcli_hide_none_typere   cli_avoid_jsoncli_enforce_requiredcli_use_class_docs_for_groupsrG   
cli_prefixcli_flag_prefix_charcli_implicit_flags'bool | Literal['dual', 'toggle'] | Nonecli_ignore_unknown_argscli_kebab_caserc   cli_shortcuts$Mapping[str, str | list[str]] | Nonera   root_parserr   parse_args_methodCallable[..., Any] | Noneadd_argument_methodadd_argument_group_methodadd_parser_methodadd_subparsers_methodformat_help_methodformatter_classrJ   rK   c              
     s  |d ur|n	|j dtjd | _|d ur|n|j dd| _|d ur%|n|j dd| _|s8| jdu r6dnd}|| _|d urA|n|j d	d| _|d urO|n|j d
d| _	|	d ur]|	n|j dd| _
|
d urk|
n|j dd| _|d ury|n|j dd| _| jd | _| jr|
ds|
ds|
dd std|
 |  jd7  _|d ur|n|j dd| _|d ur|n|j dd| _|d ur|n|j dd| _|d ur|n|j dd | _|d ur|nd}|s|d urtdt j|d| jd| j|d |d u r t| j
| j|jd u rd nt|j|| jdddn|}| j||||||||d |dvr_|du rAtjdd  }nt|ttfsRtdt | | j!| "| j#|d d S d S )Nr   r   r   Fr   TrK   nullr   r   rG   r    r   r   r1   r   z'CLI settings source prefix is invalid: r   r   r   r   zGCase-insensitive matching is only supported on the internal root parser)env_nested_delimiterenv_parse_none_strenv_parse_enums
env_prefixra   )rG   progdescriptionr   prefix_charsallow_abbrevadd_help)r   r   r   r   r   r   r   r   r   rC   z<cli_parse_args must be a list or tuple of strings, received parsed_args)$model_configgetsysargvr   r   r   r   r   r   rG   r   r   _cli_flag_prefix
startswithendswithr   isidentifierr-   r   r   r   r   rM   rN   rF   __doc__r   _connect_root_parser
isinstancer   r   r   _load_env_vars_parse_argsr   )rP   r   r   r   r   r   r   r   r   rG   r   r   r   r   r   r   ra   r   r   r   r   r   r   r   r   rQ   rL   rS   rN   1  s   $



zCliSettingsSource.__init__rk   c                 C     d S r   rL   r{   rL   rL   rS   __call__     zCliSettingsSource.__call__rj   "list[str] | tuple[str, ...] | boolCliSettingsSource[T]c                C     dS )a  
        Parse and load the command line arguments list into the CLI settings source.

        Args:
            args:
                The command line arguments to parse and load. Defaults to `None`, which means do not parse
                command line arguments. If set to `True`, defaults to sys.argv[1:]. If set to `False`, does
                not parse command line arguments.

        Returns:
            CliSettingsSource: The object instance itself.
        NrL   )rP   rj   rL   rL   rS   r     s   r   ,Namespace | SimpleNamespace | dict[str, Any]c                C  r   )a  
        Loads parsed command line arguments into the CLI settings source.

        Note:
            The parsed args must be in `argparse.Namespace`, `SimpleNamespace`, or vars dictionary
            (e.g., vars(argparse.Namespace)) format.

        Args:
            parsed_args: The parsed args to load.

        Returns:
            CliSettingsSource: The object instance itself.
        NrL   rP   r   rL   rL   rS   r        )rj   r   )list[str] | tuple[str, ...] | bool | None?Namespace | SimpleNamespace | dict[str, list[str] | str] | None%dict[str, Any] | CliSettingsSource[T]c                  s   |d ur|d urt d|d ur0|du r| ji dS |du r%tjdd  }| j| | j|dS |d ur=| jt|dS t  S )Nz/`args` and `parsed_args` are mutually exclusiveFr   TrC   )	r-   r   r   r   r   r   copyrM   r   )rP   rj   r   rQ   rL   rS   r     s   
Mapping[str, str | None]c                 C  r   r   rL   r{   rL   rL   rS   r     r   z CliSettingsSource._load_env_varsc                C  r   )a  
        Loads the parsed command line arguments into the CLI environment settings variables.

        Note:
            The parsed args must be in `argparse.Namespace`, `SimpleNamespace`, or vars dictionary
            (e.g., vars(argparse.Namespace)) format.

        Args:
            parsed_args: The parsed args to load.

        Returns:
            CliSettingsSource: The object instance itself.
        NrL   r  rL   rL   rS   r     r  r   /Mapping[str, str | None] | CliSettingsSource[T]c                  s   |d u ri S t |ttfrt|}| |}| j D ]#\}}t |tr>|dr>dd |	 D D ]}||vr=| j
||< q2qdd | D }|rat|td t fdd| D sad	| < || j tttttf || j| j| j
| _| S )
Nr   c                 S  s   g | ]}|j qS rL   )r   rx   argrL   rL   rS   r   
      z4CliSettingsSource._load_env_vars.<locals>.<listcomp>c                 S  s(   i | ]\}}| d s|tur||qS )r   )r   r(   )rx   keyvalrL   rL   rS   r|     s    z4CliSettingsSource._load_env_vars.<locals>.<dictcomp>)r  c                 3  s"    | ]}  d |v r|V  qdS )r   NrL   )rx   r_   last_selected_subcommandrL   rS   r     s     z3CliSettingsSource._load_env_vars.<locals>.<genexpr>{})r   r   r   vars_resolve_parsed_args_parser_mapr   rU   r   ru   r   maxr   anyr   r   _cli_unknown_argsrB   r   r   ra   env_ignore_emptyenv_vars)rP   r   selected_subcommandsarg_destarg_mapr   rL   r  rS   r     s4   

dict[str, list[str] | str]ri   c                 C  s$  g }t | D ]\}}t|t r9| |||rq| j|i d }|r0|jr0d|||< q| ||||< q|	drN|d urN|
| j| | j q| jdkrt|tr|dd}| j|i d }|r|jjr|||jjdv rd|v rtd|dd d| d	|||< q|S )
N,r   r   r   r   FzInput should be kebab-case "z", not "")r   r   r   %_is_nested_alias_path_only_workaroundr  r   r   join_merge_parsed_listr   r   r   r   rU   r   rr   r   r   
ValueError)rP   r   r  r_   r  cli_arg	snake_valrL   rL   rS   r  #  s2   

z&CliSettingsSource._resolve_parsed_argsr_   rU   r  rH   c                 C  s   | j |i  }|sdS tt|}|jrO|jdrO||= |jdd }d|j d| 	|| }||vr=d| dn|| dd  d	| d||< d
S dS )z
        Workaround for nested alias path environment variables not being handled.
        See https://github.com/pydantic/pydantic-settings/issues/670
        Fr   Nr  z": {}, T)
r  r   ru   nextiterr   r`   r   r   r!  )rP   r   r_   r  	known_argr
  nested_dest
nested_valrL   rL   rS   r  B  s   z7CliSettingsSource._is_nested_alias_path_only_workaroundparsed_listtuple[type | None, type | None]c                 C  sr   | j |t}|tu stt|rtdd t|D s"|}||fS |r3t|dks1|d dr3tnt	}||fS )Nc                 s  s0    | ]}|t d urt|ttfvr|V  qd S r   )r   r   r   r   r   rL   rL   rS   r   ^  s    zACliSettingsSource._get_merge_parsed_list_types.<locals>.<genexpr>rC   r   [)
_cli_dict_argsr   r   r*   r   r  r   r   r   rU   )rP   r.  r_   
merge_typeinferred_typerL   rL   rS   _get_merge_parsed_list_typesY  s   
&z.CliSettingsSource._get_merge_parsed_list_typesmerged_listc              	   C  s`  g }d }| j |i }zttt| jj}t|	dgd t
u }W n ttfy2   d }Y nw t|D ]i\}}	||}
|
d u pG|
j }|d u rO|}n||krWtd|r|	dd}	z"|	drp|	drp|	dd n|	}t| |r~d| dn|}	W n ty   Y nw |	dr|	dr|	dd }	||	 q7d	|}|rd
| dS |S )N1r   zKMixing Decode and NoDecode across different AliasPath fields is not allowed\z\\r  rC   r%  r  r0  ])r  r   r"   r)  r*  ru   rr   r   r   validate_pythonrU   StopIterationr#   	enumerater   r-   r   r   r   floatr"  r   r   )rP   r5  r_   decode_listis_use_decodecli_arg_maplist_adapteris_num_type_strrz   itemr#  	is_decodeunquoted_itemmerged_list_strrL   rL   rS   _merged_list_to_strj  s<   
$
z%CliSettingsSource._merged_list_to_strc                 C  s  zg }d}|  ||\}}|D ]}}t|ts nu| }|dr.|dr.|dd  }|r| }|drC| |||}d}n>|dsM|drT| ||}n+z	| |||}W n! t	y~ } z||u rk||}| |||}W Y d }~nd }~ww d}|s0|s| |||}q|tu r|d	 W S |t
u r| ||W S i }	|D ]
}
|	t|
 qt|	W S  ty } z
td
| d| d }~ww )NFr0  r8  rC   r%  r  r&  Tr   zParsing error encountered for z: )r4  r   rU   stripr   r   _consume_comma_consume_object_or_array_consume_string_or_numberr"  r   rF  r   jsonloadsdumps	Exceptionr-   )rP   r.  r_   r5  is_last_consumed_a_valuer2  r3  r  emerged_dictrB  rL   rL   rS   r!    sV   


z$CliSettingsSource._merge_parsed_listrB  rO  c                 C  s   |s| d |dd  S )Nz""rC   )r   )rP   rB  r5  rO  rL   rL   rS   rH    s   
z CliSettingsSource._consume_commac                 C  s   d}| dr	dnd}d}tdt|D ]K}|| dkr(||d  dkr(| }q|r+q|| dv r6|d7 }q|| d	v r_|d8 }|| |kr_|d
kr_||d |d   ||d d    S qtd| d)NrC   r&  r'  r8  Fr  r7  )r&  r0  )r'  r8  r   zMissing end delimiter ")r   ranger   r   r-   )rP   rB  r5  countclose_delimin_strconsumedrL   rL   rS   rI    s"   
z*CliSettingsSource._consume_object_or_arrayr2  type[Any] | Nonec           	      C  sz  |t urdnt|}d}|t|k r:|| dkr'|dks$||d  dkr'| }|s0|| dkr0n
|d7 }|t|k s|r@td|d |  }|tt fv rzzt| W n tys   || jkrbd}|d	vrq|dsqd| d}Y nw |	| n=d
d |
ddD \}}|dr|ds|ds|drtd| |d|d}}|	t||i ||d  S )Nr   Fr  rC   r7  r  zMismatched quotesr   )truefalser   c                 s  s    | ]}|V  qd S r   rL   )rx   kvrL   rL   rS   r     s    z>CliSettingsSource._consume_string_or_number.<locals>.<genexpr>=z1Dictionary key=val parameter is a quoted string: )rU   r   r-   rG  r   r<  r"  r   r   r   splitr   rK  rM  )	rP   rB  r5  r2  rV  is_find_end_quote
val_stringr  r  rL   rL   rS   rJ    s:   $
(z+CliSettingsSource._consume_string_or_numberr]   r   rr   r'   c                 C  s   t |jv rd}n.t|jv rd}n&t|jv r,d}t|jts+t| d|j d| dn
t	|jv r4d}nd S |j
turIt| d|j d| dd S )	NCliImplicitFlagCliExplicitFlagCliToggleFlagz
 argument r   z must have a default bool valueCliDualFlagz is not of type bool)r7   r   r6   r:   r   r   rH   r-   rW   r5   r   )rP   r]   r_   rr   cli_flag_namerL   rL   rS   _verify_cli_flag_annotations  s"   




z.CliSettingsSource._verify_cli_flag_annotationslist[tuple[str, FieldInfo]]c                 C  s  g }g g g }}}t | D ]\}}t|jv rm| s)td|j d| dt||^}}	t|dkrBtd|j d| ddd t	|j
D }
|
D ]}t|sdt|sdtd|j d| dqN|||f qt|jv rt||^}}	t|dkrtd	|j d| dt|j
tttttfd
d}|s|||f q|||f q| ||| |||f q|rt|dkrddd |D }t|j d| |rddd || D }t|j d| || | | S )Nzsubcommand argument r   z has a default valuerC   z has multiple aliasesc                 S  r   r   r   r   rL   rL   rS   r     r   z6CliSettingsSource._sort_arg_fields.<locals>.<listcomp>z$ has type not derived from BaseModelzpositional argument Tr   r(  c                 S     g | ]\}}|qS rL   rL   rx   ry   inforL   rL   rS   r         z- has multiple variadic positional arguments: c                 S  rf  rL   rL   rg  rL   rL   rS   r   "  ri  z= has variadic positional arguments and subcommand arguments: )r?   r   r9   r   is_requiredr-   rW   r>   r   r   r   r%   r&   r   r8   r<   r   r   r   r   r   rd  r   )rP   r]   positional_variadic_argpositional_argssubcommand_argsoptional_argsr_   rr   r   r   r   
field_typer   field_namesrL   rL   rS   _sort_arg_fields  sN   

z"CliSettingsSource._sort_arg_fieldsr   c                 C  r   )z#The connected root parser instance.)_root_parserr{   rL   rL   rS   r   )  s   zCliSettingsSource.root_parserparser_methodmethod_namerI   Callable[..., Any]c                   s^   d ur j du r  dkr tjtr 	 	 ddfdd}|S d u r-d fdd}|S S )NFr   r   rF   rj   "list[str] | tuple[str, ...] | None	namespaceNamespace | NonerJ   r   c                   sv   g }|rt t |ng D ]&}dj d}td| d|}|r/|d |d }|| q | ||S )Nr7  z{1,2}z^(z[^\s=]+)(.*)rC   r1   )	shlexr\  r   r   rematchgrouplowerr   )r   rj   rw  insensitive_argsr
  flag_prefixmatched)rs  rP   rL   rS   parse_args_insensitive_method8  s   zOCliSettingsSource._connect_parser_method.<locals>.parse_args_insensitive_methodrI   c                    s   t d  d)Nz0cannot connect CLI settings source root parser: z. is set to `None` but is needed for connectingr,   r~   )rt  rL   rS   none_parser_methodJ  s   
zDCliSettingsSource._connect_parser_method.<locals>.none_parser_method)NN)r   rF   rj   rv  rw  rx  rJ   r   )rj   r   rI   r   rJ   r   )ra   r   rr  rF   )rP   rs  rt  rj   rI   r  r  rL   )rt  rs  rP   rS   _connect_parser_method.  s   

z(CliSettingsSource._connect_parser_methodc                   s   |  |d d fdd}|S )	Nr   r^   r   rI   rJ   c                   sx     ds  d | fi  S  fdddD }|d  d7  < | fi |}t|ds4td	|jd
i  S )N _is_cli_mutually_exclusive_grouprequiredc                   s    i | ]}| v r|  |qS rL   )popr	  rI   rL   rS   r|   \  r}   zUCliSettingsSource._connect_group_method.<locals>.add_group_method.<locals>.<dictcomp>)titler   r  z (mutually exclusive)add_mutually_exclusive_groupzcannot connect CLI settings source root parser: group object is missing add_mutually_exclusive_group but is needed for connectingrL   )r  hasattrr-   r  )r^   rI   main_group_kwargsr|  add_argument_groupr  rS   add_group_methodW  s   


zACliSettingsSource._connect_group_method.<locals>.add_group_method)r^   r   rI   r   rJ   r   )r  )rP   r   r  rL   r  rS   _connect_group_methodT  s   z'CliSettingsSource._connect_group_methodc	           
   
     s   i  _ d fdd}	| _|d u r jr|	ntj} |d _ |d	 _ | _	 |d
 _
 |d _ |d _| _i  _tt _    j j jg  j jd g td d S )Nrj   r   rI   rJ   r   c                    s4   t j| i |\} } jD ]}| j|< qtt| S r   )r   parse_known_argsr  r   r   )rj   rI   unknown_argsr   r{   rL   rS   _parse_known_argsu  s   

zACliSettingsSource._connect_root_parser.<locals>._parse_known_argsr   r   r   r   r   r^   r]   
added_argsr`   subcommand_prefixr|  alias_prefixesmodel_default)rj   r   rI   r   rJ   r   )r  rr  r   r   
parse_argsr  r   _add_argumentr  
_add_group_add_parser_add_subparsers_format_help_formatter_classr1  r	   r   r  _add_default_help_add_parser_argsr   r   r   r(   )
rP   r   r   r   r   r   r   r   r   r  rL   r{   rS   r   h  s6   
z&CliSettingsSource._connect_root_parserc                 C  s   t | jtrD| js&t| j D ]\}}t||| jd^}}d|v r% d S q| j	| j
| jd d  d| jd d  ddtdd d S d S )N)ra   helprC   hr1   zshow this help message and exit)actionr   r  )r   rr  rF   r   r?   r   r   r>   ra   r  r   r   r   )rP   r_   rr   r   r   rL   rL   rS   r    s    
z#CliSettingsSource._add_default_helpFr^   r  r`   r  r|  r  r  is_model_suppresseddiscriminator_valsdict[str, set[Any]]is_last_discriminatorr   c                   s  d }i }t t|stt|rtt||sd n|}| |D ]\}}t||| j|||| j| j| j	| j
d| jd}||j |jr|jD ]}||}| j|j | }|g|_d|jd< | j|jd< |jd u rnd nt|j|jd< t|jdkrd n|j|jd< | jr|jd u rd nt|j|jd< |d u r| j|d	| d
t|jdkr|jnd dn|}t|dr|jr|jd d  d| dnd| d|_| j|g|jR i |j|_| j|j|g |j  d| |j! dd g t"d qIq | j# |j |jd< t$|jd< | %||||	|jd< | &|j'|jd< | j(o&|) o&|t"u |jd< | *|||||
|}|r?|jd |v r@q | +|j||j, t-|j.v r[| /|j||j!|\} | 0|j|| |j1rt2|j'dds| j3|||j||| ||j|||j4||	d q t5|j.v rg | j6|jd < q |j7st8|t9r| j:|fi |}|d u r|n|}|jddkr d7   fdd|D |_| j;|g|jR i |j |t<|7 }q | =|||||| |S )Nrf   )r^   rr   rs   r]   r_   r`   ra   rb   rd   rf   rh   Fr   r   r   rC   r  subcommandsr   )r  r   r   metavarr%  r  r'  r&  r   r  r   r   r  __pydantic_root_model__)r  r  r  store_falseno-c                   s0   g | ]} d t |dkrdnd   | qS r   )r   r   r  rL   rS   r   1  s   0 z6CliSettingsSource._add_parser_args.<locals>.<listcomp>)>r%   r   r&   
issubclassrq  r\   r  ra   r   r   configr   rh   r   r   r   r   r   rj   rI   r  r   r   r   r   r   r  r  r  r  r^   r  r   r   r(   r   CLI_SUPPRESS_help_format_metavar_formatr   r   rj  _get_arg_names_convert_append_actionr   r8   r   _convert_positional_arg_convert_bool_flagr   getattr_add_parser_submodelsr   r;   r  r   r   r   r  r  r   _add_parser_alias_paths)rP   r^   r]   r  r`   r  r|  r  r  r  r  r  
subparsersrv   r_   rr   r
  r   r   subcommand_arg	arg_namescontextrL   r  rS   r    s   





	


+
z"CliSettingsSource._add_parser_argsr   c                 C  s<   |rd|d< t |jttfddr|j| j|d < d S d S d S )Nr   r  Tr   r   )r<   r   r   r   r1  )rP   rI   rr   r   rL   rL   rS   r  8  s   z(CliSettingsSource._convert_append_actionc                 C  s   |d dkrNdd |j D }|s| jrtg}|rP| }|tu r/| jdkr-t|jtr-tnt}|tu r<|d= t	|d< d S |tu rR|d= |jrHdnd|d< d S d S d S d S )	Nr  rH   c                 S  s   g | ]}t |ttB r|qS rL   )r  r7   r6   )rx   metarL   rL   rS   r   @  s
    z8CliSettingsSource._convert_bool_flag.<locals>.<listcomp>toggler  r  
store_true)
r   r   r7   r  r   r   rH   r:   r5   r   )rP   rI   rr   r  meta_bool_flags	bool_flagrL   rL   rS   r  >  s,   
z$CliSettingsSource._convert_bool_flagr   tuple[list[str], str]c                 C  s   d}|d g}t |d< t| | j|d< | o|t u }|ddkr1|d= |r,dnd|d	< n|s7d
|d	< |d= |d= ||fS )Nr   r   r   r  r  r   +*nargs?r  )r(   r\   r   upperr   rj  r   )rP   rI   rr   r   r  r  r  rj  rL   rL   rS   r  T  s   
z)CliSettingsSource._convert_positional_argr
  r\   c              	     s*  g }|j g| D ],}|jD ]&}	t|| jkr| |	 n
||dd |	 | j}
|
 vr3||
 qq| jr\| j	 D ]\}}||v r[t
|trM|gn|}| fdd|D  q=t }||j}|d urt|jjtfd|d |tdd |D  |sg S | ttt| |jd< |S )	Nr   rC   c                 3  s    | ]	}| vr|V  qd S r   rL   rx   aliasr  rL   rS   r         z3CliSettingsSource._get_arg_names.<locals>.<genexpr>T)r   collectc                 s  s    | ]}t |V  qd S r   )r   )rx   tagrL   rL   rS   r     s    r  )r`   r   r\   r   r   r   r   r   r   r   r   rU   extendr   r   r   r<   rr   r   r   r   r   from_iterabler  r   sortedrI   )rP   r
  r  r  r  r  r  r  prefixry   arg_nametargetaliases
alias_listtagsdiscriminatorsrL   r  rS   r  i  sB   	



z CliSettingsSource._get_arg_namesr   r   r  r  r   rl   c                   sX  t |tr	tdi }|d  d|d< |j|d< |	d |d< tdd |D |d	< |d	 r8t|d
kr8td| jrSt|d
krS|d jd u rJd nt|d j|d< |t	urit
t|sctt|rht||
}n|jt	urr|j}n|jd urz|j}|d u rd| j d}|d d urt| d|d  |d< n||d< |d }| |p|}|rt|d< ||d  d|	d< d|	d< d|	d< |s| jrtnd|d  d|	d< | j|fi |}| j|gfdd|D R i |	 |jr  | d|j t ini }|D ]'}| j|||  | d|| fdd|d
d  D |||||d u d qd S )Nz8cannot have nested models in a CliMutuallyExclusiveGroupr   z optionsr  r   r  c                 s  s    | ]}t |tV  qd S r   )r  r[   )rx   r]   rL   rL   rS   r     s    

z:CliSettingsSource._add_parser_submodels.<locals>.<genexpr>r  rC   z/cannot use union with CliMutuallyExclusiveGroupz	default: z (undefined)
Fr  r  r  constzset z from JSON string (default: {})r  c                 3  s    | ]	}  | V  qd S r   rL   r   r  rL   rS   r     r  r   c                   s   g | ]	}  | d qS )r   rL   r   rw   rL   rS   r     s    z;CliSettingsSource._add_parser_submodels.<locals>.<listcomp>r%  )r^   r]   r  r`   r  r|  r  r  r  r  r  )r  r[   r-   r   r  r   r   r   r   r(   r%   r   r&   r  r   default_factoryr   _is_field_suppressedr  r   r   r  r  discriminatorr   r  )rP   r^   r]   r   r  r`   r  r  r  rI   r_   rr   r   r  r  model_group_kwargsdesc_headerr   model_groupr  rL   )r`   r  rS   r    sv   

$


&"

z'CliSettingsSource._add_parser_submodelsrv   rn   c                 C  s  |r|}|d urt |tr| j|fi |n|}| D ]g\}}	|| jkr+| | n
||dd | }
i }t|d< d|d< d|d< d|d	< |	d u rUd
|d	< t| j|
< | j |
 g}| j	|
  D ]\}}|||_
|_qd| j|g|R i | ||
 qd S d S )Nr   rC   r   zpydantic alias pathr  r   r  r   r  r   )r   r   r  r   r   r   r  r1  r   r  rj   rI   r  r   )rP   r^   rv   r  r`   r  r|  r  ry   rz   r  rI   rj   r  r
  rL   rL   rS   r    s0   	 

z)CliSettingsSource._add_parser_alias_pathsobjc                 C  s$   | j st|S tdd t|D S )Nc                 S  r   r   r   r   rL   rL   rS   r     r   z8CliSettingsSource._get_modified_args.<locals>.<listcomp>)r   r   r   rP   r  rL   rL   rS   _get_modified_args	  s   z$CliSettingsSource._get_modified_argsobj_qualnamec                 C  sx   d|v r|d | dd  dd || dd d  D  }d|}|r.| d| dS t|dkr6|S d| d	S )
NJSONrC   c                 S  s   g | ]}|d kr|qS )r  rL   r	  rL   rL   rS   r     s    z=CliSettingsSource._metavar_format_choices.<locals>.<listcomp>r  r0  r8  r&  r'  )rz   r   r   )rP   rj   r  r  rL   rL   rS   _metavar_format_choices  s   6
z)CliSettingsSource._metavar_format_choicesc                   s  t |}t|rd|jv r|jS |jS |du rdS t|tr"t|S t|tjs-t	
|r1t|S t|tttfs<|j}t|}t|rR tt j |S t	|rd ttt |S t|trx  fdd|j D S t|tr jtt j |t|dr|jdS t|dS |tdu r jS t|st|rt |d	d
r t!|d j"S dS t|tr|jS t|#dd#ddS )z\Pretty metavar representation of a type. Adapts logic from `pydantic._repr.display_as_type`.z<locals>.z...c                   s   g | ]}t | jd kqS )r   )r\   r   r   r   r{   rL   rS   r   /      z=CliSettingsSource._metavar_format_recurse.<locals>.<listcomp>rY   )r  Nr  Frootr  ztyping.r   ztyping_extensions.)$rA   r@   rY   rW   r   r$   reprtyping
ForwardRefr)   is_typealiastyperU   r/   r0   r   rR   r   r*   r  r   map_metavar_format_recurser  
is_literalr.   r   r   r   r  r   r%   r&   r  r?   r   r   )rP   r  originrL   r{   rS   r    sL   





z)CliSettingsSource._metavar_format_recursec                 C  s   |  |ddS )Nr(  r  )r  r   r  rL   rL   rS   r  C  s   z!CliSettingsSource._metavar_formatc           	      C  sj  |j r|j nd}|s| |rtS | r9|td fv r9t|jvr8|d u r&dnd}||r1d| dnd| d7 }nld| j d}tt	|sLt
t	|rVdt|| d}n?|td fvrjt|rjd| | d}n+|jtd fvrt|j|j}d|d u r|jn| d}n|jd urd| |j d}t|jvr||rd	| n|7 }tt	| jtr|d
dS |S )Nr   zifdef: z (z	required)(z
(default: )z(default factory:  %z%%)r   r  r  rj  r(   r8   r   r   r%   r   r&   r  r@   r  r   r=   r   r  r:   r  rr  r   r   )	rP   r_   rr   r  r  _helpifdefr   	enum_namerL   rL   rS   r  F  s*   
 

 zCliSettingsSource._help_formatc                 C  s"   |j r|j nd}|tkpt|jv S )Nr   )r   r  r   )rP   rr   r  rL   rL   rS   r  a  s   z&CliSettingsSource._is_field_suppressedr  valuealias_path_only_defaultslist[Any] | dict[str, Any]c                 C  s   dd |j |jfD d }|jdd }|s!||g  || }n+||i  || }|d d D ]}	||	i  ||	 }q1||d g  ||d  }tt|jd }
|dgt|
d t| d  |||
< || S )Nc                 S  s8   g | ]}t |ttfrt |tr|ntt|jd  qS )r   )r   r   r   r   choicesr  rL   rL   rS   r   h  s    zECliSettingsSource._update_alias_path_only_default.<locals>.<listcomp>r   rC   r%  r   )	r  r   path
setdefaultr   rg   r  r  r   )rP   r  r  rr   r  
alias_pathalias_nested_pathsalias_defaultcurrent_pathnested_pathalias_path_indexrL   rL   rS   _update_alias_path_only_defaulte  s(   


"z1CliSettingsSource._update_alias_path_only_defaultrK   str | list[Any] | dict[str, Any]
list_style#Literal['json', 'argparse', 'lazy']
dict_styleLiteral['json', 'env']&list[str | list[Any] | dict[str, Any]]c                 C  s   |g}t |trFt |tr1|dkr!ddd t|D g}|S |dkr/dd t|D }|S t |trF|dkrFd	d t| D }|S )
Nlazyr  c                 s  s    | ]}| V  qd S r   rL   rx   vrL   rL   rS   r     s    z9CliSettingsSource._coerce_value_styles.<locals>.<genexpr>argparsec                 S  s   g | ]}| qS rL   rL   r  rL   rL   rS   r     r  z:CliSettingsSource._coerce_value_styles.<locals>.<listcomp>envc                 S  s   g | ]\}}| d | qS )r[  rL   )rx   kr  rL   rL   rS   r     r  )r   rU   r   r   rK  rL  r   r   )rP   r  r  r  r  ru   rL   rL   rS   _coerce_value_styles  s   


z&CliSettingsSource._coerce_value_stylesserialized_argsdict[str, list[str]]positionals_firstc                 C  s,   |s
| d | d  n| d | d  | d  S )Noptional
positional
subcommandrL   )r  r  rL   rL   rS   _flatten_serialized_args  s
   z*CliSettingsSource._flatten_serialized_argsr4   _is_submodelc                 C  sF  i }g }g }g }	t |rt|n| j D ]\}
}t||
}|j|kr$qt|jv r.|d u r.qtt	| j
|  }|jrY|	|t| | j||||dd}|	| ||7 }	qtt|sett|r| j||||dd}||d 7 }||d 7 }|	|d 7 }	qtd|j}|r| nd\}}t|tttfrt|nt|}|jr| ||||}t |jv rt|tr|n|gD ]}t|tttfrt|nt|}|| qq|j!"dt#kr|d	u r|d
kr|d7 }| j$||||dD ]}|| |  |j!"dt#ddfvr|| qqdd |D dd |D |	dS )NT)r  r  r  r  r  r  r  z(-*)(.+))r   r   r  Fz--r  )r  r  r  r  c                 S  $   g | ]}t |tst|n|qS rL   r   rU   rK  rM  rx   r  rL   rL   rS   r        $ z6CliSettingsSource._serialized_args.<locals>.<listcomp>c                 S  r  rL   r  r  rL   rL   rS   r     r  )r  r  r  )%r?   r   r   r   r  r   r9   r   r)  r*  r  ru   r   r   r   _serialized_argsr  r%   r&   rz  r{  r   groupsr   r   r   r   rK  rM  rU   r   r  r8   rI   r   r   r  )rP   r]   r  r  r  r  r  rn  rl  rm  r_   rr   r  r
  sub_argsr  
flag_charsr  r  rL   rL   rS   r    sr   "

 
" 
z"CliSettingsSource._serialized_args)2r   r   r   r   r   r   r   r   r   re   r   re   r   re   r   re   rG   re   r   r   r   r   r   r   r   re   r   rc   r   r   ra   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rJ   rK   )rJ   rk   )rj   r   rJ   r   )r   r   rJ   r   )rj   r  r   r  rJ   r  )rJ   r  )r   r  rJ   r  )r   r  rJ   ri   )r   r  r_   rU   r  ri   rJ   rH   )r.  ri   r_   rU   rJ   r/  )r5  ri   r_   rU   rJ   rU   )r.  ri   r_   rU   rJ   rU   )rB  rU   r5  ri   rO  rH   rJ   rU   )rB  rU   r5  ri   rJ   rU   )rB  rU   r5  ri   r2  rW  rJ   rU   )r]   r   r_   rU   rr   r'   rJ   rK   )r]   r   rJ   re  )rJ   r   )
rs  r   rt  rU   rj   r   rI   r   rJ   ru  )r   r   rJ   ru  )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rJ   rK   )rJ   rK   )r^   r   r]   r   r  ri   r`   rU   r  rU   r|  r   r  ri   r  r   r  rH   r  r  r  rH   rJ   r   )rI   rk   rr   r'   r   rH   rJ   rK   )rI   rk   rr   r'   r  r   rJ   rK   )
rI   rk   rr   r'   r   rU   r  r   rJ   r  )r
  r\   r  rU   r  ri   r  ri   r  r  r  rH   rJ   ri   )r^   r   r]   r   r   r   r  ri   r`   rU   r  rU   r  rU   r  ri   rI   rk   r_   rU   rr   r'   r   rl   r  r   r  rH   rJ   rK   )r^   r   rv   rn   r  ri   r`   rU   r  rU   r|  r   rJ   rK   )r  r   rJ   rl   r   )rj   ri   r  r   rJ   rU   )r  r   rJ   rU   )
r_   rU   rr   r'   r  r   r  rH   rJ   rU   )rr   r'   rJ   rH   )
r  rU   r  r   rr   r'   r  rk   rJ   r  )rK  rK  )
r  r   r  r  r  r  r  r	  rJ   r
  )r  r  r  rH   rJ   ri   )rK  rK  FF)r]   r4   r  r  r  r	  r  rH   r  rH   rJ   r  )3rW   rX   rY   r   r   add_argumentr  r   
add_parseradd_subparsersformat_helpr   rN   r   r   r   r  r  r4  rF  r!  rH  rI  rJ  rd  rq  propertyr   r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  staticmethodr  r  rZ   rL   rL   rQ   rS   r      s    5 
%




-



-

&
- 




+
T
!
	
+


 r   )or   
__future__r   _annotationsr  rK  rz  ry  r   r  r  r   r   r   r   r   r   collectionsr	   collections.abcr
   r   r   enumr   	functoolsr   	itertoolsr   textwrapr   typesr   r   r   r   r   r   r   r   r   r   r   r   pydanticr   r   r   r    r!   r"   r#   pydantic._internal._reprr$   pydantic._internal._utilsr%   pydantic.dataclassesr&   pydantic.fieldsr'   pydantic_corer(   typing_inspectionr)   typing_inspection.introspectionr*   
exceptionsr-   utilsr.   r/   r0   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   r  rD   pydantic_settings.mainrE   rF   r[   r\   r   CliSubCommandCliPositionalArgrH   r   r_  r`  ra  rb  r  CliSuppressr   rU   CliUnknownArgsr   rL   rL   rL   rS   <module>   s`     4$0$	 