Repository navigation
Expand file tree
/
Copy pathsnapshots_store.py
More file actions
208 lines (175 loc) · 6.64 KB
/
Copy pathsnapshots_store.py
File metadata and controls
208 lines (175 loc) · 6.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Named filesystem + CRG snapshots for compare (restore deferred)."""
from __future__ import annotations
import json
import shutil
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import workspace as workspace_mod
TOOL_DIR = Path(__file__).resolve().parent
def _data_path() -> Path:
return workspace_mod.get().data_path
def _snapshots_dir() -> Path:
return workspace_mod.get().snapshots_dir
def _utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _new_id() -> str:
return uuid.uuid4().hex[:10]
def _ensure_dir() -> Path:
dest = _snapshots_dir()
dest.mkdir(parents=True, exist_ok=True)
return dest
def _crg_dir_for_root(root: Path) -> Path:
return root / ".code-review-graph"
def list_snapshots() -> dict[str, Any]:
root = _ensure_dir()
items = []
for d in sorted(root.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True):
if not d.is_dir():
continue
man = d / "manifest.json"
if not man.is_file():
continue
try:
meta = json.loads(man.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
continue
items.append(meta)
return {"ok": True, "snapshots": items}
def create_snapshot(name: str, *, root: Path, crg_status: dict[str, Any] | None = None) -> dict[str, Any]:
data_path = _data_path()
if not data_path.is_file():
return {"ok": False, "error": "data.json missing — generate the graph first"}
sid = _new_id()
dest = _ensure_dir() / sid
dest.mkdir(parents=True, exist_ok=False)
fs_dest = dest / "filesystem.json"
shutil.copy2(data_path, fs_dest)
crg_src = _crg_dir_for_root(root)
crg_copied = False
if crg_src.is_dir():
try:
shutil.copytree(crg_src, dest / "code-review-graph", dirs_exist_ok=True)
crg_copied = True
except OSError as exc:
# Large indexes may fail; still keep FS snapshot
crg_copied = False
crg_error = str(exc)
else:
crg_error = None
else:
crg_error = "no .code-review-graph at root"
try:
fs_data = json.loads(fs_dest.read_text(encoding="utf-8"))
nodes = len(fs_data.get("nodes") or [])
edges = len(fs_data.get("edges") or [])
except (OSError, json.JSONDecodeError):
nodes = 0
edges = 0
st = crg_status or {}
manifest = {
"id": sid,
"name": (name or sid).strip()[:120],
"created_at": _utc_now(),
"filesystem": {"nodes": nodes, "edges": edges, "file": "filesystem.json"},
"crg": {
"copied": crg_copied,
"built_at_commit": st.get("built_at_commit") or st.get("commit"),
"node_count": st.get("node_count") or st.get("nodes"),
"edge_count": st.get("edge_count") or st.get("edges"),
"error": crg_error,
},
"root": str(root),
}
(dest / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
return {"ok": True, "snapshot": manifest}
def _load_fs(sid: str) -> dict[str, Any] | None:
path = _snapshots_dir() / sid / "filesystem.json"
if not path.is_file():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
def _path_set(data: dict[str, Any]) -> dict[str, int]:
"""Map relative path -> loc or size if present."""
out: dict[str, int] = {}
for n in data.get("nodes") or []:
if not isinstance(n, dict):
continue
if n.get("kind") not in (None, "file") and n.get("type") not in (None, "file"):
# tolerate either schema
if n.get("kind") == "dir" or n.get("type") == "dir":
continue
path = n.get("path") or n.get("id") or n.get("name")
if not path or not isinstance(path, str):
continue
if path.endswith("/") or n.get("kind") == "dir":
continue
loc = n.get("loc") or n.get("lines") or n.get("size") or 0
try:
loc = int(loc)
except (TypeError, ValueError):
loc = 0
out[path.replace("\\", "/")] = loc
# Fallback: walk tree
if not out and isinstance(data.get("tree"), dict):
def walk(node: dict[str, Any], prefix: str) -> None:
kind = node.get("kind")
name = str(node.get("name") or "")
if kind == "file":
p = f"{prefix}/{name}".strip("/") if prefix else name
out[p.replace("\\", "/")] = int(node.get("loc") or node.get("lines") or 0)
return
if kind == "dir":
base = f"{prefix}/{name}".strip("/") if prefix and name else (prefix or name)
for ch in node.get("children") or []:
cname = str(ch.get("name") or "")
child = f"{base}/{cname}".strip("/") if base else cname
if ch.get("kind") == "file":
out[child.replace("\\", "/")] = int(ch.get("loc") or ch.get("lines") or 0)
elif ch.get("kind") == "dir":
walk(ch, child if base else cname)
tree = data["tree"]
for ch in tree.get("children") or []:
walk(ch, "")
return out
def compare(a: str, b: str) -> dict[str, Any]:
fa = _load_fs(a)
fb = _load_fs(b)
if fa is None or fb is None:
return {"ok": False, "error": "snapshot not found"}
pa = _path_set(fa)
pb = _path_set(fb)
sa, sb = set(pa), set(pb)
added = sorted(sb - sa)
removed = sorted(sa - sb)
changed = sorted(p for p in (sa & sb) if pa.get(p) != pb.get(p))
man_a = _snapshots_dir() / a / "manifest.json"
man_b = _snapshots_dir() / b / "manifest.json"
ma = json.loads(man_a.read_text(encoding="utf-8")) if man_a.is_file() else {}
mb = json.loads(man_b.read_text(encoding="utf-8")) if man_b.is_file() else {}
return {
"ok": True,
"a": ma,
"b": mb,
"fs": {
"added": added,
"removed": removed,
"changed": changed,
"added_count": len(added),
"removed_count": len(removed),
"changed_count": len(changed),
},
"crg": {
"a": ma.get("crg"),
"b": mb.get("crg"),
},
}
def delete_snapshot(sid: str) -> dict[str, Any]:
dest = _snapshots_dir() / sid
if not dest.is_dir():
return {"ok": False, "error": "not found"}
shutil.rmtree(dest, ignore_errors=True)
return {"ok": True, "id": sid}