
    iNA              	          d 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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rdd	lmZ dd
lmZ ddlmZ nddlmZ  ej8                  ed      ZddlmZ  G d de      Z  G d de       Z! G d de!      Z"de#deee   gee   f   fdZ$de%fdZ&de%fdZ'ddez  ee   z  de(edf   fdZ)ddez  ee   z  de*e   fdZ+ddez  ee   z  de(edf   dz  fd Z,dedefd!Z-d"ded#   z  ez  dedz  fd$Z.d%e#de#fd&Z/d%e#de#fd'Z0d(e	e   d)e1dee(edf      fd*Z2d+d,d-e#de%fd.Z3d/ede%fd0Z4d1 Z5e G d2 d3             Z6d=d4d5d6e1de#fd7Z7d>d8Z8d9e#de(e1df   fd:Z9d;e#fd<Z:y)?z^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                   *    e Zd ZdefdZded   fdZy)SentinelMetareturnc                 "    d| j                    dS )N<>)__name__clss    t/home/jay/workspace/.worktrees/task-2116-dev1/scripts/.codegraph-venv/lib/python3.12/site-packages/cyclopts/utils.py__repr__zSentinelMeta.__repr__   s    3<<.""    Fc                      y)NF r   s    r   __bool__zSentinelMeta.__bool__"   s    r!   N)r   
__module____qualname__strr    r   r$   r#   r!   r   r   r      s    # # r!   r   c                       e Zd Zd Zy)Sentinelc                     t        d      )NzGSentinel objects are not intended to be instantiated. Subclass instead.)
ValueErrorr   s    r   __new__zSentinel.__new__'   s    bccr!   N)r   r%   r&   r,   r#   r!   r   r)   r)   &   s    dr!   r)   )	metaclassc                       e Zd ZdZy)UNSETzTSpecial sentinel value indicating that no data was provided. **Do not instantiate**.N)r   r%   r&   __doc__r#   r!   r   r/   r/   +   s    ^r!   r/   targetr   c                 H     dt         t           dt         t           f fd}|S )zJClass decorator that records init argument names as a tuple to ``target``.r   r   c                     | j                   t        j                        }t        d |j                  D              t        j                        fd       }|| _         | S )Nc              3   ,   K   | ]  }|d k7  s	|  yw)selfNr#   ).0names     r   	<genexpr>z1record_init.<locals>.decorator.<locals>.<genexpr>5   s     ]TdV\nD]s   
c                      | g|i | t         j                  | t        fdt        t	        |            D              t        |      z          y )Nc              3   (   K   | ]	  }|     y wNr#   )r6   iparam_namess     r   r8   zCrecord_init.<locals>.decorator.<locals>.new_init.<locals>.<genexpr>;   s     2\a;q>2\s   )object__setattr__tuplerangelen)r5   argskwargsoriginal_initr=   r1   s      r   new_initz0record_init.<locals>.decorator.<locals>.new_init7   sJ    $000tVU2\5QTUYQZK[2\-\_dek_l-lmr!   )__init__inspect	signaturer@   
parameters	functoolswraps)r   function_signaturerF   rE   r=   r1   s      @@r   	decoratorzrecord_init.<locals>.decorator2   s_    $..}=]-?-J-J]]		'	n 
(	n
  
r!   )typer   )r1   rN   s   ` r   record_initrP   /   s&    tAw 47  r!   c                     t        | t        t        z  t        z  t        z        ryt        | t
               xr t        | t              S )NT)
isinstancelistr@   setdictr'   r   objs    r   is_iterablerX   C   s9    #te|c)D01#s##A
3(AAr!   c                 h    	 t        j                  |       xr t        | |      S # t        $ r Y yw xY 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)rH   isclass
issubclass	TypeError)hinttarget_classs     r   is_class_and_subclassr_   I   s4    t$GD,)GG s   "% 	11value.c                 :    | y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.
    r#   )rX   r@   r`   s    r   to_tuple_converterrc   _   s%      }	U	U|xr!   c                 *    t        t        |             S r;   )rS   rc   rb   s    r   to_list_converterre   w   s    "5)**r!   c                 $    | y| syt        |       S )zsConvert a string or Iterable or None into an Iterable or None.

    Intended to be used in an ``attrs.Field``.
    Nr#   )rc   rb   s    r   optional_to_tuple_converterrg   {   s    
 }e$$r!   c                 V    | t         S t        j                  |       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.
    )r/   rH   isgeneratornextrb   s    r   sort_key_converterrk      s+     }			U	#E{r!   input_value)defaultplainc                     | yt        | t              r3| 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.
    Nrm   r   )DefaultFormatterrn   )PlainFormatterzUnknown formatter: z. Must be 'default' or 'plain')rR   r'   cyclopts.help.formattersrp   rq   r+   )rl   rp   rq   s      r   help_formatter_converterrs      s]    & 	K	%)#A#%%G#?!##2;/A_`aa r!   sc                     t        j                  dd |       }t        j                  dd |      }t        j                  dd |      }|j                         S )Nz([A-Z]+)([A-Z][a-z])c                 L    | j                  d       d| j                  d       S N   _   groupms    r   <lambda>z"_pascal_to_snake.<locals>.<lambda>   s!    Aaggaj\6R r!   z([a-z])([A-Z])c                 L    | j                  d       d| j                  d       S rw   r{   r}   s    r   r   z"_pascal_to_snake.<locals>.<lambda>   !    1771:,a
|0L r!   z([0-9])([A-Z])c                 L    | j                  d       d| j                  d       S rw   r{   r}   s    r   r   z"_pascal_to_snake.<locals>.<lambda>   r   r!   )resublower)rt   snakes     r   _pascal_to_snaker      sM     FF*,RTUVEFF$&LeTEFF$&LeTE;;=r!   c                 r    t        |       j                         j                  dd      j                  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.
    ry   -)r   r   replacestrip)rt   s    r   default_name_transformr      s0    , A$$&..sC8>>sCCr!   iterablenc                 t    t        |       |z  rt        | d| d      t        |       g|z  }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)rB   r+   iterzip)r   r   	iteratorss      r   grouperr      sJ     8}qH<'<QCqABBh 1$I	(%((r!   F)allow_numberstokenc                    |sBt        t              5  t        |        | j                         dk(  r
	 ddd       y	 ddd       y| j	                  d      S # 1 sw Y   xY w)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-jNTFr   )r   r+   complexr   
startswith)r   r   s     r   is_option_liker      se    & j! 	EN{{}$ 	 	 	 	 C  	 	s    AAArW   c                 L    t        | dd      j                  d      d   t        v S )Nr%    r   r   )getattrsplitr   rV   s    r   
is_builtinr     s'    3b)//4Q7;NNNr!   c                    t        | t        t                    r| S t        |       r | |i |S t	        |       rg }| D ]  }t        |t        t                    r|j                  |       .t        |      r|j                   ||i |       Qt	        |      r|j                  t        |g|i |       {|j                  |        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.
    )rR   rO   r)   callablerX   appendresolve_callablesr@   )trC   rD   resolvedelements        r   r   r     s     !T(^${$!&!!	Q 	)G'4>2('" 8 89W% 1' KD KF KL(	) Xr!   c                   n    e Zd ZU dZeed<   	  ee      Zeed<   	 eed<   	 e	de
d    ded    fd       Zy	)

SortHelperzLSort a list of objects by an external key and retrieve the objects in-order.key)	converterfallback_keyr`   entriesr   c                 j   ddl m}m}m} g }g }g }g }g }g }	| D ]  }
|
j                  |u r|j                  d|
f       &|
j                  |u r|j                  d|
f       H|
j                  |u r|j                  d|
f       j|
j                  t        dfv r|	j                  |
j                  |
f       t        |
j                        rE|
j                  d   t        dfv r.|j                  |
j                  dd |
j                  z   |
f       |j                  |
j                  |
j                  f|
f       ! |j                  t        d             |j                  t        d             |	j                  t        d             ||z   |z   |z   |z   |	z   }|D cg c]  }|d   	 c}S c c}w )z(Sorts a sequence of :class:`SortHelper`.r   )#DEFAULT_ARGUMENTS_GROUP_SORT_MARKER"DEFAULT_COMMANDS_GROUP_SORT_MARKER$DEFAULT_PARAMETERS_GROUP_SORT_MARKERNrx   )r   )cyclopts.groupr   r   r   r   r   r/   r   rX   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combinedxs                r   r   zSortHelper.sortI  s   	
 	
 "$"$#% #%  	OEyy>>&--tUm<AA'..e}=BB(//u>udm+ ''););U(CDUYY'EIIaLUDM,I )//12ASAS1SUZ0[\$$uyy%2D2D&Eu%MN	O  	z!}- %%*Q-%8*Q-0 #%&&'  '	'
  	 ''!'''s   !F0N)r   r%   r&   r0   r
   __annotations__r   rc   r   staticmethodr   rS   r   r#   r!   r   r   r   8  sZ    V	H
 (:;L#; JJ,(h|, ,(l1C ,( ,(r!   r   decode_errorr   contextc           
      Z   | j                   j                         }|| j                  dz
     }| j                  dz
  }||z
  }|dk  rd}d}|}nd}||z
  }||z   }|t	        |      k\  rt	        |      dz   }d}	nd}	||| }
dt	        |      |z   z  dz   }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
    rx   r   r   z... z ... ^zJSONDecodeError:
    z
    
)doc
splitlineslinenocolnorB   r'   )r   r   lineslineerror_indexstartprefix_ellipsissegment_error_indexendsuffix_ellipsissegmentcarat_pointerresponses                r   json_decode_error_verbosifierr   y  s     '')E$$q()D$$q(K'!Ez) )E1

C
c$i$i!m 5oG3/2EEFLM ! 1'?:K6R_Q``bcfgsctbuv  Or!   c           
      "   ddl m} | j                  xs d} |di ddd|dt        | dd	      d
| j                  xs d	d| j
                  xs d	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   )consoler   r   s      r   !create_error_console_from_consoler     sk    %''16L ! w(94@ ((0D	
 "008D ## nn w	40 !! w	40 gx. g'7> '<6 !! --  !!!" *d3#$ Wnd;%& *d3' r!   version_stringc                 J    t        fd| j                  d      D              S )aI  Parse a PEP 440 version string into a tuple of ints, stripping pre-release suffixes.

    Parameters
    ----------
    version_string: str
        A version string like ``"2.11.2"`` or ``"2.0.0b2"``.

    Returns
    -------
    tuple[int, ...]
        Tuple of the numeric components, e.g. ``(2, 11, 2)`` or ``(2, 0, 0)``.
    c              3      K   | ]6  }t        j                  d |      xst        j                                8 yw)z\d+N)r   matchintr|   )r6   r   r~   s     r   r8   z parse_version.<locals>.<genexpr>  s2     aABHHU[]^L_G_qG_QWWYas   ??r   )r@   r   )r   r~   s    @r   parse_versionr     s!     a)=)=c)Baaar!   module_pathc                 6   ddl m} d| v r| j                  dd      \  }}n| d}}	 t        j                  |      }|rGt        ||      st        d| d	| d
      t        ||      }t        ||      st        d
| d      |S dD ]  }t        ||d      }t        ||      s|c S  t        |      D ]0  }|j                  d      rt        ||      }t        ||      s.|c S  t        d| d| d      # t
        $ r}t        d| d|       |d}~ww xY w)au  Import a Cyclopts App from a module path.

    Parameters
    ----------
    module_path : str
        Module path in format "module.name" or "module.name:app_name".
        If ":app_name" is omitted, auto-discovers by searching for common
        names (app, cli, main) or any public App instance.

    Returns
    -------
    App
        The imported Cyclopts App instance.

    Raises
    ------
    ImportError
        If the module cannot be imported.
    AttributeError
        If the specified app name doesn't exist or no App is found.
    TypeError
        If the specified attribute is not a Cyclopts App instance.
    r   )App:rx   NzCannot import module 'z': zModule 'z' has no attribute ''z ' is not a Cyclopts App instance)appclimainry   zNo Cyclopts App found in 'z'. Specify explicitly: 'z
:app_name')cycloptsr   rsplit	importlibimport_moduleImportErrorhasattrAttributeErrorr   rR   r\   dirr   )	r   r   module_nameapp_namemoduleer  r7   rW   s	            r   
import_appr    sZ   0 
k + 2 23 :X +TXO((5 vx( 8K=8LXJVW!XYYfh'#s#az)IJKK
 ' fdD)c3J F s#&$'C#s#
	 5k]BZ[fZggqr
ss1  O2;-s1#FGQNOs   C8 8	DDD)   )r   r   r   r   );r0   rK   r  rH   r   collections.abcr   r   r   r   
contextlibr   operatorr   typingr	   r
   r   r   attrsr   r   r   jsonr   r   r   r   partialsysr   rO   r   r)   r/   r'   rP   boolrX   r_   r@   rc   rS   re   rg   rk   rs   r   r   r   r   r   r   r   r   r   r   r   r  r#   r!   r   <module>r     sk   d    	 B B   7 7 CL $$Yv48F #4 d d
_H _ $q'DG); < (B B ,dSj8C=8 U38_ 0+TCZ(3-7 +DI +%tczHSM'A %eCQTHoX\F\ %c c *" 233c9"4Z"J  Dc Dc D2)hsm ) )sCx0I )$ 16 !# !$ !>OC OD O8 =( =( =(@"0A "C "Y\ "J%Pb# b%S/ b 9tC 9tr!   