o
    iUC                     @   sX  d dl Z d dlmZ d dlZd dlmZmZ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Zd dlmZ d dlZi Zi ai ZdadZdZed$d	d
Zd%ddZdddddeeef fddZeZG dd dZdd Z dd Z!dd Z"G dd dZ#G dd dZ$G dd dZ%d&deeef fd d!Z&d'deeef fd"d#Z'dS )(    N)contextmanager)ListDictUnion)Path)wrapsF<    c                 c   s    |   } g }i }t}t}| D ]}d|v r.|dd |kr)| | ||dd < || q| | |D ]}| | q6| a|adV  |a|adS )zD
    Context manager to put parsed arguments into 
    a state.
    /r   N)copyARGSPATTERNsplitappendupdatepop)parsed_argspatternremove_keysmatchedold_argsold_patternkey r   C/home/ubuntu/.local/lib/python3.10/site-packages/argbind/argbind.pyscope   s(   

r   c              	   C   sl   |  dg}|d ur| d|  | D ]\}}| d| dt|j d|  q| d d|S )N(z  # scope = z  z : z = )
)r   itemstype__name__join)	func_namefunc_kwargsr   	formattedr   valr   r   r   _format_func_debug6   s   $

r(   default)without_prefix
positionalgroupr,   c                    s   |rt |d ts|d }t|dkr|dd ng nd}|r/r/td d g t  tr7 g  fdd}|du rF|S ||S )a  Binds a functions arguments so that it looks up argument
    values in a dictionary scoped by ArgBind.

    Parameters
    ----------
    args : List[str] or [fn or Object] + List[str], optional
        List of patterns to bind the function under. If the first item
        in the list is a function or Object, then the function is bound
        here (e.g. decorate is called on the first argument). Otherwise,
        it is treated is a decorator.
    without_prefix : bool, optional
        Whether or not to bind without the function name as the prefix. 
        If True, the functions arguments will be available at "arg_name"
        rather than "func_name.arg_name", by default False
    positional : bool, optional
        Arguments that are not keyword arguments are not bound by default. If
        this is True, then the arguments will be bound as positional arguments
        in some order, by default False
    r      Nz_Combining positional arguments with scoping patterns is not allowed. Removing scoping patterns zi. 
See https://github.com/pseeth/argbind/tree/main/examples/hello_world#argbind-with-positional-argumentsc                    s   |  t  }|rt d  jdv rdd tv r't d  n	 ft< t  fdd}|rGt| d| | }|S )N__init__.r   c                     sh  t tj  i } fddt| D } D ]B\}}|j}|tjjus(r[s1 d| n| }|t	v r[||vr[t	| }||v rH|| }|||< |}t
rWt
 d| }|t|< q|| g }	t| D ]\}
} |
 d }||vrz|	| qgi } D ]\}}||v r|| ||< q|}dt	vrdt	d< t	d strt
rt
}nd }tt|| |	i |S )Nc                    s   i | ]\}} | d  |qS )r   r   ).0iarg
parametersr   r   
<dictcomp>z       z=bind.<locals>.decorator.<locals>.cmd_func.<locals>.<dictcomp>r/   r
   r   
args.debugF)listinspect	signaturer4   r    	enumerater)   	Parameteremptyr   r   	USED_ARGSr   r   DEBUGprintr(   )argskwargs
cmd_kwargs
pos_kwargsr   r'   arg_valarg_nameuse_keycmd_argsr1   r2   ordered_kwargsk_r   )funcr+   prefixr*   r3   r   cmd_funcu   sJ   

z)bind.<locals>.decorator.<locals>.cmd_func)r9   isclassgetattr__qualname__r   PARSE_FUNCSr   setattr)object_or_funcis_classrN   r,   patternsr+   r*   )rL   rM   r   	decoratord   s    

+zbind.<locals>.decorator)
isinstancestrlenwarningswarn)r*   r+   r,   rA   bound_fn_or_clsrX   r   rV   r   bind?   s    

Cr_   c                   @   s   e Zd Zdd dddZdS )bind_modulec                 C      dS NTr   )fnr   r   r   <lambda>       zbind_module.<lambda>)	filter_fnc                O   s^   t |D ](}t||}t|tts,t|dr,||r,t|g|R i |}t| || qdS )a  Binds every function/class in a specified module. The output
        class is a bound version of the original module, with the 
        attributes in the same place.

        Parameters
        ----------
        module : ModuleType
            Module or object whose attributes to bind.
        scopes : List[str] or [fn or Object] + List[str], optional
            List of patterns to bind the function under.
        filter_fn : Callable, optional
            A function that takes in the function that is to be bound, and 
            returns a boolean as to whether or not it should be bound.
            Defaults to always True, no matter what the function is.
        kwargs : keyword arguments, optional
            Keyword arguments to the bind function.

        rQ   N)dirrP   rY   r!   syshasattrr_   rS   )selfmodulerf   scopesrB   fn_namerc   bound_fnr   r   r   r.      s   
zbind_module.__init__N)r"   
__module__rQ   r.   r   r   r   r   r`      s    r`   c                   C   s   t S )z
    Gets the args that have been used so far
    by the script (e.g. their function they target
    was actually called).
    )r>   r   r   r   r   get_used_args   s   rp   c           	      C   s   t |}tj|jdd t|dR}dd tj_tj| tjd}d}g }|	dD ])}|	d	d
 
 }|dsM||krD|rDd| }|	d	d
 
 }|| q)|d| W d   dS 1 sfw   Y  dS )z5
    Dumps the provided arguments to a
    file.
    T)exist_okwc                  W   ra   rb   r   )rA   r   r   r   rd      re   zdump_args.<locals>.<lambda>)DumperNr   r/   r   -)r   osmakedirsparentopenyamlrs   ignore_aliasesdumpr   strip
startswithr   writer#   )	rA   output_pathpathfx	prev_lineoutputlinecur_liner   r   r   	dump_args   s    

"r   c                 C   s  t | ttfr%t| d}tj|tjd}W d   n1 sw   Y  ntj| tjd}d|v rK|d}i }|D ]	}|t	| q:|| |}t
j }d|v r\||d | D ]V\}}t |tr|dr~|dd }	|	|v r~||	 ||< q`t |trg }
|D ])}t |tr|dr|dd }	|	|v r|
||	  q|
| q|
| q|
||< q`d|vrt|d< |S )	zb
    Loads arguments from a given input path or file stream, if
    the file is already open.
    r)LoaderNz$includez$vars$r-   r7   )rY   rZ   r   rx   ry   loadr   r   r   	load_argsru   environr   r    r}   r8   r   r?   )input_path_or_streamr   datainclude_filesinclude_argsinclude_file_varsr   r'   lookupnew_listsubvalr   r   r   r      sJ   





r   c                   @      e Zd Zdd Zdd ZdS )str_to_listc                 C   
   || _ d S N_type)rj   r   r   r   r   r.        
zstr_to_list.__init__c                    s    | d} fdd|D }|S )N c                    s   g | ]}  |qS r   r   )r0   vrj   r   r   
<listcomp>  s    z(str_to_list.__call__.<locals>.<listcomp>)r   rj   values_valuesr   r   r   __call__  s   
zstr_to_list.__call__Nr"   ro   rQ   r.   r   r   r   r   r   r         r   c                   @   r   )str_to_tuplec                 C   r   r   
_type_list)rj   r   r   r   r   r.   !  r   zstr_to_tuple.__init__c                    s(   | d} fddt|D }t|S )Nr   c                    s   g | ]\}} j | |qS r   r   )r0   r1   r   r   r   r   r   %  r6   z)str_to_tuple.__call__.<locals>.<listcomp>)r   r;   tupler   r   r   r   r   #  s   
zstr_to_tuple.__call__Nr   r   r   r   r   r      r   r   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )str_to_dictc                 C   s   d S r   r   r   r   r   r   r.   )  s   zstr_to_dict.__init__c                 C   s(   zt |}W |S  ty   | Y S w r   )astliteral_eval
ValueError)rj   svaluer   r   r   _guess_type,  s   zstr_to_dict._guess_typec                 C   sH   | d}i }|D ]}| dd\}}| |}| |}|||< q	|S )Nr   =r-   )r   r   )rj   r   r   elemr   r'   r   r   r   r   4  s   



zstr_to_dict.__call__N)r"   ro   rQ   r.   r   r   r   r   r   r   r   (  s    r   c              	      s  t jt jd}|jdtddd |jdtddd |jdtdd	d
d t| tr+| g} d| vr4| d tD ]Ht \} }}t	|t	| @ sKq6t
|}t|j}|j}dd |D }|jd d} fdd}	|j D ]\}
}|j}|j}|t
jju}|t
jju r|rt|}|s|r<|	|
|}i }d}|
|v rtj||
 td}|||d	 < t|dkr|dd D ]}t j||< q|D ]r}ttttg}dd |D }|tu r|j|d|| d q||v r||| }|j|t |||| d q|t!u r|j|t" ||| d qt#|dr0|j$t%u r/|j&}|j|t'|||| d q|j||||| d qqv|j(}|du rGd} rus[d d	  d d|
 }n
d d	  d|
 }|d d!)t*  d"| d#7 }tj|td}||_+q6|S )$zBuilds the argument parser from all of the bound functions.

    Returns
    -------
    ArgumentParser
        Argument parser built by ArgBind.
    )formatter_classz--args.saveFz1Path to save all arguments used to run script to.)r!   requiredhelpz--args.loadz3Path to load arguments from, stored as a .yml file.z--args.debugr   z4Print arguments as they are passed to each function.)r!   r   r)   r   r)   c                 S   s   i | ]}|j |jqS r   )rF   descriptionr0   r   r   r   r   r5   a  s    
z build_parser.<locals>.<dictcomp>z!Generated arguments for function )titlec                    sv   g }| }|rdnd}r|d|   }n
|d d|   }| |dd  d ur9 D ]}| |d| q-|S )N--r	   zPATTERN/r/   r   )r   replace)r   is_kwarg	arg_namesrF   prependprW   rM   r*   r   r   _get_arg_namesi  s   
z$build_parser.<locals>._get_arg_namesr	   )widthr-   Nc                 S   s   g | ]}t | qS r   )r   r   r   r   r   r     s    z build_parser.<locals>.<listcomp>
store_true)actionr   )r!   r)   r   
__origin__r   r
   r/   z Additional scope patterns: z, zX. Use these by prefacing any of the args below with one of these patterns. For example: z VALUE.),argparseArgumentParserRawTextHelpFormatteradd_argumentrZ   intrY   r   rR   setr9   r:   docstring_parserparse__doc__paramsadd_argument_groupr4   r    r)   
annotationr<   r=   r!   textwrapfill
HELP_WIDTHr[   SUPPRESSfloatboolindexr   r   r   ri   r   r   __args__r   short_descriptionr#   r8   r   )r,   r   rL   r+   fn_groupsig	docstringparameter_helpr   r   r   r'   rE   arg_typer   r   arg_help	help_textpattern_arg_namerF   inner_types
list_typesr   r   descscope_patternr   r   r   build_parser@  s   










r   c                 C   s  | du r	t |dn| } dd tjD }|ddg |  \}}t|}||d< |d}|d}|d}d	d |D }	d
d |D }
|	D ]}|d\}}||vrZ|| ||< qG|rt|}|D ]}||vro|| ||< qc|	D ]}|d\}}||vr||vr||v r|| ||< qr|
D ] }||v r|	D ]}|d\}}||kr||vr|| ||< qq|rt	|| ||d< ||d< ||d< |S )zh
    Parses the command line and returns a dictionary.
    Builds the argument parser if p is None.
    N)r,   c                 S   s,   g | ]}| d r|d ddd qS )r   r	   r   r   )r}   r   r   r   r   r   r   r     s   , zparse_args.<locals>.<listcomp>z	args.savez	args.loadzargs.unknownr7   c                 S   s   g | ]}d |v r|qS r
   r   r0   r   r   r   r   r         c                 S   s   g | ]}d |vr|qS r   r   r   r   r   r   r     r   r
   )
r   rh   argvextendparse_known_argsvarsr   r   r   r   )r   r,   	used_argsknownunknownrA   load_args_pathsave_args_path
debug_argspattern_keystop_level_argsr   r   rF   loaded_argspattern_keyr   r   r   
parse_args  sR   



r   )r	   r   )r)   )Nr)   )(r9   
contextlibr   r   typingr   r   r   r   r   ry   rh   ru   pathlibr   r   	functoolsr   r\   rR   r   r>   r   r?   r   r   r(   r8   rZ   r_   bind_to_parserr`   rp   r   r   r   r   r   r   r   r   r   r   r   <module>   sB    
 	o0|