B
    hAZH                 @   sZ  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Zddlm	Z	 ddl
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 edZed	ejZed
ZdZeefZ ye e!f7 Z W n e"k
r   Y nX dZ#dZ$e#d e$ d Z%e#d e$ Z&dZ'dZ(dZ)d ddZ*d!ddZ+G dd de,Z-G dd de,Z.G dd de,Z/dS )"z
    werkzeug.debug.tbtools
    ~~~~~~~~~~~~~~~~~~~~~~

    This module provides various traceback related utility functions.

    :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD.
    N)
TokenError)cached_propertyescape)Console)
range_typePY2	text_typestring_types	to_native
to_unicode)get_filesystem_encodings   coding[:=]\s*([-\w.]+)s   ^(.*?)$z+^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)s   ﻿a  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>%(title)s // Werkzeug Debugger</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"
        type="text/css">
    <!-- We need to make sure this has a favicon so that the debugger does
         not by accident trigger a request to /favicon.ico which might
         change the application state. -->
    <link rel="shortcut icon"
        href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script type="text/javascript">
      var TRACEBACK = %(traceback_id)d,
          CONSOLE_MODE = %(console)s,
          EVALEX = %(evalex)s,
          EVALEX_TRUSTED = %(evalex_trusted)s,
          SECRET = "%(secret)s";
    </script>
  </head>
  <body style="background-color: #fff">
    <div class="debugger">
a        <div class="footer">
        Brought to you by <strong class="arthur">DON'T PANIC</strong>, your
        friendly Werkzeug powered traceback interpreter.
      </div>
    </div>

    <div class="pin-prompt">
      <div class="inner">
        <h3>Console Locked</h3>
        <p>
          The console is locked and needs to be unlocked by entering the PIN.
          You can find the PIN printed out on the standard output of your
          shell that runs the server.
        <form>
          <p>PIN:
            <input type=text name=pin size=14>
            <input type=submit name=btn value="Confirm Pin">
        </form>
      </div>
    </div>
  </body>
</html>
a  <h1>%(exception_type)s</h1>
<div class="detail">
  <p class="errormsg">%(exception)s</p>
</div>
<h2 class="traceback">Traceback <em>(most recent call last)</em></h2>
%(summary)s
<div class="plain">
  <form action="/?__debugger__=yes&amp;cmd=paste" method="post">
    <p>
      <input type="hidden" name="language" value="pytb">
      This is the Copy/Paste friendly version of the traceback.  <span
      class="pastemessage">You can also paste this traceback into
      a <a href="https://gist.github.com/">gist</a>:
      <input type="submit" value="create paste"></span>
    </p>
    <textarea cols="50" rows="10" name="code" readonly>%(plaintext)s</textarea>
  </form>
</div>
<div class="explanation">
  The debugger caught an exception in your WSGI application.  You can now
  look at the traceback which led to the error.  <span class="nojavascript">
  If you enable JavaScript you can also use additional features such as code
  execution (if the evalex feature is enabled), automatic pasting of the
  exceptions and much more.</span>
</div>
z
<!--

%(plaintext_cs)s

-->
a+  <h1>Interactive Console</h1>
<div class="explanation">
In this console you can execute Python expressions in the context of the
application.  The initial namespace was created by the debugger automatically.
</div>
<div class="console"><div class="inner">The Console requires JavaScript.</div></div>
zU<div class="%(classes)s">
  %(title)s
  <ul>%(frames)s</ul>
  %(description)s
</div>
z<div class="frame" id="frame-%(id)d">
  <h4>File <cite class="filename">"%(filename)s"</cite>,
      line <em class="line">%(lineno)s</em>,
      in <code class="function">%(function_name)s</code></h4>
  <div class="source">%(lines)s</div>
</div>
zV<tr class="%(classes)s">
  <td class=lineno>%(lineno)s</td>
  <td>%(code)s</td>
</tr>
Tc             C   s   t d|rdpddd| dd S )Ntruefalser   )evalexevalex_trustedconsoletitlesecrettraceback_id)CONSOLE_HTML)r   r    r   5lib/python3.7/site-packages/werkzeug/debug/tbtools.pyrender_console_html   s    
r   Fc             C   s\   t  \}}}| r|tkr x"t|D ]}|jdkr6P |j}q&W t|||}|sX|  |S )a  Get the current exception info as `Traceback` object.  Per default
    calling this method will reraise system exceptions such as generator exit,
    system exit or others.  This behavior can be disabled by passing `False`
    to the function as first parameter.
    N)sysexc_infosystem_exceptionsr   tb_next	Tracebackfilter_hidden_frames)Zignore_system_exceptionsZshow_hidden_framesskipexc_type	exc_valuetbxr   r   r   get_current_traceback   s    

r%   c               @   s4   e Zd ZdZdZdd Zdd ZeeZdd Zd	S )
LinezHelper for the source renderer.)linenocodein_framecurrentc             C   s   || _ || _d| _d| _d S )NF)r'   r(   r)   r*   )selfr'   r(   r   r   r   __init__   s    zLine.__init__c             C   s*   dg}| j r|d | jr&|d |S )Nlinezin-framer*   )r)   appendr*   )r+   rvr   r   r   classes   s    

zLine.classesc             C   s    t d| j| jt| jd S )N )r0   r'   r(   )SOURCE_LINE_HTMLjoinr0   r'   r   r(   )r+   r   r   r   render   s    
zLine.renderN)	__name__
__module____qualname____doc__	__slots__r,   r0   propertyr4   r   r   r   r   r&      s   r&   c               @   s   e Zd ZdZdd Zdd Zdd ZeeZdd	 ZeeZdddZ	dd Z
dddZdddZdd Zdd ZeeZedd Zd
S )r   zWraps a traceback.c             C   sn   || _ || _t|ts6|j}|jdkr:|jd | }n|}|| _g | _x"|rh| jt	||| |j
}qHW d S )N)Z__builtin__
exceptions.)r!   r"   
isinstancestrr5   r6   exception_typeframesr.   Framer   )r+   r!   r"   r#   r?   r   r   r   r,      s    

zTraceback.__init__c             C   s   | j s
dS g }d}xt| j D ]j}|j}|dkr@g }d}|dkrzqn:|dkrXd}|dkrzqn"|dkrpd}|d	krzqn
|s|rzq|| qW t|d
kr| j d jdkr| j dd= n| j d |kr|| j dd< dS )z.Remove the frames according to the paste spec.NF)beforebefore_and_thisrC   )resetreset_and_thisrE   )afterafter_and_thisTrG      r   Zcodeopr   )r@   hider.   lenmodule)r+   Z
new_framesZhiddenframerI   r   r   r   r      s4    zTraceback.filter_hidden_framesc             C   s   t | jtS )zIs it a syntax error?)r=   r"   SyntaxError)r+   r   r   r   is_syntax_error  s    zTraceback.is_syntax_errorc             C   s2   t | j| j}d| }tr.|ddS |S )z'String representation of the exception. zutf-8replace)	tracebackformat_exception_onlyr!   r"   r3   stripr   decode)r+   Zbufr/   r   r   r   	exception  s    zTraceback.exceptionNc             C   s:   |dkrt j}| j d }tr,|dd}|| dS )z+Log the ASCII traceback into a file object.N
zutf-8rP   )r   stderr	plaintextrstripr   encodewrite)r+   Zlogfiler#   r   r   r   log  s    zTraceback.logc             C   s   t dddd| jiidd}yddlm} W n  tk
rR   ddlm} Y nX |d	|d
}t |	 
d}|  |d |d dS )z'Create a paste and return the paste id.zWerkzeug Internal Server ErrorFztraceback.txtZcontent)descriptionZpublicfileszutf-8r   )urlopenzhttps://api.github.com/gists)dataZhtml_urlid)Zurlra   )jsondumpsrX   rZ   Zurllib2r_   ImportErrorZurllib.requestloadsreadrT   close)r+   r`   r_   r/   Zrespr   r   r   paste&  s    zTraceback.pasteTc             C   s   d}g }dg}| j s|d |r2| jr.d}nd}x8| j D ].}|d|jrXdt|j pZd| f  q:W | jrxd}nd	}td
||rd| pdd||t| j d S )z1Render the traceback for the interactive console.rO   rQ   znoframe-tracebackzSyntax Errorz+Traceback <em>(most recent call last)</em>:z<li%s>%sz title="%s"z<pre class=syntaxerror>%s</pre>z<blockquote>%s</blockquote>r1   z<h3>%s</h3>rV   )r0   r   r@   r]   )	r@   r.   rN   infor   r4   SUMMARY_HTMLr3   rU   )r+   include_titler   r@   r0   rL   Zdescription_wrapperr   r   r   render_summary=  s*    
zTraceback.render_summaryFc             C   s\   t | j}t|rdpd|rdp dd||t | j| jddt | jtdd| j| j|d S )z2Render the Full HTML page with the traceback info.r   r   F)rk   z-{2,}-)r   r   r   r   rU   r?   ZsummaryrX   Zplaintext_csr   r   )	r   rU   	PAGE_HTMLr?   rl   rX   resubra   )r+   r   r   r   excr   r   r   render_full]  s    



zTraceback.render_fullc             c   sH   dV  x4| j D ]*}d|j|j|jf V  d|j  V  qW | jV  dS )z4Like the plaintext attribute but returns a generatorz"Traceback (most recent call last):z  File "%s", line %s, in %sz    N)r@   filenamer'   function_namecurrent_linerS   rU   )r+   rL   r   r   r   generate_plaintext_tracebacko  s    z&Traceback.generate_plaintext_tracebackc             C   s   d |  S )NrV   )r3   rv   )r+   r   r   r   rX   {  s    zTraceback.plaintextc             C   s   t | S )N)ra   )r$   r   r   r   <lambda>  s    zTraceback.<lambda>)N)T)FNT)r5   r6   r7   r8   r,   r   rN   r:   rU   r\   rh   rl   rr   rv   rX   r   ra   r   r   r   r   r      s    #
	
  
r   c               @   st   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZe	dd Z
dddZedd Ze	dd Zedd ZdS )rA   zA single frame in a traceback.c             C   s  |j | _|jjj| _|jj| _|jj| _	t
|p:t
|}|dd  dkrX|d d }tj|rptj|}t|t | _| j	d| _| j	d| _|jj| _| jdd| _| jd}|d k	ryt|}W n$ tk
r   t|d	d
}Y nX || _d S )N)z.pyoz.pycr   r5   
__loader__Z__traceback_hide__FZ__traceback_info__zutf-8rP   )	tb_linenor'   tb_framef_codeco_namert   f_localslocals	f_globalsglobalsinspectZgetsourcefileZgetfileospathisfilerealpathr   r   rs   getrK   loaderr(   rI   r   UnicodeErrorr>   rT   ri   )r+   r!   r"   r#   fnri   r   r   r   r,     s*    


zFrame.__init__c             C   s(   t | jt| j| jt| j|  d S )z%Render a single frame in a traceback.)ra   rs   r'   rt   lines)
FRAME_HTMLra   r   rs   r'   rt   render_line_context)r+   r   r   r   r4     s    zFrame.renderc                sb   |   \}}}g   fdd}x|D ]}||d q$W ||d x|D ]}||d qFW d S )Nc                sH   |    } |  }t| t| } d|d| t|p<df  d S )Nz7<pre class="line %s"><span class="ws">%s</span>%s</pre>r1   )
expandtabsrY   rS   rJ   r.   r   )r-   clsZstripped_lineprefix)r/   r   r   render_line  s    z.Frame.render_line_context.<locals>.render_linerB   r*   rF   rV   )get_context_linesr3   )r+   rB   r*   rF   r   r-   r   )r/   r   r     s    


zFrame.render_line_contextc             C   s   dd t | jD }t| jdr| jjd }x&|dkrRt|| jrHP |d8 }q.W y$tt	dd ||d D }W n t
k
r   d}Y nX x||||  D ]
}d|_qW yd|| jd  _W n tk
r   Y nX |S )	z:Helper function that returns lines with extra information.c             S   s   g | ]\}}t |d  |qS )rH   )r&   ).0idxr$   r   r   r   
<listcomp>  s    z-Frame.get_annotated_lines.<locals>.<listcomp>co_firstlinenorH   r   c             S   s   g | ]}|j d  qS )rV   )r(   )r   r$   r   r   r   r     s    NT)	enumeratesourcelineshasattrr(   r   _funcdef_rematchrJ   r   Zgetblockr   r)   r'   r*   
IndexError)r+   r   r'   offsetr-   r   r   r   get_annotated_lines  s&    


zFrame.get_annotated_linessinglec             C   sB   t |tr2tr&t |tr&t|d }t|d|}t|| j| j	S )z*Evaluate code in the context of the frame.zutf-8z<interactive>)
r=   r	   r   ZunicodeUTF8_COOKIErZ   compileevalr   r   )r+   r(   moder   r   r   r     s
    
z
Frame.evalc             C   sh  d}| j dk	r^y:t| j dr,| j | j}nt| j drF| j | j}W n tk
r\   Y nX |dkrytt| j	t
 dd}W n tk
r   g S X z| }W d|  X t|tr| S d}|tr|dd }nJxHtt|D ]6\}}t| }|dk	r|d}P |dkrP qW t|}yt| W n tk
rV   d}Y nX ||d	 S )
z6The sourcecode of the file as list of unicode strings.N
get_sourceget_source_by_coderb)r   zutf-8   rH   rP   )r   r   r   rK   r   r(   	Exceptionopenr
   rs   r   IOErrorrf   rg   r=   r   
splitlines
startswithr   r   _line_refinditer
_coding_researchgroupcodecslookupLookupErrorrT   )r+   sourcefcharsetr   r   r   r   r   r     sH    






zFrame.sourcelines   c             C   s@   | j | j| d | jd  }| j | j| j|  }|| j|fS )NrH   )r   r'   ru   )r+   contextrB   Zpastr   r   r   r     s
    zFrame.get_context_linesc             C   s*   y| j | jd  S  tk
r$   dS X d S )NrH   rO   )r   r'   r   )r+   r   r   r   ru   !  s    zFrame.current_linec             C   s   t | j| jS )N)r   r   r   )r+   r   r   r   r   (  s    zFrame.consolec             C   s   t | S )N)ra   )r$   r   r   r   rw   ,  s    zFrame.<lambda>N)r   )r   )r5   r6   r7   r8   r,   r4   r   r   r   r   r   r   r:   ru   r   ra   r   r   r   r   rA     s   

6
	rA   )T)FFr   )0r8   ro   r   r   rb   r   rQ   r   tokenizer   Zwerkzeug.utilsr   r   Zwerkzeug.debug.consoler   Zwerkzeug._compatr   r   r   r	   r
   r   Zwerkzeug.filesystemr   r   r   	MULTILINEr   r   r   
SystemExitKeyboardInterruptr   GeneratorExit	NameErrorZHEADERZFOOTERrn   r   rj   r   r2   r   r%   objectr&   r   rA   r   r   r   r   <module>
   sH    


		
 
 *