Fix export handlers and search engine - add ExportHandler class and fix SearchEngine

This commit is contained in:
2026-03-22 11:48:04 +00:00
parent f79e9425a9
commit c86536dff9

View File

@@ -2,37 +2,91 @@
import json import json
from datetime import datetime from datetime import datetime
from pathlib import Path
from typing import Any from typing import Any
from snip.db.database import Database from snip.db.database import Database, get_database
def export_snippets(snippets: list[dict[str, Any]], file_path: str): class ExportHandler:
"""Export snippets to a JSON file.""" def __init__(self, db_path: str | None = None):
export_data = { self.db = get_database(db_path)
"version": "1.0",
"exported_at": datetime.utcnow().isoformat() + "Z",
"snippets": snippets,
}
with open(file_path, "w") as f: def export_all(self) -> dict[str, Any]:
json.dump(export_data, f, indent=2) """Export all snippets."""
snippets = self.db.list_snippets(limit=10000)
for s in snippets:
if isinstance(s.get("tags"), str):
s["tags"] = json.loads(s["tags"])
return {
"version": "1.0",
"exported_at": datetime.utcnow().isoformat() + "Z",
"snippets": snippets,
}
def export_collection(self, collection_id: int) -> dict[str, Any]:
"""Export a specific collection."""
snippets = self.db.get_collection_snippets(collection_id)
for s in snippets:
if isinstance(s.get("tags"), str):
s["tags"] = json.loads(s["tags"])
return {
"version": "1.0",
"exported_at": datetime.utcnow().isoformat() + "Z",
"snippets": snippets,
}
def import_snippets(db: Database, file_path: str, strategy: str = "skip") -> tuple[int, int]: def export_snippet(self, snippet_id: int) -> dict[str, Any] | None:
"""Import snippets from a JSON file.""" """Export a single snippet."""
with open(file_path, "r") as f: snippet = self.db.get_snippet(snippet_id)
data = json.load(f) if not snippet:
return None
if isinstance(snippet.get("tags"), str):
snippet["tags"] = json.loads(snippet["tags"])
return {
"version": "1.0",
"exported_at": datetime.utcnow().isoformat() + "Z",
"snippets": [snippet],
}
snippets = data.get("snippets", []) def write_export(self, file_path: str, data: dict[str, Any]):
imported = 0 """Write export data to a file."""
skipped = 0 Path(file_path).parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w") as f:
json.dump(data, f, indent=2)
for snippet_data in snippets: def import_data(self, file_path: str, strategy: str = "skip") -> dict[str, Any]:
result = db.import_snippet(snippet_data, strategy=strategy) """Import snippets from a JSON file."""
if result is None: with open(file_path, "r") as f:
skipped += 1 data = json.load(f)
else:
imported += 1
return imported, skipped snippets = data.get("snippets", [])
imported = 0
skipped = 0
replaced = 0
for snippet_data in snippets:
result = self.db.import_snippet(snippet_data, strategy=strategy)
if result is None:
skipped += 1
elif result == -1:
replaced += 1
else:
imported += 1
return {
"imported": imported,
"skipped": skipped,
"replaced": replaced,
"total": len(snippets),
}
def generate_import_summary(self, results: dict[str, Any]) -> str:
"""Generate a human-readable import summary."""
lines = [
f"Import complete!",
f" Imported: {results.get('imported', 0)}",
f" Skipped: {results.get('skipped', 0)}",
f" Replaced: {results.get('replaced', 0)}",
]
return "\n".join(lines)