
    +dC                         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dlm	Z	  ej
        d          Z G d de          ZdS )	    N   )
DataSourceDataSourceBaseNoEntry   )reload_on_changeintakec                       e Zd ZdZdZdZdZ	 	 	 	 	 	 	 	 	 	 d( fd	Zed             Z	e
d	             Zd
 Zd Zd Zd Ze
d             Zed)d            Zd Zed*d            Zd Zd Zd Zd+dZed             Z fdZexZZed             Zd Zd Zd Z d Z!d Z"d Z#d  Z$d! Z%d" Z&d# Z'd$ Z(d% Z)d& Z*e
d'             Z+ xZ,S ),Cataloga  Manages a hierarchy of data sources as a collective unit.

    A catalog is a set of available data sources for an individual
    entity (remote server, local  file, or a local
    directory of files). This can be expanded to include a
    collection of subcatalogs, which are then managed as a single unit.

    A catalog is created with a single URI or a group of URIs. A URI can
    either be a URL or a file path.

    Each catalog in the hierarchy is responsible for caching the most recent
    refresh time to prevent overeager queries.

    Attributes
    ----------
    metadata : dict
        Arbitrary information to carry along with the data source specs.
    catalogN<   Tdefaultc                    t          t          |                                            || _        || _        |pi | _        || _        || _        || _        |	| _	        t          |
t                    r.|
r,ddlm fd|
                                D             | _        n5t          |
t           t"          f          rd |
D             | _        ni | _        |dvrt%          d|z            || _        |r$t          |t(                    rt%          d          t+          j                    | _        ||n|                                 | _        |                                  dS )	a  
        Parameters
        ----------
        entries : dict, optional
            Mapping of {name: entry}
        name : str, optional
            Unique identifier for catalog. This takes precedence over whatever
            is stated in the cat file itself. Defaults to None.
        description : str, optional
            Description of the catalog. This takes precedence over whatever
            is stated in the cat file itself. Defaults to None.
        metadata: dict
            Additional information about this data
        ttl : float, optional
            Lifespan (time to live) of cached modification time. Units are in
            seconds. Defaults to 1.
        getenv: bool
            Can parameter default fields take values from the environment
        getshell: bool
            Can parameter default fields run shell commands
        persist_mode: ['always', 'default', 'never']
            Defines the use of persisted sources: if 'always', will use a
            persisted version of a data source, if it exists, if 'never' will
            always use the original source. If 'default', persisted sources
            will be used if they have not expired, and re-persisted and used
            if they have.
        storage_options : dict
            If using a URL beginning with 'intake://' (remote Intake server),
            parameters to pass to requests when issuing http commands; otherwise
            parameters to pass to remote backend file-system. Ignored for
            normal local files.
        r   UserParameterc                 Z    i | ]'\  }}|t          |t                    r
 dd |i|n|(S )name )
isinstancedict).0r   upr   s      3lib/python3.11/site-packages/intake/catalog/base.py
<dictcomp>z$Catalog.__init__.<locals>.<dictcomp>d   s`      $T  $T  $TowosuwDZXZ\`MaMa+i==+I+Id+Ib+I+I+Igi  $T  $T  $T    c                      i | ]}|d          |S r   r   r   r   s     r   r   z$Catalog.__init__.<locals>.<dictcomp>f   s    #M#M#MrBvJ#M#M#Mr   )alwaysneverr   z Persist mode (%s) not understoodzThe class intake.Catalog does not accept a string for `entries`
Did you mean to use `intake.open_catalog`? Note that in versions of intake <=0.5.4 `intake.Catalog` was an alias for `intake.open_catalog`. It is now the intake base Catalog class.N)superr   __init__r   descriptionmetadatattlgetenvgetshellstorage_optionsr   r   localr   itemsuser_parameterslisttuple
ValueErrorpmodestrtimeupdated_make_entries_container_entriesforce_reload)selfentriesr   r#   r$   r%   r&   r'   persist_moder(   r+   r   	__class__s              @r   r"   zCatalog.__init__,   s   Z 	gt%%'''	& B .ot,, 	& 	&,,,,,, $T  $T  $T  $T  |K  |Q  |Q  |S  |S  $T  $T  $TD  $77 	&#M#M_#M#M#MD  #%D == 	P?,NOOO!
 	z'3// 	!   y{{#*ZD<X<X<Z<Zr   c                 $     | di |}||_         |S )a  
        Create Catalog from the given set of entries

        Parameters
        ----------
        entries : dict-like
            A mapping of name:entry which supports dict-like functionality,
            e.g., is derived from ``collections.abc.Mapping``.
        kwargs : passed on the constructor
            Things like metadata, name; see ``__init__``.

        Returns
        -------
        Catalog instance
        r   r4   )clsr7   kwargscats       r   	from_dictzCatalog.from_dict{   s!    " cmmFmm
r   c                 8    t          | j        | j                  S )N)r   r%   )r   r   r%   r6   s    r   r=   zCatalog.kwargs   s    1111r   c                     i S )aM  Subclasses may override this to return some other dict-like.

        See RemoteCatalog below for the motivating example for this hook. This
        is typically useful for large Catalogs backed by dynamic resources such
        as databases.

        The object returned by this method must implement:

        * ``__iter__()`` -> an iterator of entry names
        * ``__getitem__(key)`` -> an Entry
        * ``items()`` -> an iterator of ``(key, Entry)`` pairs

        For best performance the object should also implement:

        * ``__len__()`` -> int
        * ``__contains__(key)`` -> boolean

        In ``__len__`` or ``__contains__`` are not implemented, intake will
        fall back on iterating through the entire catalog to compute its length
        or check for containment, which may be expensive on large catalogs.
        r   rA   s    r   r3   zCatalog._make_entries_container   s	    , 	r   c                     dS )z#Override this: load catalog entriesNr   rA   s    r   _loadzCatalog._load       r   c                 ^    t          j                     | _        |                                  dS )zImperative reload data nowN)r1   r2   rD   rA   s    r   r5   zCatalog.force_reload   s     y{{

r   c                     | j         :t          j                    | j        z
  | j         k    r|                                  dS dS dS )z,Reload catalog if sufficient time has passedN)r%   r1   r2   r5   rA   s    r   reloadzCatalog.reload   sS    H 	 ty{{T\'ADH'L 	 	  	  	  	 r   c                 8    | j                             dd          S )Nversionr   )r$   getrA   s    r   rJ   zCatalog.version   s     }  A...r   r   c                    dd l |                                                                fd|                     |                                          D             }t
                              || j        dz   | j        | j	        | j
        | j        pi                                  | j        | j                                                   }|| j        d|j        d<   | |_        |                                D ]	}||_        
|S )Nr   c                 z    i | ]6\  }t          fd D                        |                              7S )c              3      K   | ]K}|t                                                                                                                    v V  Ld S N)r0   describevalueslower)r   wordvs     r   	<genexpr>z,Catalog.search.<locals>.<dictcomp>.<genexpr>   s|        US  US  EIUY]`abakakamamatatavav]w]w]}]}]]U  US  US  US  US  US  USr   )anycopy)r   krT   rW   wordss     @r   r   z"Catalog.search.<locals>.<dictcomp>   s      T  T  Ttq!QT  US  US  US  US  MR  US  US  US  RS  RS  T1diill  T  T  Tr   )depth_search)r   r%   r&   r'   r$   r(   r+   )textupstreamsearch)rW   rR   splitwalkr*   r   r?   r   r%   r&   r'   r$   r(   r+   r>   rQ   _catalog)r6   r\   rZ   r7   r>   erW   rY   s         @@r   r^   zCatalog.search   s   

""$$ T  T  T  T  Ttyyuy/E/E/K/K/M/M  T  T  TY&;]m)r//11 0 05577   	
 	
 +/DI!F!FX!! 	 	AAJJ
r   c                 ~    t                               fd| j                                        D                       S )a[  
        Create a Catalog of a subset of entries based on a condition

        .. warning ::

           This function operates on CatalogEntry objects not DataSource
           objects.

        .. note ::

            Note that, whatever specific class this is performed on,
            the return instance is a Catalog. The entries are passed
            unmodified, so they will still reference the original catalog
            instance and include its details such as directory,.

        Parameters
        ----------
        func : function
            This should take a CatalogEntry and return True or False. Those
            items returning True will be included in the new Catalog, with the
            same entry names

        Returns
        -------
        Catalog
           New catalog with Entries that still refer to their parents
        c                 2    i | ]\  }} |          ||S r   r   )r   keyentryfuncs      r   r   z"Catalog.filter.<locals>.<dictcomp>   s1    !d!d!deX\X\]bXcXc!d#u!d!d!dr   )r   r?   r4   r*   )r6   rg   s    `r   filterzCatalog.filter   s<    8   !d!d!d!dt}?R?R?T?T!d!d!deeer   c                 V   ||ni }|g n|}| j                                         D ]\  }}|j        dk    rT|dk    rN	  |                                |||gz   |dz
             n&# t          $ r}t          |           Y d}~nd}~ww xY wd                    ||gz             }|||<   |S )a  Get all entries in this catalog and sub-catalogs

        Parameters
        ----------
        sofar: dict or None
            Within recursion, use this dict for output
        prefix: list of str or None
            Names of levels already visited
        depth: int
            Number of levels to descend; needed to truncate circular references
            and for cleaner output

        Returns
        -------
        Dict where the keys are the entry names in dotted syntax, and the
        values are entry instances.
        Nr   r   .)r4   r*   
_containerr`   	Exceptionprintjoin)	r6   sofarprefixrZ   outr   itemrb   ns	            r   r`   zCatalog.walk   s    & 0eeb16---// 		 		JD$)+ 	 DFFKKVtf_eai@@@@    !HHHDDDD 4&))ACFF
s   &A$$
B.BBc              #   ~   K   |                                                                  D ]\  }}| |            fV  dS )zBGet an iterator over (key, source) tuples for the catalog entries.N)_get_entriesr*   )r6   r   rf   s      r   r*   zCatalog.items  sT      ,,..4466 	  	 KD%-	  	 r   c              #   t   K   |                                                                  D ]} |            V  dS )z5Get an iterator over the sources for catalog entries.N)ru   rQ   )r6   rf   s     r   rQ   zCatalog.values  sH      &&((//11 	 	E%''MMMM	 	r   c                    ddl }| j        i | j        | j        d}| j                                        D ]\  }}|j                                        }|                    dd           d |	                    dg           D             |d<   	 t          |d         t                    r0d                    |d         j        |d         j        g          |d<   n# t          $ r Y nw xY w||d	         |<   |                    |          S )
z
        Produce YAML version of this catalog.

        Note that this is not the same as ``.yaml()``, which produces a YAML
        block referring to this catalog.
        r   N)r$   sourcesr   r#   r   c                 N    i | ]"}|j         |                                d          #S )r=   )r   __getstate__)r   rX   s     r   r   z%Catalog.serialize.<locals>.<dictcomp>+  s+    eeeq(8(8(Beeer   
parametersdriverrj   rx   )yamlr$   r   r#   r4   r*   _captured_init_kwargsrW   poprK   
issubclassr   rn   
__module____name__	TypeErrordump)r6   r}   outputre   rf   kws         r   	serializezCatalog.serialize  s     	"mDI^b^noo---// 		( 		(JC,1133BFF9d###eeBFFS_acLdLdeeeB|blN;; ^#&88R\-DblF[,\#]#]BxL   %'F9c""yy   s   AC
C%$C%c                     ddl m}  ||gfi |pi ddid         5 }|                    |                                            ddd           dS # 1 swxY w Y   dS )z
        Output this catalog to a file as YAML

        Parameters
        ----------
        url : str
            Location to save to, perhaps remote
        storage_options : dict
            Extra arguments for the file-system
        r   )
open_filesmodewtN)fsspecr   writer   )r6   urlr(   r   fs        r   savezCatalog.save4  s     	&%%%%%ZDD/"7RDDtDDDQG 	&1GGDNN$$%%%	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   (AAAc                     | j         |         }| |_        | j        |_        t	          d |j        D                       fd| j                                        D             }||j        pg z   |_         |            S )Nc              3   ^   K   | ](}t          |t                    r|d          n|j        V  )dS )r   N)r   r   r   r   s     r   rU   z%Catalog._get_entry.<locals>.<genexpr>J  s;      jjRjT&:&:G6

jjjjjjr   c                 "    g | ]\  }}|v	|S r   r   )r   r   r   up_namess      r   
<listcomp>z&Catalog._get_entry.<locals>.<listcomp>K  s'    WWWhdB$hBVWrWWWr   )r4   ra   r/   _pmodeset_user_parametersr+   r*   )r6   r   rf   upsr   s       @r   
_get_entryzCatalog._get_entryD  s    d#zjjSXSijjjjjWWWW$"6"<"<">">WWW!$(>(D"!Euwwr   c                 `   ddl m} i }|                                                                D ]\  }}| j                                        D ]}t          |t                    rF||d         k    r9|                                }||d<    |di |||<   |                    |           ]||j	        k    rC|j
                                        }||d<   ||d<    |di |||<   |                    |            t                      j        di |}|j                            |           |S )Nr   r   r   r   r   )r)   r   rW   r*   r+   rQ   r   r   r   r   r~   r!   configure_newupdate)
r6   r=   r   r   rX   rT   r   r   newr9   s
            r   r   zCatalog.configure_newO  s\   ((((((KKMM'')) 	& 	&DAq*1133 & &b$'' &BvJ &WWYY()9!.!4!4!4!4A

1BG| &5::<<()9%&6
!.!4!4!4!4A

1& $egg#--f--""3'''
r   c                     | j         S rO   r;   rA   s    r   ru   zCatalog._get_entriesi  s
    }r   c                 D    t          |                                           S )z,Return an iterator over catalog entry names.)iterru   rA   s    r   __iter__zCatalog.__iter__m  s    D%%''(((r   c                      t          |           S )z?Entry names in this catalog as an iterator (alias for __iter__))r   rA   s    r   keyszCatalog.keysq  s    Dzzr   c                 D    t          |                                           S rO   )lenru   rA   s    r   __len__zCatalog.__len__u  s    4$$&&'''r   c                 .    ||                                  v S rO   )ru   r6   re   s     r   __contains__zCatalog.__contains__x  s    d''))))r   c                 h    d | D             t          | j                                                  z   S )Nc                 d    g | ]-}t          j        d |          t          j        |          +|.S )z[_A-Za-z][_a-zA-Z0-9]*$)rematchkeyword	iskeyword)r   rf   s     r   r   z#Catalog.__dir__.<locals>.<listcomp>~  sN     
 
 
rx0I5'Q'Q
ZaZklqZrZr

 
 
r   )r,   __dict__r   rA   s    r   __dir__zCatalog.__dir__|  sF    
 
#
 
 
M  
 

 	
r   c                      t          |           S rO   )r,   rA   s    r   _ipython_key_completions_z!Catalog._ipython_key_completions_  s    Dzzr   c                     d| j         z  S )Nz<Intake catalog: %s>r   rA   s    r   __repr__zCatalog.__repr__  s    %	11r   c                     |dk    rt          d          |                    d          s+	 | |         S # t          $ r}t          |          |d }~ww xY wt          |          )Nrf   z(Source was not made from a catalog entry_)r   
startswithKeyErrorAttributeError)r6   rr   rb   s      r   __getattr__zCatalog.__getattr__  s     7? 	FDEEEs## 	22Dz! 2 2 2$T**12T"""s   4 
AAAc                     || j         |<   dS )a  Add entry to catalog

        This relies on the `_entries` attribute being mutable, which it normally
        is. Note that if a catalog automatically reloads, any entry added here
        may be very transient

        Parameters
        ----------
        key : str
            Key to give the entry in the cat
        entry : CatalogEntry
            The entry to include (could be local, remote)
        Nr;   )r6   re   rf   s      r   __setitem__zCatalog.__setitem__  s     #cr   c                 6    | j                             |          S )aS  Remove entry from catalog and return it

        This relies on the `_entries` attribute being mutable, which it normally
        is. Note that if a catalog automatically reloads, any entry removed here
        may soon reappear

        Parameters
        ----------
        key : str
            Key to give the entry in the cat
        )r4   r   r   s     r   r   zCatalog.pop  s     }  %%%r   c                    t          |t                    s`|| v r\|                     |          }|j        dk    r:||_        |j                            | j                                                   |S |S t          |t                    rd|v r|	                    d          }t          |t                    rt          |          dd         }d}|ro|
                    d          }||rdndz   |z   }|| j        v rCd                    |          }	 | j        |         |         } |            S # t          $ r Y kw xY w|on.t          |t                    r| }|D ]
}||         } |            S t          |          )a  Return a catalog entry by name.

        Can also use attribute syntax, like ``cat.entry_name``, or
        item lookup cat['non-python name']. This enables walking through
        nested directories with cat.name1.name2, cat['name1.name2'] *or*
        cat['name1', 'name2']
        r   rj   N r   )r   r,   r   	containerr   r+   r   rW   r0   r_   r   r4   rn   r   r-   )	r6   re   spartsrp   bitrestrq   parts	            r   __getitem__zCatalog.__getitem__  s    #t$$ 	 	$$A{i' !(()=)B)B)D)DEEEHc3 	!C3J 	!))C..Cc4   	IIaaaLEF !iill&#833b9C?T]* !88E??D!"mF3D9"suu# ! ! ! !!  ! U## 	C    $i355Lsmms   D1 1
D>=D>c                     dd d | j         dS )Nr   )r   shapedtyper$   )r$   rA   s    r   discoverzCatalog.discover  s    &RVR_```r   c                     d S rO   r   rA   s    r   _closezCatalog._close  rE   r   c                     t          | d          s'ddlm} ddlm}  |              ||           | _        nd| j        _        | j        S )N_guir   )output_notebook)GUIT)hasattr	interfacer   interface.guir   r   visible)r6   r   r   s      r   guizCatalog.gui  si    tV$$ 	%333333++++++OD		DII $DIyr   )
NNNNr   TTr   NN)r   )NNr   rO   )-r   r   __qualname____doc__r   r   authr"   classmethodr?   propertyr=   r3   rD   r5   rH   rJ   r   r^   rh   r`   r*   rQ   r   r   r   r   __call__rK   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__)r9   s   @r   r   r      s        ( IDD M M M M M M^   [( 2 2 X2  0    
     
 / / X/    *f f f<    @     
  
! ! !,& & & &        0 #"Hs  ) ) )  ( ( (* * *
 
 
  2 2 2# # ## # # & & && & &Pa a a   	 	 X	 	 	 	 	r   r   )r   loggingr   r1   source.baser   r   r   utilsr   	getLoggerloggerr   r   r   r   <module>r      s      				  = = = = = = = = = = # # # # # #		8	$	$[ [ [ [ [j [ [ [ [ [r   