"""Markup documentation table serializers (Markdown, reStructuredText)."""
from __future__ import annotations
import sys
from typing import TYPE_CHECKING, TextIO
if sys.version_info >= (3, 12):
from typing import override
else:
from typing_extensions import override
from findfmt.exceptions import UnsupportedTableStyleError
from findfmt.formatters.base import TABLE_FIELD_NAMES, Formatter, write_stream_safe
from findfmt.formatters.delimited import file_to_record
from findfmt.utils.strings import (
cell_width,
mask_control_characters,
pad_to_cell_width,
strip_ansi_escapes,
)
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from findfmt.models import FileInfo
__all__ = [
"MarkdownFormatter",
"RstFormatter",
"UnsupportedTableStyleError",
"escape_markdown_cell",
"escape_rst_cell",
]
_MARKDOWN_ALIGNMENTS: tuple[str, ...] = (
"left", # path
"left", # relative_path
"left", # tags
"left", # mime_type
"left", # shebang
"center", # is_executable
"center", # is_symlink
"right", # size_bytes
)
def escape_markdown_cell(cell: str) -> str:
"""Escape special characters, HTML metacharacters, and controls in a Markdown table cell."""
clean = strip_ansi_escapes(cell)
escaped = (
clean.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\\", "\\\\")
.replace("|", "\\|")
.replace("`", "\\`")
.replace("\t", " ")
.replace("\r\n", " ")
.replace("\n", " ")
.replace("\r", " ")
)
return mask_control_characters(escaped)
def escape_rst_cell(cell: str) -> str:
"""Escape special characters in a reStructuredText table cell."""
clean = strip_ansi_escapes(cell)
escaped = (
clean.replace("|", "\\|")
.replace("`", "\\`")
.replace("\t", " ")
.replace("\r\n", " ")
.replace("\n", " ")
.replace("\r", " ")
)
return mask_control_characters(escaped)
def _pad_cell(cell: str, width: int, alignment: str) -> str:
"""Pad a cell string according to its alignment specification respecting terminal cell width."""
return pad_to_cell_width(cell, width, align=alignment)
def _make_markdown_separator(width: int, alignment: str) -> str:
"""Construct a GFM column alignment indicator."""
if alignment == "center":
return f":{'-' * max(3, width - 2)}:"
if alignment == "right":
return f"{'-' * max(3, width - 1)}:"
return f":{'-' * max(3, width - 1)}"
def _compute_markdown_col_widths(rows: Sequence[Sequence[str]]) -> list[int]:
"""Calculate column widths for a GFM table respecting terminal cell width."""
min_widths = [5 if align == "center" else 4 for align in _MARKDOWN_ALIGNMENTS]
widths: list[int] = []
for idx, header in enumerate(TABLE_FIELD_NAMES):
max_data = max((cell_width(r[idx]) for r in rows), default=0)
widths.append(max(cell_width(header), min_widths[idx], max_data))
return widths
def _render_markdown_row(cells: Sequence[str], col_widths: Sequence[int]) -> str:
"""Format a single row of cells into a Markdown table line."""
padded = [_pad_cell(cell, col_widths[i], _MARKDOWN_ALIGNMENTS[i]) for i, cell in enumerate(cells)]
return f"| {' | '.join(padded)} |"
def _format_rst_grid(
headers: Sequence[str],
rows: Sequence[Sequence[str]],
col_widths: Sequence[int],
) -> str:
"""Render a reStructuredText grid table respecting terminal cell width."""
row_border = "+" + "+".join("-" * (w + 2) for w in col_widths) + "+"
head_border = "+" + "+".join("=" * (w + 2) for w in col_widths) + "+"
header_line = (
"| "
+ " | ".join(pad_to_cell_width(h, w, align="left") for h, w in zip(headers, col_widths, strict=True))
+ " |"
)
lines = [row_border, header_line, head_border]
for row in rows:
row_line = (
"| "
+ " | ".join(
pad_to_cell_width(cell, w, align="left") for cell, w in zip(row, col_widths, strict=True)
)
+ " |"
)
lines.append(row_line)
lines.append(row_border)
if not rows:
lines.append(row_border)
return "\n".join(lines) + "\n"
def _format_rst_simple(
headers: Sequence[str],
rows: Sequence[Sequence[str]],
col_widths: Sequence[int],
) -> str:
"""Render a reStructuredText simple table respecting terminal cell width."""
border = " ".join("=" * w for w in col_widths)
header_line = " ".join(
pad_to_cell_width(h, w, align="left") for h, w in zip(headers, col_widths, strict=True)
)
lines = [border, header_line, border]
for row in rows:
row_line = " ".join(
pad_to_cell_width(cell, w, align="left") for cell, w in zip(row, col_widths, strict=True)
)
lines.append(row_line)
lines.append(border)
return "\n".join(lines) + "\n"