
    $g.+                        d 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 ddl	m
Z
mZmZmZmZmZmZmZ e
rddlmZ ddlmZ ddlmZ dd	lmZ  ej        e          Zd
ee         dee         fdZdeeef         defdZ deeef         fdZ!dededef         fdZ"d Z#d Z$dZ%dej        defdZ&dedej        fdZ'd6defdZ(dede)fdZ*dedefdZ+de,fdZ-d7d Z.d!ee         deej        ef         fd"Z/d#ee,e0ef         de,fd$Z1d%d&dee,e,e,f         fd'Z2d( Z3d)ee         d*e,fd+Z4d7d,ed-ee,         defd.Z5	 d7d/ee         d0ed1eeef         d-ee,         dee         f
d2Z6d3eeed4f                  dee         fd5Z7dS )8z
Miscellaneous helper functions.

The formatter for ANSI colored console output is heavily based on Pygments
terminal colorizing code, originally by Georg Brandl.
    N)Iterable)TYPE_CHECKINGAnyCallableDictListOptionalTupleUnion)Redis   Queue)ResponseError)TimeoutFormatErrorlstreturnc                     d | D             S )zExcludes `None` values from a list-like object.

    Args:
        lst (list): A list (or list-like) oject

    Returns:
        object (list): The list without None values
    c                     g | ]}||S N ).0items     H/var/www/html/netbox-4.1.3/venv/lib/python3.11/site-packages/rq/utils.py
<listcomp>zcompact.<locals>.<listcomp>&   s    555TD$4D$4$4$4    r   )r   s    r   compactr      s     65S5555r   vc                     t          | t                    r|                     d          S t          | t                    r| S t	          dt          |           z            )a  Converts a bytes value to a string using `utf-8`.

    Args:
        v (Union[bytes, str]): The value (bytes or string)

    Raises:
        ValueError: If the value is not bytes or string

    Returns:
        value (Optional[str]): Either the decoded string or None
    zutf-8zUnknown type %r)
isinstancebytesdecodestr
ValueErrortype)r   s    r   as_textr&   )   sY     !U 6xx   	As		 6*T!WW4555r   c                 :     t           fd D                       S )a  Decodes the Redis hash, ensuring that keys are strings
    Most importantly, decodes bytes strings, ensuring the dict has str keys.

    Args:
        h (Dict[Any, Any]): The Redis hash

    Returns:
        Dict[str, Any]: The decoded Redis data (Dictionary)
    c              3   F   K   | ]}t          |          |         fV  d S r   )r&   )r   khs     r   	<genexpr>z$decode_redis_hash.<locals>.<genexpr>G   s2      ..qQqT"......r   )dict)r*   s   `r   decode_redis_hashr-   =   s(     ....A......r   name.c                 *   |                      d          }|dd         |d         g}}d}t          |          rr	 d                    |          }t          j        |          }nG# t
          $ r+ |                    d|                                           Y nw xY wt          |          r|.	 t          |          S # t          $ r t          d| z            w xY wd                    |          }t          ||          rt          ||          S |                                }d                    |          }	 t          ||          }n#  t          d|z            xY wt          ||          st          d| z            t          ||          S )a#  Returns an attribute from a dotted path name. Example: `path.to.func`.

    When the attribute we look for is a staticmethod, module name in its
    dotted path is not the last-before-end word

    E.g.: package_a.package_b.module_a.ClassA.my_static_method

    Thus we remove the bits from the end of the name until we can import it

    Args:
        name (str): The name (reference) to the path.

    Raises:
        ValueError: If no module is found or invalid attribute name.

    Returns:
        Any: An attribute (normally a Callable)
    .Nr   zInvalid attribute name: %s)splitlenjoin	importlibimport_moduleImportErrorinsertpop__builtins__KeyErrorr$   hasattrgetattr)	r.   	name_bitsmodule_name_bitsattribute_bitsmodulemodule_nameattribute_nameattribute_owner_nameattribute_owners	            r   import_attributerF   J   s   & 

3I'0"~	"nF


 =	=((#344K,[99F 	= 	= 	=!!!%5%9%9%;%;<<<<<	= 

 = ~	B%% 	B 	B 	B9D@AAA	B XXn--Nv~&& /v~...#''))N88N33H!&*>??H5FGGG?N33 >5<===?N333s)   )A% %2BB/B< <C;E E c                  >    t           j                                         S r   )datetimeutcnowr   r   r   rI   rI      s    ##%%%r   c                  ^    t           j                             t           j        j                  S )zReturn now in UTC)rH   nowtimezoneutcr   r   r   rK   rK      s      !2!6777r   z%Y-%m-%dT%H:%M:%S.%fZdtc                 F     | j         t          t                              S r   )strftimer&   _TIMESTAMP_FORMAT)rN   s    r   	utcformatrR      s    2;w011222r   stringc                     	 t           j                             | t                    S # t          $ r# t           j                             | d          cY S w xY w)Nz%Y-%m-%dT%H:%M:%SZ)rH   strptimerQ   r$   )rS   s    r   utcparserV      sa    H ))&2CDDD H H H ))&2FGGGGGHs   $' *AAiterablec                 J    || D ]}|r|c S 	n| D ]} ||          r|c S |S )a  Return first element of `iterable` that evaluates true, else return None
    (or an optional default value).

    >>> first([0, False, None, [], (), 42])
    42

    >>> first([0, False, None, [], ()]) is None
    True

    >>> first([0, False, None, [], ()], default='ohai')
    'ohai'

    >>> import re
    >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
    >>> m.group(1)
    'bc'

    The optional `key` argument specifies a one-argument predicate function
    like that used for `filter()`.  The `key` argument, if supplied, must be
    in keyword form.  For example:

    >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
    4

    Args:
        iterable (t.Iterable): _description_
        default (_type_, optional): _description_. Defaults to None.
        key (_type_, optional): _description_. Defaults to None.

    Returns:
        _type_: _description_
    r   )rW   defaultkeyels       r   firstr\      sj    B { 	 	B 				  	 	Bs2ww 			 Nr   objc                 X    t          | t                    ot          | t                     S )zReturns whether the obj is an iterable, but not a string

    Args:
        obj (Any): _description_

    Returns:
        bool: _description_
    )r    r   r#   r]   s    r   is_nonstring_iterabler`      s&     c8$$AZS-A-A)AAr   c                 *    t          |           r| n| gS )zWhen passed an iterable of objects, does nothing, otherwise, it returns
    a list with just that object in it.

    Args:
        obj (Any): _description_

    Returns:
        List: _description_
    )r`   r_   s    r   ensure_listrb      s     (,,7333%7r   c                      t          j        t          j                                                                                  S )zKReturns current UTC timestamp

    Returns:
        int: _description_
    )calendartimegmrH   rI   utctimetupler   r   r   current_timestamprg      s/     ?8,3355BBDDEEEr   c                 r    |t          | |          S t          |t                    rt          |          S |S )a  Get a backend class using its default attribute name or an override

    Args:
        holder (_type_): _description_
        default_name (_type_): _description_
        override (_type_, optional): _description_. Defaults to None.

    Returns:
        _type_: _description_
    )r=   r    r#   rF   )holderdefault_nameoverrides      r   backend_classrl      s?     v|,,,	Hc	"	" )))r   date_strc                 L    | sd S t          |                                           S r   )rV   r"   )rm   s    r   str_to_datero      s'     +))***r   timeoutc                 V   t          | t          j                  s| 	 t          |           } n{# t          $ rn | dd         | dd                                         }}ddddd}	 t          |          ||         z  } n$# t          t          f$ r t          d          w xY wY nw xY w| S )	zGTransfer all kinds of timeout format to an integer representing secondsNr1   iQ i  <   r   )dr*   mszTimeout must be an integer or a string representing an integer, or a string with format: digits + unit, unit can be "d", "h", "m", "s", such as "1h", "23m".)r    numbersIntegralintr$   lowerr;   r   )rp   digitunitunit_seconds       r   parse_timeoutr}      s    gw/00 W5H	'llGG 
	 
	 
	!#2#,(<(<(>(>4E %DrBBKe**{4'88)   (+   	
	 Ns'   . 7B&&A?>B&?!B  B&%B&
connectionr   c                 :   	 t          | dd          sit          | dt          d t          |                     d          d                                       d          dd         D                                  t          | d          S # t          $ r Y dS w xY w)	a/  
    Returns tuple of Redis server version.
    This function also correctly handles 4 digit redis server versions.

    Args:
        connection (Redis): The Redis connection.

    Returns:
        version (Tuple[int, int, int]): A tuple representing the semantic versioning format (eg. (5, 0, 9))
    __rq_redis_server_versionNc              3   4   K   | ]}t          |          V  d S r   )rx   )r   is     r   r+   zget_version.<locals>.<genexpr>%  s(      eec!ffeeeeeer   serverredis_versionr0      )   r   	   )r=   setattrtupler#   infor2   r   )r~   s    r   get_versionr     s    
z#>EE 	+eec*//(*C*CO*T&U&U&[&[\_&`&`acbcac&deeeee  
 z#>???   yys   B	B 
BBc                     |  |z   S )zCeiling division. Returns the ceiling of the quotient of a division operation

    Args:
        a (_type_): _description_
        b (_type_): _description_

    Returns:
        _type_: _description_
    r   )abs     r   ceildivr   ,  s     R1W:r   a_listsegment_sizec              #   j   K   t          dt          |           |          D ]}| |||z            V  dS )zSplits a list into multiple smaller lists having size `segment_size`

    Args:
        a_list (List[Any]): A list to split
        segment_size (int): The segment size to split into

    Yields:
        list: The splitted listed
    r   N)ranger3   )r   r   r   s      r   
split_listr   9  sQ       1c&kk<00 + +Q\))*****+ +r   data
max_lengthc                 N    || S t          |           |k    r| d|         dz   n| S )a  Truncate arguments with representation longer than max_length

    Args:
        data (str): The data to truncate
        max_length (Optional[int], optional): The max length. Defaults to None.

    Returns:
        truncated (str): The truncated string
    Nz...)r3   )r   r   s     r   truncate_long_stringr   G  s8     *-d))j*@*@D*%%dJr   	func_nameargskwargsc                     | dS fd|D             }fd|                                 D             }|t          |          z  }d                    |          }d                    | |          S )a  
    Returns a string representation of the call, formatted as a regular
    Python function invocation statement. If max_length is not None, truncate
    arguments with representation longer than max_length.

    Args:
        func_name (str): The funtion name
        args (Any): The function arguments
        kwargs (Dict[Any, Any]): The function kwargs
        max_length (int, optional): The max length. Defaults to None.

    Returns:
        str: A String representation of the function call.
    Nc           	      d    g | ],}t          t          t          |                              -S r   )r&   r   repr)r   argr   s     r   r   z#get_call_string.<locals>.<listcomp>j  s2    UUU,T#YY
CCDDUUUr   c                     g | ]C\  }}d                      |t          t          t          |                                        DS )z{0}={1})formatr&   r   r   )r   r)   r   r   s      r   r   z#get_call_string.<locals>.<listcomp>l  sI    vvv_c_`bc9##Aw/CDGGZ/X/X'Y'YZZvvvr   z, z{0}({1}))itemssortedr4   r   )r   r   r   r   arg_listlist_kwargss      `  r   get_call_stringr   V  s    " tUUUUPTUUUHvvvvgmgsgsguguvvvK{###H99XDY---r   queues_or_namesr   c                     ddl m} g }| D ]O}t          ||          r|                    |j                   -|                    t          |                     P|S )z6Given a list of strings or queues, returns queue namesr   r   )queuer   r    appendr.   r#   )r   r   namesqueue_or_names       r   parse_namesr   s  st    E( - -mU++ 	-LL+,,,,LL]++,,,,Lr   )NNr   )8__doc__rd   rH   rN   r5   loggingrv   collections.abcr   typingr   r   r   r   r   r	   r
   r   redisr   r   r   redis.exceptionsr   
exceptionsr   	getLogger__name__loggerr   r!   r#   r&   r-   rF   rI   rK   rQ   rR   rV   r\   boolr`   rb   rx   rg   rl   ro   floatr}   r   r   r   r   r   r   r   r   r   <module>r      sJ                $ $ $ $ $ $ S S S S S S S S S S S S S S S S S S S S  * * * * * * * * * * * *		8	$	$	6c 	6tCy 	6 	6 	6 	66uUCZ  6S 6 6 6 6(
/DcN 
/ 
/ 
/ 
/243 248CH#5 24 24 24 24j& & &8 8 8
 , 3"+ 3# 3 3 3 3HS HR[ H H H H* *H * * * *Z	Bs 	Bt 	B 	B 	B 	B
8S 
8T 
8 
8 
8 
8F3 F F F F   &+(3- +E"+s2B,C + + + +5eS1 c    (G c3m(<    0
 
 
+tCy + + + + +K Ks K K K K K K  ^b. .}.$'.15c3h.MUVY].c]. . . .:
eCL&9!: 
tCy 
 
 
 
 
 
r   