forgetproof 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.
forgetproof/copies.py ADDED
@@ -0,0 +1,155 @@
1
+ """Where else a store's bytes probably are.
2
+
3
+ On a personal machine the live store is the least dangerous copy of an agent's memory. The same
4
+ files are mirrored by sync clients, committed to git (people keep their agent's markdown memory in
5
+ a repository), left behind as `.bak` siblings, and captured by Time Machine and File History.
6
+ Cleaning the live store and saying "clean" would be a lie by omission, so every scan can be
7
+ accompanied by this report, and `fix`/`forget` can be pointed at the copies it can reach.
8
+
9
+ Nothing here reads a copy's contents or changes anything: it only names places. A copy marked
10
+ `scannable` is a path on this machine forgetproof can scan and fix like any store. A `hint` is a
11
+ place forgetproof can't reach from here (a cloud-side version history, a Time Machine volume) and
12
+ only tells the person where to look.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import subprocess
19
+ import sys
20
+ from dataclasses import asdict, dataclass
21
+ from pathlib import Path
22
+
23
+ _SIBLING_SUFFIXES = (".bak", ".backup", ".old", ".orig", ".prev", "~", ".1", ".2", " copy", " (1)", "-backup", "_backup", "-old", "_old")
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Copy:
28
+ kind: str # "sync" | "git" | "sibling" | "hint"
29
+ where: str # a path, or a description for a hint
30
+ note: str
31
+ scannable: bool # forgetproof can scan/fix this path from here
32
+
33
+ def to_dict(self) -> dict:
34
+ return asdict(self)
35
+
36
+
37
+ def _home() -> Path:
38
+ return Path.home()
39
+
40
+
41
+ def sync_roots() -> list[tuple[str, Path]]:
42
+ """Folders a sync client mirrors to a cloud, as (client, root) — only ones that exist here."""
43
+ home = _home()
44
+ env = os.environ
45
+ candidates: list[tuple[str, Path]] = []
46
+ for var in ("OneDrive", "OneDriveConsumer", "OneDriveCommercial"):
47
+ if env.get(var):
48
+ candidates.append(("OneDrive", Path(env[var])))
49
+ candidates += [
50
+ ("OneDrive", home / "OneDrive"),
51
+ ("iCloud Drive", home / "Library" / "Mobile Documents" / "com~apple~CloudDocs"),
52
+ ("Dropbox", home / "Dropbox"),
53
+ ("Google Drive", home / "Google Drive"),
54
+ ("Google Drive", home / "My Drive"),
55
+ ]
56
+ cloud_storage = home / "Library" / "CloudStorage"
57
+ if cloud_storage.is_dir():
58
+ for d in sorted(cloud_storage.iterdir()):
59
+ if d.is_dir():
60
+ candidates.append((d.name.split("-")[0], d))
61
+ if sys.platform == "win32":
62
+ for letter in "GHIJ":
63
+ drive = Path(f"{letter}:/My Drive")
64
+ if drive.is_dir():
65
+ candidates.append(("Google Drive", drive))
66
+ seen: set[Path] = set()
67
+ out = []
68
+ for client, root in candidates:
69
+ try:
70
+ r = root.resolve()
71
+ except OSError:
72
+ continue
73
+ if r.is_dir() and r not in seen:
74
+ seen.add(r)
75
+ out.append((client, r))
76
+ return out
77
+
78
+
79
+ def _under(path: Path, root: Path) -> bool:
80
+ try:
81
+ path.relative_to(root)
82
+ return True
83
+ except ValueError:
84
+ return False
85
+
86
+
87
+ def _git_root(path: Path) -> Path | None:
88
+ d = path if path.is_dir() else path.parent
89
+ for _ in range(40):
90
+ if (d / ".git").exists():
91
+ return d
92
+ if d.parent == d:
93
+ return None
94
+ d = d.parent
95
+ return None
96
+
97
+
98
+ def _git(root: Path, *args: str) -> str | None:
99
+ try:
100
+ p = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True, timeout=20)
101
+ except (OSError, subprocess.TimeoutExpired):
102
+ return None
103
+ return p.stdout if p.returncode == 0 else None
104
+
105
+
106
+ def copies_of(target: Path | str) -> list[Copy]:
107
+ """Likely copies of `target` (a store path). Never reads the store; never follows symlinks out."""
108
+ target = Path(target).resolve()
109
+ out: list[Copy] = []
110
+
111
+ for client, root in sync_roots():
112
+ if _under(target, root):
113
+ out.append(Copy("sync", str(root),
114
+ f"inside a {client} folder: {client} keeps its own copy and usually a version history "
115
+ "that erasing here doesn't touch", False))
116
+
117
+ git_root = _git_root(target)
118
+ if git_root is not None:
119
+ rel = target.relative_to(git_root).as_posix()
120
+ tracked = _git(git_root, "ls-files", "--error-unmatch", "--", rel) is not None
121
+ if tracked:
122
+ log = _git(git_root, "log", "--oneline", "--", rel) or ""
123
+ commits = len([line for line in log.splitlines() if line.strip()])
124
+ out.append(Copy("git", str(git_root / ".git"),
125
+ f"tracked in git: every past version is in the repository's history ({commits} commit(s) "
126
+ "touch it), and in any clone or remote", False))
127
+ else:
128
+ out.append(Copy("hint", str(git_root),
129
+ "inside a git repository but not tracked; check that no past commit added it", False))
130
+
131
+ base = target.name
132
+ parent = target.parent
133
+ for suffix in _SIBLING_SUFFIXES:
134
+ sibling = parent / f"{base}{suffix}"
135
+ if sibling.exists() and not sibling.is_symlink():
136
+ out.append(Copy("sibling", str(sibling), "a backup copy next to the store", True))
137
+ if target.is_file():
138
+ for extra in (target.with_name(target.name + "-wal"), target.with_name(target.name + "-journal")):
139
+ if extra.exists() and extra.stat().st_size > 0:
140
+ out.append(Copy("sibling", str(extra), "SQLite write-ahead log / rollback journal: holds recent pages, "
141
+ "including deleted rows, until a checkpoint", True))
142
+
143
+ if sys.platform == "darwin":
144
+ out.append(Copy("hint", "Time Machine", "if Time Machine is on, past snapshots of this path exist on the "
145
+ "backup disk and in local snapshots (tmutil listlocalsnapshots /)", False))
146
+ elif sys.platform == "win32":
147
+ fh = Path(os.environ.get("LOCALAPPDATA", "")) / "Microsoft" / "Windows" / "FileHistory" / "Configuration"
148
+ if fh.is_dir():
149
+ out.append(Copy("hint", "Windows File History", "File History is configured on this machine; if this path "
150
+ "is in a protected folder, past versions are on the backup drive", False))
151
+ return out
152
+
153
+
154
+ def scannable(copies: list[Copy]) -> list[Path]:
155
+ return [Path(c.where) for c in copies if c.scannable]
@@ -0,0 +1 @@
1
+ """Memory Hygiene: the forgetproof desktop app for macOS and Windows (`forgetproof desktop`)."""
@@ -0,0 +1,26 @@
1
+ """Entry point of the packaged desktop app.
2
+
3
+ With no arguments it opens the window. With arguments it is the forgetproof CLI (`Memory Hygiene.exe
4
+ sweep`, say), which is how the scheduled sweep runs from the same bundle. Imports are absolute
5
+ because PyInstaller runs this file as a script, not as part of the package.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import multiprocessing
11
+ import sys
12
+
13
+
14
+ def main() -> int:
15
+ multiprocessing.freeze_support() # a frozen app's spawned children re-enter here
16
+ if len(sys.argv) > 1 and not sys.argv[1].startswith("--"):
17
+ from forgetproof.cli import main as cli_main
18
+
19
+ return cli_main(sys.argv[1:])
20
+ from forgetproof.desktop.app import main as app_main
21
+
22
+ return app_main(sys.argv[1:])
23
+
24
+
25
+ if __name__ == "__main__":
26
+ sys.exit(main())