-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnap.py
More file actions
453 lines (367 loc) · 14.6 KB
/
snap.py
File metadata and controls
453 lines (367 loc) · 14.6 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#!/usr/bin/env python3
"""
snap -- Simple file versioning. Snapshots, diffs, restore. Mini-git, zero deps.
Save snapshots of your files, see what changed, go back to any version.
No git needed. Perfect for quick versioning of scripts, configs, documents.
Usage:
py snap.py track *.py config.yml # Track files
py snap.py save "Initial version" # Save a snapshot
py snap.py status # What changed since last snap?
py snap.py save "Fixed the bug" # Save another snapshot
py snap.py list # Show all snapshots
py snap.py diff # Diff vs last snapshot
py snap.py diff 1 # Diff vs snapshot #1
py snap.py diff 1 2 # Diff between two snapshots
py snap.py restore 1 # Restore snapshot #1
py snap.py restore 2 app.py # Restore one file from snap #2
py snap.py log app.py # Version history for a file
py snap.py show 1 # Show snapshot details
"""
import argparse
import difflib
import fnmatch
import hashlib
import json
import os
import shutil
import sys
from datetime import datetime
from pathlib import Path
SNAP_DIR = ".snapshots"
META_FILE = "meta.json"
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
CYAN = "\033[36m"
RED = "\033[31m"
def color_supported() -> bool:
if os.environ.get("NO_COLOR"):
return False
if sys.platform == "win32":
return bool(os.environ.get("TERM") or os.environ.get("WT_SESSION"))
return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
USE_COLOR = color_supported()
def c(code: str, text: str) -> str:
return f"{code}{text}{RESET}" if USE_COLOR else text
def snap_dir() -> Path:
return Path(SNAP_DIR)
def meta_path() -> Path:
return snap_dir() / META_FILE
def load_meta() -> dict:
mp = meta_path()
if not mp.exists():
return {"tracked": [], "snapshots": []}
return json.loads(mp.read_text(encoding="utf-8"))
def save_meta(meta: dict):
snap_dir().mkdir(exist_ok=True)
meta_path().write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
def file_hash(path: str) -> str:
"""SHA256 hash of file content."""
h = hashlib.sha256()
try:
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()[:16]
except (OSError, PermissionError):
return "error"
def resolve_tracked(patterns: list[str]) -> list[str]:
"""Resolve glob patterns to actual file paths."""
files = set()
for pattern in patterns:
if "*" in pattern or "?" in pattern:
for match in Path(".").glob(pattern):
if match.is_file() and SNAP_DIR not in str(match):
files.add(str(match))
else:
p = Path(pattern)
if p.is_file():
files.add(str(p))
return sorted(files)
def get_current_files(tracked: list[str]) -> dict[str, str]:
"""Get current state of tracked files: {path: hash}."""
files = {}
resolved = resolve_tracked(tracked)
for f in resolved:
files[f] = file_hash(f)
return files
def get_snap_files(snap_id: int, meta: dict) -> dict[str, str]:
"""Get files from a snapshot: {path: hash}."""
for snap in meta["snapshots"]:
if snap["id"] == snap_id:
return snap.get("files", {})
return {}
def snap_store_path(snap_id: int) -> Path:
return snap_dir() / f"snap_{snap_id:04d}"
# --- Commands ---
def cmd_track(args):
meta = load_meta()
new_patterns = args.patterns
existing = set(meta["tracked"])
added = 0
for p in new_patterns:
if p not in existing:
meta["tracked"].append(p)
existing.add(p)
added += 1
save_meta(meta)
resolved = resolve_tracked(meta["tracked"])
print(f" {c(GREEN, f'Tracking {len(resolved)} file(s)')} ({added} pattern(s) added)")
for f in resolved[:20]:
print(f" {f}")
if len(resolved) > 20:
print(c(DIM, f" ... and {len(resolved) - 20} more"))
def cmd_save(args):
meta = load_meta()
if not meta["tracked"]:
print(c(RED, " No files tracked. Use: py snap.py track <files>"))
return
snap_id = max((s["id"] for s in meta["snapshots"]), default=0) + 1
store = snap_store_path(snap_id)
store.mkdir(parents=True, exist_ok=True)
current = get_current_files(meta["tracked"])
if not current:
print(c(RED, " No tracked files found on disk."))
return
# Copy files to snapshot store
file_hashes = {}
for filepath, fhash in current.items():
dest = store / filepath.replace(os.sep, "__SEP__")
try:
shutil.copy2(filepath, dest)
file_hashes[filepath] = fhash
except (OSError, PermissionError) as e:
print(c(YELLOW, f" Warning: could not copy {filepath}: {e}"))
snapshot = {
"id": snap_id,
"message": args.message,
"timestamp": datetime.now().isoformat(),
"files": file_hashes,
"file_count": len(file_hashes),
}
meta["snapshots"].append(snapshot)
save_meta(meta)
print(f" {c(GREEN, f'Snapshot #{snap_id} saved')} -- {args.message}")
print(f" {len(file_hashes)} file(s), {datetime.now().strftime('%Y-%m-%d %H:%M')}")
def cmd_status(args):
meta = load_meta()
if not meta["tracked"]:
print(c(DIM, " No files tracked."))
return
current = get_current_files(meta["tracked"])
if not meta["snapshots"]:
print(f" {len(current)} tracked file(s), no snapshots yet.")
print(c(DIM, " Save one: py snap.py save \"Initial version\""))
return
last_snap = meta["snapshots"][-1]
last_files = last_snap["files"]
added = [f for f in current if f not in last_files]
removed = [f for f in last_files if f not in current]
modified = [f for f in current if f in last_files and current[f] != last_files[f]]
unchanged = [f for f in current if f in last_files and current[f] == last_files[f]]
print(f"\n {c(BOLD, 'Status')} (vs snapshot #{last_snap['id']})\n")
if not added and not removed and not modified:
print(f" {c(GREEN, 'Clean')} -- no changes since last snapshot")
else:
for f in modified:
print(f" {c(YELLOW, 'M')} {f}")
for f in added:
print(f" {c(GREEN, 'A')} {f}")
for f in removed:
print(f" {c(RED, 'D')} {f}")
print(f"\n {len(modified)} modified, {len(added)} added, {len(removed)} removed, {len(unchanged)} unchanged")
print()
def cmd_list(args):
meta = load_meta()
if not meta["snapshots"]:
print(c(DIM, " No snapshots yet. Save one: py snap.py save \"message\""))
return
print(f"\n {c(BOLD, 'Snapshots')} ({len(meta['snapshots'])})\n")
for snap in reversed(meta["snapshots"]):
ts = datetime.fromisoformat(snap["timestamp"]).strftime("%Y-%m-%d %H:%M")
sid = f"#{snap['id']:<4}"
print(f" {c(CYAN, sid)} {c(DIM, ts)} {snap['file_count']} files {snap['message']}")
print()
def cmd_diff(args):
meta = load_meta()
if args.id2 is not None:
# Diff between two snapshots
files_a = get_snap_files(args.id1, meta)
files_b = get_snap_files(args.id2, meta)
label_a = f"snapshot #{args.id1}"
label_b = f"snapshot #{args.id2}"
elif args.id1 is not None:
# Diff current vs specific snapshot
files_a = get_snap_files(args.id1, meta)
files_b = get_current_files(meta["tracked"])
label_a = f"snapshot #{args.id1}"
label_b = "current"
else:
# Diff current vs last snapshot
if not meta["snapshots"]:
print(c(DIM, " No snapshots to diff against."))
return
last = meta["snapshots"][-1]
files_a = last["files"]
files_b = get_current_files(meta["tracked"])
label_a = f"snapshot #{last['id']}"
label_b = "current"
all_files = set(files_a.keys()) | set(files_b.keys())
changes = 0
print(f"\n {c(BOLD, 'Diff:')} {label_a} vs {label_b}\n")
for filepath in sorted(all_files):
if filepath not in files_a:
print(f" {c(GREEN, f'+ {filepath}')} (new)")
changes += 1
elif filepath not in files_b:
print(f" {c(RED, f'- {filepath}')} (deleted)")
changes += 1
elif files_a[filepath] != files_b[filepath]:
print(f" {c(YELLOW, f'~ {filepath}')} (modified)")
# Show unified diff
_show_file_diff(filepath, args.id1, label_a, label_b, meta)
changes += 1
if changes == 0:
print(c(GREEN, " No differences."))
else:
print(f"\n {changes} file(s) changed")
print()
def _show_file_diff(filepath: str, snap_id: int | None, label_a: str, label_b: str, meta: dict):
"""Show unified diff for a specific file."""
# Get old content from snapshot
if snap_id is not None:
store = snap_store_path(snap_id)
stored = store / filepath.replace(os.sep, "__SEP__")
if stored.exists():
old_lines = stored.read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
else:
return
else:
last = meta["snapshots"][-1]
store = snap_store_path(last["id"])
stored = store / filepath.replace(os.sep, "__SEP__")
if stored.exists():
old_lines = stored.read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
else:
return
# Get current content
try:
new_lines = Path(filepath).read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
except (OSError, FileNotFoundError):
return
diff = list(difflib.unified_diff(old_lines, new_lines,
fromfile=f"{filepath} ({label_a})",
tofile=f"{filepath} ({label_b})", n=2))
for line in diff[:30]:
line = line.rstrip("\n")
if line.startswith("+++") or line.startswith("---"):
print(f" {c(BOLD, line)}")
elif line.startswith("+"):
print(f" {c(GREEN, line)}")
elif line.startswith("-"):
print(f" {c(RED, line)}")
elif line.startswith("@@"):
print(f" {c(CYAN, line)}")
else:
print(f" {c(DIM, line)}")
if len(diff) > 30:
print(c(DIM, f" ... ({len(diff) - 30} more lines)"))
def cmd_restore(args):
meta = load_meta()
snap_id = args.id
store = snap_store_path(snap_id)
if not store.exists():
print(c(RED, f" Snapshot #{snap_id} not found."))
return
snap = None
for s in meta["snapshots"]:
if s["id"] == snap_id:
snap = s
break
if not snap:
print(c(RED, f" Snapshot #{snap_id} not found in metadata."))
return
if args.file:
# Restore single file
stored = store / args.file.replace(os.sep, "__SEP__")
if not stored.exists():
print(c(RED, f" File '{args.file}' not in snapshot #{snap_id}."))
return
shutil.copy2(stored, args.file)
print(f" {c(GREEN, 'Restored')} {args.file} from snapshot #{snap_id}")
else:
# Restore all files
count = 0
for filepath in snap["files"]:
stored = store / filepath.replace(os.sep, "__SEP__")
if stored.exists():
Path(filepath).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(stored, filepath)
count += 1
print(f" {c(GREEN, f'Restored {count} file(s)')} from snapshot #{snap_id}: {snap['message']}")
def cmd_show(args):
meta = load_meta()
for snap in meta["snapshots"]:
if snap["id"] == args.id:
ts = datetime.fromisoformat(snap["timestamp"]).strftime("%Y-%m-%d %H:%M:%S")
sid = snap['id']
print(f"\n {c(BOLD, f'Snapshot #{sid}')} {snap['message']}")
print(f" Date: {ts}")
print(f" Files: {snap['file_count']}")
print(f"\n {c(DIM, 'Contents:')}")
for filepath, fhash in sorted(snap["files"].items()):
print(f" {filepath} {c(DIM, fhash)}")
print()
return
print(c(RED, f" Snapshot #{args.id} not found."))
def cmd_log(args):
meta = load_meta()
filepath = args.file
print(f"\n {c(BOLD, f'History: {filepath}')}\n")
found = False
for snap in reversed(meta["snapshots"]):
if filepath in snap.get("files", {}):
ts = datetime.fromisoformat(snap["timestamp"]).strftime("%Y-%m-%d %H:%M")
fhash = snap["files"][filepath]
sid = f"#{snap['id']}"
print(f" {c(CYAN, sid)} {c(DIM, ts)} {c(DIM, fhash)} {snap['message']}")
found = True
if not found:
print(c(DIM, f" No snapshots contain '{filepath}'."))
print()
def main():
parser = argparse.ArgumentParser(
description="snap -- simple file versioning with snapshots",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
sub = parser.add_subparsers(dest="command")
p = sub.add_parser("track", help="Track files/patterns")
p.add_argument("patterns", nargs="+", help="File paths or glob patterns")
p = sub.add_parser("save", help="Save a snapshot")
p.add_argument("message", help="Snapshot description")
sub.add_parser("status", help="Show changes since last snapshot")
sub.add_parser("list", aliases=["ls"], help="List all snapshots")
p = sub.add_parser("diff", help="Show differences")
p.add_argument("id1", nargs="?", type=int, help="Snapshot ID (or first of two)")
p.add_argument("id2", nargs="?", type=int, help="Second snapshot ID")
p = sub.add_parser("restore", help="Restore from snapshot")
p.add_argument("id", type=int, help="Snapshot ID")
p.add_argument("file", nargs="?", help="Specific file to restore")
p = sub.add_parser("show", help="Show snapshot details")
p.add_argument("id", type=int, help="Snapshot ID")
p = sub.add_parser("log", help="Version history for a file")
p.add_argument("file", help="File path")
args = parser.parse_args()
cmds = {
"track": cmd_track, "save": cmd_save, "status": cmd_status,
"list": cmd_list, "ls": cmd_list, "diff": cmd_diff,
"restore": cmd_restore, "show": cmd_show, "log": cmd_log,
}
if args.command in cmds:
cmds[args.command](args)
else:
parser.print_help()
if __name__ == "__main__":
main()