Quellcode für findfmt.formatters.structured
"""Structured data serializers (JSON, JSONL, YAML, IPYNB)."""
from __future__ import annotations
import json
import sys
from typing import TYPE_CHECKING, Any, TextIO
if sys.version_info >= (3, 12):
from typing import override
else:
from typing_extensions import override
import yaml
from findfmt.formatters.base import Formatter, write_stream_safe
if TYPE_CHECKING:
from collections.abc import Iterable
from findfmt.models import FileInfo
__all__ = [
"IpynbFormatter",
"JsonFormatter",
"JsonlFormatter",
"YamlFormatter",
"escape_surrogates",
]
_SURROGATE_MIN = 0xD800
_SURROGATE_MAX = 0xDFFF
def escape_surrogates(text: str) -> str:
r"""Escape Unicode surrogates as \uXXXX for valid UTF-8/ASCII serialization.
Args:
text: String potentially containing surrogate code points (0xD800-0xDFFF).
Returns:
String with surrogates replaced by ASCII escape sequences.
"""
if not any(_SURROGATE_MIN <= ord(c) <= _SURROGATE_MAX for c in text):
return text
return "".join(f"\\u{ord(c):04x}" if _SURROGATE_MIN <= ord(c) <= _SURROGATE_MAX else c for c in text)
[Doku]
class JsonFormatter(Formatter):
"""Deterministic JSON array formatter with configurable indentation."""
[Doku]
def __init__(
self,
*,
absolute: bool = False,
indent: int | None = 2,
no_indent: bool = False,
) -> None:
"""Initialize JsonFormatter.
Args:
absolute: Whether to emit absolute paths.
indent: Indentation spaces for pretty-printing, or None for compact.
no_indent: Whether to suppress indentation and emit compact JSON.
"""
super().__init__(absolute=absolute)
self.indent = None if no_indent else indent
self.no_indent = no_indent
[Doku]
@override
def format(self, files: Iterable[FileInfo]) -> str:
"""Format FileInfo objects into a deterministic JSON array.
Args:
files: Iterable of classified file objects.
Returns:
JSON array string ending with a newline.
"""
records = [f.to_dict(absolute=self.absolute) for f in files]
return escape_surrogates(json.dumps(records, indent=self.indent, ensure_ascii=False)) + "\n"
[Doku]
class JsonlFormatter(Formatter):
"""Line-delimited JSON (NDJSON) record serializer for streaming pipelines."""
[Doku]
def __init__(self, *, absolute: bool = False) -> None:
"""Initialize JsonlFormatter.
Args:
absolute: Whether to emit absolute paths.
"""
super().__init__(absolute=absolute)
[Doku]
def format_item(self, file_info: FileInfo) -> str:
"""Serialize a single FileInfo item to a compact JSON line.
Args:
file_info: Classified file information.
Returns:
Single line JSON string ending with a newline.
"""
data = file_info.to_dict(absolute=self.absolute)
return escape_surrogates(json.dumps(data, ensure_ascii=False)) + "\n"
[Doku]
@override
def format(self, files: Iterable[FileInfo]) -> str:
"""Format an iterable of FileInfo objects into line-delimited JSON.
Args:
files: Iterable of classified file objects.
Returns:
Concatenated JSON lines string.
"""
return "".join(self.format_item(f) for f in files)
[Doku]
@override
def stream(self, files: Iterable[FileInfo], stream: TextIO) -> None:
"""Stream FileInfo records as JSON lines directly to the output stream.
Args:
files: Iterable of classified file objects.
stream: Target text stream.
"""
for file_info in files:
write_stream_safe(stream, self.format_item(file_info))
stream.flush()
[Doku]
class YamlFormatter(Formatter):
"""Block-style YAML document serializer using PyYAML."""
[Doku]
def __init__(
self,
*,
absolute: bool = False,
indent: int = 2,
no_indent: bool = False,
) -> None:
"""Initialize YamlFormatter.
Args:
absolute: Whether to emit absolute paths.
indent: Indentation spaces for nested YAML structures.
no_indent: Whether to suppress indentation and emit compact YAML.
"""
super().__init__(absolute=absolute)
self.indent = 0 if no_indent else indent
self.no_indent = no_indent
[Doku]
@override
def format(self, files: Iterable[FileInfo]) -> str:
"""Format FileInfo objects into a clean YAML document string.
Args:
files: Iterable of classified file objects.
Returns:
YAML document string ending with a newline.
"""
records = [f.to_dict(absolute=self.absolute) for f in files]
return str(
yaml.safe_dump(
records,
sort_keys=False,
indent=self.indent,
allow_unicode=True,
default_flow_style=False,
),
)
def _json_string_literal(payload: str) -> str:
r"""Embed a JSON payload as a raw Python string literal.
``json.dumps`` escapes every double quote, so a raw triple-quoted literal can never
be terminated early by the payload; the payload also always ends with ``]``, so the
literal never ends on a backslash. The result can therefore be spliced into generated
Python source and handed to ``json.loads`` without any quoting analysis.
Args:
payload: JSON text produced by :func:`json.dumps`.
Returns:
Raw triple-quoted Python string literal containing ``payload``.
"""
return f'r"""{payload}"""'
[Doku]
class IpynbFormatter(Formatter):
"""Jupyter Notebook v4 JSON serializer pre-populated with analysis code."""
[Doku]
def __init__(self, *, absolute: bool = False) -> None:
"""Initialize IpynbFormatter.
Args:
absolute: Whether to emit absolute paths.
"""
super().__init__(absolute=absolute)
[Doku]
@override
def format(self, files: Iterable[FileInfo]) -> str:
"""Format FileInfo objects into a valid Jupyter Notebook v4 JSON string.
Args:
files: Iterable of classified file objects.
Returns:
Formatted Jupyter Notebook JSON string.
"""
records = [f.to_dict(absolute=self.absolute) for f in files]
manifest_literal = escape_surrogates(json.dumps(records, indent=2, ensure_ascii=False))
cells: list[dict[str, Any]] = [
{
"cell_type": "markdown",
"id": "intro",
"metadata": {},
"source": [
"# findfmt File Discovery Report\n",
"\n",
"Discovered files manifest generated by `findfmt`.\n",
],
},
{
"cell_type": "code",
"execution_count": None,
"id": "manifest-data",
"metadata": {},
"outputs": [],
"source": (
"import json\n"
"import pandas as pd\n\n"
"# Discovered files manifest\n"
f"FILES = json.loads({_json_string_literal(manifest_literal)})\n\n"
"# Ingest into pandas DataFrame\n"
"df = pd.DataFrame(FILES)\n\n"
"# Optional: Ingest into polars DataFrame\n"
"# import polars as pl\n"
"# pl_df = pl.DataFrame(FILES)\n\n"
"df.head()\n"
).splitlines(keepends=True),
},
{
"cell_type": "code",
"execution_count": None,
"id": "analysis",
"metadata": {},
"outputs": [],
"source": (
"# Summary statistics\n"
'print(f"Total matched files: {len(df)}")\n'
'if not df.empty and "tags" in df.columns:\n'
' print("\\nTop classification tags:")\n'
' print(df.explode("tags")["tags"].value_counts().head(10))\n'
'if not df.empty and "mime_type" in df.columns:\n'
' print("\\nTop MIME types:")\n'
' print(df["mime_type"].value_counts().head(10))\n'
).splitlines(keepends=True),
},
]
notebook: dict[str, Any] = {
"cells": cells,
"metadata": {
"language_info": {
"name": "python",
"version": "3",
},
},
"nbformat": 4,
"nbformat_minor": 5,
}
return escape_surrogates(json.dumps(notebook, indent=1, ensure_ascii=False)) + "\n"