Interrogate a codebase for docstring coverage.
—
Creates SVG and PNG badges displaying docstring coverage percentages. Supports multiple badge styles and automatic color coding based on coverage thresholds, ideal for displaying in README files and documentation.
Primary function for creating coverage badges with automatic formatting and color selection.
def create(
output: str,
result: BaseInterrogateResult,
output_format: Optional[str] = None,
output_style: Optional[str] = None
) -> str:
"""
Create a coverage badge and save to file.
Args:
output: Output file path or directory
result: Coverage results to display
output_format: Badge format ("svg" or "png", auto-detected from extension)
output_style: Badge style ("flat", "flat-square", "for-the-badge", "plastic")
Returns:
str: Path to created badge file
Raises:
OSError: If output directory is not writable
ValueError: If invalid format or style specified
"""Functions for generating badge SVG content and determining appropriate colors.
def get_badge(result, color, style=None):
"""
Generate SVG badge content.
Args:
result: Coverage percentage as float
color: Badge color (hex code or CSS color name)
style: Badge style ("flat", "flat-square", "flat-square-modified", "for-the-badge", "plastic", "social")
Returns:
str: SVG badge content as string
"""
def get_color(result):
"""
Get appropriate color for coverage percentage.
Args:
result: Coverage percentage as float
Returns:
str: Color hex code based on coverage threshold
"""Functions for saving badges and determining generation requirements.
def save_badge(badge, output, output_format=None):
"""
Save badge content to file.
Args:
badge: SVG badge content
output: Output file path
output_format: Force format ("svg" or "png", auto-detected if None)
Raises:
ImportError: If PNG format requested but cairosvg not installed
OSError: If file cannot be written
"""
def should_generate_badge(output, color, result):
"""
Determine if badge should be generated based on output and results.
Args:
output: Output path or directory
color: Badge color
result: Coverage percentage as float
Returns:
bool: True if badge should be generated
"""DEFAULT_FILENAME = "interrogate_badge"
COLORS = {
"brightgreen": "#4c1",
"green": "#97CA00",
"yellowgreen": "#a4a61d",
"yellow": "#dfb317",
"orange": "#fe7d37",
"red": "#e05d44",
"lightgrey": "#9f9f9f"
}
COLOR_RANGES = [
(95, "brightgreen"),
(90, "green"),
(75, "yellowgreen"),
(60, "yellow"),
(40, "orange"),
(0, "red")
]
SUPPORTED_OUTPUT_FORMATS = ["svg", "png"]from interrogate.badge_gen import create
from interrogate.coverage import InterrogateCoverage
from interrogate.config import InterrogateConfig
# Run coverage analysis
config = InterrogateConfig(paths=["src/"])
coverage = InterrogateCoverage(config.paths, config)
results = coverage.get_coverage()
# Create SVG badge
badge_path = create("docs/coverage.svg", results)
print(f"Badge created: {badge_path}")
# Create PNG badge (requires cairosvg)
badge_path = create("docs/coverage.png", results, output_format="png")
print(f"PNG badge created: {badge_path}")from interrogate.badge_gen import create
from interrogate.coverage import InterrogateCoverage
from interrogate.config import InterrogateConfig
config = InterrogateConfig(paths=["src/"])
coverage = InterrogateCoverage(config.paths, config)
results = coverage.get_coverage()
# Create badges with different styles
styles = ["flat", "flat-square", "for-the-badge", "plastic"]
for style in styles:
badge_path = create(f"docs/badge_{style}.svg", results, output_style=style)
print(f"Created {style} badge: {badge_path}")from interrogate.badge_gen import get_badge, get_color, save_badge
from interrogate.coverage import BaseInterrogateResult
# Create mock results
class MockResults(BaseInterrogateResult):
def __init__(self, percentage):
self.total = 100
self.covered = int(percentage)
self.missing = 100 - int(percentage)
self.perc_covered = percentage
# Generate custom badge
results = MockResults(87.5)
color = get_color(results) # Auto-select color based on percentage
badge_svg = get_badge(results, color, style="flat-square")
# Save to file
save_badge(badge_svg, "custom_badge.svg")
print(f"Custom badge created with {results.perc_covered}% coverage")from interrogate.badge_gen import create, get_badge
from interrogate.coverage import InterrogateCoverage
from interrogate.config import InterrogateConfig
config = InterrogateConfig(paths=["src/"])
coverage = InterrogateCoverage(config.paths, config)
results = coverage.get_coverage()
# Create badge with custom color
badge_svg = get_badge(results, "#ff6b35", style="for-the-badge") # Custom orange
with open("docs/custom_color_badge.svg", "w") as f:
f.write(badge_svg)
# Available predefined colors
predefined_colors = ["brightgreen", "green", "yellowgreen", "yellow", "orange", "red", "lightgrey"]
for color in predefined_colors:
badge_svg = get_badge(results, color)
with open(f"docs/badge_{color}.svg", "w") as f:
f.write(badge_svg)from interrogate.badge_gen import should_generate_badge, create
from interrogate.coverage import InterrogateCoverage
from interrogate.config import InterrogateConfig
config = InterrogateConfig(paths=["src/"])
coverage = InterrogateCoverage(config.paths, config)
results = coverage.get_coverage()
# Only generate badge if needed
output_path = "docs/coverage.svg"
if should_generate_badge(output_path, "auto", results):
badge_path = create(output_path, results)
print(f"Badge generated: {badge_path}")
else:
print("Badge generation skipped")import os
from interrogate.badge_gen import create
from interrogate.coverage import InterrogateCoverage
from interrogate.config import InterrogateConfig
def generate_coverage_badge():
"""Generate coverage badge for CI/CD pipeline."""
# Configure for CI environment
config = InterrogateConfig(
paths=["src/"],
ignore_init_method=True,
ignore_private=True,
fail_under=80.0
)
# Run analysis
coverage = InterrogateCoverage(config.paths, config)
results = coverage.get_coverage()
# Generate badge
badge_path = create("docs/coverage.svg", results, output_style="flat")
# Print results for CI logs
print(f"Coverage: {results.perc_covered:.1f}%")
print(f"Badge created: {badge_path}")
# Exit with error code if below threshold
if results.ret_code != 0:
print(f"Coverage {results.perc_covered:.1f}% below required {config.fail_under}%")
return results.ret_code
return 0
if __name__ == "__main__":
exit_code = generate_coverage_badge()
exit(exit_code)from interrogate.badge_gen import create
from interrogate.coverage import InterrogateCoverage
from interrogate.config import InterrogateConfig
# Note: PNG generation requires cairosvg package
# Install with: pip install interrogate[png]
config = InterrogateConfig(paths=["src/"])
coverage = InterrogateCoverage(config.paths, config)
results = coverage.get_coverage()
try:
# Create PNG badge
badge_path = create("docs/coverage.png", results, output_format="png")
print(f"PNG badge created: {badge_path}")
except ImportError:
print("PNG generation requires cairosvg. Install with: pip install interrogate[png]")
# Fallback to SVG
badge_path = create("docs/coverage.svg", results)
print(f"SVG badge created instead: {badge_path}")Install with Tessl CLI
npx tessl i tessl/pypi-interrogate