fontlab-python-instamix 1.0.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.
- fontlab_instamix/__init__.py +38 -0
- fontlab_instamix/__main__.py +8 -0
- fontlab_instamix/__version__.py +24 -0
- fontlab_instamix/bootstrap.py +187 -0
- fontlab_instamix/cli.py +161 -0
- fontlab_instamix/dest.py +71 -0
- fontlab_instamix/env.py +98 -0
- fontlab_instamix/extension.py +408 -0
- fontlab_instamix/gui.py +74 -0
- fontlab_instamix/ledger.py +102 -0
- fontlab_instamix/manifest.py +115 -0
- fontlab_instamix/packages.py +122 -0
- fontlab_instamix/platformdirs.py +91 -0
- fontlab_instamix/uv.py +133 -0
- fontlab_instamix/venv.py +34 -0
- fontlab_instamix/wrap.py +71 -0
- fontlab_python_instamix-1.0.0.dist-info/METADATA +134 -0
- fontlab_python_instamix-1.0.0.dist-info/RECORD +21 -0
- fontlab_python_instamix-1.0.0.dist-info/WHEEL +4 -0
- fontlab_python_instamix-1.0.0.dist-info/entry_points.txt +2 -0
- fontlab_python_instamix-1.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/extension.py
|
|
2
|
+
"""Install and uninstall ``.fontlabext`` folders and ``.fontlabextz`` zips.
|
|
3
|
+
|
|
4
|
+
Flow: unpack (zip only) -> copy the folder to
|
|
5
|
+
``<data>/Extensions/Library/<id>.fontlabext`` -> link each file named by the
|
|
6
|
+
manifest ``install`` rules into its target (symlink, or copy on Windows or
|
|
7
|
+
when symlinking fails) -> record every created path in the ledger.
|
|
8
|
+
Uninstall removes exactly the recorded paths that are still ours.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import fnmatch
|
|
14
|
+
import os
|
|
15
|
+
import runpy
|
|
16
|
+
import shutil
|
|
17
|
+
import sys
|
|
18
|
+
import tempfile
|
|
19
|
+
import zipfile
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path, PurePosixPath
|
|
22
|
+
|
|
23
|
+
from . import dest, env, ledger, manifest
|
|
24
|
+
|
|
25
|
+
EXT = ".fontlabext"
|
|
26
|
+
ZIP = ".fontlabextz"
|
|
27
|
+
LIBRARY = "Extensions/Library"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class InstallError(RuntimeError):
|
|
31
|
+
"""An extension cannot be installed or uninstalled safely."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_ext(path: Path | str) -> bool:
|
|
35
|
+
return str(path).rstrip("/\\").lower().endswith(EXT)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_zip(path: Path | str) -> bool:
|
|
39
|
+
return str(path).lower().endswith(ZIP)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def basename(path: Path | str) -> str:
|
|
43
|
+
"""Folder name without ``.fontlabext`` (the ``{}`` placeholder)."""
|
|
44
|
+
name = Path(str(path).rstrip("/\\")).name
|
|
45
|
+
return name[: -len(EXT)] if name.lower().endswith(EXT) else name
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# --- zip safety --------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def check_member(name: str) -> None:
|
|
52
|
+
"""Reject zip member names that could write outside the target folder."""
|
|
53
|
+
if "\\" in name:
|
|
54
|
+
raise InstallError(f"zip member uses backslashes: {name!r}")
|
|
55
|
+
if name.startswith("/") or (len(name) > 1 and name[1] == ":"):
|
|
56
|
+
raise InstallError(f"zip member is absolute: {name!r}")
|
|
57
|
+
if ".." in PurePosixPath(name).parts:
|
|
58
|
+
raise InstallError(f"zip member escapes the folder: {name!r}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def unpack(zip_path: Path, into: Path) -> list[Path]:
|
|
62
|
+
"""Extract a ``.fontlabextz`` into ``into``; return its ``.fontlabext`` folders."""
|
|
63
|
+
with zipfile.ZipFile(zip_path) as archive:
|
|
64
|
+
names = archive.namelist()
|
|
65
|
+
for name in names:
|
|
66
|
+
check_member(name)
|
|
67
|
+
archive.extractall(into)
|
|
68
|
+
folders = sorted(p for p in Path(into).iterdir() if p.is_dir() and is_ext(p.name))
|
|
69
|
+
if not folders:
|
|
70
|
+
raise InstallError(f"{zip_path} holds no {EXT} folder at its root")
|
|
71
|
+
return folders
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def hook_for(folder: Path) -> Path | None:
|
|
75
|
+
"""Optional installer hook next to an unpacked extension."""
|
|
76
|
+
root = folder.parent
|
|
77
|
+
for child in root.iterdir():
|
|
78
|
+
lower = child.name.lower()
|
|
79
|
+
if child.is_file() and lower in (f"install_{folder.name.lower()}.vfpy", "install.vfpy"):
|
|
80
|
+
return child
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# --- linking -----------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class Placement:
|
|
89
|
+
"""Paths created while linking one extension (relative to data)."""
|
|
90
|
+
|
|
91
|
+
data: Path
|
|
92
|
+
copy: bool
|
|
93
|
+
entries: list[dict] = field(default_factory=list)
|
|
94
|
+
|
|
95
|
+
def rel(self, path: Path) -> str:
|
|
96
|
+
return Path(path).relative_to(self.data).as_posix()
|
|
97
|
+
|
|
98
|
+
def mkdirs(self, folder: Path) -> None:
|
|
99
|
+
missing = []
|
|
100
|
+
while not folder.exists():
|
|
101
|
+
missing.append(folder)
|
|
102
|
+
folder = folder.parent
|
|
103
|
+
for item in reversed(missing):
|
|
104
|
+
item.mkdir()
|
|
105
|
+
self.entries.append({"path": self.rel(item), "kind": "dir"})
|
|
106
|
+
|
|
107
|
+
def place(self, source: Path, target: Path) -> None:
|
|
108
|
+
if target.exists() or target.is_symlink():
|
|
109
|
+
raise InstallError(f"refusing to overwrite existing {target}")
|
|
110
|
+
self.mkdirs(target.parent)
|
|
111
|
+
if not self.copy:
|
|
112
|
+
try:
|
|
113
|
+
os.symlink(source, target, target_is_directory=source.is_dir())
|
|
114
|
+
self.entries.append({"path": self.rel(target), "kind": "link", "target": str(source)})
|
|
115
|
+
return
|
|
116
|
+
except (OSError, NotImplementedError):
|
|
117
|
+
pass
|
|
118
|
+
if source.is_dir():
|
|
119
|
+
self.mkdirs(target)
|
|
120
|
+
for child in sorted(source.rglob("*")):
|
|
121
|
+
if child.is_file() and "__pycache__" not in child.parts:
|
|
122
|
+
self.place(child, target / child.relative_to(source))
|
|
123
|
+
return
|
|
124
|
+
shutil.copy2(source, target)
|
|
125
|
+
self.entries.append(
|
|
126
|
+
{"path": self.rel(target), "kind": "copy", "sha256": ledger.sha256(target), "source": str(source)}
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def default_copy() -> bool:
|
|
131
|
+
"""Copy instead of symlinking on Windows."""
|
|
132
|
+
return sys.platform == "win32"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def sources(folder: Path, pattern: str) -> list[tuple[Path, str]]:
|
|
136
|
+
"""Files matched by a ``from`` pattern, with their path below the match root.
|
|
137
|
+
|
|
138
|
+
A folder contributes all its files (its contents go into the destination);
|
|
139
|
+
a file or glob contributes the files themselves.
|
|
140
|
+
"""
|
|
141
|
+
pattern = pattern.replace("\\", "/").strip("/")
|
|
142
|
+
if ".." in PurePosixPath(pattern).parts or pattern.startswith("/"):
|
|
143
|
+
raise InstallError(f"'from' must stay inside the extension: {pattern!r}")
|
|
144
|
+
matches = sorted(folder.glob(pattern)) if any(c in pattern for c in "*?[") else [folder / pattern]
|
|
145
|
+
found = []
|
|
146
|
+
for match in matches:
|
|
147
|
+
if match.is_dir():
|
|
148
|
+
for child in sorted(match.rglob("*")):
|
|
149
|
+
if child.is_file() and "__pycache__" not in child.parts:
|
|
150
|
+
found.append((child, child.relative_to(match).as_posix()))
|
|
151
|
+
elif match.is_file():
|
|
152
|
+
found.append((match, match.name))
|
|
153
|
+
if not found:
|
|
154
|
+
raise InstallError(f"'from' {pattern!r} matches nothing in {folder.name}")
|
|
155
|
+
return [(path, rel) for path, rel in found if not fnmatch.fnmatch(path.name.lower(), manifest.MANIFEST)]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def plan(folder: Path, info: manifest.Manifest, name: str, data: Path) -> list[tuple[Path, Path]]:
|
|
159
|
+
"""Return ``(source, target)`` pairs for every file the manifest installs."""
|
|
160
|
+
pairs = []
|
|
161
|
+
for rule in info.install:
|
|
162
|
+
target_dir = Path(data) / dest.resolve(rule.to, name, info.vars)
|
|
163
|
+
for source, rel in sources(folder, rule.source):
|
|
164
|
+
pairs.append((source, target_dir / rel))
|
|
165
|
+
site = env.site_packages(data)
|
|
166
|
+
for package in info.packages:
|
|
167
|
+
source = folder / package
|
|
168
|
+
if not source.is_dir() or ".." in PurePosixPath(package).parts:
|
|
169
|
+
raise InstallError(f"python package {package!r} is not a folder in {folder.name}")
|
|
170
|
+
pairs.append((source, site / source.name))
|
|
171
|
+
targets = [t for _, t in pairs]
|
|
172
|
+
if len(set(targets)) != len(targets):
|
|
173
|
+
raise InstallError("two install rules write the same destination")
|
|
174
|
+
return pairs
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# --- install / uninstall -----------------------------------------------------
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def library_path(data: Path, ext_id: str) -> Path:
|
|
181
|
+
return Path(data) / LIBRARY / f"{ledger.check_id(ext_id)}{EXT}"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def stage(folder: Path, target: Path) -> None:
|
|
185
|
+
"""Copy ``folder`` to ``target``, replacing an older copy at the last moment."""
|
|
186
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
187
|
+
fresh = target.with_name(target.name + ".new")
|
|
188
|
+
old = target.with_name(target.name + ".old")
|
|
189
|
+
for leftover in (fresh, old):
|
|
190
|
+
if leftover.exists():
|
|
191
|
+
shutil.rmtree(leftover)
|
|
192
|
+
shutil.copytree(folder, fresh, symlinks=False, ignore=shutil.ignore_patterns("__pycache__", ".DS_Store"))
|
|
193
|
+
if target.exists():
|
|
194
|
+
target.rename(old)
|
|
195
|
+
fresh.rename(target)
|
|
196
|
+
if old.exists():
|
|
197
|
+
shutil.rmtree(old)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def install_folder(
|
|
201
|
+
folder: Path,
|
|
202
|
+
data: Path,
|
|
203
|
+
*,
|
|
204
|
+
copy: bool | None = None,
|
|
205
|
+
requirements=None,
|
|
206
|
+
editable: bool = False,
|
|
207
|
+
) -> dict:
|
|
208
|
+
"""Install one unpacked ``.fontlabext`` folder; return its ledger record.
|
|
209
|
+
|
|
210
|
+
``requirements`` is called as ``requirements(data, list_of_specs)`` when
|
|
211
|
+
the manifest lists ``python.requires`` (``packages.install`` by default).
|
|
212
|
+
``editable`` links files straight to their real (symlink-resolved)
|
|
213
|
+
sources, e.g. a project checkout, and keeps only the manifest in Library.
|
|
214
|
+
"""
|
|
215
|
+
folder = Path(folder)
|
|
216
|
+
data = Path(data)
|
|
217
|
+
info = manifest.load(folder)
|
|
218
|
+
name = basename(folder)
|
|
219
|
+
env.ensure_folders(data)
|
|
220
|
+
library = library_path(data, info.id)
|
|
221
|
+
pairs = plan(folder, info, name, data) # validate before touching anything
|
|
222
|
+
previous = ledger.read(data, info.id)
|
|
223
|
+
backup = library.with_name(library.name + ".prev")
|
|
224
|
+
if backup.exists() or backup.is_symlink():
|
|
225
|
+
_remove_tree(data, backup)
|
|
226
|
+
placement = Placement(data, default_copy() if copy is None else copy)
|
|
227
|
+
removed: list[dict] = []
|
|
228
|
+
try:
|
|
229
|
+
if previous:
|
|
230
|
+
removed = _remove_tracked(data, previous.get("entries", []))
|
|
231
|
+
if library.exists():
|
|
232
|
+
library.rename(backup) # kept until the new version is fully placed
|
|
233
|
+
if editable:
|
|
234
|
+
with tempfile.TemporaryDirectory(prefix="instamix-stage-") as temp:
|
|
235
|
+
shutil.copy2(manifest.find(folder), Path(temp) / manifest.MANIFEST)
|
|
236
|
+
stage(Path(temp), library)
|
|
237
|
+
else:
|
|
238
|
+
stage(folder, library)
|
|
239
|
+
for source, target in pairs:
|
|
240
|
+
origin = source.resolve() if editable else library / source.relative_to(folder)
|
|
241
|
+
placement.place(origin, target)
|
|
242
|
+
except Exception:
|
|
243
|
+
# Roll back: drop the new files, bring back the old Library copy and links.
|
|
244
|
+
remove_entries(data, placement.entries)
|
|
245
|
+
if library.exists() or library.is_symlink():
|
|
246
|
+
_remove_tree(data, library)
|
|
247
|
+
if backup.exists():
|
|
248
|
+
backup.rename(library)
|
|
249
|
+
restore_entries(data, removed)
|
|
250
|
+
raise
|
|
251
|
+
if backup.exists():
|
|
252
|
+
_remove_tree(data, backup)
|
|
253
|
+
record = {
|
|
254
|
+
"id": info.id,
|
|
255
|
+
"name": info.name,
|
|
256
|
+
"version": info.version,
|
|
257
|
+
"basename": name,
|
|
258
|
+
"library": placement.rel(library),
|
|
259
|
+
"requires": list(info.requires),
|
|
260
|
+
"entries": placement.entries,
|
|
261
|
+
}
|
|
262
|
+
if info.requires:
|
|
263
|
+
if requirements is None:
|
|
264
|
+
from . import packages
|
|
265
|
+
|
|
266
|
+
requirements = packages.install
|
|
267
|
+
try:
|
|
268
|
+
requirements(data, list(info.requires))
|
|
269
|
+
except Exception:
|
|
270
|
+
record["requires_failed"] = True
|
|
271
|
+
ledger.write(data, record) # files are in place; uninstall must still find them
|
|
272
|
+
raise
|
|
273
|
+
ledger.write(data, record)
|
|
274
|
+
return record
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def install(
|
|
278
|
+
path: Path,
|
|
279
|
+
data: Path,
|
|
280
|
+
*,
|
|
281
|
+
copy: bool | None = None,
|
|
282
|
+
run_hooks: bool = False,
|
|
283
|
+
requirements=None,
|
|
284
|
+
) -> list[dict]:
|
|
285
|
+
"""Install a ``.fontlabext`` folder or every folder in a ``.fontlabextz``."""
|
|
286
|
+
path = Path(path)
|
|
287
|
+
if is_zip(path) and path.is_file():
|
|
288
|
+
with tempfile.TemporaryDirectory(prefix="instamix-") as temp:
|
|
289
|
+
records, hooks = [], []
|
|
290
|
+
for folder in unpack(path, Path(temp)):
|
|
291
|
+
records.append(install_folder(folder, data, copy=copy, requirements=requirements))
|
|
292
|
+
hook = hook_for(folder)
|
|
293
|
+
if hook and hook not in hooks:
|
|
294
|
+
hooks.append(hook)
|
|
295
|
+
for hook in hooks if run_hooks else []:
|
|
296
|
+
try:
|
|
297
|
+
runpy.run_path(str(hook), run_name="__main__")
|
|
298
|
+
except Exception as error: # noqa: BLE001 - the install itself succeeded
|
|
299
|
+
print(f"instamix: hook {hook.name} failed: {error}", file=sys.stderr)
|
|
300
|
+
return records
|
|
301
|
+
if path.is_dir() and is_ext(path):
|
|
302
|
+
return [install_folder(path, data, copy=copy, requirements=requirements)]
|
|
303
|
+
raise InstallError(f"not a {EXT} folder or {ZIP} file: {path}")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _ours(path: Path, entry: dict) -> bool:
|
|
307
|
+
if entry["kind"] == "link":
|
|
308
|
+
return path.is_symlink() and os.readlink(path) == entry["target"]
|
|
309
|
+
if entry["kind"] == "copy":
|
|
310
|
+
return path.is_file() and not path.is_symlink() and ledger.sha256(path) == entry["sha256"]
|
|
311
|
+
return path.is_dir() and not path.is_symlink()
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def inside(data: Path, path: Path) -> bool:
|
|
315
|
+
"""True if ``path`` lies inside ``data``; the last part is not followed."""
|
|
316
|
+
root = Path(os.path.realpath(data))
|
|
317
|
+
parent = Path(os.path.realpath(Path(path).parent))
|
|
318
|
+
return (parent == root or root in parent.parents) and Path(path).name not in ("", ".", "..")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _entry_path(data: Path, entry: dict) -> Path | None:
|
|
322
|
+
rel = str(entry.get("path", ""))
|
|
323
|
+
if not rel or PurePosixPath(rel).is_absolute() or ".." in PurePosixPath(rel).parts or ":" in rel or "\\" in rel:
|
|
324
|
+
return None
|
|
325
|
+
path = Path(data) / rel
|
|
326
|
+
return path if inside(data, path) else None
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _remove_tracked(data: Path, entries: list[dict]) -> list[dict]:
|
|
330
|
+
"""Remove recorded paths that are still ours; return the removed entries."""
|
|
331
|
+
removed = []
|
|
332
|
+
for entry in reversed(entries):
|
|
333
|
+
path = _entry_path(data, entry)
|
|
334
|
+
if path is None or not (path.exists() or path.is_symlink()) or not _ours(path, entry):
|
|
335
|
+
continue
|
|
336
|
+
if entry["kind"] == "dir":
|
|
337
|
+
try:
|
|
338
|
+
path.rmdir()
|
|
339
|
+
except OSError:
|
|
340
|
+
continue # holds files we did not create
|
|
341
|
+
else:
|
|
342
|
+
path.unlink()
|
|
343
|
+
removed.append(entry)
|
|
344
|
+
return removed
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def remove_entries(data: Path, entries: list[dict]) -> list[str]:
|
|
348
|
+
"""Remove recorded paths that are still ours; return the ones left behind."""
|
|
349
|
+
removed = {id(e) for e in _remove_tracked(data, entries)}
|
|
350
|
+
kept = []
|
|
351
|
+
for entry in entries:
|
|
352
|
+
path = _entry_path(data, entry)
|
|
353
|
+
if id(entry) not in removed and (path is None or path.exists() or path.is_symlink()):
|
|
354
|
+
kept.append(str(entry.get("path")))
|
|
355
|
+
return kept
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def restore_entries(data: Path, entries: list[dict]) -> None:
|
|
359
|
+
"""Re-create entries removed by :func:`_remove_tracked` (rollback)."""
|
|
360
|
+
for entry in reversed(entries): # removal ran children first
|
|
361
|
+
path = _entry_path(data, entry)
|
|
362
|
+
if path is None or path.exists() or path.is_symlink():
|
|
363
|
+
continue
|
|
364
|
+
try:
|
|
365
|
+
if entry["kind"] == "dir":
|
|
366
|
+
path.mkdir()
|
|
367
|
+
elif entry["kind"] == "link":
|
|
368
|
+
os.symlink(entry["target"], path, target_is_directory=Path(entry["target"]).is_dir())
|
|
369
|
+
elif entry.get("source") and Path(entry["source"]).is_file():
|
|
370
|
+
shutil.copy2(entry["source"], path)
|
|
371
|
+
except OSError as error:
|
|
372
|
+
print(f"instamix: could not restore {path}: {error}", file=sys.stderr)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _remove_tree(data: Path, path: Path) -> None:
|
|
376
|
+
"""Delete ``path`` (inside ``data``) without following a symlinked folder."""
|
|
377
|
+
if not inside(data, path):
|
|
378
|
+
raise InstallError(f"refusing to delete outside the data folder: {path}")
|
|
379
|
+
if path.is_symlink() or path.is_file():
|
|
380
|
+
path.unlink()
|
|
381
|
+
elif path.is_dir():
|
|
382
|
+
shutil.rmtree(path) # rmtree unlinks nested symlinks, never follows them
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def uninstall_links(data: Path, record: dict) -> list[str]:
|
|
386
|
+
return remove_entries(data, record.get("entries", []))
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def uninstall(ext_id: str, data: Path) -> list[str]:
|
|
390
|
+
"""Uninstall ``ext_id``; return paths left in place because they changed."""
|
|
391
|
+
try:
|
|
392
|
+
record = ledger.read(data, ext_id)
|
|
393
|
+
except ledger.LedgerError as error:
|
|
394
|
+
raise InstallError(str(error)) from error
|
|
395
|
+
if record is None:
|
|
396
|
+
raise InstallError(f"{ext_id} is not installed")
|
|
397
|
+
kept = uninstall_links(data, record)
|
|
398
|
+
library = library_path(data, ext_id)
|
|
399
|
+
if record.get("library") not in (None, Path(library).relative_to(data).as_posix()):
|
|
400
|
+
raise InstallError(f"ledger for {ext_id} names an unexpected Library path: {record.get('library')!r}")
|
|
401
|
+
if library.exists() or library.is_symlink():
|
|
402
|
+
_remove_tree(data, library)
|
|
403
|
+
ledger.remove(data, ext_id)
|
|
404
|
+
return kept
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def installed(data: Path) -> list[dict]:
|
|
408
|
+
return ledger.records(data)
|
fontlab_instamix/gui.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/gui.py
|
|
2
|
+
"""Small PythonQt dialogs for use inside FontLab.
|
|
3
|
+
|
|
4
|
+
PythonQt is imported only when a function is called, never at module import,
|
|
5
|
+
so this module is importable outside FontLab. Without PythonQt every helper
|
|
6
|
+
falls back to the console.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _qtgui():
|
|
13
|
+
try:
|
|
14
|
+
from PythonQt import QtGui # type: ignore[import-not-found]
|
|
15
|
+
except ImportError:
|
|
16
|
+
return None
|
|
17
|
+
return QtGui
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def message(text: str, title: str = "Instamix", *, error: bool = False) -> None:
|
|
21
|
+
QtGui = _qtgui()
|
|
22
|
+
if QtGui is None:
|
|
23
|
+
print(f"{title}: {text}")
|
|
24
|
+
return
|
|
25
|
+
if error:
|
|
26
|
+
QtGui.QMessageBox.critical(None, title, text)
|
|
27
|
+
else:
|
|
28
|
+
QtGui.QMessageBox.information(None, title, text)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def confirm(text: str, title: str = "Instamix") -> bool:
|
|
32
|
+
QtGui = _qtgui()
|
|
33
|
+
if QtGui is None:
|
|
34
|
+
return input(f"{title}: {text} [y/N] ").strip().lower() in ("y", "yes")
|
|
35
|
+
buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
|
|
36
|
+
return QtGui.QMessageBox.question(None, title, text, buttons) == QtGui.QMessageBox.Yes
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def pick_file(title: str = "Choose an extension", pattern: str = "Extensions (*.fontlabextz *.fontlabext)") -> str:
|
|
40
|
+
"""Return a chosen path, or an empty string when cancelled."""
|
|
41
|
+
QtGui = _qtgui()
|
|
42
|
+
if QtGui is None:
|
|
43
|
+
return input(f"{title}: ").strip()
|
|
44
|
+
return str(QtGui.QFileDialog.getOpenFileName(None, title, "", pattern) or "")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Progress:
|
|
48
|
+
"""Context manager showing a busy progress dialog (or printing steps)."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, title: str = "Instamix", steps: int = 0):
|
|
51
|
+
self.title = title
|
|
52
|
+
self.steps = steps
|
|
53
|
+
self.dialog = None
|
|
54
|
+
|
|
55
|
+
def __enter__(self) -> Progress:
|
|
56
|
+
QtGui = _qtgui()
|
|
57
|
+
if QtGui is not None:
|
|
58
|
+
self.dialog = QtGui.QProgressDialog(self.title, "", 0, self.steps)
|
|
59
|
+
self.dialog.setCancelButton(None)
|
|
60
|
+
self.dialog.show()
|
|
61
|
+
return self
|
|
62
|
+
|
|
63
|
+
def step(self, text: str, value: int | None = None) -> None:
|
|
64
|
+
if self.dialog is None:
|
|
65
|
+
print(f"{self.title}: {text}")
|
|
66
|
+
return
|
|
67
|
+
self.dialog.setLabelText(text)
|
|
68
|
+
if value is not None:
|
|
69
|
+
self.dialog.setValue(value)
|
|
70
|
+
_qtgui().QApplication.processEvents()
|
|
71
|
+
|
|
72
|
+
def __exit__(self, *exc) -> None:
|
|
73
|
+
if self.dialog is not None:
|
|
74
|
+
self.dialog.close()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/ledger.py
|
|
2
|
+
"""Install records: ``Extensions/.instamix/<id>.json`` plus a JSONL log.
|
|
3
|
+
|
|
4
|
+
The ledger lives outside ``Extensions/Library``, which holds only installed
|
|
5
|
+
extension copies.
|
|
6
|
+
|
|
7
|
+
A record lists every path instamix created for one extension, with a kind
|
|
8
|
+
(``link``, ``copy`` or ``dir``) and, for copies, a SHA-256, so uninstall
|
|
9
|
+
removes exactly those and leaves anything the user changed.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
LEDGER_DIR = "Extensions/.instamix"
|
|
22
|
+
SAFE_ID = re.compile(r"^[A-Za-z0-9_-][A-Za-z0-9._-]*$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class LedgerError(ValueError):
|
|
26
|
+
"""An extension id that cannot name a ledger record safely."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def check_id(ext_id: str) -> str:
|
|
30
|
+
"""Return ``ext_id`` if it is a safe reverse-DNS-like name, else raise."""
|
|
31
|
+
if not isinstance(ext_id, str) or not SAFE_ID.match(ext_id) or ".." in ext_id:
|
|
32
|
+
raise LedgerError(f"invalid extension id: {ext_id!r}")
|
|
33
|
+
return ext_id
|
|
34
|
+
LOG = "install.log"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def ledger_dir(data: Path) -> Path:
|
|
38
|
+
return Path(data) / LEDGER_DIR
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def record_path(data: Path, ext_id: str) -> Path:
|
|
42
|
+
return ledger_dir(data) / f"{check_id(ext_id)}.json"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def sha256(path: Path) -> str:
|
|
46
|
+
digest = hashlib.sha256()
|
|
47
|
+
with open(path, "rb") as handle:
|
|
48
|
+
for chunk in iter(lambda: handle.read(1 << 16), b""):
|
|
49
|
+
digest.update(chunk)
|
|
50
|
+
return digest.hexdigest()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def read(data: Path, ext_id: str) -> dict | None:
|
|
54
|
+
"""Return the install record for ``ext_id`` or ``None``."""
|
|
55
|
+
path = record_path(data, ext_id)
|
|
56
|
+
if not path.is_file():
|
|
57
|
+
return None
|
|
58
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def write(data: Path, record: dict) -> Path:
|
|
62
|
+
"""Write ``record`` atomically and append it to the log."""
|
|
63
|
+
path = record_path(data, record["id"])
|
|
64
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
temp = path.with_suffix(".tmp")
|
|
66
|
+
temp.write_text(json.dumps(record, indent=2, sort_keys=True), encoding="utf-8")
|
|
67
|
+
temp.replace(path)
|
|
68
|
+
log(data, {"action": "install", "id": record["id"], "version": record.get("version")})
|
|
69
|
+
return path
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def remove(data: Path, ext_id: str) -> None:
|
|
73
|
+
path = record_path(data, ext_id)
|
|
74
|
+
if path.exists():
|
|
75
|
+
path.unlink()
|
|
76
|
+
log(data, {"action": "uninstall", "id": ext_id})
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def records(data: Path) -> list[dict]:
|
|
80
|
+
"""Return all install records, sorted by id."""
|
|
81
|
+
folder = ledger_dir(data)
|
|
82
|
+
if not folder.is_dir():
|
|
83
|
+
return []
|
|
84
|
+
found = []
|
|
85
|
+
for path in sorted(folder.glob("*.json")):
|
|
86
|
+
try:
|
|
87
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
88
|
+
check_id(record["id"])
|
|
89
|
+
except (OSError, ValueError, KeyError, TypeError) as error:
|
|
90
|
+
print(f"instamix: skipping unreadable ledger record {path}: {error}", file=sys.stderr)
|
|
91
|
+
continue
|
|
92
|
+
found.append(record)
|
|
93
|
+
return sorted(found, key=lambda r: r["id"])
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def log(data: Path, entry: dict) -> None:
|
|
97
|
+
"""Append one JSON line to the install log."""
|
|
98
|
+
folder = ledger_dir(data)
|
|
99
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
entry = {"time": time.strftime("%Y-%m-%dT%H:%M:%S"), **entry}
|
|
101
|
+
with open(folder / LOG, "a", encoding="utf-8") as handle:
|
|
102
|
+
handle.write(json.dumps(entry, sort_keys=True) + "\n")
|