o
    i*                  	   @   s8  d dl m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 d dlmZ d d	lmZ eeZd
efddZd
efddZd
efddZdd Zdee d
efddZd
ef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&ee#egef d'ed(ee d
dfd)d*Z$dS ),    )PathN)Callable)Optional)_original_sys_argv_command)is_coverage_running)
get_logger)_get_config)asboolreturnc                   C   s
   dt jv S )Ncoverage)sysmodules r   r   [/home/ubuntu/.local/lib/python3.10/site-packages/ddtrace/contrib/internal/coverage/utils.pyis_coverage_loaded   s   
r   c                 C   s   | j dduS )z4Check if pytest-cov plugin is available (installed).
pytest_covN)pluginmanager
get_plugin)configr   r   r   _is_pytest_cov_available   s   r   c                 C   sT   t | sdS | jddd}| jddd}|du rdS t|tr(|dgkr(|s(dS |S )zRCheck if pytest-cov plugin is both available and enabled via command-line options.Fz--cov)defaultz--no-covT)r   	getoption
isinstancelist)r   
cov_optionnocov_optionr   r   r   _is_pytest_cov_enabled   s   r   c                   C   s   t  sdS ttjd ddS )NFr   _datadog_patch)r   getattrr   r   r   r   r   r   _is_coverage_patched'   s   r   sys_argv_commandc                 C   s   dd | v S )Nzcoverage run -m )join)r    r   r   r   _command_invokes_coverage_run.   s   r#   c                   C   s   t ddtrdS ttS )NCOVERAGE_RUNFT)r   r	   r#   r   r   r   r   r   $_is_coverage_invoked_by_coverage_run2   s   r%   c                 C   sL   | j  D ]}|\}}t|dr#|jr#t|jdr#|jjr#|jj  S qdS )zTFind and return pytest-cov coverage instance if available from config.pluginmanager.cov_controllercovN)r   list_name_pluginhasattrr&   r'   )r   plugin_plugin_instancer   r   r   _find_pytest_cov_instance8   s   r-   c                 C   sB   ddl m} t| }|r|| tdt| dS td dS )z7Register pytest-cov instance with ddtrace if available.r   )set_coverage_instancez8Registered pytest-cov coverage instance with ddtrace: %sTz0No pytest-cov controller found in plugin managerF)'ddtrace.contrib.internal.coverage.patchr.   r-   logdebugtype)r   r.   cov_instancer   r   r   _register_pytest_cov_instanceB   s   
r4   c              
   C   s   t | }|sdS z0t|dr|  td t|dr0|jr3t|dr6|  td W dS W dS W dS W dS  tyQ } ztd| W Y d}~dS d}~ww )z.Save pytest-cov data before report generation.Nsavez7Saved pytest-cov coverage data before report generation_startedstopz&Stopped pytest-cov coverage collectionz"Could not save pytest-cov data: %s)r-   r)   r5   r0   r1   r6   r7   	Exception)r   r3   
save_errorr   r   r   _save_pytest_cov_dataP   s"   


r:   c              
   C   s  ddl m} td| || rt| }d}|rtd d}z| }|r*| nt }t|}td|t	| W n t
yS } ztd| W Y d}~nd}~ww |sz@d}	t|d	rit|jd
ri|jj}	n|rtt|drt| }	|	sxd}	td|	 ddlm}
 |
|	d}|  |}td|	 W n t
y } ztd| W Y d}~nd}~ww z|jt|d}td |W S  t
y } ztd| W Y d}~nd}~ww |t|dS )z8Generate LCOV report using either pytest-cov or ddtrace.r   )generate_lcov_reportz"Generating LCOV report to file: %sNz:Using pytest-cov instance directly to generate LCOV reportFz5pytest-cov has data in memory: %s (measured %d files)z#Could not check pytest-cov data: %sr   	data_filedata_filenamez	.coveragez8No data in memory, attempting to load from data file: %s)Coverage)r<   zLoaded data from file: %sz%Could not load coverage data file: %s)outfilez7Generated LCOV report directly from pytest-cov instancez.Direct pytest-cov report generation failed: %s)r/   r;   r0   r1   r-   get_datameasured_filessetboollenr8   r)   r   r<   r=   r   r>   loadlcov_reportstr)r   tmp_pathis_pytest_cov_enabled_funcr;   pytest_cov_instancedatahas_datarA   er<   r>   	fresh_cov
load_errorpct_covereddirect_errorr   r   r   _generate_lcov_reportf   sZ   



rR   c                 C   sP   |   std|  dS |  }|std|  t|  dS tdt| |S )z2Validate report file exists and read its contents.z$LCOV report file was not created: %sNzLCOV report file is empty: %szRead coverage report: %d bytes)existsr0   warning
read_bytes_cleanup_temp_filer1   rD   )rH   coverage_report_bytesr   r   r   _validate_and_read_report   s   rX   c              
   C   sB   z|    W dS  ty  } ztd| W Y d}~dS d}~ww )z(Clean up temporary coverage report file.z5Failed to clean up temporary coverage report file: %sN)unlinkr8   r0   r1   )rH   rM   r   r   r   rV      s   rV   c                 C   s,   | r||st d | dd dS dS dS )zEStop coverage collection if we started it ourselves (not pytest-cov).zStopping coverage.py collectionTr5   N)r0   r1   )stop_coverage_funcr   rI   r   r   r   _stop_coverage_if_needed   s   
r\   upload_funcrI   r[   c                 C   sV  zt d || rt st d t|  t s!t d W dS t d || r.t|  d}tjddd	d
}t|j}W d   n1 sHw   Y  zt	| ||}|dur`t d|| nt d| W n% t
y } zdt|v rt d| t| W Y d}~W dS  d}~ww zBt|}	|	sW t| t|| | W dS ||	|}
|
rt d nt d W t| t|| | W dS W t| t|| | W dS t| t|| | w  t
y* } zCt d| |r
|| sz|dd W n t
y	   t jddd Y nw W Y d}~dS W Y d}~dS W Y d}~dS W Y d}~dS d}~ww )a  
    Shared coverage report upload handling for pytest plugins.

    Args:
        config: pytest config object (to access pluginmanager for pytest-cov)
        upload_func: Function to call for uploading (signature: upload_func(bytes, format) -> bool)
        is_pytest_cov_enabled_func: Function to check if pytest-cov is enabled
        stop_coverage_func: Optional function to stop coverage collection
    z=Coverage report upload is enabled, checking for coverage datazVpytest-cov is enabled but coverage not running, trying to register pytest-cov instancez8Coverage is not running, skipping coverage report uploadNz;Coverage is running, attempting to generate coverage reportlcovwbz.lcovF)modesuffixdeletez4Generated LCOV coverage report: %s (%.1f%% coverage)zDGenerated LCOV coverage report: %s (coverage percentage unavailable)zNo data to reportz6No coverage data available to generate LCOV report: %sz%Successfully uploaded coverage reportz Failed to upload coverage reportz,Error in coverage report upload handling: %sTrZ   z#Could not stop coverage after error)exc_info)r0   r1   r   r4   r:   tempfileNamedTemporaryFiler   namerR   r8   rG   rV   rX   r\   )r   r]   rI   r[   coverage_formattmp_filerH   rP   report_errorrW   upload_successrM   r   r   r   handle_coverage_report   sv   





rk   )N)%pathlibr   r   rd   typingr   r   &ddtrace.contrib.internal.coverage.datar   r/   r   ddtrace.internal.loggerr   !ddtrace.internal.settings._configr   ddtrace.internal.utils.formatsr	   __name__r0   rC   r   r   r   r   r   rG   r#   r%   r-   r4   r:   rR   rX   rV   r\   bytesrk   r   r   r   r   <module>   sD    
<