o
    fr                     @   s   d Z ddg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	Z	ddl
Z
ddlZddlZddlmZ ddlZdZG dd dZd	d
 Zdd ZG dd dZdd Zdd ZdddZdd ZG dd dZdd Zedkrye  dS dS )a  program/module to trace Python program or function execution

Sample use, command line:
  trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs
  trace.py -t --ignore-dir '$prefix' spam.py eggs
  trace.py --trackcalls spam.py eggs

Sample use, programmatically
  import sys

  # create a Trace object, telling it what to ignore, and whether to
  # do tracing or line-counting or both.
  tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
                       trace=0, count=1)
  # run the new command using the given tracer
  tracer.run('main()')
  # make a report, placing output in /tmp
  r = tracer.results()
  r.write_results(show_missing=True, coverdir="/tmp")
TraceCoverageResults    N)	monotonicz#pragma NO COVERc                   @   s   e Zd ZdddZdd ZdS )_IgnoreNc                 C   s:   |st  nt || _|sg ndd |D | _ddi| _d S )Nc                 S   s   g | ]}t j|qS  )ospathnormpath.0dr   r   /usr/lib/python3.10/trace.py
<listcomp>H   s    z$_Ignore.__init__.<locals>.<listcomp>z<string>   )set_mods_dirs_ignore)selfmodulesdirsr   r   r   __init__F   s
   z_Ignore.__init__c                 C   s   || j v r
| j | S || jv rd| j |< dS | jD ]}||d r*d| j |<  dS q|d u r6d| j |< dS | jD ]}||tj rKd| j |<  dS q9d| j |< dS )Nr   .r   )r   r   
startswithr   r   sep)r   filename
modulenamemodr   r   r   r   namesL   s(   









z_Ignore.namesNN)__name__
__module____qualname__r   r   r   r   r   r   r   E   s    
r   c                 C   s    t j| }t j|\}}|S ),Return a plausible module name for the path.)r   r   basenamesplitext)r   baser   extr   r   r   _modnamew   s   r(   c                 C   s   t j| }d}tjD ] }t j|}||r+|t| t jkr+t|t|kr+|}q|r9| t|d d }n| }t j|\}}|t jd}t j	rT|t j	d}t j
|\}}|dS )r#    r   Nr   )r   r   normcasesysr   lenr   
splitdrivereplacealtsepr%   lstrip)r   comparepathlongestdirr&   driver   r'   r   r   r   _fullmodname~   s"   

r5   c                   @   s>   e Zd Z		dddZdd Zdd Zdd
dZdddZdS )r   Nc              
   C   s  || _ | j d u ri | _ | j  | _|| _| jd u ri | _| j | _|| _| jd u r-i | _| j | _|| _|| _| jrz,t| jd}t	|\}}}W d    n1 sVw   Y  | 
| j|||d W d S  tttfy } ztd| j|f tjd W Y d }~d S d }~ww d S )Nrb)callerszSkipping counts file %r: %sfile)countscopycountercalledfuncsr7   infileoutfileopenpickleloadupdate	__class__OSErrorEOFError
ValueErrorprintr+   stderr)r   r:   r=   r>   r7   r?   ferrr   r   r   r      s:   


zCoverageResults.__init__c                 C   s   | do	|dS )z_Return True if the filename does not refer to a file
        we want to have reported.
        <>)r   endswith)r   r   r   r   r   is_ignored_filename   s   z#CoverageResults.is_ignored_filenamec           	      C   sn   | j }| j}| j}|j }|j}|j}|D ]}||d||  ||< q|D ]}d||< q%|D ]}d||< q.dS )z.Merge in the data from another CoverageResultsr   r   N)r:   r=   r7   get)	r   otherr:   r=   r7   other_countsother_calledfuncsother_callerskeyr   r   r   rC      s   

zCoverageResults.updateTFc           "   
   C   s  | j r t  td | j }t|D ]\}}}td|||f  q| jrht  td d }}	t| jD ]4\\}
}}\}}}|
|krNt  td|
d |
}d}	||
kr]|	|kr]td| |}	td||||f  q3i }| jD ]\}}||i  }||< | j||f ||< qmi }| D ]\}}| |rq|dr|d	d
 }|d	u rt	j
t	j
|}t|}n|}t	j
|st	| t|}|rt|}ni }t|}t	j
||d }t|d}t|j\}}W d	   n1 sw   Y  | |||||\}}|r|rtd| | }||||f||< q|r<|r<td t|D ]}|| \}}}}td||   q(| jrz)t| jd} t| j| j | jf| d W d	   W d	S 1 sbw   Y  W d	S  ty }! ztd|! tj d W Y d	}!~!d	S d	}!~!ww d	S )af  
        Write the coverage results.

        :param show_missing: Show lines that had no hits.
        :param summary: Include coverage summary per module.
        :param coverdir: If None, the results of each module are placed in its
                         directory, otherwise it is included in the directory
                         specified.
        zfunctions called:z*filename: %s, modulename: %s, funcname: %szcalling relationships:r)   z***z  -->z    %s.%s -> %s.%sz.pycNz.coverr6   d   zlines   cov%   module   (path)z%5d   %3d%%   %s   (%s)wbr   z"Can't save counts files because %sr8   )!r=   rH   sortedr7   r:   rP   itemsrO   rN   r   r   dirnameabspathr(   existsmakedirsr5   _find_executable_linenos	linecachegetlinesjoinr@   tokenizedetect_encodingreadlinewrite_results_fileintr?   rA   dumprE   r+   rI   )"r   show_missingsummarycoverdircallsr   r   funcnamelastfile	lastcfilepfilepmodpfunccfilecmodcfuncper_filelineno	lines_hitsumscountr3   lnotabsource	coverpathfpencoding_n_hitsn_linespercentmrJ   rK   r   r   r   write_results   s   







( zCoverageResults.write_resultsc              
   C   s  z	t |d|d}W n ty' } ztd||f tjd W Y d}~dS d}~ww d}d}	|J t|dD ]9\}
}|
|v rN|d	||
   |	d7 }	|d7 }n|
|v r`t|vr`|d
 |d7 }n|d ||d q4W d   |	|fS 1 s{w   Y  |	|fS )z'Return a coverage results file in path.wr   z3trace: Could not open %r for writing: %s - skippingr8   N)r   r   r   r   z%5d: z>>>>>> z          )	r@   rE   rH   r+   rI   	enumeratewritePRAGMA_NOCOVER
expandtabs)r   r   linesr{   rx   r   r?   rK   r   r   rw   liner   r   r   rf   )  s:   




z"CoverageResults.write_results_file)NNNNN)TFNN)r    r!   r"   r   rO   rC   r   rf   r   r   r   r   r      s    

\c                 C   s,   i }t | D ]\}}||vrd||< q|S )z:Return dict where keys are lines in the line number table.r   )disfindlinestarts)codestrslinenosr   rw   r   r   r   _find_lines_from_codeI  s   r   c                 C   s4   t | |}| jD ]}t|r|t|| q|S )z<Return lineno dict for all code objects reachable from code.)r   	co_constsinspectiscoderC   _find_lines)r   r   r   cr   r   r   r   S  s   


r   c                 C   s   i }t j}t| |d;}t|j}|D ])\}}}}	}
|t jkr;|t jkr;|\}}|	\}}t||d D ]}d||< q4|}qW d   |S 1 sIw   Y  |S )zReturn a dict of possible docstring positions.

    The dict maps line numbers to strings.  There is an entry for
    line that contains only a string or a part of a triple-quoted
    string.
    r   r   N)tokenINDENTr@   rc   generate_tokensre   STRINGrange)r   r   r   
prev_ttyperJ   tokttypetstrstartendr   slinescolelineecolir   r   r   _find_strings_  s"   





r   c              
   C   s   zt | }| }|j}W d   n1 sw   Y  W n ty= } ztd| |f tjd i W  Y d}~S d}~ww t|| d}t	| |}t
||S )zAReturn dict where keys are line numbers in the line number table.Nz%Not printing coverage data for %r: %sr8   exec)rc   r@   readr   rE   rH   r+   rI   compiler   r   )r   rJ   progr   rK   r   r   r   r   r   r_   v  s$   

r_   c                   @   sv   e Zd Z			dddZdd	 Zdd
dZdd Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS ) r   r   r   r   NFc
           
      C   s   || _ || _t||| _i | _i | _d| _|| _i | _i | _	i | _
d| _|	r*t | _|r2| j| _dS |r:| j| _dS |rH|rH| j| _| j| _dS |rT| j| _| j| _dS |r`| j| _| j| _dS d| _dS )ax  
        @param count true iff it should count number of times each
                     line is executed
        @param trace true iff it should print out each line that is
                     being counted
        @param countfuncs true iff it should just output a list of
                     (filename, modulename, funcname,) for functions
                     that were called at least once;  This overrides
                     `count' and `trace'
        @param ignoremods a list of the names of modules to ignore
        @param ignoredirs a list of the names of directories to ignore
                     all of the (recursive) contents of
        @param infile file from which to read stored counts to be
                     added into the results
        @param outfile file in which to write the results
        @param timing true iff timing information be displayed
        r   Nr   )r>   r?   r   ignorer:   pathtobasename	donothingtrace_calledfuncs_callers_caller_cache
start_time_timeglobaltrace_trackcallersglobaltraceglobaltrace_countfuncsglobaltrace_ltlocaltrace_trace_and_count
localtracelocaltrace_tracelocaltrace_count)
r   rz   r   
countfuncscountcallers
ignoremods
ignoredirsr>   r?   timingr   r   r   r     s6   
zTrace.__init__c                 C   s    dd l }|j}| ||| d S )Nr   )__main____dict__runctx)r   cmdr   dictr   r   r   run  s   z	Trace.runc              	   C   s   |d u ri }|d u ri }| j st| j t| j zt||| W | j s2td  td  d S d S | j sBtd  td  w w r   )r   	threadingsettracer   r+   r   )r   r   globalslocalsr   r   r   r     s   


zTrace.runctxc             	   O   sP   d }| j st| j z||i |}W | j std  |S | j s'td  w w r   )r   r+   r   r   )r   funcargskwresultr   r   r   runfunc  s   
zTrace.runfuncc           
      C   s   |j }|j}|rt|}nd }|j}d }|| jv r&| j| d ur%| j| }nCd | j|< dd t|D }t|dkridd t|d D }t|dkridd t|d D }	t|	dkri|	d j}|| j|< |d ursd||f }|||fS )Nc                 S   s   g | ]	}t |r|qS r   )r   
isfunction)r   rJ   r   r   r   r         
z1Trace.file_module_function_of.<locals>.<listcomp>r   c                 S   s   g | ]	}t |tr|qS r   )
isinstancer   r
   r   r   r   r     r   r   c                 S   s   g | ]	}t |d r|qS )	__bases__)hasattr)r   r   r   r   r   r     r   z%s.%s)	f_codeco_filenamer(   co_namer   gcget_referrersr,   r    )
r   framer   r   r   rm   clsnamefuncsdictsclassesr   r   r   file_module_function_of  s.   






zTrace.file_module_function_ofc                 C   s4   |dkr|  |}|  |j}d| j||f< dS dS )zkHandler for call events.

        Adds information about who called who to the self._callers dict.
        callr   N)r   f_backr   )r   r   whyarg	this_funcparent_funcr   r   r   r     s
   
zTrace.globaltrace_trackcallersc                 C   s$   |dkr|  |}d| j|< dS dS )zoHandler for call events.

        Adds (filename, modulename, funcname) to the self._calledfuncs dict.
        r   r   N)r   r   )r   r   r   r   r   r   r   r   r     s   
zTrace.globaltrace_countfuncsc                 C   sp   |dkr6|j }|jdd}|r4t|}|dur0| j||}|s2| jr-td||jf  | j	S dS dS dS dS )zHandler for call events.

        If the code block being entered is to be ignored, returns `None',
        else returns self.localtrace.
        r   __file__Nz! --- modulename: %s, funcname: %s)
r   	f_globalsrP   r(   r   r   r   rH   r   r   )r   r   r   r   r   r   r   	ignore_itr   r   r   r     s"   zTrace.globaltrace_ltc                 C   s   |dkr?|j j}|j}||f}| j|dd | j|< | jr*tdt | j  dd tj	
|}td||t||f dd | jS )	Nr   r   r   %.2f r   
%s(%d): %sr)   )r   r   f_linenor:   rP   r   rH   r   r   r   r$   r`   getliner   )r   r   r   r   r   rw   rU   bnamer   r   r   r   (  s   
z Trace.localtrace_trace_and_countc                 C   sd   |dkr/|j j}|j}| jrtdt | j  dd tj|}td||t	
||f dd | jS )Nr   r   r   r   r   r)   )r   r   r   r   rH   r   r   r   r$   r`   r   r   )r   r   r   r   r   rw   r   r   r   r   r   7  s   
zTrace.localtrace_tracec                 C   s<   |dkr|j j}|j}||f}| j|dd | j|< | jS )Nr   r   r   )r   r   r   r:   rP   r   )r   r   r   r   r   rw   rU   r   r   r   r   D  s   zTrace.localtrace_countc                 C   s   t | j| j| j| j| jdS )N)r>   r?   r=   r7   )r   r:   r>   r?   r   r   )r   r   r   r   resultsL  s
   
zTrace.results)	r   r   r   r   r   r   NNFr   )r    r!   r"   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s     
2
)	c                     s  dd l } |  }|jdddd |dd}|jdd	d
dd |jddd
dd |jddd
dd |jddd
dd |d}| }|jddd
dd |jddd
dd |jdddd  |jd!d"d#d  |jd$d%d
d&d |jd'd(d
d)d |jd*d+d
d,d |d-d.}|jd/d0g d1d2 |jd3d0g d4d2 |jd5d
d6d7d2 |jd8d9d:d; |jd<| jd=d; | }|jrt	d>t	d?  fd@dAdBdC |j
D |_
fdDdC|jD |_|jr|js|dE t|j|jdF}||j|j|jS t|j|j|j|jgs|dG |jr|js|jr|dH |jr+|js+|dI |jd u r6|dJ t|j|j|j|j|j
|j|j|j|jdK	}zk|jrudd l}|j}||\}	}
}|jg|jt _!dL|j|
j"|
j#|
d dM}n:|jg|jt _!t$j%&|jt j%d< t'(|j}t)|* |jdN}W d    n	1 sw   Y  |jdLd d dO}|+||| W n( t,y } zt -dPt j!d |f  W Y d }~nd }~w t.y   Y nw |/ }|j0s||j|j|j d S d S )QNr   z	--versionversionz	trace 2.0)actionr   zMain optionsz(One of these (or --report) must be givenz-cz--count
store_truezCount the number of times each line is executed and write the counts to <module>.cover for each module executed, in the module's directory. See also --coverdir, --file, --no-report below.)r   helpz-tz--tracez3Print each line to sys.stdout before it is executedz-lz--listfuncszKeep track of which functions are executed at least once and write the results to sys.stdout after the program exits. Cannot be specified alongside --trace or --count.z-Tz--trackcallsz^Keep track of caller/called pairs and write the results to sys.stdout after the program exits.	Modifiersz-rz--reportzGenerate a report from a counts file; does not execute any code. --file must specify the results file to read, which must have been created in a previous run with --count --file=FILEz-Rz--no-reportz^Do not generate the coverage report files. Useful if you want to accumulate over several runs.z-fz--filez+File to accumulate counts over several runs)r   z-Cz
--coverdirzDirectory where the report files go. The coverage report for <package>.<module> will be written to file <dir>/<package>/<module>.coverz-mz	--missingz?Annotate executable lines that were not executed with ">>>>>> "z-sz	--summaryz\Write a brief summary for each file to sys.stdout. Can only be used with --count or --reportz-gz--timingzQPrefix each line with the time since the program started. Only used while tracingFilterszCan be specified multiple timesz--ignore-moduleappendzqIgnore the given module(s) and its submodules (if it is a package). Accepts comma separated list of module names.)r   defaultr   z--ignore-dirzWIgnore files in the given directory (multiple directories can be joined by os.pathsep).z--moduleFzTrace a module. progname?zfile to run as main program)nargsr   	argumentszarguments to the programstdlib
platstdlibc                    s4   t jt j| } | dd } t j| S )Nz$prefixz$exec_prefix)r   r   
expanduser
expandvarsr.   r	   )s)_exec_prefix_prefixr   r   parse_ignore_dir  s   zmain.<locals>.parse_ignore_dirc                 S   s$   g | ]}| d D ]}| q	qS ),)splitstrip)r   r   r   r   r   r   r     s
    
zmain.<locals>.<listcomp>c                    s&   g | ]}| tjD ]} |q
qS r   )r  r   pathsep)r   r   r  )r	  r   r   r     s
    z-r/--report requires -f/--file)r>   r?   zLmust specify one of --trace, --count, --report, --listfuncs, or --trackcallsz8cannot specify both --listfuncs and (--trace or --count)z3--summary can only be used with --count or --reportz3progname is missing: required with the main options)r   r   r   r   r>   r?   r   r   )r    r   __package__
__loader____spec__
__cached__r   )r   r    r  r  zCannot run file %r because: %s)1argparseArgumentParseradd_argumentadd_argument_groupadd_mutually_exclusive_group	REMAINDER
parse_args
ignore_dir	sysconfigget_pathignore_modulereportr9   errorr   r   missingrj   rk   anyr   rz   	listfuncs
trackcallsr   r   r   modulerunpy_get_module_detailsr   r  r+   argvparentloaderr   r   r[   io	open_coder   r   r   rE   exit
SystemExitr   	no_report)r  parsergrp_grpoptsr   tr$  module_namemod_namemod_specr   globsr~   rK   r   )r  r  r	  r   mainR  s   





















	$r7  r   r   )__doc____all__r)  r`   r   r+   r  r   rc   r   r   r   rA   timer   r   r   r   r   r(   r5   r   r   r   r   r_   r   r7  r    r   r   r   r   <module>   s@   2 0

 O 
