Hosted coverage reports for GitHub, Bitbucket and Gitlab (deprecated)
npx @tessl/cli install tessl/pypi-codecov@2.1.0⚠️ DEPRECATED: This package has been deprecated by Codecov and will be completely removed. Users should migrate to the new Codecov uploader.
A Python library and command-line tool for uploading code coverage reports to Codecov, a hosted service for tracking test coverage across multiple CI/CD platforms. The package automatically detects CI environments, processes various coverage report formats, and uploads compressed reports to Codecov with retry logic and comprehensive error handling.
pip install codecovimport codecovFor direct function access:
from codecov import main, write, read, try_to_runFor accessing version and metadata:
from codecov import __version__, __author__, __url__For accessing utility functions and constants:
from codecov import find_files, generate_toc, COLOR, opj# Public repository (token auto-detected on supported CI platforms)
codecov
# Private repository with explicit token
codecov -t your-repository-upload-token
# Target specific coverage files
codecov -f coverage.xml -f coverage.txt
# Add custom flags for grouping reports
codecov -F unittests -F integration
# Include environment variables in report
codecov -e TOXENV -e PYTHON_VERSION
# Advanced usage examples
codecov --root /path/to/project --commit abc123 --branch main
codecov --disable search --disable gcov --verbose
codecov --url https://codecov.example.com --slug owner/repo
codecov --dump --verbose # Debug mode without uploadThe codecov CLI provides comprehensive upload configuration through command-line arguments organized in functional groups:
--version: Show version information--token, -t TOKEN: Repository upload token (default: $CODECOV_TOKEN)--file, -f FILES: Target specific coverage files (multiple allowed)--flags, -F FLAGS: Custom flags for report grouping (default: $CODECOV_FLAGS)--env, -e VARS: Environment variables to include (multiple allowed)--required: Exit with code 1 on upload failure--name, -n NAME: Custom upload name (default: $CODECOV_NAME)--gcov-root ROOT: Project root directory for gcov processing--gcov-glob PATTERNS: File patterns to ignore during gcov gathering--gcov-exec EXECUTABLE: gcov executable to use (default: 'gcov')--no-gcov-out: Disable gcov output--gcov-args ARGS: Additional arguments to pass to gcov-X, --disable FEATURES: Disable features (search, detect, gcov, pycov, fix, s3)--root ROOT: Override project directory detection--commit, -c SHA: Specify commit SHA manually--prefix, -P PREFIX: Network path prefix for path resolution--branch, -b BRANCH: Specify branch name manually--build BUILD: Custom build number--pr PR: Pull request number--tag TAG: Git tag for the build--tries ATTEMPTS: Number of upload retry attempts (default: 5)--slug, -r SLUG: Repository slug format owner/repo (default: $CODECOV_SLUG)--url, -u URL: Codecov endpoint URL (default: $CODECOV_URL or https://codecov.io)--cacert BUNDLE: Certificate bundle for HTTPS verification (default: $CODECOV_CACERT)--dump: Display collected data without uploading-v, --verbose: Enable verbose output--no-color: Disable colored terminal outputimport codecov
# Basic programmatic upload with default settings
codecov.main()
# Upload with custom arguments (equivalent to CLI usage)
codecov.main(['-t', 'token', '-f', 'coverage.xml'])
# Debug mode returns detailed information
result = codecov.main(debug=True)
print(result['query']) # Upload parameters
print(result['reports']) # Collected coverage dataPrimary function for uploading coverage reports to Codecov with comprehensive CI detection and error handling.
def main(*argv, **kwargs):
"""
Main entry point for codecov functionality.
Parameters:
- *argv: Command line arguments (list of strings)
- **kwargs: Additional options including 'debug' flag
Returns:
- None: Normal execution (uploads to Codecov)
- dict: Debug information when debug=True in kwargs, containing:
- reports: collected coverage data
- codecov: parsed command line arguments
- query: upload parameters dict
- urlargs: URL arguments for upload
- result: HTTP response from upload
Raises:
- SystemExit: On critical errors or when --required flag fails
- Exception: Re-raised when debug=True in kwargs
"""Formatted output with color support for terminal display.
def write(text, color=None):
"""
Output text with optional color formatting.
Parameters:
- text (str): Text to output to stdout
- color (str): Optional color ('red', 'green', or None)
Returns:
- None
"""Safe file reading with encoding detection and error handling.
def fopen(path):
"""
Safely open and read file contents with encoding handling.
Parameters:
- path (str): File path to read
Returns:
- str: File contents or None on error
"""
def read(filepath):
"""
Read coverage report file and format with path header.
Parameters:
- filepath (str): Path to coverage report file
Returns:
- str: Formatted coverage report with '# path=filepath' header
"""Execute system commands with error handling and output capture.
def check_output(cmd, **popen_args):
"""
Execute command and return output, raising CalledProcessError on failure.
Parameters:
- cmd (list): Command and arguments to execute
- **popen_args: Additional arguments for subprocess.Popen
Returns:
- str: Command output decoded as UTF-8
Raises:
- CalledProcessError: When command returns non-zero exit code
"""
def try_to_run(cmd, shell=False, cwd=None):
"""
Attempt to run command with graceful error handling.
Parameters:
- cmd (list): Command and arguments to execute
- shell (bool): Whether to use shell execution (default: False)
- cwd (str): Working directory for command execution
Returns:
- str: Command output or None on failure
"""Execute Python coverage tool using importable module or PATH lookup.
def run_python_coverage(args):
"""
Run Python coverage tool using module import or PATH.
Parameters:
- args (list): Arguments to pass to coverage command
Returns:
- None
"""Find files matching patterns with directory exclusion support.
def find_files(directory, patterns, recursive=True, exclude_dirs=[]):
"""
Find files matching patterns in directory tree.
Parameters:
- directory (str): Directory to search
- patterns (str or list): File patterns to match (glob style)
- recursive (bool): Whether to search recursively (default: True)
- exclude_dirs (list): Directory names to exclude from search
Returns:
- generator: Yields matching file paths as strings
"""Generate file listings from version control systems.
def generate_toc(root):
"""
Generate table of contents from git/hg file listings.
Parameters:
- root (str): Repository root directory path
Returns:
- str: Newline-separated list of tracked files
"""Robust HTTP upload with exponential backoff retry logic.
def retry_upload(url, request_method, retries=5, break_codes=(200,), **kwargs):
"""
Retry HTTP upload with backoff on failure.
Parameters:
- url (str): URL to upload to
- request_method (callable): HTTP method function (requests.post, etc.)
- retries (int): Maximum number of retry attempts (default: 5)
- break_codes (tuple): HTTP status codes indicating success (default: (200,))
- **kwargs: Additional arguments for request method
Returns:
- requests.Response: Final response object
"""Data sanitization and encoding utilities.
def sanitize_arg(replacement, arg):
"""
Sanitize command line arguments by replacing ampersands.
Parameters:
- replacement (str): String to replace ampersands with
- arg (str): Argument to sanitize
Returns:
- str: Sanitized argument string
"""
def remove_non_ascii(data):
"""
Remove non-ASCII characters from data.
Parameters:
- data (bytes or str): Input data to clean
Returns:
- str: ASCII-only string
"""Internal helper functions that are technically accessible but intended for internal use.
def _add_env_if_not_empty(lst, value):
"""
Add environment variable to set if value is not empty.
Parameters:
- lst (set): Set of environment variable names to add to
- value (str): Environment variable name to potentially add
Returns:
- None: Modifies lst in place
"""# Version information
version: str = "2.1.13"
__version__: str = "2.1.13"
# Package metadata (from codecov.__version__)
__author__: str = "Codecov"
__author_email__: str = "support@codecov.io"
__copyright__: str = "Copyright 2020 Codecov"
__license__: str = "Apache 2.0"
__title__: str = "codecov"
__url__: str = "https://github.com/codecov/codecov-python"# Global color output control
COLOR: bool = True# Compiled regex patterns for file and path filtering
is_merge_commit: re.Pattern # Detect git merge commits: r"^Merge\s\w{40}\sinto\s\w{40}$"
ignored_path: re.Pattern # Paths to ignore during coverage collection: /vendor, /__pycache__, /node_modules, etc.
ignored_report: re.Pattern # Files to ignore as coverage reports: .coverage, .pyc, .js, .html, etc.
is_report: re.Pattern # Files that are coverage reports: coverage*, .gcov, .lcov, jacoco*.xml, etc.
remove_token: function # Function to sanitize tokens from URLs: removes r"token=[^\&]+" patterns# Platform-dependent utilities
quote: function # Shell argument quoting (platform-specific: shlex.quote, pipes.quote, or subprocess.list2cmdline)
opj: function # Alias for os.path.join for performanceThe package automatically detects and integrates with 15+ CI providers:
Each provider is automatically detected through environment variables, with fallback to manual configuration.
Automatically detects and processes multiple coverage formats:
The package includes comprehensive error handling:
Key environment variables for configuration:
CODECOV_TOKEN: Repository upload tokenCODECOV_FLAGS: Comma-separated flags for report groupingCODECOV_ENV: Environment variables to include in reportCODECOV_NAME: Custom name for uploadCODECOV_SLUG: Repository slug (owner/repo)CODECOV_URL: Custom Codecov endpoint URLThis package is deprecated and scheduled for removal. Users should migrate to the new Codecov uploader:
The deprecated package will stop working on February 1, 2022 and beyond.