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,115 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/manifest.py
|
|
2
|
+
"""Read and validate ``manifest.fontlabextj`` (strict JSON)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
MANIFEST = "manifest.fontlabextj"
|
|
12
|
+
ID_PATTERN = re.compile(r"^[a-z][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$")
|
|
13
|
+
_KEYS = {"id", "name", "version", "description", "min_fontlab", "python", "vars", "install", "this_file"}
|
|
14
|
+
_PYTHON_KEYS = {"requires", "packages"}
|
|
15
|
+
_RULE_KEYS = {"from", "to"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ManifestError(ValueError):
|
|
19
|
+
"""The manifest is missing, malformed or has unknown keys."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Rule:
|
|
24
|
+
source: str
|
|
25
|
+
to: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Manifest:
|
|
30
|
+
id: str
|
|
31
|
+
name: str
|
|
32
|
+
version: str
|
|
33
|
+
description: str = ""
|
|
34
|
+
min_fontlab: str = ""
|
|
35
|
+
requires: tuple[str, ...] = ()
|
|
36
|
+
packages: tuple[str, ...] = ()
|
|
37
|
+
vars: dict[str, str] = field(default_factory=dict)
|
|
38
|
+
install: tuple[Rule, ...] = ()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _strings(value, where: str) -> tuple[str, ...]:
|
|
42
|
+
if not isinstance(value, list) or not all(isinstance(v, str) and v for v in value):
|
|
43
|
+
raise ManifestError(f"{where} must be a list of non-empty strings")
|
|
44
|
+
return tuple(value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _unknown(data: dict, allowed: set[str], where: str) -> None:
|
|
48
|
+
extra = sorted(set(data) - allowed)
|
|
49
|
+
if extra:
|
|
50
|
+
raise ManifestError(f"unknown key(s) in {where}: {', '.join(extra)}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse(data: object) -> Manifest:
|
|
54
|
+
"""Validate decoded JSON and return a :class:`Manifest`."""
|
|
55
|
+
if not isinstance(data, dict):
|
|
56
|
+
raise ManifestError("manifest must be a JSON object")
|
|
57
|
+
_unknown(data, _KEYS, "manifest")
|
|
58
|
+
for key in ("id", "name", "version"):
|
|
59
|
+
if not isinstance(data.get(key), str) or not data[key].strip():
|
|
60
|
+
raise ManifestError(f"manifest needs a non-empty string {key!r}")
|
|
61
|
+
if not ID_PATTERN.match(data["id"]):
|
|
62
|
+
raise ManifestError(f"id must be lowercase reverse-DNS like com.example.tool: {data['id']!r}")
|
|
63
|
+
for key in ("description", "min_fontlab"):
|
|
64
|
+
if not isinstance(data.get(key, ""), str):
|
|
65
|
+
raise ManifestError(f"{key} must be a string")
|
|
66
|
+
python = data.get("python", {})
|
|
67
|
+
if not isinstance(python, dict):
|
|
68
|
+
raise ManifestError("python must be an object")
|
|
69
|
+
_unknown(python, _PYTHON_KEYS, "python")
|
|
70
|
+
variables = data.get("vars", {})
|
|
71
|
+
if not isinstance(variables, dict) or not all(
|
|
72
|
+
isinstance(k, str) and isinstance(v, str) for k, v in variables.items()
|
|
73
|
+
):
|
|
74
|
+
raise ManifestError("vars must map strings to strings")
|
|
75
|
+
rules = data.get("install", [])
|
|
76
|
+
if not isinstance(rules, list):
|
|
77
|
+
raise ManifestError("install must be a list")
|
|
78
|
+
parsed = []
|
|
79
|
+
for index, rule in enumerate(rules):
|
|
80
|
+
where = f"install[{index}]"
|
|
81
|
+
if not isinstance(rule, dict):
|
|
82
|
+
raise ManifestError(f"{where} must be an object")
|
|
83
|
+
_unknown(rule, _RULE_KEYS, where)
|
|
84
|
+
if not all(isinstance(rule.get(k), str) and rule[k] for k in _RULE_KEYS):
|
|
85
|
+
raise ManifestError(f"{where} needs string 'from' and 'to'")
|
|
86
|
+
parsed.append(Rule(rule["from"], rule["to"]))
|
|
87
|
+
return Manifest(
|
|
88
|
+
id=data["id"],
|
|
89
|
+
name=data["name"],
|
|
90
|
+
version=data["version"],
|
|
91
|
+
description=data.get("description", ""),
|
|
92
|
+
min_fontlab=data.get("min_fontlab", ""),
|
|
93
|
+
requires=_strings(python.get("requires", []), "python.requires"),
|
|
94
|
+
packages=_strings(python.get("packages", []), "python.packages"),
|
|
95
|
+
vars=dict(variables),
|
|
96
|
+
install=tuple(parsed),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def find(folder: Path) -> Path:
|
|
101
|
+
"""Return the manifest path inside ``folder`` (name matched case-insensitively)."""
|
|
102
|
+
for child in Path(folder).iterdir():
|
|
103
|
+
if child.is_file() and child.name.lower() == MANIFEST:
|
|
104
|
+
return child
|
|
105
|
+
raise ManifestError(f"no {MANIFEST} in {folder}")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def load(folder: Path) -> Manifest:
|
|
109
|
+
"""Read and validate the manifest of a ``.fontlabext`` folder."""
|
|
110
|
+
path = find(folder)
|
|
111
|
+
try:
|
|
112
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
113
|
+
except json.JSONDecodeError as exc:
|
|
114
|
+
raise ManifestError(f"{path}: invalid JSON: {exc}") from exc
|
|
115
|
+
return parse(data)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/packages.py
|
|
2
|
+
"""Install PyPI or ``git+`` packages into FontLab's site-packages with uv.
|
|
3
|
+
|
|
4
|
+
Uses ``uv pip install --target <site-packages> --python-version 3.11
|
|
5
|
+
--python-platform <triple>`` so packages match FontLab's embedded Python,
|
|
6
|
+
whatever Python runs instamix.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path, PurePosixPath
|
|
14
|
+
|
|
15
|
+
from . import env, uv
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def install_args(data: Path, specs: list[str], *, upgrade: bool = False) -> list[str]:
|
|
19
|
+
"""uv arguments (without the uv binary) for installing ``specs``."""
|
|
20
|
+
if not specs:
|
|
21
|
+
raise ValueError("no packages to install")
|
|
22
|
+
args = [
|
|
23
|
+
"pip",
|
|
24
|
+
"install",
|
|
25
|
+
"--target",
|
|
26
|
+
str(env.site_packages(data)),
|
|
27
|
+
"--python-version",
|
|
28
|
+
env.FONTLAB_PYTHON,
|
|
29
|
+
"--python-platform",
|
|
30
|
+
env.uv_platform(),
|
|
31
|
+
]
|
|
32
|
+
if upgrade:
|
|
33
|
+
args.append("--upgrade")
|
|
34
|
+
return args + list(specs)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def install(
|
|
38
|
+
data: Path,
|
|
39
|
+
specs: list[str],
|
|
40
|
+
*,
|
|
41
|
+
upgrade: bool = False,
|
|
42
|
+
uv_bin: Path | None = None,
|
|
43
|
+
runner=subprocess.run,
|
|
44
|
+
) -> subprocess.CompletedProcess:
|
|
45
|
+
"""Install ``specs`` into ``<data>/python/3.11/site-packages``."""
|
|
46
|
+
env.site_packages(data).mkdir(parents=True, exist_ok=True)
|
|
47
|
+
uv_bin = uv_bin or uv.ensure(data)
|
|
48
|
+
return uv.run(uv_bin, install_args(data, specs, upgrade=upgrade), runner=runner)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def dist_name(folder: str) -> str:
|
|
52
|
+
"""Distribution name from a ``*.dist-info`` folder name."""
|
|
53
|
+
return folder[: -len(".dist-info")].rsplit("-", 1)[0]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def listed(data: Path) -> list[tuple[str, str]]:
|
|
57
|
+
"""``(name, version)`` of every distribution in site-packages."""
|
|
58
|
+
site = env.site_packages(data)
|
|
59
|
+
if not site.is_dir():
|
|
60
|
+
return []
|
|
61
|
+
found = []
|
|
62
|
+
for info in sorted(site.glob("*.dist-info")):
|
|
63
|
+
stem = info.name[: -len(".dist-info")]
|
|
64
|
+
name, _, version = stem.rpartition("-")
|
|
65
|
+
found.append((name or stem, version))
|
|
66
|
+
return found
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _normal(name: str) -> str:
|
|
70
|
+
return name.lower().replace("-", "_").replace(".", "_")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def uninstall(data: Path, name: str) -> list[str]:
|
|
74
|
+
"""Remove a distribution installed with ``--target`` using its RECORD.
|
|
75
|
+
|
|
76
|
+
``uv pip uninstall`` cannot address a ``--target`` folder, so this reads
|
|
77
|
+
the RECORD file directly. Returns the removed relative paths.
|
|
78
|
+
"""
|
|
79
|
+
site = env.site_packages(data)
|
|
80
|
+
infos = [i for i in site.glob("*.dist-info") if _normal(dist_name(i.name)) == _normal(name)]
|
|
81
|
+
if not infos:
|
|
82
|
+
raise ValueError(f"{name} is not installed in {site}")
|
|
83
|
+
removed = []
|
|
84
|
+
root = Path(os.path.realpath(site))
|
|
85
|
+
for info in infos:
|
|
86
|
+
record = info / "RECORD"
|
|
87
|
+
lines = record.read_text(encoding="utf-8").splitlines() if record.is_file() else []
|
|
88
|
+
parents: set[Path] = set()
|
|
89
|
+
for line in lines:
|
|
90
|
+
rel = line.split(",", 1)[0]
|
|
91
|
+
if not rel or "\\" in rel or PurePosixPath(rel).is_absolute() or ".." in PurePosixPath(rel).parts:
|
|
92
|
+
continue
|
|
93
|
+
target = site / rel
|
|
94
|
+
# Check the folder holding the entry, never following the entry itself.
|
|
95
|
+
parent = Path(os.path.realpath(target.parent))
|
|
96
|
+
if parent != root and root not in parent.parents:
|
|
97
|
+
continue
|
|
98
|
+
if target.is_symlink() or target.is_file():
|
|
99
|
+
target.unlink()
|
|
100
|
+
removed.append(rel)
|
|
101
|
+
parents.add(target.parent)
|
|
102
|
+
_prune(site, info, parents)
|
|
103
|
+
return removed
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _prune(site: Path, info: Path, parents: set[Path]) -> None:
|
|
107
|
+
"""Delete ``info`` and the now-empty folders above removed files, up to ``site``."""
|
|
108
|
+
import shutil
|
|
109
|
+
|
|
110
|
+
if info.is_dir() and not info.is_symlink():
|
|
111
|
+
shutil.rmtree(info)
|
|
112
|
+
for folder in sorted(parents, key=lambda p: -len(p.parts)):
|
|
113
|
+
while folder != site and site in folder.parents:
|
|
114
|
+
if folder.is_symlink() or not folder.is_dir():
|
|
115
|
+
break
|
|
116
|
+
cache = folder / "__pycache__"
|
|
117
|
+
if cache.is_dir() and not cache.is_symlink() and all(c.suffix == ".pyc" for c in cache.iterdir()):
|
|
118
|
+
shutil.rmtree(cache)
|
|
119
|
+
if any(folder.iterdir()):
|
|
120
|
+
break
|
|
121
|
+
folder.rmdir()
|
|
122
|
+
folder = folder.parent
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/platformdirs.py
|
|
2
|
+
"""Tiny subset of platformdirs: the two folders instamix needs.
|
|
3
|
+
|
|
4
|
+
Adapted from platformdirs (https://github.com/tox-dev/platformdirs).
|
|
5
|
+
|
|
6
|
+
MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2010-202x The platformdirs developers
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import os
|
|
32
|
+
import sys
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
_DOCUMENTS_GUID = "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def user_data_dir_macos() -> Path:
|
|
39
|
+
"""``~/Library/Application Support``."""
|
|
40
|
+
return Path.home() / "Library" / "Application Support"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _documents_via_ctypes() -> str:
|
|
44
|
+
import ctypes
|
|
45
|
+
from ctypes import wintypes
|
|
46
|
+
|
|
47
|
+
class GUID(ctypes.Structure):
|
|
48
|
+
_fields_ = [
|
|
49
|
+
("Data1", wintypes.DWORD),
|
|
50
|
+
("Data2", wintypes.WORD),
|
|
51
|
+
("Data3", wintypes.WORD),
|
|
52
|
+
("Data4", wintypes.BYTE * 8),
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
guid = GUID()
|
|
56
|
+
ole32 = ctypes.WinDLL("ole32") # type: ignore[attr-defined]
|
|
57
|
+
ole32.CLSIDFromString(ctypes.c_wchar_p(_DOCUMENTS_GUID), ctypes.byref(guid))
|
|
58
|
+
path_ptr = ctypes.c_wchar_p()
|
|
59
|
+
shell32 = ctypes.WinDLL("shell32") # type: ignore[attr-defined]
|
|
60
|
+
result = shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0x4000, None, ctypes.byref(path_ptr))
|
|
61
|
+
try:
|
|
62
|
+
if result != 0 or not path_ptr.value:
|
|
63
|
+
raise OSError("SHGetKnownFolderPath failed for Documents")
|
|
64
|
+
return path_ptr.value
|
|
65
|
+
finally:
|
|
66
|
+
ole32.CoTaskMemFree(path_ptr)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _documents_via_registry() -> str:
|
|
70
|
+
import winreg # type: ignore[import-not-found]
|
|
71
|
+
|
|
72
|
+
key = r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
|
|
73
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) as handle:
|
|
74
|
+
return str(winreg.QueryValueEx(handle, "Personal")[0])
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def user_documents_dir_windows() -> Path:
|
|
78
|
+
"""Windows Documents folder: known-folder API, registry, then USERPROFILE."""
|
|
79
|
+
for resolver in (_documents_via_ctypes, _documents_via_registry):
|
|
80
|
+
try:
|
|
81
|
+
return Path(os.path.normpath(resolver()))
|
|
82
|
+
except Exception: # noqa: BLE001 - fall through to the next resolver
|
|
83
|
+
continue
|
|
84
|
+
return Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Documents"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def default_data_dir(platform: str = sys.platform) -> Path:
|
|
88
|
+
"""FontLab 9's default data folder when FontLab itself cannot tell us."""
|
|
89
|
+
if platform == "win32":
|
|
90
|
+
return user_documents_dir_windows() / "FontLab" / "FontLab 9"
|
|
91
|
+
return user_data_dir_macos() / "FontLab" / "FontLab 9"
|
fontlab_instamix/uv.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/uv.py
|
|
2
|
+
"""Find, download and run uv as its own binary.
|
|
3
|
+
|
|
4
|
+
Never runs ``sys.executable``: inside FontLab that is FontLab itself.
|
|
5
|
+
uv is downloaded from GitHub releases into ``<data>/python/uv/`` and its
|
|
6
|
+
SHA-256 is checked against the ``.sha256`` file published with the release.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import io
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import tarfile
|
|
18
|
+
import urllib.request
|
|
19
|
+
import zipfile
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from . import env
|
|
23
|
+
|
|
24
|
+
RELEASES = "https://github.com/astral-sh/uv/releases"
|
|
25
|
+
CANDIDATES = (
|
|
26
|
+
"~/.local/bin/uv",
|
|
27
|
+
"~/.cargo/bin/uv",
|
|
28
|
+
"/opt/homebrew/bin/uv",
|
|
29
|
+
"/usr/local/bin/uv",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class UvError(RuntimeError):
|
|
34
|
+
"""uv is missing, failed to download, or a uv command failed."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def exe_name() -> str:
|
|
38
|
+
return "uv.exe" if sys.platform == "win32" else "uv"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def local_uv(data: Path) -> Path:
|
|
42
|
+
"""Where instamix keeps its own uv: ``<data>/python/uv/uv``."""
|
|
43
|
+
return Path(data) / "python" / "uv" / exe_name()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def find(data: Path | None = None) -> Path | None:
|
|
47
|
+
"""Return a usable uv binary or ``None``."""
|
|
48
|
+
candidates = []
|
|
49
|
+
if data is not None:
|
|
50
|
+
candidates.append(local_uv(data))
|
|
51
|
+
if os.environ.get("UV"):
|
|
52
|
+
candidates.append(Path(os.environ["UV"]))
|
|
53
|
+
found = shutil.which("uv")
|
|
54
|
+
if found:
|
|
55
|
+
candidates.append(Path(found))
|
|
56
|
+
candidates += [Path(c).expanduser() for c in CANDIDATES]
|
|
57
|
+
for candidate in candidates:
|
|
58
|
+
if candidate.is_file() and os.access(candidate, os.X_OK):
|
|
59
|
+
return candidate
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def asset_name(plat: str = sys.platform) -> str:
|
|
64
|
+
triple = env.uv_platform(plat)
|
|
65
|
+
return f"uv-{triple}.zip" if plat == "win32" else f"uv-{triple}.tar.gz"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def asset_url(version: str | None = None, plat: str = sys.platform) -> str:
|
|
69
|
+
base = f"{RELEASES}/download/{version}" if version else f"{RELEASES}/latest/download"
|
|
70
|
+
return f"{base}/{asset_name(plat)}"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def fetch_bytes(url: str) -> bytes:
|
|
74
|
+
"""Download ``url`` (kept small so tests can replace it)."""
|
|
75
|
+
with urllib.request.urlopen(url, timeout=120) as response:
|
|
76
|
+
return response.read()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def extract_binary(archive: bytes, name: str, plat: str = sys.platform) -> bytes:
|
|
80
|
+
"""Return the bytes of the uv binary inside a release archive."""
|
|
81
|
+
wanted = "uv.exe" if plat == "win32" else "uv"
|
|
82
|
+
if name.endswith(".zip"):
|
|
83
|
+
with zipfile.ZipFile(io.BytesIO(archive)) as zipped:
|
|
84
|
+
for member in zipped.namelist():
|
|
85
|
+
if member.rsplit("/", 1)[-1] == wanted:
|
|
86
|
+
return zipped.read(member)
|
|
87
|
+
else:
|
|
88
|
+
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tarred:
|
|
89
|
+
for member in tarred.getmembers():
|
|
90
|
+
if member.isfile() and member.name.rsplit("/", 1)[-1] == wanted:
|
|
91
|
+
handle = tarred.extractfile(member)
|
|
92
|
+
if handle:
|
|
93
|
+
return handle.read()
|
|
94
|
+
raise UvError(f"{name} does not contain {wanted}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def download(data: Path, version: str | None = None, fetch=fetch_bytes) -> Path:
|
|
98
|
+
"""Download uv into ``<data>/python/uv/`` and return its path."""
|
|
99
|
+
url = asset_url(version)
|
|
100
|
+
name = asset_name()
|
|
101
|
+
archive = fetch(url)
|
|
102
|
+
expected = fetch(url + ".sha256").decode("ascii", "replace").split()[0].lower()
|
|
103
|
+
actual = hashlib.sha256(archive).hexdigest()
|
|
104
|
+
if expected != actual:
|
|
105
|
+
raise UvError(f"uv checksum mismatch for {name}: expected {expected}, got {actual}")
|
|
106
|
+
target = local_uv(data)
|
|
107
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
108
|
+
temp = target.with_name(target.name + ".tmp")
|
|
109
|
+
temp.write_bytes(extract_binary(archive, name))
|
|
110
|
+
temp.chmod(0o755)
|
|
111
|
+
temp.replace(target)
|
|
112
|
+
return target
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def ensure(data: Path, *, allow_download: bool = True) -> Path:
|
|
116
|
+
"""Return uv, downloading it if needed and allowed."""
|
|
117
|
+
found = find(data)
|
|
118
|
+
if found:
|
|
119
|
+
return found
|
|
120
|
+
if not allow_download:
|
|
121
|
+
raise UvError("uv not found; run: fontlab-instamix uv fetch")
|
|
122
|
+
return download(data)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def run(uv: Path, args: list[str], runner=subprocess.run) -> subprocess.CompletedProcess:
|
|
126
|
+
"""Run ``uv <args>``; raise :class:`UvError` on failure."""
|
|
127
|
+
command = [str(uv), *args]
|
|
128
|
+
extra = {"creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0)} if sys.platform == "win32" else {}
|
|
129
|
+
result = runner(command, capture_output=True, text=True, **extra)
|
|
130
|
+
if result.returncode != 0:
|
|
131
|
+
detail = (result.stderr or result.stdout or "").strip()
|
|
132
|
+
raise UvError(f"uv {' '.join(args)} failed ({result.returncode}): {detail}")
|
|
133
|
+
return result
|
fontlab_instamix/venv.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/venv.py
|
|
2
|
+
"""``<data>/.venv`` matching FontLab's Python version, created by uv."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import env, uv
|
|
10
|
+
|
|
11
|
+
VENV = ".venv"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def path(data: Path) -> Path:
|
|
15
|
+
return Path(data) / VENV
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def python(venv: Path) -> Path:
|
|
19
|
+
if sys.platform == "win32":
|
|
20
|
+
return venv / "Scripts" / "python.exe"
|
|
21
|
+
return venv / "bin" / "python"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def create(data: Path, uv_bin: Path, runner=None) -> Path:
|
|
25
|
+
"""Create ``<data>/.venv`` for Python 3.11 unless it exists."""
|
|
26
|
+
venv = path(data)
|
|
27
|
+
if python(venv).exists():
|
|
28
|
+
return venv
|
|
29
|
+
args = ["venv", "--python", env.FONTLAB_PYTHON, str(venv)]
|
|
30
|
+
if runner is None:
|
|
31
|
+
uv.run(uv_bin, args)
|
|
32
|
+
else:
|
|
33
|
+
uv.run(uv_bin, args, runner=runner)
|
|
34
|
+
return venv
|
fontlab_instamix/wrap.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# this_file: src/fontlab_instamix/wrap.py
|
|
2
|
+
"""Wrap a script or folder of scripts into a ``.fontlabext`` and ``.fontlabextz``."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import zipfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import manifest
|
|
13
|
+
|
|
14
|
+
SCRIPT_SUFFIXES = (".py", ".vfpy")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def slug(text: str) -> str:
|
|
18
|
+
"""Lowercase id part from free text."""
|
|
19
|
+
value = re.sub(r"[^a-z0-9-]+", "-", text.lower()).strip("-")
|
|
20
|
+
return value if value and value[0].isalpha() else f"x{value}" if value else "extension"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def make_folder(
|
|
24
|
+
source: Path,
|
|
25
|
+
out_dir: Path,
|
|
26
|
+
ext_id: str,
|
|
27
|
+
*,
|
|
28
|
+
name: str | None = None,
|
|
29
|
+
version: str = "0.1.0",
|
|
30
|
+
) -> Path:
|
|
31
|
+
"""Create ``<out_dir>/<ext_id>.fontlabext`` with ``source`` under ``scripts/``.
|
|
32
|
+
|
|
33
|
+
The manifest installs the scripts into ``Scripts/<ext_id>/``.
|
|
34
|
+
"""
|
|
35
|
+
source = Path(source)
|
|
36
|
+
if not source.exists():
|
|
37
|
+
raise FileNotFoundError(source)
|
|
38
|
+
if source.is_file() and source.suffix.lower() not in SCRIPT_SUFFIXES:
|
|
39
|
+
raise ValueError(f"not a FontLab script (.py or .vfpy): {source}")
|
|
40
|
+
folder = Path(out_dir) / f"{ext_id}.fontlabext"
|
|
41
|
+
if folder.exists():
|
|
42
|
+
raise FileExistsError(folder)
|
|
43
|
+
scripts = folder / "scripts"
|
|
44
|
+
scripts.mkdir(parents=True)
|
|
45
|
+
if source.is_dir():
|
|
46
|
+
shutil.copytree(source, scripts, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", ".DS_Store"))
|
|
47
|
+
else:
|
|
48
|
+
shutil.copy2(source, scripts / source.name)
|
|
49
|
+
data = {
|
|
50
|
+
"id": ext_id,
|
|
51
|
+
"name": name or source.stem,
|
|
52
|
+
"version": version,
|
|
53
|
+
"install": [{"from": "scripts", "to": "Scripts/{}"}],
|
|
54
|
+
}
|
|
55
|
+
manifest.parse(data)
|
|
56
|
+
(folder / manifest.MANIFEST).write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
57
|
+
return folder
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make_zip(folders: list[Path], zip_path: Path) -> Path:
|
|
61
|
+
"""Zip ``.fontlabext`` folders (the folders themselves, not their contents)."""
|
|
62
|
+
zip_path = Path(zip_path)
|
|
63
|
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
|
|
64
|
+
for folder in folders:
|
|
65
|
+
folder = Path(folder)
|
|
66
|
+
manifest.load(folder)
|
|
67
|
+
for path in sorted(folder.rglob("*")):
|
|
68
|
+
if "__pycache__" in path.parts or path.name == ".DS_Store" or path.is_dir():
|
|
69
|
+
continue
|
|
70
|
+
archive.write(path, (Path(folder.name) / path.relative_to(folder)).as_posix())
|
|
71
|
+
return zip_path
|