keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/update.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""Check for updates and fetch the new installer (docs/INSTALL.md).
|
|
2
|
+
|
|
3
|
+
The app checks quietly a minute after it starts and every 6 hours (`server.update_quietly`), and
|
|
4
|
+
for KeepfoldSetup installs downloads the new installer in the background. Nothing is installed
|
|
5
|
+
without a click.
|
|
6
|
+
|
|
7
|
+
Stdlib only. `latest` asks GitHub for the latest release of `REPO` and sends nothing about
|
|
8
|
+
the user (a generic User-Agent). `download` takes only that repo's release assets, follows
|
|
9
|
+
redirects only to GitHub's download hosts, caps the size and checks the SHA-256 that the release
|
|
10
|
+
publishes. `launch` starts the new KeepfoldSetup.exe with `--update`; it waits for the app to exit.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
import tomllib
|
|
22
|
+
import urllib.request
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
from importlib.metadata import version as _dist_version
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from urllib.error import HTTPError, URLError
|
|
27
|
+
from urllib.parse import unquote, urljoin, urlsplit
|
|
28
|
+
|
|
29
|
+
from keepfold._proc import proxy_env
|
|
30
|
+
|
|
31
|
+
REPO = "alenissacsam-2/keepfold" # the GitHub repo that holds the plugin marketplace
|
|
32
|
+
HERE = Path(__file__).resolve()
|
|
33
|
+
CHECKOUT = HERE.parents[2] # the source checkout of an editable install
|
|
34
|
+
|
|
35
|
+
API = "https://api.github.com"
|
|
36
|
+
EXE = "KeepfoldSetup.exe"
|
|
37
|
+
SHA = EXE + ".sha256" # the release checksum, saved beside a downloaded installer
|
|
38
|
+
MARKER = "keepfold-install.txt" # installer/setup_app.py drops it in the install folder
|
|
39
|
+
MAX_BYTES = 200 * 2**20
|
|
40
|
+
TIMEOUT = 10
|
|
41
|
+
DOWNLOADS = f"https://github.com/{REPO}/releases/download/"
|
|
42
|
+
_VERSION = re.compile(r"v?(\d+(?:\.\d+){1,3})")
|
|
43
|
+
_REDIRECTS = (301, 302, 303, 307, 308)
|
|
44
|
+
# where GitHub sends release downloads (raw.githubusercontent.com serves anyone's files: never)
|
|
45
|
+
_CDN = ("objects.githubusercontent.com", "release-assets.githubusercontent.com")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class UpdateError(ValueError):
|
|
49
|
+
"""A failure the app shows in plain words (a ValueError: the app's jobs show its text)."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
53
|
+
def redirect_request(self, *a, **k): # a 3xx then raises HTTPError; _get checks the target
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_opener = urllib.request.build_opener(_NoRedirect).open
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_version(tag) -> tuple[int, ...]:
|
|
61
|
+
m = _VERSION.fullmatch(tag.strip()) if isinstance(tag, str) else None
|
|
62
|
+
if not m: # pre-releases (v1.0.0-rc1) and odd tags are not offered
|
|
63
|
+
raise UpdateError(f"{tag!r} is not a release version Keepfold can update to.")
|
|
64
|
+
return tuple(int(x) for x in m[1].split("."))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def newer(a: tuple[int, ...], b: tuple[int, ...]) -> bool:
|
|
68
|
+
"""a > b, with 0.2 == 0.2.0."""
|
|
69
|
+
return a + (0,) * (4 - len(a)) > b + (0,) * (4 - len(b))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def current() -> str:
|
|
73
|
+
return _dist_version("keepfold")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def install_dir(exe: str | None = None) -> Path | None:
|
|
77
|
+
"""The KeepfoldSetup.exe install folder this Python runs from, or None (a dev install)."""
|
|
78
|
+
p = Path(exe or sys.executable).resolve()
|
|
79
|
+
return next((d for d in p.parents if (d / MARKER).is_file()), None)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def mode() -> str:
|
|
83
|
+
return "installer" if install_dir() else "dev"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def tool_source() -> Path | None:
|
|
87
|
+
"""The local folder a non-editable `uv tool install <folder>` built this copy from (read
|
|
88
|
+
from the tool's uv-receipt.toml), else None."""
|
|
89
|
+
receipt = next((d / "uv-receipt.toml" for d in HERE.parents
|
|
90
|
+
if (d / "uv-receipt.toml").is_file()), None)
|
|
91
|
+
try:
|
|
92
|
+
reqs = tomllib.loads(receipt.read_text(encoding="utf-8"))["tool"]["requirements"]
|
|
93
|
+
except (AttributeError, OSError, ValueError, KeyError, TypeError): # no or odd receipt
|
|
94
|
+
return None
|
|
95
|
+
src = next((r.get("directory") for r in reqs
|
|
96
|
+
if isinstance(r, dict) and r.get("name") == "keepfold"), None)
|
|
97
|
+
return Path(src) if isinstance(src, str) else None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def command(tag: str) -> str:
|
|
101
|
+
"""What a dev install runs to update, as docs/INSTALL.md says (a clone, else from git)."""
|
|
102
|
+
if (CHECKOUT / ".git").exists():
|
|
103
|
+
return f'cd "{CHECKOUT}"; git pull; uv tool install --editable . --reinstall'
|
|
104
|
+
if (src := tool_source()) is not None: # a fixed copy of a folder: rebuild it from there
|
|
105
|
+
pull = f'cd "{src}"; git pull; ' if (src / ".git").exists() else ""
|
|
106
|
+
return f'{pull}uv tool install --force --reinstall "{src}"'
|
|
107
|
+
return f"uv tool install --force git+https://github.com/{REPO}@{tag}"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _get(url: str, opener, accept: str):
|
|
111
|
+
req = urllib.request.Request(url, headers={"Accept": accept, "User-Agent": "keepfold-updater"})
|
|
112
|
+
return (opener or _opener)(req, timeout=TIMEOUT)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def latest(opener=None, api: str = API) -> dict:
|
|
116
|
+
try:
|
|
117
|
+
with _get(f"{api}/repos/{REPO}/releases/latest", opener,
|
|
118
|
+
"application/vnd.github+json") as r:
|
|
119
|
+
data = json.loads(r.read(2**20))
|
|
120
|
+
except HTTPError as e:
|
|
121
|
+
if e.code in (403, 429): # 60 API calls an hour per address: a campus network runs out
|
|
122
|
+
return _latest_from_page(opener, (e.headers or {}).get("X-RateLimit-Reset"))
|
|
123
|
+
if e.code == 404:
|
|
124
|
+
raise UpdateError("GitHub found no Keepfold release just now (the project page may be "
|
|
125
|
+
"unavailable for a while). Try again later.") from None
|
|
126
|
+
raise UpdateError(f"GitHub answered {e.code}. Try again later.") from None
|
|
127
|
+
except (URLError, OSError) as e:
|
|
128
|
+
raise UpdateError("Could not reach GitHub. Check your internet connection and try "
|
|
129
|
+
f"again ({getattr(e, 'reason', e)}).") from None
|
|
130
|
+
except ValueError:
|
|
131
|
+
raise UpdateError("GitHub sent an answer Keepfold could not read. Try again later.") \
|
|
132
|
+
from None
|
|
133
|
+
if not isinstance(data, dict):
|
|
134
|
+
raise UpdateError("GitHub sent an answer Keepfold could not read. Try again later.")
|
|
135
|
+
tag = data.get("tag_name")
|
|
136
|
+
if data.get("prerelease") or data.get("draft"):
|
|
137
|
+
raise UpdateError(f"The newest release ({tag}) is a pre-release; Keepfold only updates "
|
|
138
|
+
"to full releases.")
|
|
139
|
+
ver = parse_version(tag)
|
|
140
|
+
notes = f"https://github.com/{REPO}/releases/tag/{tag}" # built, never taken from the answer
|
|
141
|
+
assets = {a.get("name"): a for a in data.get("assets") or [] if isinstance(a, dict)}
|
|
142
|
+
exe, sha = assets.get(EXE), assets.get(EXE + ".sha256")
|
|
143
|
+
if not exe or not sha:
|
|
144
|
+
raise UpdateError(f"Keepfold {tag} has no {EXE} with its .sha256 on GitHub, so it cannot "
|
|
145
|
+
f"be installed from here. See {notes}")
|
|
146
|
+
want = f"{DOWNLOADS}{tag}/{EXE}" # exactly this release's files, no `..` tricks
|
|
147
|
+
links = (exe.get("browser_download_url"), sha.get("browser_download_url"))
|
|
148
|
+
if links != (want, want + ".sha256"):
|
|
149
|
+
raise UpdateError(f"Keepfold {tag}'s download links are not this release's files; stopped. "
|
|
150
|
+
f"See {notes}")
|
|
151
|
+
return {"tag": tag, "version": ver, "notes_url": notes,
|
|
152
|
+
"exe_url": want, "sha_url": want + ".sha256",
|
|
153
|
+
"exe_size": int(exe.get("size") or 0)}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _latest_from_page(opener, reset=None) -> dict:
|
|
157
|
+
"""The latest release without the API: github.com/<repo>/releases/latest redirects to its
|
|
158
|
+
tag (never a draft or a pre-release), and the asset links follow from the tag. The size is
|
|
159
|
+
unknown until the download; the .sha256 check is the same."""
|
|
160
|
+
page = f"https://github.com/{REPO}/releases/latest"
|
|
161
|
+
try: # X-RateLimit-Reset: when the API takes this network again (epoch seconds)
|
|
162
|
+
when = "after " + datetime.fromtimestamp(int(reset)).strftime("%H:%M")
|
|
163
|
+
except (TypeError, ValueError, OverflowError, OSError):
|
|
164
|
+
when = "in an hour"
|
|
165
|
+
limited = UpdateError("GitHub is refusing update checks from this network for now (it "
|
|
166
|
+
"limits how often one network may ask, and a VPN or a campus network "
|
|
167
|
+
f"is shared by many). Try again {when}, or download KeepfoldSetup.exe "
|
|
168
|
+
f"from the release page: {page}")
|
|
169
|
+
try:
|
|
170
|
+
with _get(page, opener, "text/html"):
|
|
171
|
+
raise limited # no redirect: no release to go to
|
|
172
|
+
except HTTPError as e:
|
|
173
|
+
loc = urljoin(page, e.headers.get("Location") or "") if e.code in _REDIRECTS else ""
|
|
174
|
+
except (URLError, OSError):
|
|
175
|
+
raise limited from None
|
|
176
|
+
m = re.fullmatch(rf"https://github\.com/{re.escape(REPO)}/releases/tag/([^/?#]+)", loc)
|
|
177
|
+
if not m:
|
|
178
|
+
raise limited
|
|
179
|
+
tag = unquote(m[1])
|
|
180
|
+
ver = parse_version(tag)
|
|
181
|
+
want = f"{DOWNLOADS}{tag}/{EXE}"
|
|
182
|
+
return {"tag": tag, "version": ver, "exe_url": want, "sha_url": want + ".sha256",
|
|
183
|
+
"notes_url": f"https://github.com/{REPO}/releases/tag/{tag}", "exe_size": 0}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def dest_dir(info: dict) -> Path:
|
|
187
|
+
return Path.home() / ".keepfold" / "tmp" / f"update-{'.'.join(map(str, info['version']))}"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _fetch(url: str, opener):
|
|
191
|
+
"""Open a release asset, following redirects only to GitHub's https download hosts."""
|
|
192
|
+
if not isinstance(url, str) or not url.startswith(DOWNLOADS):
|
|
193
|
+
raise UpdateError(f"Refused a download that is not a Keepfold release file: {url}")
|
|
194
|
+
for _ in range(5):
|
|
195
|
+
try:
|
|
196
|
+
return _get(url, opener, "application/octet-stream")
|
|
197
|
+
except HTTPError as e:
|
|
198
|
+
if e.code not in _REDIRECTS:
|
|
199
|
+
raise UpdateError(f"GitHub answered {e.code} for {url}. Try again later.") \
|
|
200
|
+
from None
|
|
201
|
+
url = urljoin(url, e.headers.get("Location") or "")
|
|
202
|
+
p = urlsplit(url)
|
|
203
|
+
if p.scheme != "https" or (p.hostname or "") not in _CDN:
|
|
204
|
+
raise UpdateError(f"The download was sent to {p.hostname or url}, which is not "
|
|
205
|
+
"GitHub; stopped.") from None
|
|
206
|
+
except (URLError, OSError) as e:
|
|
207
|
+
raise UpdateError("The download stopped. Check your internet connection and try "
|
|
208
|
+
f"again ({getattr(e, 'reason', e)}).") from None
|
|
209
|
+
raise UpdateError("The download was redirected too many times; stopped.")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def download(info: dict, dest: Path, on_progress=None, cancel=None, opener=None) -> Path | None:
|
|
213
|
+
"""`dest`/KeepfoldSetup.exe, checked against the release's .sha256; None when `cancel` (an
|
|
214
|
+
Event) is set. A partial or mismatched file is deleted."""
|
|
215
|
+
if info["exe_size"] > MAX_BYTES:
|
|
216
|
+
raise UpdateError(f"The update is larger than {MAX_BYTES // 2**20} MB; stopped.")
|
|
217
|
+
with _fetch(info["sha_url"], opener) as r:
|
|
218
|
+
m = re.match(rb"\s*([0-9a-fA-F]{64})\b", r.read(4096))
|
|
219
|
+
if not m:
|
|
220
|
+
raise UpdateError("The release's checksum file is not readable; stopped.")
|
|
221
|
+
want = m[1].decode().lower()
|
|
222
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
223
|
+
out = dest / EXE
|
|
224
|
+
if out.is_file() and _sha256(out) == want: # prepared before a restart: not fetched again
|
|
225
|
+
(dest / SHA).write_text(want, encoding="ascii")
|
|
226
|
+
return out
|
|
227
|
+
part = out.with_name(EXE + ".part")
|
|
228
|
+
h, got, said = hashlib.sha256(), 0, -1
|
|
229
|
+
try:
|
|
230
|
+
with _fetch(info["exe_url"], opener) as r, open(part, "wb") as f:
|
|
231
|
+
total = int(r.headers.get("Content-Length") or info["exe_size"] or 0)
|
|
232
|
+
if total > MAX_BYTES:
|
|
233
|
+
raise UpdateError(f"The update is larger than {MAX_BYTES // 2**20} MB; stopped.")
|
|
234
|
+
while chunk := r.read(1 << 16):
|
|
235
|
+
if cancel is not None and cancel.is_set():
|
|
236
|
+
break
|
|
237
|
+
got += len(chunk)
|
|
238
|
+
if got > MAX_BYTES:
|
|
239
|
+
raise UpdateError(f"The update is larger than {MAX_BYTES // 2**20} MB; "
|
|
240
|
+
"stopped.")
|
|
241
|
+
h.update(chunk)
|
|
242
|
+
f.write(chunk)
|
|
243
|
+
if on_progress and got >> 20 != said: # once per MB
|
|
244
|
+
said = got >> 20
|
|
245
|
+
on_progress(got, total)
|
|
246
|
+
except BaseException:
|
|
247
|
+
part.unlink(missing_ok=True)
|
|
248
|
+
raise
|
|
249
|
+
if cancel is not None and cancel.is_set():
|
|
250
|
+
part.unlink(missing_ok=True)
|
|
251
|
+
return None
|
|
252
|
+
if h.hexdigest() != want:
|
|
253
|
+
part.unlink(missing_ok=True)
|
|
254
|
+
raise UpdateError("The download does not match the release's checksum, so it was "
|
|
255
|
+
"deleted. Try again later.")
|
|
256
|
+
os.replace(part, out)
|
|
257
|
+
(dest / SHA).write_text(want, encoding="ascii") # what `prepared` checks at the next launch
|
|
258
|
+
return out
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _sha256(p: Path) -> str:
|
|
262
|
+
h = hashlib.sha256()
|
|
263
|
+
with open(p, "rb") as f:
|
|
264
|
+
while chunk := f.read(1 << 20):
|
|
265
|
+
h.update(chunk)
|
|
266
|
+
return h.hexdigest()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def prepared() -> Path | None:
|
|
270
|
+
"""The update-<version> folder (dest_dir) of an installer already downloaded for a newer
|
|
271
|
+
Keepfold than this one, whose file still matches the release checksum saved beside it; the
|
|
272
|
+
newest such, else None. The launch sweep keeps it, so a restart does not fetch it again."""
|
|
273
|
+
best: tuple | None = None
|
|
274
|
+
try:
|
|
275
|
+
cur = parse_version(current())
|
|
276
|
+
except (UpdateError, ValueError):
|
|
277
|
+
return None
|
|
278
|
+
for d in (Path.home() / ".keepfold" / "tmp").glob("update-*"):
|
|
279
|
+
try:
|
|
280
|
+
v = parse_version(d.name.removeprefix("update-"))
|
|
281
|
+
ok = newer(v, cur) and (best is None or newer(v, best[0])) and \
|
|
282
|
+
_sha256(d / EXE) == (d / SHA).read_text(encoding="ascii").strip().lower()
|
|
283
|
+
except (UpdateError, OSError, UnicodeDecodeError):
|
|
284
|
+
continue
|
|
285
|
+
if ok:
|
|
286
|
+
best = (v, d)
|
|
287
|
+
return best[1] if best else None
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def launch(exe: Path, app_pid: int, install: Path | None = None) -> None:
|
|
291
|
+
"""Start the new installer detached; it waits for `app_pid` to exit, then updates."""
|
|
292
|
+
args = [str(exe), "--update", "--wait-pid", str(app_pid)]
|
|
293
|
+
if install is not None:
|
|
294
|
+
args += ["--dir", str(install)]
|
|
295
|
+
flags = getattr(subprocess, "DETACHED_PROCESS", 0) | \
|
|
296
|
+
getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
297
|
+
# PyInstaller's temp-folder variables must not reach the new installer (as child_env does);
|
|
298
|
+
# the system proxy does, for its uv (which reads only HTTPS_PROXY)
|
|
299
|
+
subprocess.Popen(args, creationflags=flags, close_fds=True,
|
|
300
|
+
env={**proxy_env(), "PYINSTALLER_RESET_ENVIRONMENT": "1"})
|