Add graph, analyzers, and exporters modules
This commit is contained in:
88
src/exporters/json_exporter.py
Normal file
88
src/exporters/json_exporter.py
Normal file
@@ -0,0 +1,88 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
from src.graph.builder import GraphBuilder
|
||||
|
||||
|
||||
class JSONExporter:
|
||||
def __init__(self, graph_builder: GraphBuilder):
|
||||
self.graph_builder = graph_builder
|
||||
|
||||
def export(self, output_path: Path, include_code: bool = False) -> None:
|
||||
data = self._build_export_data(include_code)
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
def get_string(self, include_code: bool = False) -> str:
|
||||
data = self._build_export_data(include_code)
|
||||
return json.dumps(data, indent=2)
|
||||
|
||||
def _build_export_data(self, include_code: bool) -> dict:
|
||||
graph_data = self.graph_builder.serialize()
|
||||
|
||||
nodes = []
|
||||
for node_data in graph_data["nodes"]:
|
||||
node = {
|
||||
"id": node_data["id"],
|
||||
"type": node_data["type"],
|
||||
"name": node_data["name"],
|
||||
"label": node_data.get("label", node_data["name"]),
|
||||
}
|
||||
if node_data.get("file_path"):
|
||||
node["file_path"] = node_data["file_path"]
|
||||
if node_data.get("start_line"):
|
||||
node["start_line"] = node_data["start_line"]
|
||||
node["end_line"] = node_data["end_line"]
|
||||
nodes.append(node)
|
||||
|
||||
edges = []
|
||||
for edge_data in graph_data["edges"]:
|
||||
edge = {
|
||||
"source": edge_data["source"],
|
||||
"target": edge_data["target"],
|
||||
"type": edge_data.get("type", "depends"),
|
||||
}
|
||||
if edge_data.get("label"):
|
||||
edge["label"] = edge_data["label"]
|
||||
edges.append(edge)
|
||||
|
||||
return {
|
||||
"version": "1.0",
|
||||
"graph_type": "knowledge_graph",
|
||||
"nodes": nodes,
|
||||
"edges": edges,
|
||||
"statistics": {
|
||||
"total_nodes": len(nodes),
|
||||
"total_edges": len(edges),
|
||||
},
|
||||
}
|
||||
|
||||
def export_for_d3(self, output_path: Path) -> None:
|
||||
graph_data = self.graph_builder.serialize()
|
||||
|
||||
nodes = []
|
||||
for node_data in graph_data["nodes"]:
|
||||
nodes.append({
|
||||
"id": node_data["id"],
|
||||
"name": node_data["name"],
|
||||
"type": node_data["type"],
|
||||
})
|
||||
|
||||
links = []
|
||||
for edge_data in graph_data["edges"]:
|
||||
links.append({
|
||||
"source": edge_data["source"],
|
||||
"target": edge_data["target"],
|
||||
"type": edge_data.get("type", "depends"),
|
||||
})
|
||||
|
||||
d3_data = {
|
||||
"nodes": nodes,
|
||||
"links": links,
|
||||
}
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(d3_data, f, indent=2)
|
||||
Reference in New Issue
Block a user