113 lines
4.6 KiB
Python
113 lines
4.6 KiB
Python
"""Explicit local library import/rollback and read-only object_info snapshot CLI."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import hashlib
|
|
import json
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
from calliope.comfyui.companions import load_companions
|
|
from calliope.comfyui.delivery_scope import exclusion_for
|
|
from calliope.comfyui.library import import_library, load_snapshot, rollback_batch
|
|
from calliope.db import get_db, migrate_db
|
|
|
|
|
|
def write(path: Path, data: object) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
snap = commands.add_parser("snapshot")
|
|
snap.add_argument("--url", required=True)
|
|
snap.add_argument("--output", type=Path, required=True)
|
|
for command in ("import", "rollback"):
|
|
sub = commands.add_parser(command)
|
|
sub.add_argument(
|
|
"--db", type=Path, required=True, help="Explicit local database; never a remote service"
|
|
)
|
|
sub.add_argument("--output-dir", type=Path, required=True)
|
|
if command == "import":
|
|
sub.add_argument("--root", type=Path, required=True)
|
|
sub.add_argument("--source-commit", required=True)
|
|
sub.add_argument("--snapshot", type=Path)
|
|
sub.add_argument("--companions", type=Path)
|
|
else:
|
|
sub.add_argument("--batch-id", required=True)
|
|
args = parser.parse_args()
|
|
if args.command == "snapshot":
|
|
data = {
|
|
"source_url": args.url.rstrip("/") + "/object_info",
|
|
"captured_at": datetime.now(timezone.utc).isoformat(),
|
|
}
|
|
try:
|
|
response = httpx.get(data["source_url"], timeout=10, trust_env=False)
|
|
response.raise_for_status()
|
|
info = response.json()
|
|
if not isinstance(info, dict) or not info:
|
|
raise ValueError("object_info must be a nonempty object")
|
|
data.update(status="captured", object_info=info)
|
|
except (httpx.HTTPError, ValueError) as exc:
|
|
data.update(status="unavailable", error=f"{type(exc).__name__}: {exc}")
|
|
write(args.output, data)
|
|
print(data["status"])
|
|
if data["status"] != "captured":
|
|
raise SystemExit(1)
|
|
return
|
|
if args.command == "import" and not args.root.is_dir():
|
|
parser.error("--root 必须为存在的目录,避免误报空库成功")
|
|
snapshot = load_snapshot(args.snapshot) if args.command == "import" else None
|
|
companions = (
|
|
load_companions(args.companions) if args.command == "import" and args.companions else None
|
|
)
|
|
asyncio.run(migrate_db(args.db))
|
|
conn = get_db(args.db)
|
|
try:
|
|
if args.command == "import":
|
|
report = import_library(
|
|
conn,
|
|
args.root,
|
|
source_commit=args.source_commit,
|
|
snapshot=snapshot,
|
|
companions=companions,
|
|
)
|
|
documents = []
|
|
for row in conn.execute(
|
|
"SELECT source_repo_path, source_sha, import_state, doc_json "
|
|
"FROM workflows WHERE source_repo_path IS NOT NULL ORDER BY source_repo_path"
|
|
):
|
|
if exclusion_for(row["source_repo_path"]):
|
|
# Historical rows stay in the DB, outside current delivery exports.
|
|
continue
|
|
doc = json.loads(row["doc_json"])
|
|
key = hashlib.sha256(row["source_repo_path"].encode()).hexdigest()[:16]
|
|
write(args.output_dir / "documents" / (key + ".json"), doc)
|
|
documents.append(
|
|
{
|
|
"path": row["source_repo_path"],
|
|
"source_sha": row["source_sha"],
|
|
"state": row["import_state"],
|
|
"doc_done": bool(row["doc_json"] and doc["status"]["doc_done"]),
|
|
"source_review_scope": (doc.get("source_review") or {}).get("scope", []),
|
|
"document": "documents/" + key + ".json",
|
|
}
|
|
)
|
|
write(args.output_dir / "manifest.json", documents)
|
|
else:
|
|
report = rollback_batch(conn, args.batch_id)
|
|
write(args.output_dir / (args.command + "_report.json"), report)
|
|
print(json.dumps({k: v for k, v in report.items() if k != "files"}, ensure_ascii=False))
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|