U
    e9                     @   s  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 d dlmZ d dl	m
Z
 d dlmZmZmZ d dlmZ d dlmZ d d	lmZmZ ed
d ZedejZedejZedejZedZedZedd ZG dd deZedd ZeedfddZ edd Z!edd Z"dd Z#dd d!d"Z$G d#d$ d$eZ%dd d%d&Z&ed'ej'Z(d(d) Z)ed*d+ Z*ed3d-d.Z+d/d0 Z,d1d2 Z-ee-e.Z/dS )4    N)GzipFile)compress)BytesIO)SuspiciousFileOperation)SimpleLazyObjectkeep_lazy_textlazy)_lazy_re_compile)gettext)gettext_lazypgettextc                 C   s2   | s| S t | tst| } | d  | dd  S )z(Capitalize the first letter of a string.r      N)
isinstancestrupper)x r   5/tmp/pip-unpacked-wheel-lctamlir/django/utils/text.pycapfirst   s
    
r   z<[^>]+?>|([^<>\s]+)z<[^>]+?>|(.)z<(/)?(\S+?)(?:(\s*/)|\s.*?)?>z\r\n|\rz&(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))c                    s    fdd}d | S )aC  
    A word-wrap function that preserves existing line breaks. Expects that
    existing line breaks are posix newlines.

    Preserve all white space except added line breaks consume the space on
    which they break the line.

    Don't wrap long words, thus the output text may have lines longer than
    ``width``.
    c                  3   s     dD ]} t| dr"d p$}t| |kr| d |d  dd }|dkrz| dd }|dkrz| V  d} qd| d |d   V  | |d  } t| drd p}q*| r
| V  q
d S )NT
r    r    z%s
)
splitlinesminendswithlenrfindfind)line	max_widthspacetextwidthr   r   
_generator/   s    zwrap.<locals>._generatorr   )join)r"   r#   r$   r   r!   r   wrap"   s    r&   c                       sZ   e Zd ZdZdZ fddZdddZdd	d
Zdd ZdddZ	dd Z
dd Z  ZS )	Truncatorz
    An object used to truncate text, either by characters or words.

    When truncating HTML text (either chars or words), input will be limited to
    at most `MAX_LENGTH_HTML` characters.
    i@KL c                    s   t   fdd d S )Nc                      s   t  S Nr   r   r"   r   r   <lambda>O       z$Truncator.__init__.<locals>.<lambda>)super__init__)selfr"   	__class__r*   r   r.   N   s    zTruncator.__init__Nc                 C   s@   |d krt dd}d|kr&|d|i S ||r4|S d||f S )Nz%String to return when truncating textu   %(truncated_text)s…z%(truncated_text)sZtruncated_textz%s%s)r   r   )r/   r"   truncater   r   r   add_truncation_textQ   s     
zTruncator.add_truncation_textFc                 C   sx   |    t|}td| j}|}| d|D ]"}t|s.|d8 }|dkr. qRq.|rh| ||||dS | ||||S )a  
        Return the text truncated to be no longer than the specified number
        of characters.

        `truncate` specifies what should be used to notify that the string has
        been truncated, defaulting to a translatable string of an ellipsis.
        NFCr   r   r   F)	_setupintunicodedata	normalize_wrappedr3   	combining_truncate_html_text_chars)r/   numr2   htmllengthr"   truncate_lencharr   r   r   chars`   s    
zTruncator.charsc           	      C   sj   d}d}t |D ]T\}}t|r$q|d7 }|dkr@||kr@|}||kr| |d|pVd |  S q|S )z2Truncate a string after a certain number of chars.r   Nr   )	enumerater7   r:   r3   )	r/   r?   r2   r"   r@   Zs_lenZ	end_indexirA   r   r   r   r<   w   s    
zTruncator._text_charsc                 C   s4   |    t|}|r(| ||| j|dS | ||S )z
        Truncate a string after a certain number of words. `truncate` specifies
        what should be used to notify that the string has been truncated,
        defaulting to ellipsis.
        T)r5   r6   r;   r9   _text_words)r/   r=   r2   r>   r?   r   r   r   words   s
    zTruncator.wordsc                 C   s>   | j  }t||kr4|d| }| d||S d|S )zk
        Truncate a string after a certain number of words.

        Strip newlines in the string.
        Nr   )r9   splitr   r3   r%   )r/   r?   r2   rF   r   r   r   rE      s
    
zTruncator._text_wordsc                 C   s  |r|dkrdS d}t || jkr4|d| j }d}d}d}d}	d}
g }|rPtnt}|
|kr&|||}|srq&|d}|d r|
d7 }
|
|krT|}	qTt|d }|rT|
|krqT| \}}}|	 }|s||krqT|rz|
|}W n tk
r   Y nX ||d d }qT|d| qT| d|}|
|krT|rP|rP||7 }|S |d|	 }|rn||7 }|D ]}|d| 7 }qr|S )	a  
        Truncate HTML to a certain number of chars (not counting tags and
        comments), or, if words is True, then to a certain number of words.
        Close opened tags if they were correctly closed in the given HTML.

        Preserve newlines in the HTML.
        r   r   FNT)	brcollinkbaseimgparamareahrinputr   z</%s>)r   MAX_LENGTH_HTMLre_wordsre_charssearchendre_tagmatchgroupslowerindex
ValueErrorinsertr3   )r/   r?   r2   r"   r@   rF   Zsize_limitedZhtml4_singletsposZend_text_posZcurrent_lenZ	open_tagsregexmtagZclosing_tagtagnameZself_closingrD   Ztruncate_textoutr   r   r   r;      s^    


zTruncator._truncate_html)N)NF)NF)__name__
__module____qualname____doc__rQ   r.   r3   rB   r<   rF   rE   r;   __classcell__r   r   r0   r   r'   C   s   


r'   c                 C   s:   t |  dd}tdd|}|dkr6td|  |S )aY  
    Return the given string converted to a string that can be used for a clean
    filename. Remove leading and trailing spaces; convert other spaces to
    underscores; and remove anything that is not an alphanumeric, dash,
    underscore, or dot.
    >>> get_valid_filename("john's portrait in 2004.jpg")
    'johns_portrait_in_2004.jpg'
    r   _z(?u)[^-\w.]r   >   r   ...z$Could not derive file name from '%s')r   stripreplaceresubr   )namesr   r   r   get_valid_filename   s
    
rq   orc                 C   sV   | sdS t | dkr t| d S dtddd | dd	 D t|t| d	 f S )
a   
    >>> get_text_list(['a', 'b', 'c', 'd'])
    'a, b, c or d'
    >>> get_text_list(['a', 'b', 'c'], 'and')
    'a, b and c'
    >>> get_text_list(['a', 'b'], 'and')
    'a and b'
    >>> get_text_list(['a'])
    'a'
    >>> get_text_list([])
    ''
    r   r   r   z%s %s %sz, c                 s   s   | ]}t |V  qd S r(   r)   ).0rD   r   r   r   	<genexpr>   s     z get_text_list.<locals>.<genexpr>N)r   r   rh   r%   )list_	last_wordr   r   r   get_text_list  s    
rx   c                 C   s   t dt| S )z*Normalize CRLF and CR newlines to just LF.r   )re_newlinesrn   r   r*   r   r   r   normalize_newlines&  s    rz   c                    sV   ddddddddddddddddddddddddddd	 d
  fdd|  D S )z@Convert a phone number with letters into its numeric equivalent.23456789)abcdefghrD   jklr_   nopqrrp   tuvwr   yzr   c                 3   s   | ]}  ||V  qd S r(   )get)rs   r   Zchar2numberr   r   rt   K  s     z phone2numeric.<locals>.<genexpr>)r%   rY   )Zphoner   r   r   phone2numeric,  s8    r   c                 C   s   dt |  S )N   a)secrets	randbelowmax_random_bytesr   r   r   _get_random_filenameN  s    r   r   c                C   s\   t | ddd}|s|S t|}t|d d }tj|d< t|d }t|| |dd   S )N   r   )compresslevelmtime
          )gzip_compress
memoryview	bytearraygzipFNAMEr   bytes)rp   r   Zcompressed_dataZcompressed_viewheaderfilenamer   r   r   compress_stringR  s    
r   c                   @   s   e Zd Zdd ZdS )StreamingBufferc                 C   s   |   }| d |   |S )Nr   )getvalueseekr2   )r/   retr   r   r   readb  s    
zStreamingBuffer.readN)rc   rd   re   r   r   r   r   r   r   a  s   r   c             	   c   sr   t  }|rt|nd }t|dd|dd6}| V  | D ] }|| | }|r8|V  q8W 5 Q R X | V  d S )Nwbr   r   )r   moder   fileobjr   )r   r   r   r   write)sequencer   bufr   zfileitemdatar   r   r   compress_sequencej  s"        

r   z
    ((?:
        [^\s'"]*
        (?:
            (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
            [^\s'"]*
        )+
    ) | \S+)
c                 c   s"   t t| D ]}|d V  qdS )a  
    Generator that splits a string by spaces, leaving quoted phrases together.
    Supports both single and double quotes, and supports escaping quotes with
    backslashes. In the output, strings will keep their initial and trailing
    quote marks and escaped quotes will remain escaped (the results can then
    be further processed with unescape_string_literal()).

    >>> list(smart_split(r'This is "a person\'s" test.'))
    ['This', 'is', '"a person\\\'s"', 'test.']
    >>> list(smart_split(r"Another 'person\'s' test."))
    ['Another', "'person\\'s'", 'test.']
    >>> list(smart_split(r'A "\"funky\" style" test.'))
    ['A', '"\\"funky\\" style"', 'test.']
    r   N)smart_split_refinditerr   )r"   bitr   r   r   smart_split  s    r   c                 C   sT   | r | d dks | d | d kr,t d|  | d }| dd d| |ddS )	al  
    Convert quoted string literals to unquoted strings with escaped quotes and
    backslashes unquoted::

        >>> unescape_string_literal('"abc"')
        'abc'
        >>> unescape_string_literal("'abc'")
        'abc'
        >>> unescape_string_literal('"a \"bc\""')
        'a "bc"'
        >>> unescape_string_literal("'\'ab\' c'")
        "'ab' c"
    r   z"'ru   zNot a string literal: %rr   z\%sz\\\)r[   rl   )rp   quoter   r   r   unescape_string_literal  s     r   Fc                 C   sZ   t | } |rtd| } ntd| ddd} tdd|  } tdd| d	S )
a  
    Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
    dashes to single dashes. Remove characters that aren't alphanumerics,
    underscores, or hyphens. Convert to lowercase. Also strip leading and
    trailing whitespace, dashes, and underscores.
    NFKCZNFKDasciiignorez[^\w\s-]r   z[-\s]+-z-_)	r   r7   r8   encodedecoderm   rn   rY   rk   )valueZallow_unicoder   r   r   slugify  s     r   c                 C   s   t d|   S )zQ
    Split CamelCase and convert to lowercase. Strip surrounding whitespace.
    z \1)re_camel_casern   rk   rY   )r   r   r   r   camel_case_to_spaces  s    r   c                 O   s   | j ||S )zk
    Apply str.format() on 'format_string' where format_string, args,
    and/or kwargs might be lazy.
    )format)format_stringargskwargsr   r   r   _format_lazy  s    r   )F)0r   rm   r   r7   r   r   r   ior   Zdjango.core.exceptionsr   Zdjango.utils.functionalr   r   r   Zdjango.utils.regex_helperr	   Zdjango.utils.translationr
   rh   r   r   r   SrR   rS   rV   ry   r   r&   r'   rq   rx   rz   r   r   r   r   r   VERBOSEr   r   r   r   r   r   r   Zformat_lazyr   r   r   r   <module>   s\   


  9


!		
