a
    _g^                    @  s  U 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
mZmZ ejdkrld dlmZ d dlmZmZmZmZmZ d dlmZm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"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.m/Z/m0Z0m1Z1m2Z2 d dl3Z3d dl4m5Z5 d dl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= d dl>m?Z? d dl@mAZAmBZBmCZC d dlDmEZEmFZFmGZG d dlHmIZI d dlJmKZK d dlLmMZM d dl3mNZNmOZOmPZPmQZQ d dlRmSZS e%r.ejdkrd dlTaTndaTd dlUaUd dlVaVd dlWmXZX d dlYmZZZ e/deXe9B dZ[ndaVdaTdaUe&Z[dddd Z\ddd!d"Z]ddd#d$Z^e0ee_e.e0ee_f  f Z`e0ee_e.e0ee_f  f Zaed%Zbd&ecd'< ed%Zdd(ecd)< G d*d+ d+ZeG d,d- d-ZfG d.d/ d/egZhG d0d1 d1ZiG d2d3 d3ZjG d4d5 d5ZkG d6d7 d7ZlG d8d9 d9eZmG d:d; d;e9Zne/d<ZoeNe0eodf eif ZpeNeoejf Zqe/d=erdZseNesekf ZteNeself ZueZveNeoevf Zwddd?d@dAdBdCdDZxG dEdF dFe_ZyG dGdH dHeZzG dIdJ dJezZ{G dKdL dLezZ|G dMdN dNezZ}G dOdP dPe}Z~G dQdR dRe}ZG dSdT dTeZG dUdV dVee)eo ZG dWdX dXeZG dYdZ dZe|eZG d[d\ d\e|eZG d]d^ d^eZG d_d` d`e|eZG dadb dbe+e_e-e_ f ZG dcdd ddeZddfd?dfdgdhdiZddjdjdkdldmdnZddod?d?djdodpdqdrZddededdsdtdjd?d?djdodudvdwZdxdyd?dzd{d|Zdxd?d}d~dZdxdyd?dzddZddxdd?d?d?dddZddd}ddZdxdddddZdxdddddZdddddZi d>fdfddd?ddddZdd?dddZdS )    )annotationsN)ABCabstractmethod   	   )BooleanOptionalAction)SUPPRESSArgumentParser	NamespaceRawDescriptionHelpFormatter_SubParsersAction)defaultdictdeque)asdictis_dataclass)Enum)Path)dedent)BuiltinFunctionTypeFunctionTypeSimpleNamespace)TYPE_CHECKINGAnyCallableDictGenericIteratorMappingNoReturnOptionalSequenceTypeVarUnioncastoverload)dotenv_values)AliasChoices	AliasPath	BaseModelJson	RootModelSecretTypeAdapter)Representation)WithArgsTypesorigin_is_uniontyping_base)deep_updateis_model_classlenient_issubclass)is_pydantic_dataclass)	FieldInfo)PydanticUndefined)	Annotated_AnnotatedAliasget_args
get_origin)path_type_labelr      )PydanticDataclass)BaseSettingsPydanticModel)boundNonereturnc               
   C  sL   t d urd S zdd l a W n. tyF }  ztd| W Y d } ~ n
d } ~ 0 0 d S )Nr   zBPyYAML is not installed, run `pip install pydantic-settings[yaml]`)yamlImportErrore rJ   g/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/pydantic_settings/sources.pyimport_yamlF   s    rL   c               
   C  sl   t jdk rTtd urd S zdd laW qh tyP }  ztd| W Y d } ~ qhd } ~ 0 0 ntd ur`d S dd lad S )Nr=   r   zAtomli is not installed, run `pip install pydantic-settings[toml]`)sysversion_infotomlirG   tomllibrH   rJ   rJ   rK   import_tomlP   s    
"rQ   c               
   C  s\   z(ddl ma ddlma ddlma W n. tyV }  ztd| W Y d } ~ n
d } ~ 0 0 d S )Nr   )TokenCredential)ResourceNotFoundError)SecretClientzdAzure Key Vault dependencies are not installed, run `pip install pydantic-settings[azure-key-vault]`)Zazure.core.credentialsrR   Zazure.core.exceptionsrS   Zazure.keyvault.secretsrT   rG   rH   rJ   rJ   rK   import_azure_key_vault`   s    rU    PathTypeDEFAULT_PATH
DotenvTypeENV_FILE_SENTINELc                   @  s   e Zd ZdZdS )NoDecodez0Annotation to prevent decoding of a field value.N__name__
__module____qualname____doc__rJ   rJ   rJ   rK   r[   y   s   r[   c                   @  s   e Zd ZdZdS )ForceDecodez.Annotation to force decoding of a field value.Nr\   rJ   rJ   rJ   rK   ra      s   ra   c                   @  s   e Zd ZdS )SettingsErrorNr]   r^   r_   rJ   rJ   rJ   rK   rb      s   rb   c                   @  s   e Zd ZdS )_CliSubCommandNrc   rJ   rJ   rJ   rK   rd      s   rd   c                   @  s   e Zd ZdS )_CliPositionalArgNrc   rJ   rJ   rJ   rK   re      s   re   c                   @  s   e Zd ZdS )_CliImplicitFlagNrc   rJ   rJ   rJ   rK   rf      s   rf   c                   @  s   e Zd ZdS )_CliExplicitFlagNrc   rJ   rJ   rJ   rK   rg      s   rg   c                      s<   e Zd Zddddd fddZdd	d
 fddZ  ZS )_CliInternalArgParserTboolr   rC   )cli_exit_on_errorkwargsrE   c                   s   t  jf i | || _d S N)super__init___cli_exit_on_error)selfrj   rk   	__class__rJ   rK   rn      s    z_CliInternalArgParser.__init__strr   )messagerE   c                   s$   | j std| t | d S )Nzerror parsing CLI: )ro   rb   rm   error)rp   rt   rq   rJ   rK   ru      s    z_CliInternalArgParser.error)T)r]   r^   r_   rn   ru   __classcell__rJ   rJ   rq   rK   rh      s   rh   c                   @  s   e Zd ZdS )CliMutuallyExclusiveGroupNrc   rJ   rJ   rJ   rK   rw      s   rw   T_CliBoolFlagTri   bool | NonezOptional[PydanticModel])modelis_requiredrj   rE   c           	      C  s   t | }|du r2t|r2|jd}t|tr2|}|du r>d}g }t| D ]8\}}t|j	v rNt
| |dur|t
| |  S || qN|r|rdd| dnd}|rt|nt|dS )a  
    Get the subcommand from a model.

    Args:
        model: The model to get the subcommand from.
        is_required: Determines whether a model must have subcommand set and raises error if not
            found. Defaults to `True`.
        cli_exit_on_error: Determines whether this function exits with error if no subcommand is found.
            Defaults to model_config `cli_exit_on_error` value if set. Otherwise, defaults to `True`.

    Returns:
        The subcommand model if found, otherwise `None`.

    Raises:
        SystemExit: When no subcommand is found and is_required=`True` and cli_exit_on_error=`True`
            (the default).
        SettingsError: When no subcommand is found and is_required=`True` and
            cli_exit_on_error=`False`.
    Nrj   Tz#Error: CLI subcommand is required {, }z@Error: CLI subcommand is required but no subcommands were found.)typer3   model_configget
isinstanceri   _get_model_fieldsitemsrd   metadatagetattrappendjoin
SystemExitrb   )	r{   r|   rj   	model_clsmodel_defaultsubcommands
field_name
field_infoerror_messagerJ   rJ   rK   get_subcommand   s(    

r   c                   @  s   e Zd ZdS )EnvNoneTypeNrc   rJ   rJ   rJ   rK   r      s   r   c                   @  s   e Zd ZdZddddZdddd	d
ZdddddZeddddZeddddZ	e
ddddddZdddddZddddddd d!Zddddd"d#d$Ze
ddd%d&Zd'S )(PydanticBaseSettingsSourcezi
    Abstract base class for settings sources, every settings source classes should inherit from it.
    type[BaseSettings])settings_clsc                 C  s   || _ |j| _i | _i | _d S rl   )r   r   config_current_state_settings_sources_data)rp   r   rJ   rJ   rK   rn      s    z#PydanticBaseSettingsSource.__init__dict[str, Any]rC   )staterE   c                 C  s
   || _ dS )z
        Record the state of settings from the previous settings sources. This should
        be called right before __call__.
        Nr   )rp   r   rJ   rJ   rK   _set_current_state   s    z-PydanticBaseSettingsSource._set_current_statezdict[str, dict[str, Any]])statesrE   c                 C  s
   || _ dS )z
        Record the state of settings from all previous settings sources. This should
        be called right before __call__.
        Nr   )rp   r   rJ   rJ   rK   _set_settings_sources_data   s    z5PydanticBaseSettingsSource._set_settings_sources_datarD   c                 C  s   | j S )z`
        The current state of the settings, populated by the previous settings sources.
        r   rp   rJ   rJ   rK   current_state   s    z(PydanticBaseSettingsSource.current_statec                 C  s   | j S )z=
        The state of all previous settings sources.
        r   r   rJ   rJ   rK   settings_sources_data  s    z0PydanticBaseSettingsSource.settings_sources_datar6   rs   tuple[Any, str, bool]fieldr   rE   c                 C  s   dS )a  
        Gets the value, the key for model creation, and a flag to determine whether value is complex.

        This is an abstract method that should be overridden in every settings source classes.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple that contains the value, key and a flag to determine whether value is complex.
        NrJ   rp   r   r   rJ   rJ   rK   get_field_value  s    z*PydanticBaseSettingsSource.get_field_valueri   r   rE   c                 C  s   t |j|jS )z
        Checks whether a field is complex, in which case it will attempt to be parsed as JSON.

        Args:
            field: The field.

        Returns:
            Whether the field is complex.
        )_annotation_is_complex
annotationr   )rp   r   rJ   rJ   rK   field_is_complex  s    
z+PydanticBaseSettingsSource.field_is_complexr   r   r   valuevalue_is_complexrE   c                 C  s(   |dur$|  |s|r$| |||S |S )aF  
        Prepares the value of a field.

        Args:
            field_name: The field name.
            field: The field.
            value: The value of the field that has to be prepared.
            value_is_complex: A flag to determine whether value is complex.

        Returns:
            The prepared value.
        N)r   decode_complex_value)rp   r   r   r   r   rJ   rJ   rK   prepare_field_value*  s    z.PydanticBaseSettingsSource.prepare_field_value)r   r   r   rE   c                 C  s6   |r,t |jv s(| jddu r,t|jvr,|S t|S )a  
        Decode the value for a complex field

        Args:
            field_name: The field name.
            field: The field.
            value: The value of the field that has to be prepared.

        Returns:
            The decoded value for further preparation
        Zenable_decodingF)r[   r   r   r   ra   jsonloads)rp   r   r   r   rJ   rJ   rK   r   ;  s    z/PydanticBaseSettingsSource.decode_complex_valuec                 C  s   d S rl   rJ   r   rJ   rJ   rK   __call__O  s    z#PydanticBaseSettingsSource.__call__N)r]   r^   r_   r`   rn   r   r   propertyr   r   r   r   r   r   r   r   rJ   rJ   rJ   rK   r      s   r   c                      sX   e Zd ZdZdddd fddZdd	d
dddZddddZd	dddZ  ZS )DefaultSettingsSourcea  
    Source class for loading default object values.

    Args:
        settings_cls: The Settings class.
        nested_model_default_partial_update: Whether to allow partial updates on nested model default object fields.
            Defaults to `False`.
    Nr   rz   )r   #nested_model_default_partial_updatec                   s   t  | i | _|d ur|n| jdd| _| jr|j D ]\\}}t||^}}|d }t	t
|jr|t|j| j|< q>tt
|jr>|j | j|< q>d S )Nr   Fr   )rm   rn   defaultsr   r   r   model_fieldsr   _get_alias_namesr   r   defaultr   r3   Z
model_dump)rp   r   r   r   r   alias_names_preferred_aliasrq   rJ   rK   rn   ^  s    zDefaultSettingsSource.__init__r6   rs   r   r   c                 C  s   dS N)NrV   FrJ   r   rJ   rJ   rK   r   o  s    z%DefaultSettingsSource.get_field_valuer   rD   c                 C  s   | j S rl   )r   r   rJ   rJ   rK   r   s  s    zDefaultSettingsSource.__call__c                 C  s   | j j d| j dS )Nz%(nested_model_default_partial_update=))rr   r]   r   r   rJ   rJ   rK   __repr__v  s    zDefaultSettingsSource.__repr__)N	r]   r^   r_   r`   rn   r   r   r   rv   rJ   rJ   rq   rK   r   T  s
   	r   c                      sZ   e Zd ZdZddddd fddZd	d
ddddZddddZd
dddZ  ZS )InitSettingsSourcezX
    Source class for loading values provided during settings class initialization.
    Nr   r   rz   )r   init_kwargsr   c                   s2   || _ t | |d ur|n| jdd| _d S )Nr   F)r   rm   rn   r   r   r   )rp   r   r   r   rq   rJ   rK   rn     s    zInitSettingsSource.__init__r6   rs   r   r   c                 C  s   dS r   rJ   r   rJ   rJ   rK   r     s    z"InitSettingsSource.get_field_valuerD   c                 C  s$   | j rttttf | jS | jS rl   )r   r-   r   rs   r   Zdump_pythonr   r   rJ   rJ   rK   r     s    zInitSettingsSource.__call__c                 C  s   | j j d| jdS )Nz(init_kwargs=r   )rr   r]   r   r   rJ   rJ   rK   r     s    zInitSettingsSource.__repr__)Nr   rJ   rJ   rq   rK   r   |  s    r   c                	      s   e Zd Zddddddddd fddZd	d	d
ddZdd	ddddZddddddZdddddZdd	ddddZddddZ	  Z
S ) PydanticBaseEnvSettingsSourceNr   rz   
str | NonerC   )r   case_sensitive
env_prefixenv_ignore_emptyenv_parse_none_strenv_parse_enumsrE   c                   s   t  | |d ur|n| jdd| _|d ur4|n| jdd| _|d urP|n| jdd| _|d url|n
| jd| _|d ur|n
| jd| _d S )Nr   Fr   rV   r   r   r   )	rm   rn   r   r   r   r   r   r   r   )rp   r   r   r   r   r   r   rq   rJ   rK   rn     s    	z&PydanticBaseEnvSettingsSource.__init__rs   )r   rE   c                 C  s   | j s| S |S rl   )r   lower)rp   r   rJ   rJ   rK   _apply_case_sensitive  s    z3PydanticBaseEnvSettingsSource._apply_case_sensitiver6   zlist[tuple[str, str, bool]]r   c                 C  s8  g }t |jttfr |j }n|j}|rt |tr|D ]t}t |trn||| |t	|dkrddndf q8t |tr8t
t|d }||| |t	|dkrdndf q8n||| |df |r| jddr4tt|jrt|j|jr||| | j| df n||| | j| df |S )a  
        Extracts field info. This info is used to get the value of field from environment variables.

        It returns a list of tuples, each tuple contains:
            * field_key: The key of field that has to be used in model creation.
            * env_name: The environment variable name of the field.
            * value_is_complex: A flag to determine whether the value from environment variable
              is complex and has to be parsed.

        Args:
            field (FieldInfo): The field.
            field_name (str): The field name.

        Returns:
            list[tuple[str, str, bool]]: List of tuples, each tuple contains field_key, env_name, and value_is_complex.
           TFr   populate_by_name)r   validation_aliasr'   r(   Zconvert_to_aliaseslistrs   r   r   lenr$   r   r   r0   r;   r   _union_is_complexr   r   )rp   r   r   r   Zv_aliasaliasZ	first_argrJ   rJ   rK   _extract_field_info  s(    

(
 z1PydanticBaseEnvSettingsSource._extract_field_infor   )r   field_valuesrE   c                 C  s   i }|  D ]\}}d}|j}t|}tt|jrft|dkrftd|v rf|D ]}	|	durP|	} qfqP|rtt|ds~|||< q|j  D ]&\}
}|j	s|

 |
 kr|} qq|s|||< qt|jtrt|tr| ||||
< q|||
< q|S )ae  
        Replace field names in values dict by looking in models fields insensitively.

        By having the following models:

            ```py
            class SubSubSub(BaseModel):
                VaL3: str

            class SubSub(BaseModel):
                Val2: str
                SUB_sub_SuB: SubSubSub

            class Sub(BaseModel):
                VAL1: str
                SUB_sub: SubSub

            class Settings(BaseSettings):
                nested: Sub

                model_config = SettingsConfigDict(env_nested_delimiter='__')
            ```

        Then:
            _replace_field_names_case_insensitively(
                field,
                {"val1": "v1", "sub_SUB": {"VAL2": "v2", "sub_SUB_sUb": {"vAl3": "v3"}}}
            )
            Returns {'VAL1': 'v1', 'SUB_sub': {'Val2': 'v2', 'SUB_sub_SuB': {'VaL3': 'v3'}}}
        N   r   )r   r   r:   r0   r;   r   r   hasattrr   r   r   r4   r)   r   dict'_replace_field_names_case_insensitively)rp   r   r   valuesnamer   Zsub_model_fieldr   argsargZsub_model_field_namefrJ   rJ   rK   r     s0    &
zEPydanticBaseEnvSettingsSource._replace_field_names_case_insensitively)field_valuerE   c                 C  sJ   i }|  D ]8\}}t|ts<t|ts,|n| |||< qd||< q|S )ze
        Recursively parse values that are of "None" type(EnvNoneType) to `None` type(None).
        N)r   r   r   r   _replace_env_none_type_values)rp   r   r   keyr   rJ   rJ   rK   r   '  s    

z;PydanticBaseEnvSettingsSource._replace_env_none_type_valuesr   c           	      C  sX   |  ||\}}}|sN| jddr,||ksN| ||}|d ^}}|||fS |||fS )a8  
        Gets the value, the preferred alias key for model creation, and a flag to determine whether value
        is complex.

        Note:
            In V3, this method should either be made public, or, this method should be removed and the
            abstract method get_field_value should be updated to include a "use_preferred_alias" flag.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple that contains the value, preferred key and a flag to determine whether value is complex.
        r   Fr   )r   r   r   r   )	rp   r   r   r   	field_keyr   Zfield_infosZpreferred_keyr   rJ   rJ   rK   _get_resolved_field_value5  s    
z7PydanticBaseEnvSettingsSource._get_resolved_field_valuerD   c                 C  s6  i }| j j D ]\}}z| ||\}}}W n@ typ } z(td| d| jj d|W Y d }~n
d }~0 0 z| ||||}W n@ t	y } z(td| d| jj d|W Y d }~n
d }~0 0 |d ur| j
d urt|tr| |}nt|trd }| js(t|tr(| ||||< q|||< q|S )Nzerror getting value for field "z" from source ""zerror parsing value for field ")r   r   r   r   	Exceptionrb   rr   r]   r   
ValueErrorr   r   r   r   r   r   r   )rp   datar   r   r   r   r   rI   rJ   rJ   rK   r   L  s>    

z&PydanticBaseEnvSettingsSource.__call__)NNNNN)r]   r^   r_   rn   r   r   r   r   r   r   rv   rJ   rJ   rq   rK   r     s         ,Er   c                
      s   e Zd ZdZdddddddddd fd	d
Zdd fddZedddddddZddddddZddddZ	  Z
S )SecretsSettingsSourcezE
    Source class for loading settings values from secret files.
    Nr   PathType | Nonerz   r   rC   )r   secrets_dirr   r   r   r   r   rE   c                   s4   t  |||||| |d ur"|n
| jd| _d S )Nr   )rm   rn   r   r   r   )rp   r   r   r   r   r   r   r   rq   rJ   rK   rn   u  s    
zSecretsSettingsSource.__init__r   rD   c                   s   i }| j du r|S t| j ttjfr,| j gn| j }dd |D }g | _|D ],}| sjtd| d qJ| j	| qJt
| js|S | jD ]}| stdt| qt  S )z4
        Build fields from "secrets" files.
        Nc                 S  s   g | ]}t | qS rJ   )r   
expanduser).0prJ   rJ   rK   
<listcomp>      z2SecretsSettingsSource.__call__.<locals>.<listcomp>zdirectory "z" does not existz.secrets_dir must reference a directory, not a )r   r   rs   osPathLikesecrets_pathsexistswarningswarnr   r   is_dirrb   r<   rm   r   )rp   ZsecretsZsecrets_dirsr   pathrq   rJ   rK   r     s     
 

zSecretsSettingsSource.__call__r   rs   ri   Path | None)dir_path	file_namer   rE   c                 C  sB   |  D ]4}|j|kr|  S |s|j | kr|  S qdS )af  
        Find a file within path's directory matching filename, optionally ignoring case.

        Args:
            dir_path: Directory path.
            file_name: File name.
            case_sensitive: Whether to search for file name case sensitively.

        Returns:
            Whether file path or `None` if file does not exist in directory.
        N)iterdirr   r   )clsr   r   r   r   rJ   rJ   rK   find_case_path  s    

z$SecretsSettingsSource.find_case_pathr6   r   r   c                 C  s   |  ||D ]r\}}}t| jD ]\}| ||| j}|s:q | r\|  ||f    S tj	d| dt
| ddd q qd||fS )al  
        Gets the value for field from secret file and a flag to determine whether value is complex.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple that contains the value (`None` if the file does not exist), key, and
                a flag to determine whether value is complex.
        zattempted to load secret file "z" but found a z	 instead.   )
stacklevelN)r   reversedr   r   r   is_file	read_textstripr   r   r<   )rp   r   r   r   env_namer   Zsecrets_pathr   rJ   rJ   rK   r     s    
z%SecretsSettingsSource.get_field_valuec                 C  s   | j j d| jdS )Nz(secrets_dir=r   )rr   r]   r   r   rJ   rJ   rK   r     s    zSecretsSettingsSource.__repr__)NNNNNN)r]   r^   r_   r`   rn   r   classmethodr   r   r   rv   rJ   rJ   rq   rK   r   p  s         "r   c                
      s   e Zd ZdZd(ddddddddd fdd	Zd
dddZddddddZddddddddZdddddZd)dddddd d!Z	ddd
d"d#d$d%Z
ddd&d'Z  ZS )*EnvSettingsSourcezN
    Source class for loading settings values from environment variables.
    Nr   rz   r   rC   )r   r   r   env_nested_delimiterr   r   r   rE   c                   sJ   t  |||||| |d ur"|n
| jd| _t| j| _|  | _	d S )Nr  )
rm   rn   r   r   r  r   r   env_prefix_len_load_env_varsenv_vars)rp   r   r   r   r  r   r   r   rq   rJ   rK   rn     s    
zEnvSettingsSource.__init__Mapping[str, str | None]rD   c                 C  s   t tj| j| j| jS rl   )parse_env_varsr   environr   r   r   r   rJ   rJ   rK   r    s    z EnvSettingsSource._load_env_varsr6   rs   r   r   c                 C  s>   d}|  ||D ]"\}}}| j|}|dur q4q|||fS )ah  
        Gets the value for field from environment variables and a flag to determine whether value is complex.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple that contains the value (`None` if not found), key, and
                a flag to determine whether value is complex.
        N)r   r	  r   )rp   r   r   env_valr   r  r   rJ   rJ   rK   r     s    z!EnvSettingsSource.get_field_valuer   ri   r   c           
   
   C  s   |  |\}}| jr0t|j|}|du r,|n|}|s8|rt|trF|S |du rh| ||| j}|r|S qz| |||}W n, t	y }	 z|s|	W Y d}	~	n
d}	~	0 0 t|t
rt|| ||| jS |S n|dur|S dS )a  
        Prepare value for the field.

        * Extract value for nested field.
        * Deserialize value to python object for complex field.

        Args:
            field: The field.
            field_name: The field name.

        Returns:
            A tuple contains prepared value for the field.

        Raises:
            ValuesError: When There is an error in deserializing value for complex field.
        N)_field_is_complexr   _annotation_enum_name_to_valr   r   r   explode_env_varsr	  r   r   r   r2   )
rp   r   r   r   r   
is_complexallow_parse_failureZenum_valZenv_val_builtrI   rJ   rJ   rK   r     s*    

z%EnvSettingsSource.prepare_field_valueztuple[bool, bool]r   c                 C  s>   |  |rd}n&tt|jr2t|j|jr2d}ndS d|fS )za
        Find out if a field is complex, and if so whether JSON errors should be ignored
        FT)FF)r   r0   r;   r   r   r   )rp   r   r  rJ   rJ   rK   r  6  s    
z#EnvSettingsSource._field_is_complexzFieldInfo | Any | NonezFieldInfo | None)r   r   r   rE   c                 C  s   |sdS t |tr|jn|}tt|s2t |tr\t|D ]}| |||}|r:|  S q:nt|slt	|rt
|}| D ]v\}}	| |	|D ]`\}
}}
|du s|r||ks||kr|	    S q| | ks| | kr|	    S qq|dS )aK  
        Find the field in a sub model by key(env name)

        By having the following models:

            ```py
            class SubSubModel(BaseSettings):
                dvals: Dict

            class SubModel(BaseSettings):
                vals: list[str]
                sub_sub_model: SubSubModel

            class Cfg(BaseSettings):
                sub_model: SubModel
            ```

        Then:
            next_field(sub_model, 'vals') Returns the `vals` field of `SubModel` class
            next_field(sub_model, 'sub_sub_model') Returns `sub_sub_model` field of `SubModel` class

        Args:
            field: The field.
            key: The key (env name).
            case_sensitive: Whether to search for key case sensitively.

        Returns:
            Field if it finds the next field otherwise `None`.
        N)r   r6   r   r0   r;   r/   r:   
next_fieldr3   r5   r   r   r   r   )rp   r   r   r   r   type_Ztype_has_keyfieldsr   r   r   r  rJ   rJ   rK   r  F  s$      zEnvSettingsSource.next_fieldr   )r   r   r	  rE   c                   sr  t t|jt}fdd||D }i }| D ]4\ }t fdd|D sXq6 jd }|j	^}	}
}|}|}|
D ]*}
||j}t|tr||i }q
||j}|s|r8|r8|r|\}}nd\}}|r8z|||}W n0 ty6 } z|s"|W Y d}~n
d}~0 0 t|tr6||vsdt|trd|| i kr6|||< q6|S )a  
        Process env_vars and extract the values of keys containing env_nested_delimiter into nested dictionaries.

        This is applied to a single field, hence filtering by env_var prefix.

        Args:
            field_name: The field name.
            field: The field.
            env_vars: Environment variables.

        Returns:
            A dictionary contains extracted values from nested env values.
        c                   s    g | ]\}}}|  j  qS rJ   )r  )r   r   r  r   rJ   rK   r     s   z6EnvSettingsSource.explode_env_vars.<locals>.<listcomp>c                 3  s   | ]}  |V  qd S rl   )
startswith)r   prefix)r  rJ   rK   	<genexpr>  r   z5EnvSettingsSource.explode_env_vars.<locals>.<genexpr>N)TT)r4   r;   r   r   r   r   anyr  splitr  r  r   r   
setdefaultr  r   r   r   )rp   r   r   r	  Zis_dictprefixesresultr  Zenv_name_without_prefixr   keyslast_keyenv_varZtarget_fieldr   r  Zallow_json_failurerI   rJ   )r  rp   rK   r  |  s>    



"
z"EnvSettingsSource.explode_env_varsc                 C  s   | j j d| jd| jdS )Nz(env_nested_delimiter=, env_prefix_len=r   )rr   r]   r  r  r   rJ   rJ   rK   r     s    zEnvSettingsSource.__repr__)NNNNNN)N)r]   r^   r_   r`   rn   r  r   r   r  r  r  r   rv   rJ   rJ   rq   rK   r    s          ". 67r  c                      s   e Zd ZdZedddddddfddddddddddd
 fd	d
ZddddZeddddddddddddddZdddddZ	ddddZ
dd fddZdddd Z  ZS )!DotEnvSettingsSourcezB
    Source class for loading settings values from env files.
    Nr   zDotenvType | Noner   rz   rC   )
r   env_fileenv_file_encodingr   r   r  r   r   r   rE   c
           
   	     sP   |t kr|n
|jd| _|d ur&|n
|jd| _t |||||||	 d S )Nr#  r$  )rZ   r   r   r#  r$  rm   rn   )
rp   r   r#  r$  r   r   r  r   r   r   rq   rJ   rK   rn     s    zDotEnvSettingsSource.__init__r
  rD   c                 C  s   |   S rl   )_read_env_filesr   rJ   rJ   rK   r    s    z#DotEnvSettingsSource._load_env_varsFencodingr   ignore_emptyparse_none_strr   ri   	file_pathr'  r   r(  r)  rE   c                C  s   t | |p
dd}t||||S )Nutf8r'  )r&   r  )r+  r'  r   r(  r)  Z	file_varsrJ   rJ   rK   _static_read_env_file  s    	z*DotEnvSettingsSource._static_read_env_filer+  rE   c                 C  s   | j || j| j| j| jdS )Nr&  )r.  r$  r   r   r   )rp   r+  rJ   rJ   rK   _read_env_file  s    z#DotEnvSettingsSource._read_env_filec                 C  s^   | j }|d u ri S t|ttjfr(|g}i }|D ](}t| }| r0|| 	| q0|S rl   )
r#  r   rs   r   r   r   r   r   updater0  )rp   Z	env_filesZdotenv_varsr#  Zenv_pathrJ   rJ   rK   r%    s    z$DotEnvSettingsSource._read_env_filesr   c                   s   t   }| jddk}| j D ]\}}|r$||v r:q$d}| jj D ]l\}}| ||D ]N\}}	}||	kst	|j
|jstt|j
r^t|j
|jr^||	r^d} qq^|rJ qqJ|s$|r|| jr|t| jd  }
|||
< q$|||< q$|S )NextraZforbidFT)rm   r   r   r   r	  r   r   r   r   r   r   r   r0   r;   r   r  r   r   )rp   r   Zis_extra_allowedr  Z	env_valueZenv_usedr   r   r   Zfield_env_nameZnormalized_env_namerq   rJ   rK   r     s6    



zDotEnvSettingsSource.__call__rs   c              
   C  s.   | j j d| jd| jd| jd| jd
S )Nz
(env_file=z, env_file_encoding=, env_nested_delimiter=r!  r   )rr   r]   r#  r$  r  r  r   rJ   rJ   rK   r   '  s    zDotEnvSettingsSource.__repr__)r]   r^   r_   r`   rZ   rn   r  staticmethodr.  r0  r%  r   r   rv   rJ   rJ   rq   rK   r"    s*   &#r"  c                      s  e Zd ZdZ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
fddddddddddddddddd	d	d	d	d	dd
d fddZeddddZedddddZedddddZddddddd fddZeddd d!Zedddd"d!Zdd#dd$dd%d!Zd&d'd(d)d*d+Zd&d'd'd)d,d-Zd'd&d.d'd/d0d1Zd'd&d'd2d3d4Zd'd&d5d'd6d7d8Zd9d'd:d;d<d=d>Zd9d'd:d
d<d?d@Zd9dAdBdCdDZedEddFdGZd	d'dddHdIdJdKZd	dHdLdMdNZejejejej	e
fdEd	d	d	d	d	dd
dOdPdQZdd9d&d'd'dd&ddRdS	dTdUZd'd'dVdWdXZdd:dd
dYdZd[Zd'd'd&d\d&d&d]d^d_Zdd9d;d&d'd'd'd&dd'd:d\dd
d`dadbZ ddcd&d'd'dd
dddedfZ!dd\dgdhdiZ"dtd&dd'djdkdlZ#dd'dgdmdnZ$dd'dgdodpZ%d'd:dd'dqdrdsZ&  Z'S )u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`.
            Otherwse, 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: Whether `bool` fields should be implicitly converted into CLI boolean flags.
            (e.g. --flag, --no-flag). Defaults to `False`.
        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`.
        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`.
        formatter_class: A class for customizing the root parser help text. Defaults to `argparse.RawDescriptionHelpFormatter`.
    NTr   r   z)bool | list[str] | tuple[str, ...] | Nonerz   r   zCallable[..., Any] | NonerC   )r   cli_prog_namecli_parse_argscli_parse_none_strcli_hide_none_typecli_avoid_jsoncli_enforce_requiredcli_use_class_docs_for_groupsrj   
cli_prefixcli_flag_prefix_charcli_implicit_flagscli_ignore_unknown_argscli_kebab_caser   root_parserparse_args_methodadd_argument_methodadd_argument_group_methodadd_parser_methodadd_subparsers_methodformatter_classrE   c              	     s  |d ur|n|j dtjd | _|d ur.|n|j dd| _|d urJ|n|j dd| _|sp| jdu rldn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|j dd| _|d ur|n|j dd| _| jd | _| jr\|
ds@|
ds@|
dd sNtd|
 |  jd7  _|d urj|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 r6t| j
| j|jd u r d nt|j|| jddn|}| j|||||||d |dvr|du rvtjdd  }n"t|ttfstdt| | j | !| j"|d d S )Nr6  r   r9  Fr:  TrC   nullr;  r<  rj   r=  rV   r>  -r   .z'CLI settings source prefix is invalid: r?  r@  rA  zGCase-insensitive matching is only supported on the internal root parser)r  r   r   r   r   )rj   progdescriptionrH  prefix_charsallow_abbrev)rB  rC  rD  rE  rF  rG  rH  NFr   z>cli_parse_args must be List[str] or Tuple[str, ...], recieved parsed_args)#r   r   rM   argvr6  r9  r:  r8  r;  r<  rj   r=  r>  _cli_flag_prefixr  endswithreplaceisidentifierrb   r?  r@  rA  rm   rn   rh   r`   r   _connect_root_parserr   r   tupler   r  _parse_argsrB  )rp   r   r6  r7  r8  r9  r:  r;  r<  rj   r=  r>  r?  r@  rA  r   rB  rC  rD  rE  rF  rG  rH  rq   rJ   rK   rn   [  s    *	


zCliSettingsSource.__init__r   rD   c                 C  s   d S rl   rJ   r   rJ   rJ   rK   r     s    zCliSettingsSource.__call__z"list[str] | tuple[str, ...] | boolzCliSettingsSource[T])r   rE   c                C  s   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.
        NrJ   )rp   r   rJ   rJ   rK   r     s    z,Namespace | SimpleNamespace | dict[str, Any])rR  rE   c                C  s   dS )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.
        NrJ   rp   rR  rJ   rJ   rK   r     s    )r   rR  z)list[str] | tuple[str, ...] | bool | Nonez?Namespace | SimpleNamespace | dict[str, list[str] | str] | Nonez%dict[str, Any] | CliSettingsSource[T])r   rR  rE   c                  s   |d ur|d urt dnf|d urb|du r6| ji dS |du rLtjdd  }| j| | j|dS |d urv| j|dS t  S d S )Nz/`args` and `parsed_args` are mutually exclusiveFrQ  Tr   )rb   r  rM   rS  rZ  rB  rm   r   )rp   r   rR  rq   rJ   rK   r     s    
r
  c                 C  s   d S rl   rJ   r   rJ   rJ   rK   r    s    z CliSettingsSource._load_env_varsc                C  s   dS )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.
        NrJ   r[  rJ   rJ   rK   r    s    rQ  z/Mapping[str, str | None] | CliSettingsSource[T]c                  s0  |d u ri S t |ttfr"t|}g }| D ]`\}}t |trR| ||||< q.|dr.|d ur.|dd | }| j	| | }|
| q.| j	 D ]$}| D ]}||vr| j||< qqdd | D }|rt|td t fdd| D sd	| < tttttf || j| j| j| _| S )
N:subcommand:r   c                 S  s    i | ]\}}| d s||qS )r\  )rU  )r   r   valrJ   rJ   rK   
<dictcomp>8  r   z4CliSettingsSource._load_env_vars.<locals>.<dictcomp>)r   c                 3  s    | ]}  d |v r|V  qdS )rK  NrJ   )r   r   Zlast_selected_subcommandrJ   rK   r  ;  r   z3CliSettingsSource._load_env_vars.<locals>.<genexpr>z{})r   r   r   varsr   r   _merge_parsed_listrU  r  _cli_subcommandsr   r   r8  maxr   r  r  r  r$   r   rs   r   r   r	  )rp   rR  Zselected_subcommandsr   r^  subcommand_namesubcommand_destr   rJ   r`  rK   r  !  s8    
	list[str]rs   z%tuple[Optional[type], Optional[type]])parsed_listr   rE   c                 C  sl   | j |t}|tu s8tt|r8tdd t|D s>|}n&|r`t|dks\|d dr`tnt	}||fS )Nc                 s  s.   | ]&}|t d urt|ttfvr|V  qd S rl   )r   r;   r   r   r   r  rJ   rJ   rK   r  N  s   zACliSettingsSource._get_merge_parsed_list_types.<locals>.<genexpr>r   r   [)
_cli_dict_argsr   r   r0   r;   r  r:   r   r  rs   )rp   rh  r   
merge_typeinferred_typerJ   rJ   rK   _get_merge_parsed_list_typesG  s    
	&z.CliSettingsSource._get_merge_parsed_list_typesc                 C  s  zg }d}|  ||\}}|D  ]}t|ts6 q"| }|drb|drb|dd  }|r| }|dr| |||}d}qb|ds|dr| ||}nXz| |||}W nD t	y } z*||u r||}| |||}W Y d }~n
d }~0 0 d}qb|s | |||}q |tu r6|d	 W S |t
u rTdd| dW S i }	|D ]}
|	t|
 q\t|	W S W n: ty } z td
| d| W Y d }~n
d }~0 0 d S )NFrj  ]r   ,{Tr   zParsing error encountered for z: )rn  r   rs   r  r  rU  _consume_comma_consume_object_or_array_consume_string_or_numberr   r   r   r1  r   r   dumpsr   rb   )rp   rh  r   merged_listis_last_consumed_a_valuerl  rm  r^  rI   Zmerged_dictitemrJ   rJ   rK   rb  Z  sJ    


$


z$CliSettingsSource._merge_parsed_listri   )ry  rw  rx  rE   c                 C  s   |s| d |dd  S )Nz""r   )r   )rp   ry  rw  rx  rJ   rJ   rK   rs    s    
z CliSettingsSource._consume_comma)ry  rw  rE   c                 C  s   d}| drdnd}tdt|D ]l}|| dv r>|d7 }q$|| dv r$|d8 }|| |kr$|dkr$||d |d   ||d d    S q$td| d	d S )
Nr   rr  r~   ro  )rr  rj  )r~   ro  r   zMissing end delimiter "r   )r  ranger   r   rb   )rp   ry  rw  countZclose_delimconsumedrJ   rJ   rK   rt    s    
z*CliSettingsSource._consume_object_or_arraytype[Any] | None)ry  rw  rl  rE   c           	      C  sx  |t urdnt|}d}|t|k rj|| dkrN|dksH||d  dkrN| }|s`|| dkr`qj|d7 }q|rvtd|d |  }|tt fv rzt| W n> ty   || jkrd}|d	vr|dsd| d}Y n0 |	| nd
d |
ddD \}}|drB|dsB|dsB|drBtd| |d|d }}|	t||i ||d  S )Nr   Fr   r   \rq  zMismatched quotesrI  )truefalserI  c                 s  s   | ]
}|V  qd S rl   rJ   )r   kvrJ   rJ   rK   r    r   z>CliSettingsSource._consume_string_or_number.<locals>.<genexpr>=z1Dictionary key=val parameter is a quoted string: )rs   r   rb   r  r   floatr   r8  r  r   r  rU  r   rv  )	rp   ry  rw  rl  r|  Zis_find_end_quoteZ
val_stringr   r^  rJ   rJ   rK   ru    s4    $

0z+CliSettingsSource._consume_string_or_numberztype[BaseModel]r6   zlist[type[BaseModel]])r{   r   r   rE   c                 C  s   t |js|jfnt |j}| jr4tdd |D }g }|D ]x}t|tfddrhtd|j d| n&t|tfddrtd|j d| t	t
|stt
|r<|t
| q<|S )Nc                 S  s   g | ]}|t d ur|qS rl   r   ri  rJ   rJ   rK   r     r   z5CliSettingsSource._get_sub_models.<locals>.<listcomp>F)is_include_originz.CliSubCommand is not outermost annotation for rK  z1CliPositionalArg is not outermost annotation for )r:   r   r9  rY  _annotation_contains_typesrd   rb   r]   re   r3   _strip_annotatedr5   r   )rp   r{   r   r   field_types
sub_modelsr  rJ   rJ   rK   _get_sub_models  s    z!CliSettingsSource._get_sub_modelsc                 C  s   t |jv rd}nt|jv r d}nd S |jturLt| d|j d| dn:tjdk r|j	t
u r|jd u rt| d|j d| dd S )NCliImplicitFlagCliExplicitFlagz
 argument rK  z is not of type boolr   z, must have default for python versions < 3.9)rf   r   rg   r   ri   rb   r]   rM   rN   r   r7   default_factory)rp   r{   r   r   Zcli_flag_namerJ   rJ   rK   _verify_cli_flag_annotations  s    



z.CliSettingsSource._verify_cli_flag_annotationszlist[tuple[str, FieldInfo]])r{   rE   c                 C  sx  g g g   }}}t | D ]L\}}t|jv r| sRtd|j d| dnxt||^}}t|dkrtd|j d| ddd t	|j
D }	|	D ],}
t|
st|
std|j d| dq|||f qt|jv rN| s
td	|j d| dn4t||^}}t|dkr>td	|j d| d|||f q| ||| |||f q|| | S )
Nzsubcommand argument rK  z has a default valuer   z has multiple aliasesc                 S  s   g | ]}|t d ur|qS rl   r  ri  rJ   rJ   rK   r     r   z6CliSettingsSource._sort_arg_fields.<locals>.<listcomp>z$ has type not derived from BaseModelzpositional argument )r   r   rd   r   r|   rb   r]   r   r   r:   r   r3   r5   r   re   r  )rp   r{   Zpositional_argsZsubcommand_argsZoptional_argsr   r   r   r   r  Z
field_typerJ   rJ   rK   _sort_arg_fields  s2    

z"CliSettingsSource._sort_arg_fieldsrx   c                 C  s   | j S )z#The connected root parser instance.)_root_parserr   rJ   rJ   rK   rB    s    zCliSettingsSource.root_parserzCallable[..., Any])parser_methodmethod_namer   rk   rE   c                   sp   d urFj du rF dkrFtjtrFddddddfdd	}|S d u rhdddd
 fdd}|S S d S )NFrC  rh   z"list[str] | tuple[str, ...] | NonezNamespace | Noner   )rB  r   	namespacerE   c                   sv   g }|rt t |ng D ]L}dj d}td| d|}|r^|d |d }|| q | ||S )Nr~  z{1,2}z^(z[^\s=]+)(.*)r   r   )	shlexr  r   r>  rematchgroupr   r   )rB  r   r  Zinsensitive_argsr   flag_prefixZmatched)r  rp   rJ   rK   parse_args_insensitive_method  s    zOCliSettingsSource._connect_parser_method.<locals>.parse_args_insensitive_methodr   rk   rE   c                    s   t d  dd S )Nz0cannot connect CLI settings source root parser: z. is set to `None` but is needed for connecting)rb   r   rk   )r  rJ   rK   none_parser_method  s    
zDCliSettingsSource._connect_parser_method.<locals>.none_parser_method)NN)r   r   r  rh   )rp   r  r  r   rk   r  r  rJ   )r  r  rp   rK   _connect_parser_method  s     
	  z(CliSettingsSource._connect_parser_method)rE  rE   c                   s&   |  |d dddd fdd}|S )NrE  r   )parserrk   rE   c                   s|     ds$  d | fi  S  fdddD }|d  d7  < | fi |}t|dshtd	|jf i  S d S )
N _is_cli_mutually_exclusive_grouprequiredc                   s    i | ]}| v r|  |qS rJ   )popr   r   rk   rJ   rK   r_  )  r   zUCliSettingsSource._connect_group_method.<locals>.add_group_method.<locals>.<dictcomp>)titlerM  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 connecting)r  r   rb   r  )r  rk   Zmain_group_kwargsr  add_argument_groupr  rK   add_group_method$  s    


zACliSettingsSource._connect_group_method.<locals>.add_group_method)r  )rp   rE  r  rJ   r  rK   _connect_group_method!  s    z'CliSettingsSource._connect_group_method)rB  rC  rD  rE  rF  rG  rH  rE   c           	   
   C  s   dddddd}|| _ |d u r0| jr*|ntj}| |d| _| |d| _| || _| |d| _	| |d	| _
|| _i | _tt| _| j| j| jg | j| jd g td
 d S )Nr   r   r  c                  _  s   t j| i |d S Nr   )r
   parse_known_argsr  rJ   rJ   rK   _parse_known_args?  s    zACliSettingsSource._connect_root_parser.<locals>._parse_known_argsrC  rD  rF  rG  r  r{   
added_args
arg_prefixsubcommand_prefixr  alias_prefixesr   )r  r@  r
   
parse_argsr  rZ  _add_argumentr  
_add_group_add_parser_add_subparsers_formatter_classrk  r   r   rc  _add_parser_argsrB  r   r   r7   )	rp   rB  rC  rD  rE  rF  rG  rH  r  rJ   rJ   rK   rX  5  s,    

z&CliSettingsSource._connect_root_parserr
   )	r  r{   r  r  r  r  r  r   rE   c	                   s
  d }	i }
t t|s tt|r2tt||s2d n|}| |D ]\}}| |||}t|||
| jd\}}|d }t|j	v r|D ]P}| 
t|dkr|jn|}| | }| | }|| j| d |< t|dkrd n|j}| jr|jd u rd nt|j}|	d u rB| j|d| dt|dkr:|jnd dn|	}	t|	dr|	jrt|	jd d  d	| d
n
d| d
|	_| j| j|	||| j|jd u rd nt|jd|g | | d| | dd g td qq@| j t|jttttt fdd}|o| }i }t!|d< | "||||d< | #|j|d< | j$oN|% oN|tu |d< |r|j&d ur|s| | | j'd  n
| | |d< | (|||||}|r@|d |v rq@|rd|d< t|jtt fddr|j| j)|d < t*|j	v r$| 
|+ |d< |d g}|d= |d= d | ,||| |r^| j-|||||| ||||||d q@|s@|d urt.|tr| j/|fi |}|t|7 }| j0|g fdd|D R i | q@|t|7 }| j0|g fdd|D R i | q@| 1||
|||| |S )N)alias_path_argsr   r   r   r\  r   )r  destrM  metavarrp  rq  r~   rr  )helprH  rM  rK  r  T)is_strip_annotatedr   r  r  r  r   actionrV   )r   c                 3  s&   | ]} d t |  | V  qd S rl   r   r   r   r  rJ   rK   r    r   z5CliSettingsSource._add_parser_args.<locals>.<genexpr>c                 3  s&   | ]} d t |  | V  qd S rl   r  r  r  rJ   rK   r    r   )2r3   r   r5   
issubclassr  r  r   r   rd   r   _check_kebab_namer   r]   rc  rM  r<  r`   r   r  r   r  r  r  r  r7   rT  r  r   r   setr   r!   r   CLI_SUPPRESS_help_format_metavar_formatr;  r|   r   r  _get_arg_namesrk  re   upper_convert_bool_flag_add_parser_submodelsr   r  r  _add_parser_alias_paths)rp   r  r{   r  r  r  r  r  r   Z
subparsersr  r   r   r  r   is_alias_path_onlyr   Zsubcommand_aliasre  rf  Zsubcommand_helpZis_append_actionZis_parser_submodelrk   	arg_namesrJ   r  rK   r  X  s    




	




(z"CliSettingsSource._add_parser_args)r   rE   c                 C  s   | j r|ddS |S )Nr   rJ  )rA  rV  )rp   r   rJ   rJ   rK   r    s    z#CliSettingsSource._check_kebab_name)rk   r   r   rE   c                 C  s   |d dkrd }|j tur |j }|tur,|}tjdks@t|tr| jsPt|jv rt	|jvr|d= tjdkrnt
ndt|   |d< d S )Nr  ri   r   Zstore_r  )r   r7   rM   rN   r   ri   r?  rf   r   rg   r   rs   r   )rp   rk   r   r   r   rJ   rJ   rK   r    s    
 z$CliSettingsSource._convert_bool_flagztuple[str, ...])r  r  r  r   r  rE   c           
   	   C  sf   g }|g| D ]R}|D ]H}|  || jkr4| | n||dd | }	|	|vr||	 qq|S )NrV   r   )r  r   rV  r   )
rp   r  r  r  r   r  r  r  r   arg_namerJ   rJ   rK   r    s    z CliSettingsSource._get_arg_names)r  r{   r  r  r  r  r  r  rk   r   r   r   r   rE   c                   s   t |trtdd }i }|d  d|d< |j|d< |	d |d< tdd |D |d	< |d	 rtt|d
krttd| jrt|d
kr|d jd u rd nt|d j|d< |t	urt
t|stt|rt||
}n"|jt	ur|j}n|jd ur|j}|d u rBd| j d}|d d ur:t| d|d  |d< n||d< |d }| js||d  d|d  d|	d< | j|fi |}| j|gfdd|D R i |	 |D ]J}| j|||  | d||r|n| fdd|d
d  D |d qd S )Nz8cannot have nested models in a CliMutuallyExclusiveGroupr   z optionsr  rM  r  c                 s  s   | ]}t |tV  qd S rl   )r  rw   )r   r{   rJ   rJ   rK   r  .  s   z:CliSettingsSource._add_parser_submodels.<locals>.<genexpr>r  r   z/cannot use union with CliMutuallyExclusiveGroupz	default: z (undefined)
zset z from JSON stringr  c                 3  s   | ]}  | V  qd S rl   rJ   r  r  rJ   rK   r  J  r   rK  c                   s   g | ]}  | d qS )rK  rJ   r  )r  rJ   rK   r   S  r   z;CliSettingsSource._add_parser_submodels.<locals>.<listcomp>r  )r  rw   rb   rM  r  r   r<  r`   r   r7   r3   r   r5   r   r   r  r8  r:  r   r  r  r  )rp   r  r{   r  r  r  r  r  r  rk   r   r   r   r   Zmodel_groupZmodel_group_kwargsZdesc_headerr   rJ   )r  r  rK   r    sV    

$


&z'CliSettingsSource._add_parser_submodelsdict[str, str])r  r  r  r  r  r  rE   c                 C  s  |r|}|d ur2t |tr.| j|fi |n|}|d}|rL|d d n|}| D ]\}	}
|rhdn|	}	|| jkr| |	 n||dd |	 }i }t|d< d|d< | |	 |d< |
d	ks|rd	|d
< nd|d< d|d
< ||vrX|| | j	|| j
 | fi | qXd S )NrK  rp  rV   r   r   zpydantic alias pathr  r  r   r  r   r  r   )r   r   r  rU  r   r   rV  r  r   r  rT  )rp   r  r  r  r  r  r  contextZis_nested_alias_pathr   r  r  rk   rJ   rJ   rK   r  W  s.    	 


z)CliSettingsSource._add_parser_alias_pathsobjrE   c                 C  s(   | j st|S tdd t|D S d S )Nc                 S  s   g | ]}|t d ur|qS rl   r  ri  rJ   rJ   rK   r   ~  r   z8CliSettingsSource._get_modified_args.<locals>.<listcomp>)r9  r:   rY  rp   r  rJ   rJ   rK   _get_modified_argsz  s    z$CliSettingsSource._get_modified_args)r   obj_qualnamerE   c                 C  s|   d|v r>|d | dd  dd || dd d  D  }d|}|r\| d| dS t|dkrl|S d| d	S d S )
NJSONr   c                 S  s   g | ]}|d kr|qS )r  rJ   r  rJ   rJ   rK   r     r   z=CliSettingsSource._metavar_format_choices.<locals>.<listcomp>rq  rj  ro  rr  r~   )indexr   r   )rp   r   r  r  rJ   rJ   rK   _metavar_format_choices  s    6
z)CliSettingsSource._metavar_format_choicesc                 C  st  t |}t|r&d|jv r |jS |jS |du r2dS t|trDt|S t|tjrXt	|S t|t
ttfsn|j}tt|r| tt| j| |S t|tjtjfv r| ttt	| |S t|tr| dd |D S t|tr$| jtt| j| |t|dr|jnt	|dS |tdu r8| jS t|rFd	S t|trX|jS t|d
dddS dS )z\Pretty metavar representation of a type. Adapts logic from `pydantic._repr.display_as_type`.z<locals>.z...c                 S  s   g | ]
}|j qS rJ   r   r   r^  rJ   rJ   rK   r     r   z=CliSettingsSource._metavar_format_recurse.<locals>.<listcomp>r_   )r  Nr  ztyping.rV   ztyping_extensions.)r  _is_functionr_   r]   r   r.   reprtyping_extensionsZTypeAliasTypers   r1   r/   r   rr   r0   r;   r  r   map_metavar_format_recurser  Literaltypingr4   r   r   r8  r3   rV  r  rJ   rJ   rK   r    s:    


z)CliSettingsSource._metavar_format_recursec                 C  s   |  |ddS )Nr}   rq  )r  rV  r  rJ   rJ   rK   r    s    z!CliSettingsSource._metavar_format)r   r   r   rE   c                 C  sn  |j r|j nd}|tks"t|jv r&tS | rv|td fv rvt|jvrt|d u rPdnd}||rfd| dn
d| d7 }nd| j d}tt|st	t|rdt
|| d}n|td fvrt|rd| | d}n\|jtd fvrt|j|j}d|d u r|jn| d}n |jd ur4d| |j d}||rFd	| n|7 }tt| jtrj|d
dS |S )NrV   zifdef: z (z	required)(z
(default: r   z(default factory:  %z%%)rM  r  r   r|   r7   re   r8  r3   r   r5   r   r  r  r   _annotation_enum_val_to_namer   r  r  r  r
   rV  )rp   r   r   r   Z_helpZifdefr   Z	enum_namerJ   rJ   rK   r    s&    
"zCliSettingsSource._help_format)N)(r]   r^   r_   r`   r
   add_argumentr  r   
add_parseradd_subparsersr   rn   r%   r   r  rn  rb  rs  rt  ru  r  r  r  r   rB  r  r  rX  r  r  r  r  r  r  r  r  r  r  r  rv   rJ   rJ   rq   rK   r5  .  s   /@{&-&# (E#	$r5  c                   @  s0   e Zd ZdddddZeddddd	Zd
S )ConfigFileSourceMixinr   r   )filesrE   c                 C  sX   |d u ri S t |ttjfr"|g}i }|D ](}t| }| r*|| | q*|S rl   )	r   rs   r   r   r   r   r   r1  
_read_file)rp   r  ra  filer+  rJ   rJ   rK   _read_files  s    z!ConfigFileSourceMixin._read_filesr   )r   rE   c                 C  s   d S rl   rJ   )rp   r   rJ   rJ   rK   r    s    z ConfigFileSourceMixin._read_fileN)r]   r^   r_   r  r   r  rJ   rJ   rJ   rK   r    s   r  c                      sN   e Zd ZdZedfdddd fddZd	d
dddZddddZ  ZS )JsonConfigSettingsSourcez>
    A source class that loads variables from a JSON file
    Nr   r   r   )r   	json_filejson_file_encodingc                   sV   |t kr|n
|jd| _|d ur&|n
|jd| _| | j| _t || j d S )Nr  r  )	rX   r   r   json_file_pathr  r  Z	json_datarm   rn   )rp   r   r  r  rq   rJ   rK   rn     s    
z!JsonConfigSettingsSource.__init__r   r   r/  c                 C  s<   t || jd}t|W  d    S 1 s.0    Y  d S Nr-  )openr  r   load)rp   r+  r  rJ   rJ   rK   r    s    z#JsonConfigSettingsSource._read_filers   rD   c                 C  s   | j j d| j dS )Nz(json_file=r   )rr   r]   r  r   rJ   rJ   rK   r     s    z!JsonConfigSettingsSource.__repr__	r]   r^   r_   r`   rX   rn   r  r   rv   rJ   rJ   rq   rK   r    s   r  c                      sJ   e Zd ZdZefddd fddZddd	d
dZddddZ  ZS )TomlConfigSettingsSourcez>
    A source class that loads variables from a TOML file
    r   r   )r   	toml_filec                   s<   |t kr|n
|jd| _| | j| _t || j d S )Nr  )rX   r   r   toml_file_pathr  	toml_datarm   rn   )rp   r   r  rq   rJ   rK   rn     s    z!TomlConfigSettingsSource.__init__r   r   r/  c                 C  sb   t   t|dd<}tjdk r6t|W  d    S t|W  d    S 1 sT0    Y  d S )Nrb)moder=   )rQ   r  rM   rN   rO   r  rP   )rp   r+  r  rJ   rJ   rK   r    s
    
z#TomlConfigSettingsSource._read_filers   rD   c                 C  s   | j j d| j dS )Nz(toml_file=r   )rr   r]   r  r   rJ   rJ   rK   r     s    z!TomlConfigSettingsSource.__repr__r  rJ   rJ   rq   rK   r    s
   	r  c                      sB   e Zd ZdZddddd fddZedd	d
dddZ  ZS )!PyprojectTomlConfigSettingsSourcezK
    A source class that loads variables from a `pyproject.toml` file.
    Nr   r   rC   )r   r  rE   c                   sj   |  ||jdd| _|jdd| _| | j| _| jD ]}| j|i | _q<tt| 	|| j d S )NZpyproject_toml_depthr   Zpyproject_toml_table_header)Ztoolzpydantic-settings)
_pick_pyproject_toml_filer   r   r  Ztoml_table_headerr  r  rm   r  rn   )rp   r   r  r   rq   rJ   rK   rn     s    
z*PyprojectTomlConfigSettingsSource.__init__intr   )provideddepthrE   c                 C  sp   | r|   S t d }d}| sl|jjd }||k rl| rD|S t|j|jkrVql|jjd }|d7 }q0|S )zPick a `pyproject.toml` file path to use.

        Args:
            provided: Explicit path provided when instantiating this class.
            depth: Number of directories up the tree to check of a pyproject.toml.

        zpyproject.tomlr   r   )resolver   cwdr   parentrs   root)r  r  rvr{  childrJ   rJ   rK   r  $  s    	
z;PyprojectTomlConfigSettingsSource._pick_pyproject_toml_file)N)r]   r^   r_   r`   rn   r4  r  rv   rJ   rJ   rq   rK   r    s
    r  c                      sN   e Zd ZdZedfdddd fddZd	d
dddZddddZ  ZS )YamlConfigSettingsSourcez>
    A source class that loads variables from a yaml file
    Nr   r   r   )r   	yaml_fileyaml_file_encodingc                   sV   |t kr|n
|jd| _|d ur&|n
|jd| _| | j| _t || j d S )Nr
  r  )	rX   r   r   yaml_file_pathr  r  Z	yaml_datarm   rn   )rp   r   r
  r  rq   rJ   rK   rn   B  s    
z!YamlConfigSettingsSource.__init__r   r   r/  c                 C  sF   t   t|| jd}t|p"i W  d    S 1 s80    Y  d S r  )rL   r  r  rF   Z	safe_load)rp   r+  r
  rJ   rJ   rK   r  Q  s    z#YamlConfigSettingsSource._read_filers   rD   c                 C  s   | j j d| j dS )Nz(yaml_file=r   )rr   r]   r  r   rJ   rJ   rK   r   V  s    z!YamlConfigSettingsSource.__repr__r  rJ   rJ   rq   rK   r	  =  s   r	  c                   @  sb   e Zd ZU ded< ded< ded< dddd	d
ZdddddZddddZddddZdS )AzureKeyVaultMappingzdict[str, str | None]_loaded_secretsrT   _secret_clientrg  _secret_namesrC   )secret_clientrE   c                 C  s&   i | _ || _dd | j D | _d S )Nc                 S  s   g | ]
}|j qS rJ   r  )r   secretrJ   rJ   rK   r   e  r   z1AzureKeyVaultMapping.__init__.<locals>.<listcomp>)r  r  Zlist_properties_of_secretsr  rp   r  rJ   rJ   rK   rn   _  s    zAzureKeyVaultMapping.__init__rs   r   )r   rE   c                 C  sH   || j vr>z| j|j| j |< W n ty<   t|Y n0 | j | S rl   )r  r  Z
get_secretr   r   KeyError)rp   r   rJ   rJ   rK   __getitem__g  s    
z AzureKeyVaultMapping.__getitem__r   rD   c                 C  s
   t | jS rl   )r   r  r   rJ   rJ   rK   __len__p  s    zAzureKeyVaultMapping.__len__zIterator[str]c                 C  s
   t | jS rl   )iterr  r   rJ   rJ   rK   __iter__s  s    zAzureKeyVaultMapping.__iter__N)r]   r^   r_   __annotations__rn   r  r  r  rJ   rJ   rJ   rK   r  Z  s   
	r  c                	      sf   e Zd ZU ded< ded< ded< ddddd	d	d
dd fddZddddZddddZ  ZS )AzureKeyVaultSettingsSourcers   _urlrR   _credentialrT   r  Nr   r   rz   rC   )r   url
credentialr   r   r   rE   c              	     s0   t   || _|| _t j|d|dd||d d S )NTz--F)r   r   r  r   r   r   )rU   r  r  rm   rn   )rp   r   r  r  r   r   r   rq   rJ   rK   rn   |  s    	z$AzureKeyVaultSettingsSource.__init__zMapping[str, Optional[str]]rD   c                 C  s   t | j| jd}t|S )N)Z	vault_urlr  )rT   r  r  r  r  rJ   rJ   rK   r    s    z*AzureKeyVaultSettingsSource._load_env_varsc                 C  s   | j j d| jd| jdS )Nz(url=r3  r   )rr   r]   r  r  r   rJ   rJ   rK   r     s    z$AzureKeyVaultSettingsSource.__repr__)NNN)r]   r^   r_   r  rn   r  r   rv   rJ   rJ   rq   rK   r  w  s   
    r  Frs   )r   r   rE   c                 C  s   |r| S |   S rl   r   )r   r   rJ   rJ   rK   _get_env_var_key  s    r   r   zstr | None | EnvNoneType)r   r)  rE   c                 C  s   | |kr|d us| S t | S rl   )r   )r   r)  rJ   rJ   rK   _parse_env_none_str  s    r!  r
  )r	  r   r(  r)  rE   c                   s    fdd|   D S )Nc                   s.   i | ]&\}}r|d kst | t|qS )rV   )r   r!  )r   kvr   r(  r)  rJ   rK   r_    s   z"parse_env_vars.<locals>.<dictcomp>)r   )r	  r   r(  r)  rJ   r$  rK   r    s    r  r&  r   r*  c                C  s    t dt tj| ||||dS )Nzmread_env_file will be removed in the next version, use DotEnvSettingsSource._static_read_env_file if you mustr&  )r   r   DeprecationWarningr"  r.  )r+  r'  r   r(  r)  rJ   rJ   rK   read_env_file  s    r&  r}  z	list[Any])r   r   rE   c                 C  s   z8| d ur6t | tr6| jdd }|d ur6|dkr6|} W n tyJ   Y n0 tdd |D rbdS t| trt| ^}}t	||S t
| }|tu rdS t| pt|pt|dpt|dS )Nr  ZRootModelRootTypec                 s  s   | ]}t |tV  qd S rl   )r   r*   )r   mdrJ   rJ   rK   r    r   z)_annotation_is_complex.<locals>.<genexpr>FZ__pydantic_core_schema__Z__get_pydantic_core_schema__)r  r+   r  r   	TypeErrorr  r   r9   r:   r   r;   r,   _annotation_is_complex_innerr   )r   r   Zroot_annotationinnermetaoriginrJ   rJ   rK   r     s,    

r   )r   rE   c              	   C  s2   t | ttfrdS t | ttttttt	fp0t
| S rP  )r4   rs   bytesr)   r   r!   rY  r  	frozensetr   r   r   rJ   rJ   rK   r)    s
    r)  c                   s   t  fddt| D S )Nc                 3  s   | ]}t | V  qd S rl   )r   r  r   rJ   rK   r    r   z$_union_is_complex.<locals>.<genexpr>)r  r:   )r   r   rJ   r0  rK   r     s    r   ztuple[Any, ...])r   typesr  r  rE   c                 C  sP   |rt | } |du r$t| |v r$dS t| D ]}t||d|dr, dS q,| |v S )NT)r  r  )r  r;   r:   r  )r   r1  r  r  r  rJ   rJ   rK   r    s    r  r   c                 C  s   t | tkrt| d } q | S r  )r;   r8   r:   r/  rJ   rJ   rK   r  	  s    r  zOptional[str])r   r   rE   c                 C  sN   | t | gt| R D ]2}t|tr|tdd |D v r||j  S qd S )Nc                 s  s   | ]}|j V  qd S rl   )r   r  rJ   rJ   rK   r  	  r   z/_annotation_enum_val_to_name.<locals>.<genexpr>)r;   r:   r4   r   rY  r   )r   r   r  rJ   rJ   rK   r  		  s
    
r  )r   r   rE   c                 C  sL   | t | gt| R D ]0}t|tr|tdd |D v r||   S qd S )Nc                 s  s   | ]}|j V  qd S rl   r  r  rJ   rJ   rK   r  	  r   z/_annotation_enum_name_to_val.<locals>.<genexpr>)r;   r:   r4   r   rY  )r   r   r  rJ   rJ   rK   r  	  s
    
r  z	type[Any]zdict[str, FieldInfo])r   rE   c                 C  s<   t | rt| dr| jS t| r&| jS td| j dd S )N__pydantic_fields__zError: z? is not subclass of BaseModel or pydantic.dataclasses.dataclass)r5   r   r2  r3   r   rb   r]   )r   rJ   rJ   rK   r   	  s
    r   r6   r  ztuple[tuple[str, ...], bool])r   r   r  r   rE   c           
      C  s&  g }d}t |j|jfs(|| g7 }d}ng }|j|jfD ]p}|d u rHq8q8t|trb|| d}q8t|tr|jD ](}t|tr|| d}qr|| qrq8|| q8|D ]P}	tt|	j	d }|s|
 n|}t|	j	dkrdnd||< |s|r|| q|sdd |D }tt||fS )	NTFr   r   r   r   c                 S  s   g | ]}|  qS rJ   r  )r   Z
alias_namerJ   rJ   rK   r   A	  r   z$_get_alias_names.<locals>.<listcomp>)r  r   r   r   rs   r   r'   choicesr$   r   r   r   rY  r   fromkeys)
r   r   r  r   r   r  Znew_alias_pathsr   r   Z
alias_pathrJ   rJ   rK   r   !	  s8    






r   r  c                 C  s   t | ttfS rl   )r   r   r   )r  rJ   rJ   rK   r  E	  s    r  )TN)F)N)FFN)TF)
__future__r   Z_annotationsr   r   r  r  rM   r  r   abcr   r   rN   argparser   r	   r
   r   r   r   collectionsr   r   dataclassesr   r   enumr   pathlibr   textwrapr   r1  r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r  Zdotenvr&   Zpydanticr'   r(   r)   r*   r+   r,   r-   Zpydantic._internal._reprr.   Z pydantic._internal._typing_extrar/   r0   r1   Zpydantic._internal._utilsr2   r3   r4   Zpydantic.dataclassesr5   Zpydantic.fieldsr6   Zpydantic_corer7   r8   r9   r:   r;   Zpydantic_settings.utilsr<   rP   rO   rF   Zpydantic._internal._dataclassesr?   Zpydantic_settings.mainr@   rA   rL   rQ   rU   rs   rY   rW   rX   r  rZ   r[   ra   r   rb   rd   re   rf   rg   rh   rw   rx   ZCliSubCommandZCliPositionalArgri   ry   r  r  r  ZCliSuppressr   r   r   r   r   r   r   r  r"  r5  r  r  r  r  r	  r  r  r   r!  r  r&  r   r)  r   r  r  r  r  r   r   r  rJ   rJ   rJ   rK   <module>   s   
@$

 1m(" Sg dt       !.#   "	  	$