U
    祡ce                     @   s  d dl mZ d dlZd dlZd dlZd dlmZmZ d dlm	Z	 d dl
mZmZ d dlmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZmZmZmZmZm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( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= dd	l>m Z  ddl?m@Z@ eA dkZBdZCdZDdddddddddd 	ee, eeE eEeeF eGeGeGeeeFef  eEeeeH eHee gef d!
d"d#ZIeG d$d% d%ZJeG d&d' d'ZKeG d(d) d)ZLeG d*d+ d+ZMG d,d- d-e4ZNG d.d/ d/ZOePd0krdd1l+m,Z, e, Z+d dlZedd2d3d4ZQedd2d5d6ZRdd7d8d9ZSeS  dS ):    )absolute_importN)	dataclassfield)walk_tb)
ModuleTypeTracebackType)	AnyCallableDictIterableListOptionalSequenceTypeUnion)guess_lexer_for_filename)CommentKeywordNameNumberOperatorString)Text)Token)ClassNotFound   )pretty)	loop_last)Columns)ConsoleConsoleOptionsConsoleRenderableRenderResultgroup)	Constrain)RegexHighlighterReprHighlighter)Panel)render_scope)Style)Syntax)ThemeWindows
   P   d      FT )	consolewidthextra_linestheme	word_wrapshow_localsindent_guidessuppress
max_frames)
r2   r3   r4   r5   r6   r7   r8   r9   r:   returnc        	      
      s   | dkrt tjdn| tt ttt dd	f	dd tdd fdd}	zt }
|	|
 tj	W S  t
k
r   tj	} t_	| Y S X dS )	a8  Install a rich traceback handler.

    Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.


    Args:
        console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
        width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
        extra_lines (int, optional): Extra lines of code. Defaults to 3.
        theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
            a theme appropriate for the platform.
        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
        show_locals (bool, optional): Enable display of local variables. Defaults to False.
        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.

    Returns:
        Callable: The previous exception handler that was replaced.

    N)file)type_value	tracebackr;   c                    s*    tj| || d d S )N)r3   r4   r5   r6   r7   r8   r9   r:   )print	Tracebackfrom_exception)r=   r>   r?   )	r4   r8   r:   r7   r9   r5   traceback_consoler3   r6   r1   2/tmp/pip-unpacked-wheel-qkhzhrww/rich/traceback.py
excepthookF   s    zinstall.<locals>.excepthook)ipr;   c                    sb   i j  ttd d fdd}ddtttd dfdd_|_ fd	d
_d S )N)argskwargsr;   c                     s   | | | dS )zEwrap the default ip.showtraceback to store info for ip._showtracebackNr1   rG   rH   )default_showtracebacktb_datar1   rD   ipy_show_traceback_   s    zCinstall.<locals>.ipy_excepthook_closure.<locals>.ipy_show_tracebackF)	is_syntax)rG   rM   rH   r;   c                    st     }| rdn|d }dd}d|r2dnd}t|D ]}|dkrP qX|j}q@ |d |d | i dS )z2Internally called traceback from ip._showtracebackN   Zrunning_compiled_codeF	tb_offsetr   r   )Z_get_exc_infogetrangetb_next)rM   rG   rH   Z	exc_tupletbZcompiledrO   _)rE   rF   rK   r1   rD   ipy_display_tracebacke   s    zFinstall.<locals>.ipy_excepthook_closure.<locals>.ipy_display_tracebackc                     s    | ddi|S )NrM   Tr1   rI   )rU   r1   rD   <lambda>   s   z9install.<locals>.ipy_excepthook_closure.<locals>.<lambda>)Zshowtracebackr   boolZ_showtracebackZshowsyntaxerror)rF   rL   )rE   )rJ   rF   rU   rK   rD   ipy_excepthook_closure[   s      z'install.<locals>.ipy_excepthook_closure)r   sysstderrr   BaseExceptionr   r   r   Zget_ipythonrE   	Exception)r2   r3   r4   r5   r6   r7   r8   r9   r:   rX   rF   old_excepthookr1   )
rE   r4   r8   r:   r7   r9   r5   rC   r3   r6   rD   install$   s      )r^   c                   @   sL   e Zd ZU eed< eed< eed< dZeed< dZee	ee
jf  ed< dS )Framefilenamelinenoname lineNlocals)__name__
__module____qualname__str__annotations__intrd   re   r   r
   r   Noder1   r1   r1   rD   r_      s
   
r_   c                   @   s6   e Zd ZU eed< eed< eed< eed< eed< dS )_SyntaxErroroffsetr`   rd   ra   msgN)rf   rg   rh   rk   rj   ri   r1   r1   r1   rD   rm      s
   
rm   c                   @   sP   e Zd ZU eed< eed< dZee ed< dZe	ed< e
edZee ed< dS )	Stackexc_type	exc_valueNsyntax_errorFis_cause)default_factoryframes)rf   rg   rh   ri   rj   rs   r   rm   rt   rW   r   listrv   r   r_   r1   r1   r1   rD   rp      s
   
rp   c                   @   s   e Zd ZU ee ed< dS )TracestacksN)rf   rg   rh   r   rp   rj   r1   r1   r1   rD   rx      s   
rx   c                   @   s   e Zd ZdgZdS )PathHighlighterz(?P<dim>.*/)(?P<bold>.+)N)rf   rg   rh   Z
highlightsr1   r1   r1   rD   rz      s   rz   c                   @   sR  e Zd ZdZddddddZddd	dd
d
deeddfee ee	 e	ee
 eeee	e	eee
ef  e	dddZedd	dd
d
deeddf
ee eee ee	 e	ee
 eeee	e	eee
ef  e	d dddZed
eefee eee ee	e	edddZeeedddZe eedddZee
e
e
dddZe eedd d!Z dS )"rA   a  A Console renderable that renders a traceback.

    Args:
        trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
            the last exception.
        width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
        extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
        theme (str, optional): Override pygments theme used in traceback.
        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
        show_locals (bool, optional): Enable display of local variables. Defaults to False.
        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
            Defaults to 10.
        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
        max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

    textpythonZcythonZpyrex)rc   z.pyz.pxdz.pyxz.pxiNr/   r0   FTr1   )tracer3   r4   r5   r6   r7   r8   locals_max_lengthlocals_max_stringr9   r:   c                 C   s  |d krHt  \}}}|d ks.|d ks.|d kr6td| j||||d}|| _|| _|| _t|pdd| _	|| _
|| _|| _|| _|	| _g | _|
D ]Z}t|ts|jd k	st|dtj|j}n|}tjtj|}| j| q|dkrtd|nd| _d S )Nz9Value for 'trace' required if not called in except: blockr7   Z	ansi_darkz+ must be a module with '__file__' attributer      )rY   exc_info
ValueErrorextractr}   r3   r4   r*   Z	get_themer5   r6   r7   r8   r~   r   r9   
isinstanceri   __file__AssertionErrorospathdirnamenormpathabspathappendmaxr:   )selfr}   r3   r4   r5   r6   r7   r8   r~   r   r9   r:   rq   rr   r?   Zsuppress_entityr   r1   r1   rD   __init__   sB       
zTraceback.__init__)rq   rr   r?   r3   r4   r5   r6   r7   r8   r~   r   r9   r:   r;   c                 C   s0   | j ||||d}| |||||||	|
|||dS )a  Create a traceback from exception info

        Args:
            exc_type (Type[BaseException]): Exception type.
            exc_value (BaseException): Exception value.
            traceback (TracebackType): Python Traceback object.
            width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
            theme (str, optional): Override pygments theme used in traceback.
            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
            show_locals (bool, optional): Enable display of local variables. Defaults to False.
            indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
                Defaults to 10.
            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
            suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
            max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

        Returns:
            Traceback: A Traceback instance that may be printed.
        r   )
r3   r4   r5   r6   r7   r8   r~   r   r9   r:   )r   )clsrq   rr   r?   r3   r4   r5   r6   r7   r8   r~   r   r9   r:   Zrich_tracebackr1   r1   rD   rB      s&    &   zTraceback.from_exception)rq   rr   r?   r7   r~   r   r;   c                    s  g }d}ddl m}	 ttddd}
t|
|j|
||d}t|trtt|j	pPd|j
pXd|jp`d|jphd	|jd
|_|| |jj}t|D ]\}}|jj}|r|dstj|stj|	|}|jddrqt|pd||jj|r fdd|j D ndd}|| |jddr|jdd= qt|dd}|rZ|j}|}|j }d}q$|j!}|rt|dds|j}|}|j }d}q$qq$t"|d}|S )a  Extract traceback information.

        Args:
            exc_type (Type[BaseException]): Exception type.
            exc_value (BaseException): Exception value.
            traceback (TracebackType): Python Traceback object.
            show_locals (bool, optional): Enable display of local variables. Defaults to False.
            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
                Defaults to 10.
            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.

        Returns:
            Trace: A Trace instance which you can use to construct a `Traceback`.
        Fr   )_IMPORT_CWD)_objectr;   c                 S   s&   z
t | W S  tk
r    Y dS X dS )z1Don't allow exceptions from __str__ to propagate.z<exception str() failed>N)ri   r\   )r   r1   r1   rD   safe_strS  s    
z#Traceback.extract.<locals>.safe_str)rq   rr   rt   ?rc   )rn   r`   ra   rd   ro   <Z_rich_traceback_omitc                    s"   i | ]\}}|t j| d qS ))
max_length
max_string)r   Ztraverse).0keyr>   r~   r   r1   rD   
<dictcomp>x  s    z%Traceback.extract.<locals>.<dictcomp>N)r`   ra   rb   re   _rich_traceback_guard	__cause__T__suppress_context__)ry   )#Zrichr   r   ri   rp   rf   r   SyntaxErrorrm   rn   r`   ra   r{   ro   rs   r   rv   r   f_codeco_filename
startswithr   r   isabsjoinf_localsrP   r_   co_nameitemsgetattr	__class____traceback____context__rx   )r   rq   rr   r?   r7   r~   r   ry   rt   r   r   stackr   frame_summaryZline_nor`   framecauser}   r1   r   rD   r   5  sp    

		
zTraceback.extract)r2   optionsr;   c                 c   s  | j }| }|j}t|t|t|t|tj|t	|t
tdd |t|ttdd |t	|tj|tj|tj|tj|t|t|tjtdd ddd}t }tt| jjD ]$\}}	|	jrt| |	d|ddd	d
}
t|
| j}
|| |
V  W 5 Q R X |	jd k	r||. tt| |	j|ddd	| jd| jV  W 5 Q R X t|	j ddf||	jj V  n>|	j!rt|	j ddf||	j!V  nt|	j dfV  |s|	j"rt#dV  qt#dV  qd S )NT)Zdim)Zbold)r   pygments.textpygments.stringpygments.functionpygments.numberzrepr.indentzrepr.strz
repr.bracezrepr.numberzrepr.bool_truezrepr.bool_falsez	repr.nonezscope.borderzscope.equalsz	scope.keyzscope.key.specialF)Zinheritz7[traceback.title]Traceback [dim](most recent call last)ztraceback.border)r   r   )titlestyleborder_styleexpandpaddingztraceback.border.syntax_error)r   r   r   r   r3   z: ztraceback.exc_typezI
[i]The above exception was the direct cause of the following exception:
zH
[i]During handling of the above exception, another exception occurred:
)$r5   Zget_background_styleZget_style_for_tokenr+   	TextTokenr   r   r   ZFunctionr   r   r)   r   ConstantZ	Delimiterr   r&   r   reversedr}   ry   rv   r'   _render_stackr$   r3   Z	use_themers   _render_syntax_errorr   assemblerq   ro   rr   rt   from_markup)r   r2   r   r5   Zbackground_styleZtoken_styleZtraceback_themehighlighterlastr   Zstack_renderabler1   r1   rD   __rich_console__  s    

zTraceback.__rich_console__)rs   r;   c                 c   s   t  }t }|jdkrHtjd|j dfdt|jdfdd}||V  ||j }d|_	t
|jd	 t|}|d
|| |tjdd|  d dd7 }|V  d S )Nz<stdin> r   :r   r   r   r   Tr   zbold underline
u   [traceback.offset]▲[/])r&   rz   r`   r   r   ri   ra   rd   rstripZno_wrapminrn   lenZstylizer   )r   rs   r   path_highlighterr{   Zsyntax_error_textrn   r1   r1   rD   r     s&    

zTraceback._render_syntax_error)r`   coder;   c                 C   s   t j|d }|sP|d}|dkr2|d | n|}|drPd| krPdS z| j|pht||j	W S  t
k
r   Y dS X d S )Nr   z#!r|   r{   )r   r   splitextindexr   lowerLEXERSrP   r   rb   r   )r   r`   r   extZnew_line_index
first_liner1   r1   rD   _guess_lexer  s    
zTraceback._guess_lexer)r   r;   c                 #   s   t  }j}i  ttd fdd}ttt dfdd}d }jdkrjtjd t|j	jd  }d	}t
|j	D ]\}}	|r||krd
}qx|r|d k	sttdt| ddddV  d	}|dk}
|	jtfddjD }tj|t|	jdddt|	jdfd|	jdfdd}|	jds8|
s8dV  |V  |	jdr\||	E d H  qx|sxzZ||	j}|	j|}t|||d
|	jj |	jj f|	jhjdjd	d
}dV  W n: tk
r } ztd| dfV  W 5 d }~X Y qxX |	jrt|f||	ddn|V  qxd S ) N)r`   r;   c              	      sB     | }|dkr>t| dddd}| }W 5 Q R X | | < |S )zRead files, and cache results on filename.

            Args:
                filename (str): Filename to read

            Returns:
                str: Contents of file
            Nrtzutf-8replace)encodingerrors)rP   openread)r`   r   Z	code_file)
code_cacher1   rD   	read_code  s    	
   z*Traceback._render_stack.<locals>.read_code)r   r;   c                 3   s&   | j r"t| j d j j jdV  d S )Nre   )r   r8   r   r   )re   r(   r8   r~   r   )r   )r   r1   rD   render_locals*  s    z.Traceback._render_stack.<locals>.render_localsr   rN   FTz
... z frames hidden ...centerztraceback.error)Zjustifyr   c                 3   s   | ]}  |V  qd S )N)r   )r   r   )frame_filenamer1   rD   	<genexpr>M  s     z*Traceback._render_stack.<locals>.<genexpr>r   r   r   r   z in r   r   r   rc   X   )r5   Zline_numbersZ
line_rangeZhighlight_linesr6   Z
code_widthr8   dedentr   r   )r   )rz   r5   ri   r_   r   r!   r:   rQ   r   rv   	enumerater   r   r`   anyr9   r   ra   rb   r   r   r*   r4   r6   r8   r\   re   r   )r   r   r   r5   r   r   Zexclude_framesZexcludedZframe_indexr   firstZ
suppressedr{   r   Z
lexer_namesyntaxerrorr1   )r   r   r   rD   r     s    





zTraceback._render_stack)!rf   rg   rh   __doc__r   LOCALS_MAX_LENGTHLOCALS_MAX_STRINGr   rx   rk   ri   rW   r   r   r   r   classmethodr   r   r[   r   rB   r   r   r    r"   r   r#   rm   r   r   rp   r   r1   r1   r1   rD   rA      s   
.6i NrA   __main__)r   )ar;   c                 C   s   d}t ||   d S )Nr   )r@   )r   Zoner1   r1   rD   bar  s    r   c                 C   s"   d}ddddhdd}t |  d S )NTzPaul AtreideszVladimir HarkonnenzThufir HawatzDuncan Idaho)NFT)
charactersZatomic_types)r   )r   r   Zzedr1   r1   rD   foo  s    	r   )r;   c                   C   s@   z"zt d W n   t Y nX W n   tjdd Y nX d S )Nr   Tr   )r   Zslfkjsldkfjr2   print_exceptionr1   r1   r1   rD   r     s    r   )T
__future__r   r   platformrY   Zdataclassesr   r   r?   r   typesr   r   typingr   r	   r
   r   r   r   r   r   r   Zpygments.lexersr   Zpygments.tokenr   r   r   r   r   r   r   r   r   Zpygments.utilr   rc   r   Z_loopr   columnsr   r2   r   r    r!   r"   r#   Z	constrainr$   r   r%   r&   Zpanelr'   Zscoper(   r   r)   r   r*   r{   r5   r+   systemWINDOWSr   r   rk   ri   rW   r[   r^   r_   rm   rp   rx   rz   rA   rf   r   r   r   r1   r1   r1   rD   <module>   s   , l   R

