Coverage for src/jsoncrack_for_sphinx/schema/schema_utils.py: 63%
38 statements
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-24 22:26 +0000
« prev ^ index » next coverage.py v7.10.0, created at 2025-07-24 22:26 +0000
1"""
2Schema file utilities and validation.
3"""
5import json
6from pathlib import Path
7from typing import Any, Dict, List
10def validate_schema_file(schema_path: Path) -> bool:
11 """
12 Validate that a schema file contains valid JSON.
14 Args:
15 schema_path: Path to the schema file
17 Returns:
18 True if the file contains valid JSON, False otherwise
19 """
20 try:
21 with open(schema_path, "r", encoding="utf-8") as f:
22 json.load(f)
23 return True
24 except (json.JSONDecodeError, FileNotFoundError):
25 return False
28def find_schema_files(schema_dir: Path, pattern: str = "*.schema.json") -> List[Path]:
29 """
30 Find all schema files in a directory matching a pattern.
32 Args:
33 schema_dir: Directory to search for schema files
34 pattern: Glob pattern to match schema files
36 Returns:
37 List of paths to schema files
38 """
39 if not schema_dir.exists():
40 return []
42 return list(schema_dir.glob(pattern))
45def get_schema_info(schema_path: Path) -> Dict[str, Any]:
46 """
47 Extract basic information from a schema file.
49 Args:
50 schema_path: Path to the schema file
52 Returns:
53 Dictionary containing schema information
54 """
55 if not schema_path.exists():
56 raise FileNotFoundError(f"Schema file not found: {schema_path}")
58 try:
59 with open(schema_path, "r", encoding="utf-8") as f:
60 schema_data = json.load(f)
62 info = {
63 "file_name": schema_path.name,
64 "title": schema_data.get("title", ""),
65 "description": schema_data.get("description", ""),
66 "type": schema_data.get("type", ""),
67 "properties": list(schema_data.get("properties", {}).keys()),
68 "required": schema_data.get("required", []),
69 }
71 return info
73 except json.JSONDecodeError:
74 # Return default values for invalid JSON
75 return {
76 "file_name": schema_path.name,
77 "title": "",
78 "description": "",
79 "type": "",
80 "properties": [],
81 "required": [],
82 }
83 except Exception:
84 # Return default values for other errors
85 return {
86 "file_name": schema_path.name,
87 "title": "",
88 "description": "",
89 "type": "",
90 "properties": [],
91 "required": [],
92 }
95def create_schema_index(schema_dir: Path) -> str:
96 """
97 Create an index of all schema files in a directory.
99 Args:
100 schema_dir: Directory containing schema files
102 Returns:
103 reStructuredText index of all schemas
104 """
105 schema_files = find_schema_files(schema_dir)
107 if not schema_files:
108 return "No schema files found."
110 rst_lines = [
111 "Schema Index",
112 "============",
113 "",
114 ]
116 for schema_file in sorted(schema_files):
117 try:
118 info = get_schema_info(schema_file)
119 rst_lines.extend(
120 [
121 f"**{info['file_name']}**",
122 "",
123 f" :Title: {info['title']}",
124 f" :Type: {info['type']}",
125 f" :Properties: {', '.join(info['properties'])}",
126 "",
127 ]
128 )
129 except Exception as e:
130 rst_lines.extend(
131 [
132 f"**{schema_file.name}** (Error: {e})",
133 "",
134 ]
135 )
137 return "\n".join(rst_lines)