
    +d+                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	m
Z
mZ d Zd Zd ej        fdZddZd Zd	 Zd
 ZddZddZddZddZd Zeeeeeeeeeed dZ d Z! G d de"          Z#d Z$dS )    N)Environment	Undefinedmetac              #     K   t          |           } 	 	 t          |           }n# t          $ r Y dS w xY wt          |t                    r|V  =	 t          |          }t          j        ||           } n# t          $ r |V  Y nw xY ww)z Flatten an arbitrarily deep listTN)iternextStopIteration
isinstancestr	itertoolschain	Exception)iterableitemdatas      4lib/python3.11/site-packages/intake/catalog/utils.pyflattenr      s       H~~H	>>DD 	 	 	EE	 dC   	JJJ	::D tX66HH 	 	 	JJJJJ	s   $ 
22$A5 5BBc                 F     t          j                    fd            }|S )Nc                 D    |                                    | g|R i |S N)reload)selfargskwargsfs      r   wrapperz!reload_on_change.<locals>.wrapper*   s0    q'''''''    )	functoolswraps)r   r   s   ` r   reload_on_changer    )   s8    _Q( ( ( ( ( Nr   c                 >    t          |t          ||                     S )zClamp float between given range)maxmin)valueloweruppers      r   clampr'   2   s    uc%''(((r    c                     t          | t                    r| j        } t          |t                    r|j        }t          j        | |          S r   )r
   r   _undefined_nameosgetenv)xdefaults     r   	_j_getenvr/   7   sH    !Y '9%% *)9Q   r   c                     t          | t                    r| j        } 	 t          j        |                                           S # t          t          f$ r Y dS w xY w)Nr(   )r
   r   r*   
subprocesscheck_outputdecodeIOErrorOSErrorr-   s    r   _j_getshellr7   ?   se    !Y &q))00222W   rrs   %A AAc                 L    t          | t                    r| j        } d|d| dS )Nz{{(z)}})r
   r   r*   )r-   funcnames     r   _j_passthroughr;   H   s0    !Y #88QQQ''r   c                    t          | t                    r$fd|                                 D             S t          | t          t          t
          f          r( t          |           fd| D                       S t          | t                    rt                      }rst          |j
        d<   nd |j
        d<   rrt          |j
        d<   nd |j
        d<   rst          |j
        d<   nd |j
        d<   rrt          |j
        d	<   nd
 |j
        d	<   |                    |           }t          j        |          z  |                    |                                         S | S )Nc                 @    i | ]\  }}|t          |          S  _expand).0kvall_varsclientcontextr,   getshells      r   
<dictcomp>z_expand.<locals>.<dictcomp>P   s2    aaatqRS71gxJJaaar   c           	   3   @   K   | ]}t          |          V  d S r   r?   )rA   rC   rD   rE   rF   r,   rG   s     r   	<genexpr>z_expand.<locals>.<genexpr>R   s6      ZZSTwq'8VVXNNZZZZZZr   envc                 $    t          | d          S )NrK   r:   r;   r6   s    r   <lambda>z_expand.<locals>.<lambda>X   s    ^A-N-N-N r   
client_envc                 $    t          | d          S )NrP   rM   rN   r6   s    r   rO   z_expand.<locals>.<lambda>\   s    N1|4\4\4\ r   shellc                 $    t          | d          S )NrR   rM   rN   r6   s    r   rO   z_expand.<locals>.<lambda>`   s    ~a'/R/R/R r   client_shellc                 $    t          | d          S )NrT   rM   rN   r6   s    r   rO   z_expand.<locals>.<lambda>d   s    nQQ_6`6`6` r   )r
   dictitemslisttuplesettyper   r   r/   globalsr7   parser   find_undeclared_variablesfrom_stringrender)prF   rD   rE   r,   rG   jinjaasts    `````  r   r@   r@   N   s   !T aaaaaaaaWXW^W^W`W`aaaa	AeS)	*	* tAwwZZZZZZZZXYZZZZZZ	As		  	O& 	O#,EM%  #N#NEM%  	]f 	]*3EM,''*\*\EM,' 	SF 	S%0EM'""%R%REM'" 	a 	a,7EM.)),`,`EM.)kk!nnD23777  ##**7333 r   FTc                 X    t          |          }t          | |||||          }|r||fS |S )a;  
    Render variables in context into the set of parameters with jinja2.

    For variables that are not strings, nothing happens.

    Parameters
    ----------
    pars: dict
        values are strings containing some jinja2 controls
    context: dict
        values to use while rendering
    return_left: bool
        whether to return the set of variables in context that were not used
        in rendering parameters

    Returns
    -------
    dict with the same keys as ``pars``, but updated values; optionally also
    return set of unused parameter names.
    )rZ   r@   )parsrF   return_leftrE   r,   rG   rD   outs           r   expand_templatesrh   m   s=    * 7||H
$668
D
DC H}Jr   c                    t          j        d|           }|rY|sW|rU|                                }t          j                            |d         t          |          dk    r|d         nd          } t          j        d|           }|r<|r:|r8t          j                            |                                d         d          } t          j        d|           }|r|s|r	 t          j        |                                d                   }t          j
        |                                                              d          } n# t          j        t          f$ r d} Y nw xY wt          j        d|           }|r|r|r	 t          j        |                                d                   }t          j
        |                                                              d          } n# t          j        t          f$ r d} Y nw xY w| S )	a  Compile env, client_env, shell and client_shell commands

    Execution rules:
    - env() and shell() execute where the cat is loaded, if getenv and getshell
      are True, respectively
    - client_env() and client_shell() execute only if client is True and
      getenv/getshell are also True.

    If both getenv and getshell are False, this method does nothing.

    If the environment variable is missing or the shell command fails, the
    output is an empty string.
    zenv\((.*),?(.*)\)r      r(   zclient_env\((.*)\)zshell\((.*)\)utf8zclient_shell\((.*)\))rematchgroupsr+   environgetlenshlexsplitr1   r2   rstripr3   CalledProcessErrorr5   )r.   rE   r,   rG   rgscmds          r   expand_defaultsry      s    	%w//A F FF FXXZZ*..AR1(D1"EE
&00A 4V 4 4*..A33
!7++A  H 	+ahhjjm,,C -c2299;;BB6JJGG-w7 	 	 	GGG	
('22A V  	+ahhjjm,,C -c2299;;BB6JJGG-w7 	 	 	GGG	Ns&    A%E E! E! A%G& &H Hc                    |                                  |D ]i}|                    |j        |j                  }|Et	          |t
                    rt          ||||          }|                    |          |j        <   j                    fd|	                                D                        t          | d|||          \  }fd	                                D             |D ]M}|j        v rB|                    |j                           |j        <                       |j                   N|                     |           t          |d|||          }|                     fd|	                                D                        |                     dd           |                                  	                                D ]4\  }	fd	|D             D ] }
|
                    |                    | <   !5| S )
a  Produce open arguments by merging various inputs

    This function is called in the context of a catalog entry, when finalising
    the arguments for instantiating the corresponding data source.

    The three sets of inputs to be considered are:
    - the arguments section of the original spec (params)
    - UserParameters associated with the entry (spec_pars)
    - explicit arguments provided at instantiation time, like entry(arg=value)
      (user_inputs)

    Both spec_pars and user_inputs can be considered as template variables and
    used in expanding string values in params.

    The default value of a spec_par, if given, may have embedded env and shell
    functions, which will be evaluated before use, if the default is used and
    the corresponding getenv/getsgell are set. Similarly, string value params
    will also have access to these functions within jinja template groups,
    as well as full jinja processing.

    Where a key exists in both the spec_pars and the user_inputs, the
    user_input wins. Where user_inputs contains keys not seen elsewhere, they
    are regarded as extra kwargs to pass to the data source.

    Where spec pars have the same name as keys in params, their type, max/min
    and allowed fields are used to validate the final values of the
    corresponding arguments.

    Parameters
    ----------
    params : dict
        From the entry's original spec
    user_inputs : dict
        Provided by the user/calling function
    spec_pars : list of UserParameters
        Default and validation instances
    client : bool
        Whether this is all running on a client to a remote server - sets
        which of the env/shell functions are in operation.
    getenv : bool
        Whether to allow pulling environment variables. If False, the
        template blocks will pass through unevaluated
    getshell : bool
        Whether or not to allow executing of shell commands. If False, the
        template blocks will pass through unevaluated

    Returns
    -------
    Final parameter dict
    N)r,   rG   rE   c                 $    i | ]\  }}|v	||S r>   r>   )rA   rB   rC   rF   s      r   rH   zmerge_pars.<locals>.<dictcomp>   s)    MMMTQAW<LMAqMMMr   Tc                 $    i | ]\  }}|v 	||S r>   r>   rA   rB   rC   lefts      r   rH   zmerge_pars.<locals>.<dictcomp>   s(    ===119=q!===r   Fc                 $    i | ]\  }}|v 	||S r>   r>   r}   s      r   rH   zmerge_pars.<locals>.<dictcomp>   s(    EEEDAq19E1aEEEr   CATALOG_DIRc                 *    g | ]}|j         k    |S r>   )name)rA   ra   rB   s     r   
<listcomp>zmerge_pars.<locals>.<listcomp>   s$    77716Q;71777r   )copyrp   r   r.   r
   r   ry   validateupdaterW   rh   removepop)paramsuser_inputs	spec_parsrE   r,   rG   parvalrg   rC   sprF   rB   r~   s              @@@r   
merge_parsr      s)   f kkmmG 2 2ooch44 	2#s## \%c&8TZ[[[ #S 1 1GCHNNMMMM[%6%6%8%8MMMNNN $QQIC=======G " "8w 	" #WSX-> ? ?GCHKK!!!
MM#";PXYYK
MMEEEEK$5$5$7$7EEEFFF
JJ}d#####%% / /17777i777 	/ 	/BF1I..F1II	/ Mr   c                     dd l }| sd} 	 t          |            d| v r| d         } n# t          $ r Y nw xY w|                    |           S )Nr   __datetime__as_str)pandasr   	TypeErrorto_datetime)rC   r   s     r   coerce_datetimer      sy    MMM Q Q 	(A	     a   s   & 
33c                     dd l }t          | t                    r?|t          t          fvr/	  |j        |           } n# t
          t          t          f$ r Y nw xY w ||           S )Nr   )rc   r
   r   r   literal_eval
ValueErrorr   RuntimeError)r$   rulerc   s      r   with_str_parser     s~    JJJ% $sO.D"D 	$C$U++EEI|4 	 	 	D	 4;;s   < AAc                     | S r   r>   r6   s    r   rO   rO   &  s    q r   )booldatetimerV   floatrY   mlistintrX   r   unicodeotherc                 
   d| v r.|                      d          \  }                     d          nd| |S t          |          j        | k    r|S | dk    rt	          |t
          t          t          f          rt          |          S t	          |t                    rF	 t          j        |          }t          |          S # t          $ r}t          d          |d}~ww xY w|S t          |          }|
 |            nt          ||          }t	          |t                    r" fd|                                D             }t	          |t
          t          t          f          r |fd|D                       }|S )a#  
    Convert a value to a specific type.

    If the value is already the given type, then the original value is
    returned. If the value is None, then the default value given by the
    type constructor is returned. Otherwise, the type constructor converts
    and returns the value.
    []Nr   zFailed to coerce string to listc                 B    i | ]\  }}|t                   |          S r>   COERCION_RULES)rA   rB   rC   inners      r   rH   zcoerce.<locals>.<dictcomp>J  s,    CCCtq!q.'**CCCr   c              3   B   K   | ]}t                   |          V  d S r   r   )rA   rC   r   s     r   rJ   zcoerce.<locals>.<genexpr>L  s0      77a&q))777777r   )rs   rt   r[   __name__r
   rY   rZ   rV   rX   r   rc   r   r   r   r   rW   )dtyper$   eoprg   r   s        @r   coercer   *  s    e| {{3''uS!! E{{u$  	eeS$/00 	;;eS!! 	KK(//E{{" K K K !BCCJK		B
>""$$$^E2%>%>C#t D DCCCCsyy{{CCC#tS)** 8u 8b7777377777Js   !"C 
C#CC#c                       e Zd ZdS )RemoteCatalogErrorN)r   
__module____qualname__r>   r   r   r   r   P  s        Dr   r   c                     t                      }|                                 D ]5\  }}|                    |          }t          j        |          }d|v r dS 6dS )z:Check is any value in args dict needs CATALOG_DIR variabler   TF)r   rW   r]   r   r^   )r   rK   rB   argparsed_contentvarss         r   _has_catalog_dirr   T  sc    
--C**,,  33-n==D  	44	5r   )r(   )FFTT)FTTr   )%rc   r   r   r+   rl   rr   r1   sysjinja2r   r   r   r   r    maxsizer'   r/   r7   r;   r@   rh   ry   r   r   r   r   rV   r   rY   rX   r   r   r   r   r   r   r   r>   r   r   <module>r      s   


         				 				      



 / / / / / / / / / /  *    ) ) ) )
! ! ! !  ( ( (  >   8# # # #LL L L L^! ! ! !"	 	 	 [ # # #L	 	 	 	 	 	 	 	    r   