Skip to content

markdown_reporter

Full name: tenets.core.reporting.markdown_reporter

markdown_reporter

Markdown report generator module.

This module provides Markdown report generation functionality for creating plain text reports that can be viewed in any text editor, converted to other formats, or integrated with documentation systems.

The Markdown reporter generates clean, readable reports with support for tables, code blocks, and structured content.

Classes

MarkdownReporter

Python
MarkdownReporter(config: TenetsConfig)

Markdown report generator.

Generates Markdown-formatted reports from analysis results, suitable for documentation, GitHub, and other Markdown-supporting platforms.

ATTRIBUTEDESCRIPTION
config

Configuration object

logger

Logger instance

toc_entries

Table of contents entries

TYPE:List[str]

Initialize Markdown reporter.

PARAMETERDESCRIPTION
config

TenetsConfig instance

TYPE:TenetsConfig

Source code in tenets/core/reporting/markdown_reporter.py
Python
def __init__(self, config: TenetsConfig):
    """Initialize Markdown reporter.

    Args:
        config: TenetsConfig instance
    """
    self.config = config
    self.logger = get_logger(__name__)
    self.toc_entries: List[str] = []
Functions
generate
Python
generate(sections: List[ReportSection], metadata: Dict[str, Any], output_path: Path, report_config: ReportConfig) -> Path

Generate Markdown report.

PARAMETERDESCRIPTION
sections

Report sections

TYPE:List[ReportSection]

metadata

Report metadata

TYPE:Dict[str, Any]

output_path

Output file path

TYPE:Path

report_config

Report configuration

TYPE:ReportConfig

RETURNSDESCRIPTION
Path

Path to generated report

TYPE:Path

Example

reporter = MarkdownReporter(config) report_path = reporter.generate( ... sections, ... metadata, ... Path("report.md") ... )

Source code in tenets/core/reporting/markdown_reporter.py
Python
def generate(
    self,
    sections: List[ReportSection],
    metadata: Dict[str, Any],
    output_path: Path,
    report_config: ReportConfig,
) -> Path:
    """Generate Markdown report.

    Args:
        sections: Report sections
        metadata: Report metadata
        output_path: Output file path
        report_config: Report configuration

    Returns:
        Path: Path to generated report

    Example:
        >>> reporter = MarkdownReporter(config)
        >>> report_path = reporter.generate(
        ...     sections,
        ...     metadata,
        ...     Path("report.md")
        ... )
    """
    self.logger.debug(f"Generating Markdown report to {output_path}")

    # Reset TOC entries
    self.toc_entries = []

    # Generate Markdown content
    markdown_content = self._generate_markdown(sections, metadata, report_config)

    # Write to file
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(markdown_content)

    self.logger.info(f"Markdown report generated: {output_path}")
    return output_path

Functions

create_markdown_report

Python
create_markdown_report(sections: List[ReportSection], output_path: Path, title: str = 'Code Analysis Report', config: Optional[TenetsConfig] = None) -> Path

Convenience function to create Markdown report.

PARAMETERDESCRIPTION
sections

Report sections

TYPE:List[ReportSection]

output_path

Output path

TYPE:Path

title

Report title

TYPE:strDEFAULT:'Code Analysis Report'

config

Optional configuration

TYPE:Optional[TenetsConfig]DEFAULT:None

RETURNSDESCRIPTION
Path

Path to generated report

TYPE:Path

Example

from tenets.core.reporting.markdown_reporter import create_markdown_report report_path = create_markdown_report( ... sections, ... Path("report.md"), ... title="Analysis Report" ... )

Source code in tenets/core/reporting/markdown_reporter.py
Python
def create_markdown_report(
    sections: List[ReportSection],
    output_path: Path,
    title: str = "Code Analysis Report",
    config: Optional[TenetsConfig] = None,
) -> Path:
    """Convenience function to create Markdown report.

    Args:
        sections: Report sections
        output_path: Output path
        title: Report title
        config: Optional configuration

    Returns:
        Path: Path to generated report

    Example:
        >>> from tenets.core.reporting.markdown_reporter import create_markdown_report
        >>> report_path = create_markdown_report(
        ...     sections,
        ...     Path("report.md"),
        ...     title="Analysis Report"
        ... )
    """
    if config is None:
        config = TenetsConfig()

    reporter = MarkdownReporter(config)
    report_config = ReportConfig(title=title, format="markdown")
    metadata = {"title": title, "generated_at": datetime.now().isoformat()}

    return reporter.generate(sections, metadata, output_path, report_config)

format_markdown_table

Python
format_markdown_table(headers: List[str], rows: List[List[Any]], alignment: Optional[List[str]] = None) -> str

Format data as a Markdown table.

PARAMETERDESCRIPTION
headers

Table headers

TYPE:List[str]

rows

Table rows

TYPE:List[List[Any]]

alignment

Column alignment (left, right, center)

TYPE:Optional[List[str]]DEFAULT:None

RETURNSDESCRIPTION
str

Formatted Markdown table

TYPE:str

Example

from tenets.core.reporting.markdown_reporter import format_markdown_table table = format_markdown_table( ... ["Name", "Value", "Status"], ... [["Test", 42, "Pass"], ["Demo", 17, "Fail"]] ... ) print(table)

Source code in tenets/core/reporting/markdown_reporter.py
Python
def format_markdown_table(
    headers: List[str], rows: List[List[Any]], alignment: Optional[List[str]] = None
) -> str:
    """Format data as a Markdown table.

    Args:
        headers: Table headers
        rows: Table rows
        alignment: Column alignment (left, right, center)

    Returns:
        str: Formatted Markdown table

    Example:
        >>> from tenets.core.reporting.markdown_reporter import format_markdown_table
        >>> table = format_markdown_table(
        ...     ["Name", "Value", "Status"],
        ...     [["Test", 42, "Pass"], ["Demo", 17, "Fail"]]
        ... )
        >>> print(table)
    """
    if not headers or not rows:
        return ""

    lines = []

    # Calculate column widths
    widths = [len(str(h)) for h in headers]
    for row in rows:
        for i, cell in enumerate(row):
            widths[i] = max(widths[i], len(str(cell)))

    # Format headers
    header_parts = []
    for i, header in enumerate(headers):
        header_parts.append(str(header).ljust(widths[i]))
    lines.append("| " + " | ".join(header_parts) + " |")

    # Format separator with alignment
    separator_parts = []
    for i, width in enumerate(widths):
        sep = "-" * width
        if alignment and i < len(alignment):
            align = alignment[i].lower()
            if align == "center":
                sep = ":" + sep[1:-1] + ":"
            elif align == "right":
                sep = sep[:-1] + ":"
            elif align == "left":
                sep = ":" + sep[1:]
        separator_parts.append(sep)
    lines.append("|" + "|".join(separator_parts) + "|")

    # Format rows
    for row in rows:
        row_parts = []
        for i, cell in enumerate(row):
            if i < len(widths):
                cell_str = str(cell)
                if alignment and i < len(alignment):
                    align = alignment[i].lower()
                    if align == "right":
                        row_parts.append(cell_str.rjust(widths[i]))
                    elif align == "center":
                        row_parts.append(cell_str.center(widths[i]))
                    else:
                        row_parts.append(cell_str.ljust(widths[i]))
                else:
                    row_parts.append(cell_str.ljust(widths[i]))
        lines.append("| " + " | ".join(row_parts) + " |")

    return "\n".join(lines)

create_markdown_summary

Python
create_markdown_summary(analysis_results: Dict[str, Any], max_length: int = 1000) -> str

Create a Markdown summary of analysis results.

PARAMETERDESCRIPTION
analysis_results

Analysis results

TYPE:Dict[str, Any]

max_length

Maximum length in characters

TYPE:intDEFAULT:1000

RETURNSDESCRIPTION
str

Markdown summary

TYPE:str

Example

from tenets.core.reporting.markdown_reporter import create_markdown_summary summary = create_markdown_summary(analysis_results) print(summary)

Source code in tenets/core/reporting/markdown_reporter.py
Python
def create_markdown_summary(analysis_results: Dict[str, Any], max_length: int = 1000) -> str:
    """Create a Markdown summary of analysis results.

    Args:
        analysis_results: Analysis results
        max_length: Maximum length in characters

    Returns:
        str: Markdown summary

    Example:
        >>> from tenets.core.reporting.markdown_reporter import create_markdown_summary
        >>> summary = create_markdown_summary(analysis_results)
        >>> print(summary)
    """
    lines = []

    # Title
    lines.append("# Code Analysis Summary")
    lines.append("")

    # Quick stats
    lines.append("## Quick Stats")
    lines.append("")

    if "overview" in analysis_results:
        overview = analysis_results["overview"]
        lines.append(f"- **Files:** {overview.get('total_files', 0)}")
        lines.append(f"- **Lines:** {overview.get('total_lines', 0):,}")
        lines.append(f"- **Health Score:** {overview.get('health_score', 0):.1f}/100")

    lines.append("")

    # Top issues
    if "issues" in analysis_results:
        issues = analysis_results["issues"]
        critical = sum(1 for i in issues if i.get("severity") == "critical")
        high = sum(1 for i in issues if i.get("severity") == "high")

        if critical > 0 or high > 0:
            lines.append("## Critical Issues")
            lines.append("")
            if critical > 0:
                lines.append(f"- 🚨 **{critical} critical issues** found")
            if high > 0:
                lines.append(f"- ⚠️ **{high} high priority issues** found")
            lines.append("")

    # Top recommendations
    if "recommendations" in analysis_results:
        lines.append("## Top Recommendations")
        lines.append("")

        for i, rec in enumerate(analysis_results["recommendations"][:3], 1):
            if isinstance(rec, dict):
                lines.append(f"{i}. {rec.get('action', rec)}")
            else:
                lines.append(f"{i}. {rec}")
        lines.append("")

    # Truncate if needed
    result = "\n".join(lines)
    if len(result) > max_length:
        result = result[: max_length - 3] + "..."

    return result