CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-codecov

Hosted coverage reports for GitHub, Bitbucket and Gitlab (deprecated)

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

Codecov Python Uploader

⚠️ 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.

Package Information

  • Package Name: codecov
  • Language: Python
  • Installation: pip install codecov
  • Dependencies: requests>=2.7.9, coverage
  • License: Apache 2.0
  • Version: 2.1.13

Core Imports

import codecov

For direct function access:

from codecov import main, write, read, try_to_run

For 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

Basic Usage

Command Line Usage

# 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 upload

Command Line Interface Reference

The codecov CLI provides comprehensive upload configuration through command-line arguments organized in functional groups:

Basic Options

  • --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 Integration Options

  • --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

Advanced Configuration

  • -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)

Enterprise/Self-hosted Options

  • --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)

Debugging Options

  • --dump: Display collected data without uploading
  • -v, --verbose: Enable verbose output
  • --no-color: Disable colored terminal output

Programmatic Usage

import 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 data

Capabilities

Main Entry Point

Primary 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
    """

Console Output

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
    """

File Operations

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
    """

Command Execution

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
    """

Coverage Tool Integration

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
    """

File Discovery

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
    """

Repository Analysis

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
    """

HTTP Upload with Retry

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 Processing

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 Utilities

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
    """

Constants and Global Variables

Package Metadata

# 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"

Configuration

# Global color output control
COLOR: bool = True

Pattern Matching

# 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

Utility Aliases

# 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 performance

CI Provider Support

The package automatically detects and integrates with 15+ CI providers:

  • Travis CI: Comprehensive integration with build matrix support
  • CircleCI: Full build and workflow detection
  • Jenkins: GitHub pull request builder plugin support
  • GitHub Actions: Native workflow and PR detection
  • GitLab CI: Pipeline and merge request support
  • AppVeyor: Windows build environment support
  • Buildkite: Pipeline and job detection
  • Codeship: Build number and URL tracking
  • Drone.io: Build directory and link support
  • Shippable: Pull request and branch detection
  • Semaphore: Thread-aware build tracking
  • TeamCity: Version and build number detection
  • Wercker: Git integration and build tracking
  • Greenhouse: Pull request and build URL support
  • Cirrus CI: Task and build URL generation
  • Magnum: Branch and commit detection

Each provider is automatically detected through environment variables, with fallback to manual configuration.

Coverage Report Formats

Automatically detects and processes multiple coverage formats:

  • Python: coverage.py XML output, .coverage files
  • gcov: GNU coverage format (.gcov files)
  • LCOV: lcov.info format
  • Clover: clover.xml format (Java, C#)
  • Cobertura: cobertura.xml format
  • Jacoco: jacoco.xml format (Java)
  • JavaScript: coverage-final.json, coverage-summary.json

Error Handling

The package includes comprehensive error handling:

  • Missing Reports: Assertion error when no coverage reports found
  • CI Detection Failures: Graceful fallback to manual configuration
  • Upload Failures: Automatic retry with exponential backoff
  • File Reading Errors: Individual file failures don't stop execution
  • Network Issues: S3 upload fallback to direct HTTP endpoint

Environment Variables

Key environment variables for configuration:

  • CODECOV_TOKEN: Repository upload token
  • CODECOV_FLAGS: Comma-separated flags for report grouping
  • CODECOV_ENV: Environment variables to include in report
  • CODECOV_NAME: Custom name for upload
  • CODECOV_SLUG: Repository slug (owner/repo)
  • CODECOV_URL: Custom Codecov endpoint URL

Migration Notice

This 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.

Install with Tessl CLI

npx tessl i tessl/pypi-codecov

docs

index.md

tile.json