
    ɯeiFQ              
      |   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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 d dlmZ d dlZd dlmZ d d	lmZ d d
lmZmZ d dlmZmZmZm Z   ed      Z! ejD                  e#      Z$ejJ                  ejL                  z  Z'ejP                  ejR                  z  Z*dZ+d#dZ, G d de      Z- G d de      Z. G d d      Z/ G d d      Z0 e0de e.e e-d      d      g      Z1e1je                  dejf                   e4              e1je                  dd       d$d Z5d! Z6g d"Z7y)%    )annotationsN)Iterable)methodcaller)Path)AnyCallableLiteral
NamedTupleTypeVar)warn)Table)
IS_WINDOWS)CONFIG_FILECONNECTIONS_FILE)ConfigManagerErrorConfigSourceErrorErrorMissingConfigOptionError_T3SF_SKIP_WARNING_FOR_READ_PERMISSIONS_ON_CONFIG_FILEc                 X    t        j                  t        d      j                         dk(  S )zECheck if the warning should be skipped based on environment variable.falsetrue)osgetenvSKIP_WARNING_ENV_VARlower     d/var/www/html/glpi_dashboard/venv/lib/python3.12/site-packages/snowflake/connector/config_manager.py8_should_skip_warning_for_read_permissions_on_config_filer!   #   s"    99)7399;vEEr   c                  .    e Zd ZU dZdZded<   dZded<   y)ConfigSliceOptionsz;Class that defines settings individual configuration files.Tboolcheck_permissionsFonly_in_sliceN)__name__
__module____qualname____doc__r%   __annotations__r&   r   r   r    r#   r#   (   s    E"t"M4r   r#   c                  ,    e Zd ZU ded<   ded<   ded<   y)ConfigSlicer   pathr#   optionsstrsectionN)r'   r(   r)   r+   r   r   r    r-   r-   /   s    
JLr   r-   c                      e Zd ZdZdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
dZddZedd       Zedd       ZddZ	dd	Z
y)ConfigOptiona  ConfigOption represents a flag/setting.

    This class knows how to read the value out of all different sources and implements
    order of precedence between them.

    It also provides value parsing and verification.

    Attributes:
        name: Name of this ConfigOption.
        parse_str: A function that can turn str to the desired type, useful
          for reading value from environmental variable.
        choices: An iterable of all possible values that are allowed for
          this option.
        env_name: Environmental variable value should be read from, if not
          supplied, we'll construct this. False disables reading from
          environmental variables, None uses the auto generated variable name
          and explicitly provided string overwrites the default one.
        default: The value we should resolve to when the option is not defined
          in any of the sources. When it's None we treat that as there's no
          default value.
        _root_manager: Reference to the root manager. Used to efficiently
          refer to cached config file. Is supplied by the parent
          ConfigManager.
        _nest_path: The names of the ConfigManagers that this option is
          nested in. Used to be able to efficiently resolve where to retrieve
          value out of the configuration file and construct environment
          variable name. This is supplied by the parent ConfigManager.
    N)	parse_strchoicesenv_namedefault_root_managerc                   |t        d      |t        d      || _        || _        || _        ||gz   | _        || _        || _        || _        y)a  Create a config option that can read values from different sources.

        Args:
            name: Name to assign to this ConfigOption.
            parse_str: String parser function for this instance.
            choices: List of possible values for this instance.
            env_name: Environmental variable name value should be read from.
              Providing a string will use that environment variable, False disables
              reading value from environmental variables and the default None generates
              an environmental variable name for it using the _nest_path and name.
            default: Default value for the option. Used in case the value is
              is not defined in any of the sources.
            _root_manager: Reference to the root manager. Should be supplied by
              the parent ConfigManager.
            _nest_path: The names of the ConfigManagers that this option is
              nested in. This is supplied by the parent ConfigManager.
        Nz_root_manager cannot be Nonez_nest_path cannot be None)	TypeErrornamer4   r5   
_nest_pathr8   r6   r7   )selfr;   r4   r5   r6   r7   r8   r<   s           r    __init__zConfigOption.__init__S   sa    8  :;;788	"$v-,9 r   c                4   d}| j                         \  }}|s	 | j                         }d}| j                  r6|| j                  vr(t        d| j                   d| d| j                         |S # t        $ r | j                  d}| j                  }n Y kw xY w)zuRetrieve a value of option.

        This function implements order of precedence between different sources.
        zenvironment variablezconfiguration filedefault_valuezThe value of z read from z is not part of )_get_env_get_configr   r7   r5   r   option_name)r=   source
loaded_envvalues       r    rF   zConfigOption.value{   s    
 ( MMO
E((*- <<E5# 0 01(*4<<.:   , <<+,F LLE s   A/ /%BBc                >    dj                  | j                  dd       S )zBUser-friendly name of the config option. Includes self._nest_path..   N)joinr<   r=   s    r    rC   zConfigOption.option_name   s     xx+,,r   c                n    t        t        d      | j                  dd       }ddj                  |       S )z8The default environmental variable name for this option.upperrI   N
SNOWFLAKE__)mapr   r<   rJ   )r=   piecess     r    default_env_namezConfigOption.default_env_name   s7     \'*DOOAB,?@CHHV,-..r   c                P   | j                   du ry| j                   | j                   }n| j                  }t        j                  j	                  |      }|y|}| j
                  | j                  |      }t        |t        t        j                  f      rd|j                  fS d|fS )zGet value from environment variable if possible.

        Returns whether it was able to load the data and the loaded value
        itself.
        F)FNT)r6   rR   r   environgetr4   
isinstancer   tomlkitTOMLDocumentrF   )r=   r6   env_var
loaded_vars       r    rA   zConfigOption._get_env   s     ==E!==$}}H ,,H**..*?&
>>%0Jj5'*>*>"?@))))Zr   c                   | j                   j                  0| j                   j                  | j                   j                          | j                   j                  }|#t	        d| j                   j
                   d      | j                  dd D ]  }	 ||   }
 t        |t        t        j                  f      r|j                  S |S # t        j                  j                  $ r t        d| j                   d      w xY w)zGet value from the cached config file if possible.

        Since this is the last resource for retrieving the value it raises
        a MissingConfigOptionError if it's unable to find this option.
        NzRoot manager 'z' is missing file_pathrI   zConfiguration option 'zk' is not defined anywhere, have you forgotten to set it in a configuration file, or environmental variable?)r8   conf_file_cache	file_pathread_configr   r;   r<   rW   
exceptionsNonExistentKeyr   rC   rV   r   rX   rF   )r=   eks      r    rB   zConfigOption._get_config   s    ..6"",,8**,..9$ !3!3!8!8 99OP  $ 	AaD	 a%!5!56777N %%44 .,T-=-=,> ?1 1 s   C

7D)r;   r0   r4   zCallable[[str], _T] | Noner5   zIterable[Any] | Noner6   zstr | None | Literal[False]r7   z
Any | Noner8   zConfigManager | Noner<   zlist[str] | NonereturnNone)rc   r   )rc   r0   )rc   ztuple[bool, str | _T | None])r'   r(   r)   r*   r>   rF   propertyrC   rR   rA   rB   r   r   r    r3   r3   5   s    B 15(,04".2& & .	&
 && .& & ,& %& 
&P0 - - / /
 2r   r3   c                      e Zd ZdZddd	 	 	 	 	 ddZedd       Z	 d	 	 	 ddZed	 	 	 ddZ	dd	Z
dd
ZddZddZy)ConfigManagera	  Read a TOML configuration file with managed multi-source precedence.

    Note that multi-source precedence is actually implemented by ConfigOption.
    This is done to make sure that special handling can be done for special options.
    As an example, think of not allowing to provide passwords by command line arguments.

    This class is updatable at run-time, allowing other libraries to add their
    own configuration options and sub-managers before resolution.

    This class can simply be thought of as nestable containers for ConfigOptions.
    It holds extra information necessary for efficient nesting purposes.

    Sub-managers allow option groups to exist, e.g. the group "snowflake.cli.output"
    could have 2 options in it: debug (boolean flag) and format (a string like "json",
    or "csv").

    When a ConfigManager tries to retrieve ConfigOptions' value the _root_manager
    will read and cache the TOML file from the file it's pointing at, afterwards
    updating the read cache can be forced by calling read_config.

    Attributes:
        name: The name of the ConfigManager. Used for nesting and emitting
          useful error messages.
        file_path: Path to the file where this and all child ConfigManagers
          should read their values out of. Can be omitted for all child
          managers. Root manager could also miss this value, but this will
          result in an exception when a value is read that isn't available from
          a preceding config source.
        conf_file_cache: Cache to store what we read from the TOML file.
        _sub_managers: List of ConfigManagers that are nested under the current manager.
        _sub_parsers: Alias for the old name of _sub_managers in the first release, please use
          the new name now, as this might get deprecated in the future.
        _options: List of ConfigOptions that are under the current manager.
        _root_manager: Reference to the root manager. Used to efficiently propagate to
          child options.
        _nest_path: The names of the ConfigManagers that this manager is nested
          under. Used to efficiently propagate to child options.
        _slices: List of config slices, where optional sections could be read from.
          Note that this feature might become deprecated soon.
    N)r]   _slicesc                   |
t               }|| _        || _        || _        t	               | _        t	               | _        d| _        | | _        |g| _	        y)a  Creates a new ConfigManager.

        Args:
            name: Name of this ConfigManager.
            file_path: File this manager should read values from. Can be omitted
              for all child managers.
            _slices: List of ConfigSlices to consider. A configuration file's slice is a
              section that can optionally reside in a different file. Note that this
              feature might get deprecated soon.
        N)
listr;   r]   rh   dict_options_sub_managersr\   r8   r<   )r=   r;   r]   rh   s       r    r>   zConfigManager.__init__  sS    " ?fG	"157;v<@ -1&r   c                R    t        j                  dt        d       | j                  S )z
        Alias for the old name of ``_sub_managers``.

        This used to be the original name  in the first release, please use the
        new name, as this might get deprecated in the future.
        z;_sub_parsers has been deprecated, use _sub_managers instead   
stacklevel)warningsr   DeprecationWarningrm   rK   s    r    _sub_parserszConfigManager._sub_parsers!  s'     	I	

 !!!r   c                .   | j                   t        d      t        j                         }t	        |       }t        j                  | j                   |dff| j                        D ]  \  }}}|j                  r||= 	 |j                         s)	 t        sr|j                  rf|j!                         j"                  t$        z  dk7  rB|j!                         }t'        |j"                        dd }t)        dt        |       d	|       t        s0|j                  r$|j!                         j"                  t*        z  dk7  s\t-        t.        d
      r|j!                         j0                  dk7  rt|j!                         j0                  t/        j2                         k7  rEdt        |       dt        |       dt4         d}	t7               st9        dt        |       |	        t        j                  dt        |              	 t        j:                  |j=                               }
||
}|
||<    || _         y# t        $ r& t        j                  dt        |       d       Y w xY w# t>        $ r}t)        dt        |       d      |d}~ww xY w)a  Read and cache config file contents.

        This function should be explicitly called if the ConfigManager's cache is
        outdated. Most likely when someone's doing development and are interactively
        adding new options to their configuration file.
        NzDConfigManager is trying to read config file, but it doesn't have oner%   z%Fail to read configuration file from z- due to no permission on its parent directoryr   zfile 'u   ' is writable by group or others — this poses a security risk because it allows unauthorized users to modify sensitive settings. Your Permission: getuidz(.
 * To change owner, run `chown $USER "z1"`.
 * To restrict permissions, run `chmod 0600 "z6"`.
 * To skip this warning, set environment variable z=true.
zBad owner or permissions on z reading configuration file from z)An unknown error happened while loading '')!r]   r   rW   rX   r#   	itertoolschainrh   r&   existsPermissionErrorLOGGERdebugr0   r   r%   statst_modeWRITABLE_BY_OTHERSoctr   READABLE_BY_OTHERShasattrr   st_uidrx   r   r!   r   parse	read_text	Exceptionr\   )r=   skip_file_permissions_checkread_config_fileconfig_slice_optionsfilepsliceoptionsr1   	file_statfile_permissionschmod_messageread_config_piecera   s               r    r^   zConfigManager.read_config0  s    >>!$  #//1  2"== 
 -6OOnn2D9;LL-
 7	>(E< ))$W-||~ &  22JJL((+==B!JJL	#&y'8'8#9"##> 'SZL  )}  ~N  }O  P   22 JJL((+==B B)

++q0

++ryy{: #LCPUJ<  XJ  KN  OT  KU  JV  VM  Nb  Mc  ck  !lOQ7E
|M?STLL;CJ<HI$+MM%//2C$D!
 #4 ,= )o7	>p  0_ # ;CJ<Gtu 	N  'B3u:,aPs*   ?H;#I-;+I*)I*-	J6JJ)
option_clsc                   | j                   |d<   | j                  |d<    |di |}| j                  |j                         || j                  |j                  <   y)as  Add a ConfigOption to this ConfigManager.

        Args:
            option_cls: The class that should be instantiated. This class
              should be a child class of ConfigOption. Mainly useful for cases
              where the default ConfigOption needs to be extended, for example
              if a new configuration option source needs to be supported.
        r8   r<   Nr   )r8   r<   _check_child_conflictr;   rl   )r=   r   kwargs
new_options       r    
add_optionzConfigManager.add_option  sZ     #'"4"4#| 


 	"":??3)3joo&r   c                    || j                   j                         | j                  j                         z  v rt        d| d| j                   d      y)zCheck if a sub-manager, or ConfigOption conflicts with given name.

        Args:
            name: Name to check against children.
        ry   z<' sub-manager, or option conflicts with a child element of 'N)rl   keysrm   r   r;   r=   r;   s     r    r   z#ConfigManager._check_child_conflict  s\     DMM&&(4+=+=+B+B+DDE$D6UVZV_V_U``ab  Fr   c                      j                  |j                         | j                  |j                  <   d fd |       y)a  Nest another ConfigManager under this one.

        This function recursively updates _nest_path and _root_manager of all
        children under new_child.

        Args:
            new_child: The ConfigManager to be nested under the current one.
        Notes:
            We currently don't support re-nesting a ConfigManager. Only nest a
            manager under another one once.
        c                N   j                   | _         j                  | j                  z   | _        | j                  j                         D ]
  } |        | j                  j                         D ]1  }j                   |_         j                  |j                  z   |_        3 y )N)r8   r<   rm   valuesrl   )nodesub_manageroption_root_setter_helperr=   s      r    r   z9ConfigManager.add_submanager.<locals>._root_setter_helper  s    !%!3!3D"oo?DO#1188: 1#K01 --..0 H'+'9'9$$(OOf6G6G$G!Hr   N)r   rg   )r   r;   rm   )r=   	new_childr   s   ` @r    add_submanagerzConfigManager.add_submanager  s;     	""9>>2-69>>*		H 	I&r   c                ^    t        j                  dt        d        | j                  |i |S )Nz=add_subparser has been deprecated, use add_submanager insteadro   rp   )rr   r   rs   r   )r=   argsr   s      r    add_subparserzConfigManager.add_subparser  s1    K	

 #t""D3F33r   c                    || j                   v r| j                   |   j                         S || j                  vrt        d| d      | j                  |   S )zGet either sub-manager, or option in this manager with name.

        If an option is retrieved, we call get() on it to return its value instead.

        Args:
            name: Name to retrieve.
        z>No ConfigManager, or ConfigOption can be found with the name 'ry   )rl   rF   rm   r   r   s     r    __getitem__zConfigManager.__getitem__  sg     4== ==&,,..t)))###'&+  !!$''r   )r;   r0   r]   zPath | Nonerh   zlist[ConfigSlice] | None)rc   zdict[str, ConfigManager])F)r   r$   rc   rd   )r   ztype[ConfigOption]rc   rd   )r;   r0   rc   rd   )r   rg   rc   rd   )rc   rd   )r;   r0   rc   zConfigOption | ConfigManager)r'   r(   r)   r*   r>   re   rt   r^   r3   r   r   r   r   r   r   r   r    rg   rg      s    'Z "&,0! ! 	!
 *!@ " "  -2M0%)M0 
M0d *64 '4
 
4,	'84(r   rg   CONFIG_MANAGERTrv   connections)r;   r]   rh   )r;   r4   r7   default_connection_namer7   )r;   r7   c            	         t         d   } t         d   }| |vr(t        d|  dt        |j                                      i ||    S )Nr   r   zDefault connection with name 'z"' cannot be found, known ones are )r   r   rj   r   )def_connection_namer   s     r    _get_default_connection_paramsr     sh    ()BC /K+-,-@,A B/K$$&'(*
 	

 0k-.//r   c                z    | dk(  r"t        j                  dt        d       t        S t	        dt
        d|       )NCONFIG_PARSERz=CONFIG_PARSER has been deprecated, use CONFIG_MANAGER insteadro   rp   zmodule z has no attribute )rr   r   rs   r   AttributeErrorr'   )r;   s    r    __getattr__r     s@    K	

 
78,.@I
JJr   )r3   rg   r   r   )rc   r$   )rc   zdict[str, Any])8
__future__r   rz   loggingr   r   rr   collections.abcr   operatorr   pathlibr   typingr   r   r	   r
   r   r   rW   tomlkit.itemsr   snowflake.connector.compatr   snowflake.connector.constantsr   r   snowflake.connector.errorsr   r   r   r   r   	getLoggerr'   r~   S_IRGRPS_IROTHr   S_IWGRPS_IWOTHr   r   r!   r#   r-   r3   rg   r   r   r   rk   r   r   __all__r   r   r    <module>r      sC   "   	   $ !  > >    1 G  T]			8	$\\DLL0 \\DLL0 L F
   * _ _D|( |(~ 	"& 	
   	mmF  
   	"  	0Kr   