Source code for jsoncrack_for_sphinx.generators.rst_generator
"""RST generation utilities for JSON schemas."""importjsonfrompathlibimportPathfromtypingimportAny,Dict,Optional
[docs]defschema_to_rst(schema_path:Path,title:Optional[str]=None)->str:""" Convert a JSON schema file to reStructuredText format. This function is provided as a fixture for tests to convert schema files to reStructuredText format. Args: schema_path: Path to the JSON schema file title: Optional title for the schema section Returns: reStructuredText representation of the schema """ifnotschema_path.exists():raiseFileNotFoundError(f"Schema file not found: {schema_path}")try:# Read and validate JSON schemawithopen(schema_path,"r",encoding="utf-8")asf:schema_data=json.load(f)# Create simple HTML representation of schemahtml_content=_generate_simple_schema_html(schema_data)# Convert to RSTrst_lines=[]iftitle:rst_lines.extend([title,"="*len(title),"",])rst_lines.extend([".. raw:: html","",' <div class="json-schema-container">',f" {html_content}"," </div>","",])return"\n".join(rst_lines)exceptjson.JSONDecodeErrorase:raiseValueError(f"Invalid JSON in schema file {schema_path}: {e}")exceptExceptionase:raiseRuntimeError(f"Error processing schema file {schema_path}: {e}")
def_generate_simple_schema_html(schema_data:Dict[str,Any])->str:""" Generate simple HTML representation of a JSON schema. Args: schema_data: JSON schema data Returns: HTML string representing the schema """html_parts=[]# Add title if presentif"title"inschema_data:html_parts.append(f'<h3>{schema_data["title"]}</h3>')# Add description if presentif"description"inschema_data:html_parts.append(f'<p>{schema_data["description"]}</p>')# Add basic schema infohtml_parts.append('<div class="schema-info">')if"type"inschema_data:html_parts.append(f'<p><strong>Type:</strong> {schema_data["type"]}</p>')# Add properties if it's an object schemaifschema_data.get("type")=="object"and"properties"inschema_data:html_parts.append("<h4>Properties:</h4>")html_parts.append("<ul>")forprop_name,prop_infoinschema_data["properties"].items():prop_type=prop_info.get("type","unknown")prop_desc=prop_info.get("description","")is_required=prop_nameinschema_data.get("required",[])required_text=" (required)"ifis_requiredelse""prop_line=(f"<li><strong>{prop_name}</strong> "f"({prop_type}){required_text}")html_parts.append(prop_line)ifprop_desc:html_parts.append(f"<br>{prop_desc}")html_parts.append("</li>")html_parts.append("</ul>")# Add raw schema as collapsible sectionhtml_parts.append("<details>")html_parts.append("<summary>Raw Schema</summary>")html_parts.append("<pre>")html_parts.append(json.dumps(schema_data,indent=2))html_parts.append("</pre>")html_parts.append("</details>")html_parts.append("</div>")return"\n".join(html_parts)