secondkey 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ """File and directory snapshots (tar.gz) for rm, git clean and friends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import tarfile
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from ..classify import Action
13
+ from ..policy import Policy
14
+ from ..store import Snapshot
15
+ from ..util import human_size
16
+ from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
17
+
18
+
19
+ def _size(path: str) -> tuple[int, int]:
20
+ """(bytes, file count) for a file or directory tree, not following symlinks."""
21
+ if os.path.islink(path) or os.path.isfile(path):
22
+ return os.lstat(path).st_size, 1
23
+ total, count = 0, 0
24
+ for root, dirs, files in os.walk(path):
25
+ for f in files:
26
+ try:
27
+ total += os.lstat(os.path.join(root, f)).st_size
28
+ count += 1
29
+ except OSError:
30
+ pass
31
+ return total, count
32
+
33
+
34
+ def measure(paths: list[str]) -> tuple[int, int, list[str]]:
35
+ total, count, existing = 0, 0, []
36
+ for p in paths:
37
+ if os.path.lexists(p):
38
+ b, c = _size(p)
39
+ total, count = total + b, count + c
40
+ existing.append(p)
41
+ return total, count, existing
42
+
43
+
44
+ def archive(paths: list[str], dest: Path) -> list[dict[str, Any]]:
45
+ entries = []
46
+ with tarfile.open(dest / "files.tar.gz", "w:gz") as tar:
47
+ for i, p in enumerate(paths):
48
+ tar.add(p, arcname=str(i), recursive=True)
49
+ entries.append({"i": i, "path": os.path.abspath(p), "dir": os.path.isdir(p) and not os.path.islink(p)})
50
+ return entries
51
+
52
+
53
+ def unarchive(snap_path: str, entries: list[dict[str, Any]], force: bool) -> list[str]:
54
+ conflicts = [e["path"] for e in entries if os.path.lexists(e["path"])]
55
+ if conflicts and not force:
56
+ raise RestoreError("these paths exist again, so restoring would overwrite them: "
57
+ + ", ".join(conflicts[:5]) + (" ..." if len(conflicts) > 5 else "")
58
+ + ". Move them away or re-run with --force.")
59
+ done = []
60
+ with tempfile.TemporaryDirectory(prefix="secondkey-restore-") as tmp, \
61
+ tarfile.open(Path(snap_path) / "files.tar.gz", "r:gz") as tar:
62
+ try:
63
+ tar.extractall(tmp, filter="data") # Python 3.12+ safe extraction
64
+ except TypeError: # pragma: no cover - older Python
65
+ tar.extractall(tmp)
66
+ for e in entries:
67
+ src, dst = os.path.join(tmp, str(e["i"])), e["path"]
68
+ if os.path.lexists(dst):
69
+ if os.path.isdir(dst) and not os.path.islink(dst):
70
+ shutil.rmtree(dst)
71
+ else:
72
+ os.remove(dst)
73
+ os.makedirs(os.path.dirname(dst) or "/", exist_ok=True)
74
+ shutil.move(src, dst)
75
+ done.append(dst)
76
+ return done
77
+
78
+
79
+ class FilesProvider(Provider):
80
+ name = "files"
81
+
82
+ def plan(self, action: Action, policy: Policy) -> list[str]:
83
+ paths = action.target.get("paths") or []
84
+ total, count, existing = measure(paths)
85
+ if not existing:
86
+ raise NothingToProtect("none of the paths exist")
87
+ if total > policy.max_file_snapshot_bytes:
88
+ raise SnapshotUnavailable(f"{human_size(total)} is over the {human_size(policy.max_file_snapshot_bytes)} file snapshot limit")
89
+ return [f"{count} file{'s' if count != 1 else ''}, {human_size(total)} in {len(existing)} path{'s' if len(existing) != 1 else ''}"]
90
+
91
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
92
+ paths = action.target.get("paths") or []
93
+ total, count, existing = measure(paths)
94
+ if not existing:
95
+ raise NothingToProtect("none of the paths exist")
96
+ if total > policy.max_file_snapshot_bytes:
97
+ raise SnapshotUnavailable(f"{human_size(total)} is over the file snapshot limit")
98
+ entries = archive(existing, dest)
99
+ names = ", ".join(os.path.relpath(p, action.target.get("cwd") or os.getcwd()) for p in existing[:3])
100
+ label = f"{names}{' ...' if len(existing) > 3 else ''} ({count} files, {human_size(total)})"
101
+ return label, {"entries": entries, "bytes": total, "files": count}
102
+
103
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
104
+ return [f"put back {e['path']}" for e in snap.meta["entries"]]
105
+
106
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
107
+ done = unarchive(snap.path, snap.meta["entries"], force)
108
+ return [f"restored {p}" for p in done]
@@ -0,0 +1,216 @@
1
+ """Git snapshots: pin commits with refs under refs/secondkey/ so nothing is garbage-collected."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from ..classify import Action
11
+ from ..policy import Policy
12
+ from ..store import Snapshot
13
+ from ..util import CommandError, run
14
+ from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
15
+ from .files import archive, measure, unarchive
16
+
17
+
18
+ def git(repo: str, *args: str, check: bool = True) -> str:
19
+ return run(["git", "-C", repo, *args], check=check).stdout.strip()
20
+
21
+
22
+ def _repo_root(repo: str) -> str:
23
+ try:
24
+ return git(repo, "rev-parse", "--show-toplevel")
25
+ except CommandError as e:
26
+ raise SnapshotUnavailable(f"not a git repository: {repo}") from e
27
+
28
+
29
+ def _head(repo: str) -> str | None:
30
+ out = run(["git", "-C", repo, "rev-parse", "--verify", "-q", "HEAD"], check=False)
31
+ return out.stdout.strip() or None
32
+
33
+
34
+ def _branch(repo: str) -> str | None:
35
+ out = run(["git", "-C", repo, "symbolic-ref", "--short", "-q", "HEAD"], check=False)
36
+ return out.stdout.strip() or None
37
+
38
+
39
+ def _push_targets(repo: str, target: dict[str, Any]) -> tuple[str, list[str]]:
40
+ remote = target.get("remote") or "origin"
41
+ branches = []
42
+ for ref in target.get("refs") or []:
43
+ dst = ref.split(":", 1)[-1] if ":" in ref else ref
44
+ dst = re.sub(r"^refs/heads/", "", dst.lstrip("+"))
45
+ if dst and dst != "HEAD":
46
+ branches.append(dst)
47
+ elif dst == "HEAD" and _branch(repo):
48
+ branches.append(_branch(repo)) # type: ignore[arg-type]
49
+ if not branches:
50
+ cur = _branch(repo)
51
+ if not cur:
52
+ raise SnapshotUnavailable("can't tell which branch is being pushed (detached HEAD)")
53
+ branches = [cur]
54
+ return remote, branches
55
+
56
+
57
+ def _clean_candidates(repo: str, target: dict[str, Any]) -> list[str]:
58
+ args = ["clean", "-n"]
59
+ if target.get("dirs"):
60
+ args.append("-d")
61
+ if target.get("ignored"):
62
+ args.append("-x")
63
+ out = git(repo, *args)
64
+ root = _repo_root(repo)
65
+ files = []
66
+ for line in out.splitlines():
67
+ if line.startswith("Would remove "):
68
+ files.append(os.path.join(repo, line[len("Would remove "):].rstrip("/")))
69
+ return [f for f in files if os.path.abspath(f).startswith(root)]
70
+
71
+
72
+ class GitProvider(Provider):
73
+ name = "git"
74
+
75
+ def plan(self, action: Action, policy: Policy) -> list[str]:
76
+ t, cat = action.target, action.category
77
+ repo = t.get("repo") or os.getcwd()
78
+ _repo_root(repo)
79
+ if cat in ("git.force_push", "git.delete_remote_branch"):
80
+ remote, branches = _push_targets(repo, t)
81
+ return [f"{remote}/{b} will be pinned before it is overwritten" for b in branches]
82
+ if cat == "git.reset_hard":
83
+ dirty = git(repo, "status", "--porcelain", "--untracked-files=no")
84
+ n = len([ln for ln in dirty.splitlines() if ln.strip()])
85
+ return [f"HEAD {(_head(repo) or 'none')[:8]} and {n} uncommitted change{'s' if n != 1 else ''} will be saved"]
86
+ if cat == "git.clean":
87
+ files = _clean_candidates(repo, t)
88
+ total, count, _ = measure(files)
89
+ if total > policy.max_file_snapshot_bytes:
90
+ raise SnapshotUnavailable("untracked files are over the file snapshot limit")
91
+ return [f"{len(files)} untracked path{'s' if len(files) != 1 else ''} ({count} files) will be archived"]
92
+ if cat == "git.branch_delete":
93
+ return [f"branch {b} will be pinned" for b in t.get("branches") or []]
94
+ return [f"HEAD {(_head(repo) or 'none')[:8]} and working-tree changes will be saved"]
95
+
96
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
97
+ t, cat = action.target, action.category
98
+ repo = _repo_root(t.get("repo") or os.getcwd())
99
+ sid = dest.name
100
+ meta: dict[str, Any] = {"repo": repo, "category": cat, "head": _head(repo), "branch": _branch(repo)}
101
+
102
+ if cat in ("git.force_push", "git.delete_remote_branch"):
103
+ remote, branches = _push_targets(repo, t)
104
+ pinned = []
105
+ for b in branches:
106
+ ref = f"refs/secondkey/{sid}/remote/{b}"
107
+ ls = git(repo, "ls-remote", remote, f"refs/heads/{b}")
108
+ sha = ls.split()[0] if ls else None
109
+ if sha:
110
+ git(repo, "fetch", "--no-tags", "-q", remote, f"+refs/heads/{b}:{ref}")
111
+ pinned.append({"branch": b, "sha": sha, "ref": ref if sha else None})
112
+ meta.update(remote=remote, branches=pinned)
113
+ label = ", ".join(f"{remote}/{p['branch']}@{(p['sha'] or 'new')[:8]}" for p in pinned)
114
+ return label, meta
115
+
116
+ if cat == "git.branch_delete":
117
+ pinned = []
118
+ for b in t.get("branches") or []:
119
+ sha = run(["git", "-C", repo, "rev-parse", "--verify", "-q", f"refs/heads/{b}"], check=False).stdout.strip()
120
+ if sha:
121
+ git(repo, "update-ref", f"refs/secondkey/{sid}/branch/{b}", sha)
122
+ pinned.append({"branch": b, "sha": sha})
123
+ if not pinned:
124
+ raise NothingToProtect("none of the branches exist")
125
+ meta["branches"] = pinned
126
+ return ", ".join(f"branch {p['branch']}@{p['sha'][:8]}" for p in pinned), meta
127
+
128
+ if cat == "git.clean":
129
+ files = _clean_candidates(repo, t)
130
+ if not files:
131
+ raise NothingToProtect("git clean would not remove anything")
132
+ meta["entries"] = archive(files, dest)
133
+ return f"{len(files)} untracked paths in {os.path.basename(repo)}", meta
134
+
135
+ # reset --hard, checkout -- ., restore, stash drop/clear, rebase and other rewrites
136
+ if meta["head"]:
137
+ git(repo, "update-ref", f"refs/secondkey/{sid}/head", meta["head"])
138
+ stash = git(repo, "stash", "create") if meta["head"] else ""
139
+ if stash:
140
+ git(repo, "update-ref", f"refs/secondkey/{sid}/worktree", stash)
141
+ meta["worktree"] = stash or None
142
+ stashes = git(repo, "stash", "list", "--format=%H%x09%gs", check=False)
143
+ meta["stashes"] = [ln.split("\t", 1) for ln in stashes.splitlines() if ln.strip()]
144
+ for i, (sha, _msg) in enumerate(meta["stashes"]):
145
+ git(repo, "update-ref", f"refs/secondkey/{sid}/stash/{i}", sha)
146
+ label = f"{os.path.basename(repo)} HEAD {(meta['head'] or 'none')[:8]}" + (" + uncommitted changes" if stash else "")
147
+ return label, meta
148
+
149
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
150
+ m, cat = snap.meta, snap.meta["category"]
151
+ if cat in ("git.force_push", "git.delete_remote_branch"):
152
+ return [f"force-push {m['remote']}/{b['branch']} back to {b['sha'][:8]}" if b["sha"]
153
+ else f"{m['remote']}/{b['branch']} did not exist before; leave it" for b in m["branches"]]
154
+ if cat == "git.branch_delete":
155
+ return [f"recreate branch {b['branch']} at {b['sha'][:8]}" for b in m["branches"]]
156
+ if cat == "git.clean":
157
+ return [f"put back {len(m['entries'])} untracked paths"]
158
+ lines = [f"reset {os.path.basename(m['repo'])} to {(m['head'] or '')[:8]}"]
159
+ if m.get("worktree"):
160
+ lines.append("re-apply the uncommitted changes saved before the command")
161
+ if m.get("stashes"):
162
+ lines.append(f"re-store any of the {len(m['stashes'])} saved stash entries that are missing")
163
+ lines.append("your current uncommitted changes are saved first, so this is itself undoable")
164
+ return lines
165
+
166
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
167
+ m, cat, repo = snap.meta, snap.meta["category"], snap.meta["repo"]
168
+ if not os.path.isdir(repo):
169
+ raise RestoreError(f"repository {repo} no longer exists")
170
+ out: list[str] = []
171
+ if cat in ("git.force_push", "git.delete_remote_branch"):
172
+ for b in m["branches"]:
173
+ if not b["sha"]:
174
+ out.append(f"{m['remote']}/{b['branch']} was new; left as is")
175
+ continue
176
+ git(repo, "push", "--force", m["remote"], f"{b['ref']}:refs/heads/{b['branch']}")
177
+ out.append(f"{m['remote']}/{b['branch']} restored to {b['sha'][:8]}")
178
+ return out
179
+ if cat == "git.branch_delete":
180
+ for b in m["branches"]:
181
+ exists = run(["git", "-C", repo, "rev-parse", "--verify", "-q", f"refs/heads/{b['branch']}"], check=False).stdout.strip()
182
+ if exists and exists != b["sha"] and not force:
183
+ raise RestoreError(f"branch {b['branch']} exists again at {exists[:8]}; use --force to move it")
184
+ if exists:
185
+ git(repo, "branch", "-f", b["branch"], b["sha"])
186
+ else:
187
+ git(repo, "branch", b["branch"], b["sha"])
188
+ out.append(f"branch {b['branch']} restored at {b['sha'][:8]}")
189
+ return out
190
+ if cat == "git.clean":
191
+ return [f"restored {p}" for p in unarchive(snap.path, m["entries"], force)]
192
+
193
+ safety = git(repo, "stash", "create")
194
+ if safety:
195
+ git(repo, "update-ref", f"refs/secondkey/{snap.id}/before-undo", safety)
196
+ out.append(f"saved your current uncommitted changes as {safety[:8]} (refs/secondkey/{snap.id}/before-undo)")
197
+ if m["head"]:
198
+ git(repo, "reset", "-q", "--hard", m["head"])
199
+ out.append(f"HEAD reset to {m['head'][:8]}")
200
+ if m.get("worktree"):
201
+ git(repo, "stash", "apply", "-q", m["worktree"])
202
+ out.append("uncommitted changes re-applied")
203
+ current = {ln.strip() for ln in git(repo, "stash", "list", "--format=%H", check=False).splitlines()}
204
+ for sha, msg in reversed(m.get("stashes") or []):
205
+ if sha not in current:
206
+ git(repo, "stash", "store", "-m", msg or "restored by secondkey", sha)
207
+ out.append(f"stash restored: {msg}")
208
+ return out
209
+
210
+ def cleanup(self, snap: Snapshot) -> None:
211
+ repo = snap.meta.get("repo")
212
+ if not repo or not os.path.isdir(repo):
213
+ return
214
+ refs = run(["git", "-C", repo, "for-each-ref", "--format=%(refname)", f"refs/secondkey/{snap.id}/"], check=False).stdout
215
+ for ref in refs.split():
216
+ run(["git", "-C", repo, "update-ref", "-d", ref], check=False)
@@ -0,0 +1,97 @@
1
+ """Kubernetes snapshots: export the objects about to be deleted as YAML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import yaml
9
+
10
+ from ..classify import Action
11
+ from ..policy import Policy
12
+ from ..store import Snapshot
13
+ from ..util import CommandError, run
14
+ from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
15
+
16
+ DROP_FLAGS = ("--force", "--now", "--wait", "--grace-period", "--cascade", "--ignore-not-found", "--timeout",
17
+ "--dry-run", "--interactive", "-i", "--raw", "--output", "-o")
18
+ VOLATILE = ("uid", "resourceVersion", "creationTimestamp", "generation", "managedFields", "selfLink", "deletionTimestamp",
19
+ "deletionGracePeriodSeconds", "ownerReferences")
20
+
21
+
22
+ def get_args(args: list[str]) -> list[str]:
23
+ """Turn `delete <what>` arguments into `get <what> -o yaml`."""
24
+ out, i, swapped = [], 0, False
25
+ while i < len(args):
26
+ a = args[i]
27
+ if not swapped and a == "delete":
28
+ out.append("get")
29
+ swapped = True
30
+ elif a.split("=", 1)[0] in DROP_FLAGS:
31
+ if "=" not in a and a in ("--grace-period", "--cascade", "--timeout", "--output", "-o") and i + 1 < len(args):
32
+ i += 1
33
+ else:
34
+ out.append(a)
35
+ i += 1
36
+ return out + ["-o", "yaml"]
37
+
38
+
39
+ def clean(doc: dict[str, Any]) -> dict[str, Any]:
40
+ items = doc.get("items") if doc.get("kind", "").endswith("List") else [doc]
41
+ cleaned = []
42
+ for it in items or []:
43
+ it = dict(it)
44
+ it.pop("status", None)
45
+ md = dict(it.get("metadata") or {})
46
+ for k in VOLATILE:
47
+ md.pop(k, None)
48
+ ann = dict(md.get("annotations") or {})
49
+ ann.pop("kubectl.kubernetes.io/last-applied-configuration", None)
50
+ if ann:
51
+ md["annotations"] = ann
52
+ else:
53
+ md.pop("annotations", None)
54
+ it["metadata"] = md
55
+ if it.get("kind") == "Service":
56
+ spec = dict(it.get("spec") or {})
57
+ for k in ("clusterIP", "clusterIPs"):
58
+ spec.pop(k, None)
59
+ it["spec"] = spec
60
+ cleaned.append(it)
61
+ return {"apiVersion": "v1", "kind": "List", "items": cleaned}
62
+
63
+
64
+ class K8sProvider(Provider):
65
+ name = "k8s"
66
+
67
+ def _export(self, action: Action) -> dict[str, Any]:
68
+ args = get_args(action.target.get("args") or [])
69
+ try:
70
+ out = run(["kubectl", *args], cwd=action.target.get("cwd"), timeout=120).stdout
71
+ except CommandError as e:
72
+ raise SnapshotUnavailable(f"kubectl get failed: {e.stderr.strip()[:300]}") from e
73
+ return clean(yaml.safe_load(out) or {})
74
+
75
+ def plan(self, action: Action, policy: Policy) -> list[str]:
76
+ doc = self._export(action)
77
+ names = [f"{i.get('kind')}/{i['metadata'].get('name')}" for i in doc["items"]]
78
+ return [f"{len(names)} object{'s' if len(names) != 1 else ''}: " + ", ".join(names[:6]) + (" ..." if len(names) > 6 else "")]
79
+
80
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
81
+ doc = self._export(action)
82
+ if not doc["items"]:
83
+ raise NothingToProtect("kubectl found no matching objects")
84
+ (dest / "resources.yaml").write_text(yaml.safe_dump(doc, sort_keys=False))
85
+ names = [f"{i.get('kind')}/{i['metadata'].get('name')}" for i in doc["items"]]
86
+ return ", ".join(names[:4]) + (" ..." if len(names) > 4 else ""), {"objects": names, "cwd": action.target.get("cwd")}
87
+
88
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
89
+ return [f"kubectl apply {len(snap.meta['objects'])} saved objects: " + ", ".join(snap.meta["objects"][:6]),
90
+ "workloads are recreated from their spec; data in deleted volumes is not restored"]
91
+
92
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
93
+ try:
94
+ out = run(["kubectl", "apply", "-f", str(Path(snap.path) / "resources.yaml")], cwd=snap.meta.get("cwd"), timeout=300).stdout
95
+ except CommandError as e:
96
+ raise RestoreError(f"kubectl apply failed: {e.stderr.strip()[:400]}") from e
97
+ return [ln for ln in out.splitlines() if ln.strip()]
@@ -0,0 +1,104 @@
1
+ """MySQL / MariaDB snapshots with mysqldump.
2
+
3
+ Restore replays the dump (DROP TABLE IF EXISTS + CREATE + INSERT) inside the
4
+ client, so rows written to those tables after the snapshot are replaced.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import subprocess
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from ..classify import Action
15
+ from ..policy import Policy
16
+ from ..store import Snapshot
17
+ from ..util import CommandError, run
18
+ from .base import NothingToProtect, Provider, RestoreError, SnapshotUnavailable
19
+
20
+
21
+ def _args(conn: dict[str, str]) -> list[str]:
22
+ a = []
23
+ for key, flag in (("host", "-h"), ("port", "-P"), ("user", "-u")):
24
+ if conn.get(key):
25
+ a += [flag, str(conn[key])]
26
+ return a
27
+
28
+
29
+ def _env(conn: dict[str, str]) -> dict[str, str]:
30
+ env = dict(os.environ)
31
+ if conn.get("password"):
32
+ env["MYSQL_PWD"] = conn["password"] # keeps the password off the process list
33
+ return env
34
+
35
+
36
+ def _bare(table: str) -> str:
37
+ return table.split(".")[-1].strip("`\"")
38
+
39
+
40
+ def _query(conn: dict[str, str], sql: str) -> list[list[str]]:
41
+ try:
42
+ out = run(["mysql", "-N", "-B", *_args(conn), conn["database"], "-e", sql], env=_env(conn), timeout=60).stdout
43
+ except CommandError as e:
44
+ raise SnapshotUnavailable(f"can't query MySQL: {e.stderr.strip()[:300]}") from e
45
+ return [ln.split("\t") for ln in out.splitlines() if ln]
46
+
47
+
48
+ class MySQLProvider(Provider):
49
+ name = "mysql"
50
+
51
+ def _present(self, conn: dict[str, str], tables: list[str]) -> list[str]:
52
+ names = ",".join("'" + _bare(t).replace("'", "''") + "'" for t in tables)
53
+ rows = _query(conn, f"SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name IN ({names})")
54
+ found = {r[0] for r in rows}
55
+ return [t for t in tables if _bare(t) in found]
56
+
57
+ def plan(self, action: Action, policy: Policy) -> list[str]:
58
+ conn, tables = action.target.get("conn") or {}, action.target.get("tables") or []
59
+ if not conn.get("database") or not tables:
60
+ raise SnapshotUnavailable("no database or table names found")
61
+ present = self._present(conn, tables)
62
+ lines = [f"{t}: does not exist (nothing to lose)" for t in tables if t not in present]
63
+ for t in present:
64
+ n = int(_query(conn, f"SELECT COUNT(*) FROM `{_bare(t)}`")[0][0])
65
+ lines.append(f"{t}: {n:,} rows")
66
+ return lines
67
+
68
+ def take(self, action: Action, dest: Path, policy: Policy) -> tuple[str, dict[str, Any]]:
69
+ conn, tables = action.target.get("conn") or {}, action.target.get("tables") or []
70
+ present = self._present(conn, tables)
71
+ if not present:
72
+ raise NothingToProtect("none of the tables exist")
73
+ counts = {t: int(_query(conn, f"SELECT COUNT(*) FROM `{_bare(t)}`")[0][0]) for t in present}
74
+ dump = dest / "dump.sql"
75
+ try:
76
+ with open(dump, "w") as fh:
77
+ proc = subprocess.run(["mysqldump", "--single-transaction", "--add-drop-table", *_args(conn),
78
+ conn["database"], *[_bare(t) for t in present]],
79
+ stdout=fh, stderr=subprocess.PIPE, text=True, env=_env(conn), timeout=3600)
80
+ except FileNotFoundError as e:
81
+ raise SnapshotUnavailable("mysqldump not found on PATH; install the MySQL client tools") from e
82
+ if proc.returncode != 0:
83
+ raise SnapshotUnavailable(f"mysqldump failed: {proc.stderr.strip()[:300]}")
84
+ label = ", ".join(f"{t} ({n:,} rows)" for t, n in counts.items())
85
+ return label, {"conn": conn, "tables": present, "counts": counts}
86
+
87
+ def describe_restore(self, snap: Snapshot, mode: str | None = None) -> list[str]:
88
+ return [f"{t}: replace with the {n:,} rows saved before the command" for t, n in snap.meta["counts"].items()] + \
89
+ ["rows written to these tables after the snapshot will be lost"]
90
+
91
+ def restore(self, snap: Snapshot, mode: str | None = None, force: bool = False) -> list[str]:
92
+ conn = snap.meta["conn"]
93
+ with open(Path(snap.path) / "dump.sql") as fh:
94
+ proc = subprocess.run(["mysql", *_args(conn), conn["database"]], stdin=fh, capture_output=True, text=True,
95
+ env=_env(conn), timeout=7200)
96
+ if proc.returncode != 0:
97
+ raise RestoreError(f"mysql restore failed: {proc.stderr.strip()[:400]}")
98
+ out = []
99
+ for t, n in snap.meta["counts"].items():
100
+ got = int(_query(conn, f"SELECT COUNT(*) FROM `{_bare(t)}`")[0][0])
101
+ if got != n:
102
+ raise RestoreError(f"{t}: expected {n:,} rows after restore, found {got:,}")
103
+ out.append(f"verified {t}: {got:,} rows")
104
+ return out