o
    i8                  	   @   s  d Z ddlZddlZddlZddlmZmZmZmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZ ddlmZmZ edZerSdd	lmZ dd
lmZ ddlmZ nddlmZ ejeddZddlmZ G dd deZG dd dedZ G dd de Z!de"deee gee f fddZ#de$fddZ%de$fddZ&ddeB ee B de'ed f fd!d"Z(ddeB ee B de)e fd#d$Z*ddeB ee B de'ed f dB fd%d&Z+dedefd'd(Z,d)ded* B eB dedB fd+d,Z-d-e"de"fd.d/Z.d-e"de"fd0d1Z/d2ee d3e0dee'ed f  fd4d5Z1d6d7d8e"de$fd9d:Z2d;ede$fd<d=Z3d>d? Z4eG d@dA dAZ5dLdCdDdEe0de"fdFdGZ6dMdJdKZ7dS )Nz^To prevent circular dependencies, this module should never import anything else from Cyclopts.    N)CallableIterableIteratorSequence)suppress)
itemgetter)TYPE_CHECKINGAnyLiteralTypeVar)fieldfrozenT)JSONDecodeError)r   Console)defineT)unsafe_hash)stdlib_module_namesc                   @   s,   e Zd ZdefddZded fddZdS )SentinelMetareturnc                 C   s   d| j  dS )N<>)__name__cls r   T/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/cyclopts/utils.py__repr__   s   zSentinelMeta.__repr__Fc                 C   s   dS )NFr   r   r   r   r   __bool__!   s   zSentinelMeta.__bool__N)r   
__module____qualname__strr   r
   r   r   r   r   r   r      s    r   c                   @   s   e Zd Zdd ZdS )Sentinelc                 C   s   t d)NzGSentinel objects are not intended to be instantiated. Subclass instead.)
ValueErrorr   r   r   r   __new__&   s   zSentinel.__new__N)r   r    r!   r%   r   r   r   r   r#   %   s    r#   )	metaclassc                   @   s   e Zd ZdZdS )UNSETzTSpecial sentinel value indicating that no data was provided. **Do not instantiate**.N)r   r    r!   __doc__r   r   r   r   r'   *   s    r'   targetr   c                    s"   dt t dt t f fdd}|S )zJClass decorator that records init argument names as a tuple to ``target``.r   r   c                    sH   | j  t }tdd |jD t  fdd}|| _ | S )Nc                 s   s    | ]	}|d kr|V  qdS )selfNr   ).0namer   r   r   	<genexpr>4   s    z1record_init.<locals>.decorator.<locals>.<genexpr>c              	      sJ    | g|R i | t | tfddtt|D t|  d S )Nc                 3   s    | ]} | V  qd S Nr   )r+   i)param_namesr   r   r-   :   s    zCrecord_init.<locals>.decorator.<locals>.new_init.<locals>.<genexpr>)object__setattr__tuplerangelen)r*   argskwargs)original_initr0   r)   r   r   new_init6   s   4z0record_init.<locals>.decorator.<locals>.new_init)__init__inspect	signaturer3   
parameters	functoolswraps)r   function_signaturer9   r)   )r8   r0   r   	decorator1   s   
zrecord_init.<locals>.decorator)typer   )r)   rB   r   rA   r   record_init.   s   rD   c                 C   s0   t | ttB tB tB rdS t | t ot | tS )NT)
isinstancelistr3   setdictr"   r   objr   r   r   is_iterableB   s   rK   c                 C   s,   zt | o
t| |W S  ty   Y dS w )ac  Safely check if a type is both a class and a subclass of target_class.

    Parameters
    ----------
    hint : Any
        The type to check.
    target_class : type
        The target class to check subclass relationship against.

    Returns
    -------
    bool
        True if hint is a class and is a subclass of target_class, False otherwise.
    F)r;   isclass
issubclass	TypeError)hinttarget_classr   r   r   is_class_and_subclassH   s
   rQ   value.c                 C   s"   | du rdS t | rt| S | fS )a  Convert a single element or an iterable of elements into a tuple.

    Intended to be used in an ``attrs.Field``. If :obj:`None` is provided, returns an empty tuple.
    If a single element is provided, returns a tuple containing just that element.
    If an iterable is provided, converts it into a tuple.

    Parameters
    ----------
    value: Any | Iterable[Any] | None
        An element, an iterable of elements, or None.

    Returns
    -------
    tuple[Any, ...]: A tuple containing the elements.
    Nr   )rK   r3   rR   r   r   r   to_tuple_converter^   s
   rT   c                 C   s   t t| S r.   )rF   rT   rS   r   r   r   to_list_converterv   s   rU   c                 C   s   | du rdS | s
dS t | S )zsConvert a string or Iterable or None into an Iterable or None.

    Intended to be used in an ``attrs.Field``.
    Nr   )rT   rS   r   r   r   optional_to_tuple_converterz   s
   rV   c                 C   s"   | du rt S t| rt| S | S )aB  Convert sort_key value, consuming generators with :func:`next`.

    Parameters
    ----------
    value : Any
        The sort_key value to convert. Can be None, a generator, or any other value.

    Returns
    -------
    Any
        UNSET if value is None, ``next(value)`` if generator, otherwise value unchanged.
    N)r'   r;   isgeneratornextrS   r   r   r   sort_key_converter   s
   
rY   input_value)defaultplainc                 C   s^   | du rdS t | tr-| dkrddlm} | S | dkr%ddlm} | S td| d| S )	a  Convert string literals to help formatter instances.

    Parameters
    ----------
    input_value : None | Literal["default", "plain"] | Any
        The input value to convert. Can be None, "default", "plain", or a formatter instance.

    Returns
    -------
    Any | None
        None, or a HelpFormatter instance.

    Notes
    -----
    Lazily imports formatters to avoid importing Rich during normal execution.
    Nr[   r   )DefaultFormatterr\   )PlainFormatterzUnknown formatter: z. Must be 'default' or 'plain')rE   r"   cyclopts.help.formattersr]   r^   r$   )rZ   r]   r^   r   r   r   help_formatter_converter   s   
r`   sc                 C   s>   t ddd | }t ddd |}t ddd |}| S )Nz([A-Z]+)([A-Z][a-z])c                 S      |  d d|  d S N   _   groupmr   r   r   <lambda>       z"_pascal_to_snake.<locals>.<lambda>z([a-z])([A-Z])c                 S   rb   rc   rg   ri   r   r   r   rk      rl   z([0-9])([A-Z])c                 S   rb   rc   rg   ri   r   r   r   rk      rl   )resublower)ra   snaker   r   r   _pascal_to_snake   s   rq   c                 C   s   t |  dddS )a  Converts a python identifier into a CLI token.

    Performs the following operations (in order):

    1. Convert PascalCase to snake_case.
    2. Convert the string to all lowercase.
    3. Replace ``_`` with ``-``.
    4. Strip any leading/trailing ``-`` (also stripping ``_``, due to point 3).

    Intended to be used with :attr:`App.name_transform` and :attr:`Parameter.name_transform`.

    Parameters
    ----------
    s: str
        Input python identifier string.

    Returns
    -------
    str
        Transformed name.
    re   -)rq   ro   replacestrip)ra   r   r   r   default_name_transform   s   ru   iterablenc                 C   s<   t | | rt| d| dt| g| }t|ddiS )a-  Collect data into non-overlapping fixed-length chunks or blocks.

    https://docs.python.org/3/library/itertools.html#itertools-recipes

    Parameters
    ----------
    iterable: Sequence[Any]
        Some iterable sequence to group.
    n: int
        Number of elements to put in each group.
    z is not divisible by .strictF)r5   r$   iterzip)rv   rw   	iteratorsr   r   r   grouper   s   r}   F)allow_numberstokenc                C   s`   |s+t t t|  |  dkr	 W d   dS 	 W d   dS 1 s&w   Y  | dS )a8  Checks if a token looks like an option.

    Namely, negative numbers are not options, but a token like ``--foo`` is.

    Parameters
    ----------
    token: str
        String to interpret.
    allow_numbers: bool
        If :obj:`True`, then negative numbers (e.g. ``"-2"``) will return :obj:`True`.
        Otherwise, numbers will be interpreted as non-option-like (:obj:`False`).
        Note: ``-j`` **is option-like**, even though it can represent an imaginary number.

    Returns
    -------
    bool
        Whether or not the ``token`` is option-like.
    z-jNTFrr   )r   r$   complexro   
startswith)r   r~   r   r   r   is_option_like   s   
 
r   rJ   c                 C   s   t | dddd tv S )Nr     rx   r   )getattrsplitr   rI   r   r   r   
is_builtin  s   r   c                 O   s   t | ttr	| S t| r| |i |S t| rWg }| D ]6}t |ttr+|| qt|r:|||i | qt|rM|t|g|R i | q|| qt|S | S )a  Recursively resolves callable elements in a tuple.

    Returns an object that "looks like" the input, but with all callable's invoked
    and replaced with their return values. Positional and keyword elements will be
    passed along to each invocation.
    )rE   rC   r#   callablerK   appendresolve_callablesr3   )tr6   r7   resolvedelementr   r   r   r     s    r   c                   @   sX   e Zd ZU dZeed< 	 eedZeed< 	 eed< 	 e	de
d  ded  fdd	Zd
S )
SortHelperzLSort a list of objects by an external key and retrieve the objects in-order.key)	converterfallback_keyrR   entriesr   c                 C   sL  ddl m}m}m} g }g }g }g }g }g }	| D ]b}
|
j|u r'|d|
f q|
j|u r4|d|
f q|
j|u rA|d|
f q|
jtdfv rQ|	|
j|
f qt|
jro|
jd tdfv ro||
jdd |
j |
f q||
j|
jf|
f q|j	t
dd |j	t
dd |	j	t
dd || | | | |	 }dd |D S )z(Sorts a sequence of :class:`SortHelper`.r   )#DEFAULT_ARGUMENTS_GROUP_SORT_MARKER"DEFAULT_COMMANDS_GROUP_SORT_MARKER$DEFAULT_PARAMETERS_GROUP_SORT_MARKERNrd   )r   c                 S   s   g | ]}|d  qS )rd   r   )r+   xr   r   r   
<listcomp>u  s    z#SortHelper.sort.<locals>.<listcomp>)cyclopts.groupr   r   r   r   r   r'   r   rK   sortr   )r   r   r   r   default_commands_groupdefault_arguments_groupdefault_parameters_groupuser_sort_keyordered_no_user_sort_keyno_user_sort_keyentrycombinedr   r   r   r   H  sF   


 zSortHelper.sortN)r   r    r!   r(   r	   __annotations__r   rT   r   staticmethodr   rF   r   r   r   r   r   r   7  s   
  r      decode_errorr   contextc              	   C   s   | j  }|| jd  }| jd }|| }|dkr d}d}|}nd}|| }|| }|t|kr9t|d }d}	nd}	||| }
dt||  d }d| |
 |	 d	| d
t|  }|S )zNot intended to be a super robust implementation, but robust enough to be helpful.

    Parameters
    ----------
    context: int
        Number of surrounding-character context
    rd   r   r   z... z ... ^zJSONDecodeError:
    z
    
)doc
splitlineslinenocolnor5   r"   )r   r   lineslineerror_indexstartprefix_ellipsissegment_error_indexendsuffix_ellipsissegmentcarat_pointerresponser   r   r   json_decode_error_verbosifierx  s(   

 r   consoler   c                 C   s  ddl m} | jp
d}|di ddd|dt| dd	d
| jp d	d| jpyd	d| jd| jdt| dd	d| jdt| dddt| dddt| dd	dt| ddd| j	d| j
d| jdt| dd	dt| dd	dt| dd	S d| jd| jdt| dd	d| jdt| dddt| dddt| dd	dt| ddd| j	d| j
d| jdt| dd	dt| dd	dt| dd	S ) a'  Create an error console (stderr=True) that inherits settings from a source console.

    Parameters
    ----------
    console : Console
        Source Rich Console to copy settings from.

    Returns
    -------
    Console
        New Rich Console with stderr=True and inherited settings.
    r   r   autostderrTcolor_systemforce_terminal_force_terminalNforce_jupyterforce_interactive	soft_wrapwidthheight_heighttab_sizemarkup_markupemoji_emojiemoji_variant_emoji_variant	highlight
_highlightno_colorlegacy_windowssafe_box_environget_datetimeget_timer   )rich.consoler   r   r   
is_jupyteris_interactiver   _widthr   r   r   r   )r   r   r   r   r   r   !create_error_console_from_console  s   

	
	
r   )r   )r   r   r   r   )8r(   r>   r;   rm   collections.abcr   r   r   r   
contextlibr   operatorr   typingr   r	   r
   r   attrsr   r   r   jsonr   r   r   r   partialsysr   rC   r   r#   r'   r"   rD   boolrK   rQ   r3   rT   rF   rU   rV   rY   r`   rq   ru   intr}   r   r   r   r   r   r   r   r   r   r   <module>   sT    $&"*
%&@%