lawspec 0.36.5__tar.gz

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.
lawspec-0.36.5/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 brain-fuel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.1
2
+ Name: lawspec
3
+ Version: 0.36.5
4
+ Summary: Portable executable laws
5
+ Home-page: https://github.com/brain-fuel/lawspec
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Topic :: Software Development :: Compilers
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+
13
+ # LawSpec
14
+
15
+ Portable executable laws: LawSpec specifications, checked and compiled to many
16
+ languages. This package installs the `lawspec` command.
17
+
18
+ pip install lawspec
19
+ lawspec --version
20
+
21
+ The wheel carries the `lawspec` executable for your platform (macOS and Linux:
22
+ the native build with the native Canon bundle; Windows: the Go host). On other
23
+ platforms pip builds the Go host from the source distribution, which needs Go
24
+ (it fetches a pinned toolchain when `go` is missing or too old). Nothing in
25
+ this package interprets a LawSpec command.
26
+
27
+ See https://github.com/brain-fuel/lawspec for the documentation.
@@ -0,0 +1,15 @@
1
+ # LawSpec
2
+
3
+ Portable executable laws: LawSpec specifications, checked and compiled to many
4
+ languages. This package installs the `lawspec` command.
5
+
6
+ pip install lawspec
7
+ lawspec --version
8
+
9
+ The wheel carries the `lawspec` executable for your platform (macOS and Linux:
10
+ the native build with the native Canon bundle; Windows: the Go host). On other
11
+ platforms pip builds the Go host from the source distribution, which needs Go
12
+ (it fetches a pinned toolchain when `go` is missing or too old). Nothing in
13
+ this package interprets a LawSpec command.
14
+
15
+ See https://github.com/brain-fuel/lawspec for the documentation.
@@ -0,0 +1,384 @@
1
+ """A PEP 517 build backend that builds LawSpec's Go host for this machine.
2
+
3
+ The source distribution is what pip installs on a platform without a
4
+ prebuilt wheel. Building its wheel builds `goforge.dev/lawspec/cmd/lawspec`
5
+ at this version with Go: the `go` on PATH when it is at least the version
6
+ pinned in go-toolchain.json, otherwise the pinned toolchain, downloaded from
7
+ go.dev into the user cache and verified against its SHA-256. The Go host is
8
+ then packaged by tools/package-wheel.py (beside this file in the sdist),
9
+ which also writes the sdist.
10
+
11
+ Environment: LAWSPEC_PIP_CACHE names the cache directory,
12
+ LAWSPEC_PIP_GO_TAGS adds Go build tags, and GOFLAGS, GOPROXY and the other Go
13
+ variables are the caller's.
14
+ """
15
+
16
+ import hashlib
17
+ import importlib.util
18
+ import json
19
+ import os
20
+ import platform
21
+ import re
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import sysconfig
26
+ import tarfile
27
+ import tempfile
28
+ import urllib.request
29
+ import zipfile
30
+
31
+ MODULE = "goforge.dev/lawspec/cmd/lawspec"
32
+ _GOARCH = {
33
+ "x86_64": "amd64",
34
+ "amd64": "amd64",
35
+ "arm64": "arm64",
36
+ "aarch64": "arm64",
37
+ "i386": "386",
38
+ "i686": "386",
39
+ "x86": "386",
40
+ "armv7l": "arm",
41
+ "ppc64le": "ppc64le",
42
+ "riscv64": "riscv64",
43
+ "s390x": "s390x",
44
+ }
45
+
46
+
47
+ class BuildError(Exception):
48
+ """The Go host cannot be built here."""
49
+
50
+
51
+ def _directory():
52
+ return os.path.dirname(os.path.abspath(__file__))
53
+
54
+
55
+ def _tool():
56
+ """Loads package-wheel.py, from the sdist root or tools/."""
57
+ path = os.path.join(_directory(), "package-wheel.py")
58
+ if not os.path.isfile(path):
59
+ path = os.path.join(
60
+ os.path.dirname(os.path.dirname(_directory())),
61
+ "tools",
62
+ "package-wheel.py",
63
+ )
64
+ spec = importlib.util.spec_from_file_location("package_wheel", path)
65
+ module = importlib.util.module_from_spec(spec)
66
+ spec.loader.exec_module(module)
67
+ return module
68
+
69
+
70
+ def _pin_path():
71
+ for base in (
72
+ _directory(),
73
+ os.path.join(os.path.dirname(os.path.dirname(_directory())), "tools"),
74
+ ):
75
+ path = os.path.join(base, "go-toolchain.json")
76
+ if os.path.isfile(path):
77
+ return path
78
+ raise BuildError("go-toolchain.json is missing from the sources")
79
+
80
+
81
+ def project_version():
82
+ """Returns the version pyproject.toml states."""
83
+ with open(
84
+ os.path.join(_directory(), "pyproject.toml"), encoding="utf-8"
85
+ ) as handle:
86
+ found = re.search(r'(?m)^version = "([^"]+)"$', handle.read())
87
+ if not found:
88
+ raise BuildError("pyproject.toml has no version")
89
+ return found.group(1)
90
+
91
+
92
+ def load_pin(path=None):
93
+ """Reads the toolchain pin: {"version": "go1.x.y", "files": {...}}."""
94
+ with open(path or _pin_path(), encoding="utf-8") as handle:
95
+ pin = json.load(handle)
96
+ if not isinstance(pin.get("version"), str) or not isinstance(
97
+ pin.get("files"), dict
98
+ ):
99
+ raise BuildError("go-toolchain.json needs a version and files")
100
+ parse_go_version(pin["version"])
101
+ return pin
102
+
103
+
104
+ def parse_go_version(text):
105
+ """Returns (major, minor, patch) of `go1.26.5`, `go1.25`, `go1.26rc1`."""
106
+ found = re.match(r"go(\d+)\.(\d+)(?:\.(\d+))?", text or "")
107
+ if not found:
108
+ raise BuildError("not a Go version: %r" % (text,))
109
+ return tuple(int(part or 0) for part in found.groups())
110
+
111
+
112
+ def go_version(executable, runner=subprocess.run):
113
+ """Returns the version of a go executable, or None if it will not run."""
114
+ try:
115
+ out = runner(
116
+ [executable, "version"],
117
+ stdout=subprocess.PIPE,
118
+ stderr=subprocess.DEVNULL,
119
+ check=True,
120
+ )
121
+ return parse_go_version(
122
+ out.stdout.decode().split()[2] if out.stdout else ""
123
+ )
124
+ except (OSError, subprocess.CalledProcessError, BuildError, IndexError):
125
+ return None
126
+
127
+
128
+ def host_target(system=None, machine=None):
129
+ """Returns (goos, goarch) of this machine."""
130
+ system = (system or sys.platform).lower()
131
+ goos = (
132
+ "darwin"
133
+ if system.startswith("darwin")
134
+ else "windows"
135
+ if system.startswith(("win", "cygwin"))
136
+ else "linux"
137
+ if system.startswith("linux")
138
+ else "freebsd"
139
+ if system.startswith("freebsd")
140
+ else system
141
+ )
142
+ machine = (machine or platform.machine()).lower()
143
+ return goos, _GOARCH.get(machine, machine)
144
+
145
+
146
+ def select_pinned(pin, goos, goarch):
147
+ """Returns the pin's download for a target, or fails clearly."""
148
+ entry = pin["files"].get("%s-%s" % (goos, goarch))
149
+ if entry is None:
150
+ raise BuildError(
151
+ "LawSpec has no prebuilt wheel for %s/%s, and no Go %s toolchain "
152
+ "is pinned for it (pinned: %s). Install Go %s or later from "
153
+ "https://go.dev/dl/ and put it on PATH, then install again."
154
+ % (
155
+ goos,
156
+ goarch,
157
+ pin["version"],
158
+ ", ".join(sorted(pin["files"])),
159
+ pin["version"][2:],
160
+ )
161
+ )
162
+ for key in ("url", "sha256"):
163
+ if not isinstance(entry.get(key), str):
164
+ raise BuildError(
165
+ "the toolchain pin for %s-%s lacks %s" % (goos, goarch, key)
166
+ )
167
+ return entry
168
+
169
+
170
+ def cache_directory(environ=None, system=None, home=None):
171
+ """Returns the directory toolchains are cached in."""
172
+ environ = os.environ if environ is None else environ
173
+ system = system or sys.platform
174
+ if environ.get("LAWSPEC_PIP_CACHE"):
175
+ return environ["LAWSPEC_PIP_CACHE"]
176
+ home = home or os.path.expanduser("~")
177
+ if system == "darwin":
178
+ base = os.path.join(home, "Library", "Caches")
179
+ elif system.startswith("win"):
180
+ base = environ.get("LOCALAPPDATA") or os.path.join(
181
+ home, "AppData", "Local"
182
+ )
183
+ else:
184
+ base = environ.get("XDG_CACHE_HOME") or os.path.join(home, ".cache")
185
+ return os.path.join(base, "lawspec", "pip")
186
+
187
+
188
+ def verify_sha256(path, expected):
189
+ """Fails unless the file's SHA-256 is the expected one."""
190
+ sha = hashlib.sha256()
191
+ with open(path, "rb") as handle:
192
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
193
+ sha.update(chunk)
194
+ if sha.hexdigest() != expected.lower():
195
+ raise BuildError(
196
+ "%s has SHA-256 %s, but the pin says %s; refusing "
197
+ "to use it" % (path, sha.hexdigest(), expected)
198
+ )
199
+
200
+
201
+ def _inside(directory, name):
202
+ target = os.path.realpath(os.path.join(directory, name))
203
+ return target == directory or target.startswith(directory + os.sep)
204
+
205
+
206
+ def extract(archive, directory):
207
+ """Unpacks a .tar.gz or .zip, refusing entries outside the directory."""
208
+ directory = os.path.realpath(directory)
209
+ if archive.endswith(".zip"):
210
+ with zipfile.ZipFile(archive) as zipped:
211
+ for name in zipped.namelist():
212
+ if not _inside(directory, name):
213
+ raise BuildError("unsafe path in archive: " + name)
214
+ zipped.extractall(directory)
215
+ return
216
+ with tarfile.open(archive) as tarred:
217
+ for member in tarred.getmembers():
218
+ if (
219
+ not _inside(directory, member.name)
220
+ or member.isdev()
221
+ or (
222
+ (member.issym() or member.islnk())
223
+ and not _inside(
224
+ directory,
225
+ os.path.join(
226
+ os.path.dirname(member.name), member.linkname
227
+ ),
228
+ )
229
+ )
230
+ ):
231
+ raise BuildError("unsafe entry in archive: " + member.name)
232
+ tarred.extractall(directory)
233
+
234
+
235
+ def download(url, destination, opener=urllib.request.urlopen):
236
+ """Downloads a URL to a file."""
237
+ try:
238
+ with opener(url) as response, open(destination, "wb") as sink:
239
+ shutil.copyfileobj(response, sink, 1 << 20)
240
+ except OSError as error:
241
+ raise BuildError("cannot download %s: %s" % (url, error))
242
+
243
+
244
+ def ensure_toolchain(pin, goos, goarch, cache, fetch=download):
245
+ """Returns the go executable of the pinned toolchain, fetching it once."""
246
+ entry = select_pinned(pin, goos, goarch)
247
+ root = os.path.join(cache, "%s-%s-%s" % (pin["version"], goos, goarch))
248
+ executable = os.path.join(
249
+ root, "go", "bin", "go.exe" if goos == "windows" else "go"
250
+ )
251
+ if os.path.isfile(executable):
252
+ return executable
253
+ os.makedirs(cache, exist_ok=True)
254
+ work = tempfile.mkdtemp(prefix=".fetch-", dir=cache)
255
+ try:
256
+ archive = os.path.join(work, os.path.basename(entry["url"]))
257
+ sys.stderr.write(
258
+ "lawspec: downloading Go %s from %s\n"
259
+ % (pin["version"], entry["url"])
260
+ )
261
+ fetch(entry["url"], archive)
262
+ verify_sha256(archive, entry["sha256"])
263
+ unpacked = os.path.join(work, "unpacked")
264
+ os.mkdir(unpacked)
265
+ extract(archive, unpacked)
266
+ try:
267
+ os.replace(unpacked, root)
268
+ except OSError:
269
+ if not os.path.isfile(executable): # not a concurrent install
270
+ raise
271
+ finally:
272
+ shutil.rmtree(work, ignore_errors=True)
273
+ return executable
274
+
275
+
276
+ def find_go(
277
+ pin,
278
+ goos,
279
+ goarch,
280
+ cache,
281
+ which=shutil.which,
282
+ version_of=go_version,
283
+ fetch=download,
284
+ ):
285
+ """Returns (go, fetched): the go on PATH if recent enough, else pinned."""
286
+ wanted = parse_go_version(pin["version"])
287
+ found = which("go")
288
+ if found:
289
+ have = version_of(found)
290
+ if have and have >= wanted:
291
+ return found, False
292
+ return ensure_toolchain(pin, goos, goarch, cache, fetch), True
293
+
294
+
295
+ def build_host(version, goos, goarch, work, environ=None):
296
+ """Builds the Go host into `work` and returns its path."""
297
+ environ = dict(os.environ if environ is None else environ)
298
+ pin = load_pin()
299
+ go, fetched = find_go(pin, goos, goarch, cache_directory(environ))
300
+ output = os.path.join(work, "bin")
301
+ os.makedirs(output)
302
+ scratch = os.path.join(work, "scratch")
303
+ os.makedirs(scratch)
304
+ environ.update(
305
+ {
306
+ "GOBIN": output,
307
+ "CGO_ENABLED": "0",
308
+ "GOWORK": "off",
309
+ "GOFLAGS": "-mod=mod",
310
+ }
311
+ )
312
+ if fetched:
313
+ environ["GOTOOLCHAIN"] = "local"
314
+ command = [go, "install", "-trimpath"]
315
+ if environ.get("LAWSPEC_PIP_GO_TAGS"):
316
+ command += ["-tags", environ["LAWSPEC_PIP_GO_TAGS"]]
317
+ command.append("%s@v%s" % (MODULE, version))
318
+ sys.stderr.write("lawspec: building the Go host: %s\n" % " ".join(command))
319
+ result = subprocess.run(command, cwd=scratch, env=environ)
320
+ if result.returncode != 0:
321
+ raise BuildError(
322
+ "`go install %s@v%s` failed (exit %d)"
323
+ % (MODULE, version, result.returncode)
324
+ )
325
+ binary = os.path.join(
326
+ output, "lawspec.exe" if goos == "windows" else "lawspec"
327
+ )
328
+ if not os.path.isfile(binary):
329
+ raise BuildError("go install produced no " + binary)
330
+ return binary
331
+
332
+
333
+ def wheel_platform_tag(platform_name=None, machine=None):
334
+ """Returns the wheel platform tag of the executable built on this machine.
335
+
336
+ A universal2 Python reports a macOS tag for both architectures, but the
337
+ Go host is built for the machine's own, so the tag names that one.
338
+ """
339
+ tag = re.sub(r"[-.]", "_", platform_name or sysconfig.get_platform())
340
+ found = re.fullmatch(r"(macosx_\d+_\d+)_(universal2|fat64|intel)", tag)
341
+ if found:
342
+ arch = (machine or platform.machine()).lower()
343
+ tag = "%s_%s" % (
344
+ found.group(1),
345
+ "arm64" if arch in ("arm64", "aarch64") else "x86_64",
346
+ )
347
+ return tag
348
+
349
+
350
+ def get_requires_for_build_wheel(config_settings=None):
351
+ """Returns the build requirements: none."""
352
+ return []
353
+
354
+
355
+ def get_requires_for_build_sdist(config_settings=None):
356
+ """Returns the build requirements: none."""
357
+ return []
358
+
359
+
360
+ def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
361
+ """Builds the Go host and packages it as this platform's wheel."""
362
+ version = project_version()
363
+ goos, goarch = host_target()
364
+ tool = _tool()
365
+ work = tempfile.mkdtemp(prefix="lawspec-build-")
366
+ try:
367
+ binary = build_host(version, goos, goarch, work)
368
+ tag = wheel_platform_tag()
369
+ try:
370
+ path = tool.build_wheel(
371
+ version, wheel_directory, binary, [tag], goos == "windows"
372
+ )
373
+ except tool.PackageError as error:
374
+ raise BuildError(str(error))
375
+ finally:
376
+ shutil.rmtree(work, ignore_errors=True)
377
+ return os.path.basename(path)
378
+
379
+
380
+ def build_sdist(sdist_directory, config_settings=None):
381
+ """Writes the source distribution."""
382
+ return os.path.basename(
383
+ _tool().build_sdist(project_version(), sdist_directory)
384
+ )
@@ -0,0 +1,61 @@
1
+ {
2
+ "version": "go1.25.0",
3
+ "files": {
4
+ "darwin-amd64": {
5
+ "url": "https://go.dev/dl/go1.25.0.darwin-amd64.tar.gz",
6
+ "sha256": "5bd60e823037062c2307c71e8111809865116714d6f6b410597cf5075dfd80ef"
7
+ },
8
+ "darwin-arm64": {
9
+ "url": "https://go.dev/dl/go1.25.0.darwin-arm64.tar.gz",
10
+ "sha256": "544932844156d8172f7a28f77f2ac9c15a23046698b6243f633b0a0b00c0749c"
11
+ },
12
+ "freebsd-amd64": {
13
+ "url": "https://go.dev/dl/go1.25.0.freebsd-amd64.tar.gz",
14
+ "sha256": "86e6fe0a29698d7601c4442052dac48bd58d532c51cccb8f1917df648138730b"
15
+ },
16
+ "freebsd-arm64": {
17
+ "url": "https://go.dev/dl/go1.25.0.freebsd-arm64.tar.gz",
18
+ "sha256": "451d0da1affd886bfb291b7c63a6018527b269505db21ce6e14724f22ab0662e"
19
+ },
20
+ "linux-386": {
21
+ "url": "https://go.dev/dl/go1.25.0.linux-386.tar.gz",
22
+ "sha256": "8c602dd9d99bc9453b3995d20ce4baf382cc50855900a0ece5de9929df4a993a"
23
+ },
24
+ "linux-amd64": {
25
+ "url": "https://go.dev/dl/go1.25.0.linux-amd64.tar.gz",
26
+ "sha256": "2852af0cb20a13139b3448992e69b868e50ed0f8a1e5940ee1de9e19a123b613"
27
+ },
28
+ "linux-arm64": {
29
+ "url": "https://go.dev/dl/go1.25.0.linux-arm64.tar.gz",
30
+ "sha256": "05de75d6994a2783699815ee553bd5a9327d8b79991de36e38b66862782f54ae"
31
+ },
32
+ "linux-armv6l": {
33
+ "url": "https://go.dev/dl/go1.25.0.linux-armv6l.tar.gz",
34
+ "sha256": "a5a8f8198fcf00e1e485b8ecef9ee020778bf32a408a4e8873371bfce458cd09"
35
+ },
36
+ "linux-ppc64le": {
37
+ "url": "https://go.dev/dl/go1.25.0.linux-ppc64le.tar.gz",
38
+ "sha256": "0f18a89e7576cf2c5fa0b487a1635d9bcbf843df5f110e9982c64df52a983ad0"
39
+ },
40
+ "linux-riscv64": {
41
+ "url": "https://go.dev/dl/go1.25.0.linux-riscv64.tar.gz",
42
+ "sha256": "c018ff74a2c48d55c8ca9b07c8e24163558ffec8bea08b326d6336905d956b67"
43
+ },
44
+ "linux-s390x": {
45
+ "url": "https://go.dev/dl/go1.25.0.linux-s390x.tar.gz",
46
+ "sha256": "34e5a2e19f2292fbaf8783e3a241e6e49689276aef6510a8060ea5ef54eee408"
47
+ },
48
+ "windows-386": {
49
+ "url": "https://go.dev/dl/go1.25.0.windows-386.zip",
50
+ "sha256": "df9f39db82a803af0db639e3613a36681ab7a42866b1384b3f3a1045663961a7"
51
+ },
52
+ "windows-amd64": {
53
+ "url": "https://go.dev/dl/go1.25.0.windows-amd64.zip",
54
+ "sha256": "89efb4f9b30812eee083cc1770fdd2913c14d301064f6454851428f9707d190b"
55
+ },
56
+ "windows-arm64": {
57
+ "url": "https://go.dev/dl/go1.25.0.windows-arm64.zip",
58
+ "sha256": "27bab004c72b3d7bd05a69b6ec0fc54a309b4b78cc569dd963d8b3ec28bfdb8c"
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,571 @@
1
+ #!/usr/bin/env python3
2
+ """Writes LawSpec's pip packages: platform wheels and the source distribution.
3
+
4
+ Run it with `python3 -I`, using the standard library only:
5
+
6
+ python3 -I tools/package-wheel.py --platform <platform> --binary <path> \
7
+ [--canon <dir>] [--resources <npm dir>] --version <v> --out <dir>
8
+ python3 -I tools/package-wheel.py --sdist --version <v> --out <dir>
9
+
10
+ Platforms: darwin-arm64, darwin-x64, linux-arm64, linux-x64, windows-x64,
11
+ windows-arm64. The binary is `lawspec-native` (the first four) or the Go host
12
+ `lawspec.exe` (Windows); `--canon` is the native Canon bundle directory
13
+ (`canon`, `canon.json`, `presets/`) and `--resources` the built npm package
14
+ directory (npm/), of which the wheel carries what `lawspec learn` serves:
15
+ `learn/`, `core.wasm.gz` and `core_jsffi.js`. It leaves out `core.wasm`, which
16
+ the executable never serves and the archive makes redundant (17 MB of a wheel
17
+ PyPI caps at 100 MiB); `lawspec learn` serves the archive as it is when there
18
+ is no `core.wasm` beside it.
19
+
20
+ The output is deterministic: entries are sorted, timestamps come from
21
+ SOURCE_DATE_EPOCH (or the commit time, or 1980-01-01 outside a checkout), and
22
+ permissions are fixed (0755 for executables, 0644 otherwise). The wheel's
23
+ macOS tag is the binaries' real minimum macOS version, from their Mach-O load
24
+ commands, never lower than the platform's floor.
25
+
26
+ The in-tree build backend (hosts/python/build_backend.py) imports this file to
27
+ write the wheel it builds from the sdist.
28
+ """
29
+
30
+ import argparse
31
+ import base64
32
+ import gzip
33
+ import hashlib
34
+ import io
35
+ import os
36
+ import re
37
+ import stat
38
+ import struct
39
+ import subprocess
40
+ import sys
41
+ import tarfile
42
+ import time
43
+ import zipfile
44
+
45
+ NAME = "lawspec"
46
+ SUMMARY = "Portable executable laws"
47
+ HOMEPAGE = "https://github.com/brain-fuel/lawspec"
48
+ LICENSE_NAME = "MIT"
49
+ REQUIRES_PYTHON = ">=3.9"
50
+ CLASSIFIERS = (
51
+ "Programming Language :: Python :: 3",
52
+ "License :: OSI Approved :: MIT License",
53
+ "Topic :: Software Development :: Compilers",
54
+ )
55
+ ENTRY_POINTS = "[console_scripts]\nlawspec = lawspec._launcher:main\n"
56
+ DEFAULT_EPOCH = 315532800 # 1980-01-01, the earliest zip timestamp.
57
+ NATIVE = "lawspec/_native"
58
+
59
+ # platform -> (executable format, architecture, platform tags, macOS floor).
60
+ PLATFORMS = {
61
+ "darwin-arm64": ("macho", "arm64", ("macosx_{}_{}_arm64",), (11, 0)),
62
+ "darwin-x64": ("macho", "x64", ("macosx_{}_{}_x86_64",), (10, 15)),
63
+ "linux-arm64": (
64
+ "elf",
65
+ "arm64",
66
+ ("manylinux_2_17_aarch64", "musllinux_1_1_aarch64"),
67
+ None,
68
+ ),
69
+ "linux-x64": (
70
+ "elf",
71
+ "x64",
72
+ ("manylinux_2_17_x86_64", "musllinux_1_1_x86_64"),
73
+ None,
74
+ ),
75
+ "windows-x64": ("pe", "x64", ("win_amd64",), None),
76
+ "windows-arm64": ("pe", "arm64", ("win_arm64",), None),
77
+ }
78
+ MACHINE = { # (format, architecture) -> the code the file header holds.
79
+ ("macho", "arm64"): 0x0100000C,
80
+ ("macho", "x64"): 0x01000007,
81
+ ("elf", "arm64"): 183,
82
+ ("elf", "x64"): 62,
83
+ ("pe", "arm64"): 0xAA64,
84
+ ("pe", "x64"): 0x8664,
85
+ }
86
+
87
+
88
+ class PackageError(Exception):
89
+ """The inputs cannot make the package asked for."""
90
+
91
+
92
+ def here():
93
+ """Returns the directory of this file."""
94
+ return os.path.dirname(os.path.abspath(__file__))
95
+
96
+
97
+ def python_package_dir():
98
+ """Returns the directory holding pyproject.toml and src/.
99
+
100
+ This is the sdist root when this file sits in one, else hosts/python.
101
+ """
102
+ if os.path.isfile(os.path.join(here(), "pyproject.toml")):
103
+ return here()
104
+ return os.path.join(os.path.dirname(here()), "hosts", "python")
105
+
106
+
107
+ def first_file(*candidates):
108
+ """Returns the first candidate that is a file."""
109
+ for candidate in candidates:
110
+ if os.path.isfile(candidate):
111
+ return candidate
112
+ raise PackageError("none of these exists: " + ", ".join(candidates))
113
+
114
+
115
+ def source_epoch(environ=None, directory=None):
116
+ """Returns the timestamp every entry gets.
117
+
118
+ Args:
119
+ environ: The environment; the process's by default.
120
+ directory: Where to ask git for the commit time; this file's directory.
121
+
122
+ Returns:
123
+ SOURCE_DATE_EPOCH, else the HEAD commit time, else 1980-01-01.
124
+ """
125
+ environ = os.environ if environ is None else environ
126
+ value = environ.get("SOURCE_DATE_EPOCH")
127
+ if value:
128
+ if not value.isdigit():
129
+ raise PackageError("SOURCE_DATE_EPOCH is not an integer: " + value)
130
+ return max(int(value), DEFAULT_EPOCH)
131
+ try:
132
+ out = subprocess.run(
133
+ ["git", "log", "-1", "--format=%ct"],
134
+ cwd=directory or here(),
135
+ stdout=subprocess.PIPE,
136
+ stderr=subprocess.DEVNULL,
137
+ check=True,
138
+ )
139
+ return max(int(out.stdout.decode().strip()), DEFAULT_EPOCH)
140
+ except (OSError, subprocess.CalledProcessError, ValueError):
141
+ return DEFAULT_EPOCH
142
+
143
+
144
+ # ---- executable formats -------------------------------------------------
145
+
146
+
147
+ def _read(path, count):
148
+ with open(path, "rb") as handle:
149
+ return handle.read(count)
150
+
151
+
152
+ def machine_of(path):
153
+ """Returns (format, machine code) of an executable, or None."""
154
+ head = _read(path, 4096)
155
+ if head[:4] == b"\xcf\xfa\xed\xfe":
156
+ return "macho", struct.unpack_from("<I", head, 4)[0]
157
+ if head[:4] == b"\x7fELF":
158
+ return "elf", struct.unpack_from("<H", head, 18)[0]
159
+ if head[:2] == b"MZ":
160
+ offset = struct.unpack_from("<I", head, 0x3C)[0]
161
+ with open(path, "rb") as handle:
162
+ handle.seek(offset)
163
+ pe = handle.read(6)
164
+ if pe[:4] == b"PE\0\0":
165
+ return "pe", struct.unpack_from("<H", pe, 4)[0]
166
+ return None
167
+
168
+
169
+ def check_executable(platform, path):
170
+ """Fails unless the file is an executable for the platform."""
171
+ kind, arch = PLATFORMS[platform][:2]
172
+ found = machine_of(path)
173
+ if found != (kind, MACHINE[(kind, arch)]):
174
+ raise PackageError(
175
+ "%s is not a %s %s executable for %s (found %s)"
176
+ % (path, kind, arch, platform, found)
177
+ )
178
+
179
+
180
+ def macho_minimum_os(path):
181
+ """Returns the (major, minor) macOS a thin 64-bit Mach-O needs, or None.
182
+
183
+ Reads LC_BUILD_VERSION (0x32) and LC_VERSION_MIN_MACOSX (0x24).
184
+ """
185
+ with open(path, "rb") as handle:
186
+ head = handle.read(32)
187
+ if head[:4] != b"\xcf\xfa\xed\xfe":
188
+ return None
189
+ ncmds, size = struct.unpack_from("<II", head, 16)
190
+ commands = handle.read(size)
191
+ offset = 0
192
+ for _ in range(ncmds):
193
+ cmd, length = struct.unpack_from("<II", commands, offset)
194
+ value = None
195
+ if cmd == 0x32: # platform, minos, sdk, ntools
196
+ platform, value = struct.unpack_from("<II", commands, offset + 8)
197
+ if platform != 1: # macOS
198
+ value = None
199
+ elif cmd == 0x24:
200
+ value = struct.unpack_from("<I", commands, offset + 8)[0]
201
+ if value is not None:
202
+ return value >> 16, (value >> 8) & 0xFF
203
+ offset += length
204
+ return None
205
+
206
+
207
+ def platform_tags(platform, binaries=(), override=None):
208
+ """Returns the wheel platform tags for a platform.
209
+
210
+ Args:
211
+ platform: One of PLATFORMS.
212
+ binaries: The Mach-O files whose minimum macOS the tag must cover.
213
+ override: A (major, minor) macOS minimum to use instead of the files'.
214
+
215
+ Returns:
216
+ A list of tags (two on Linux: glibc and musl).
217
+ """
218
+ if platform not in PLATFORMS:
219
+ raise PackageError(
220
+ "unknown platform %s (one of %s)"
221
+ % (platform, ", ".join(sorted(PLATFORMS)))
222
+ )
223
+ tags, floor = PLATFORMS[platform][2:]
224
+ if floor is None:
225
+ return list(tags)
226
+ wanted = [floor]
227
+ if override:
228
+ wanted.append(override)
229
+ else:
230
+ wanted += [m for m in map(macho_minimum_os, binaries) if m]
231
+ major, minor = max(wanted)
232
+ if major >= 11:
233
+ # Tags for macOS 11 and later carry no minor version, so a binary that
234
+ # needs 15.4 is tagged for 16.0 rather than claiming 15.0.
235
+ if minor:
236
+ major += 1
237
+ minor = 0
238
+ return [tags[0].format(major, minor)]
239
+
240
+
241
+ # ---- the zip ------------------------------------------------------------
242
+
243
+
244
+ def _digest(path):
245
+ sha = hashlib.sha256()
246
+ size = 0
247
+ with open(path, "rb") as handle:
248
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
249
+ sha.update(chunk)
250
+ size += len(chunk)
251
+ return sha.digest(), size
252
+
253
+
254
+ def record_entry(name, digest, size):
255
+ """Returns one RECORD line."""
256
+ encoded = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
257
+ return "%s,sha256=%s,%d" % (name, encoded, size)
258
+
259
+
260
+ def _walk(directory, prefix):
261
+ """Yields (archive name, path, executable) for each file, sorted."""
262
+ for root, dirs, files in os.walk(directory):
263
+ dirs[:] = sorted(d for d in dirs if d != "__pycache__")
264
+ for name in sorted(files):
265
+ path = os.path.join(root, name)
266
+ relative = os.path.relpath(path, directory).replace(os.sep, "/")
267
+ executable = bool(os.stat(path).st_mode & stat.S_IXUSR)
268
+ yield prefix + "/" + relative, path, executable
269
+
270
+
271
+ RESOURCE_FILES = ("core.wasm.gz", "core_jsffi.js")
272
+
273
+
274
+ def _resources(directory):
275
+ """Yields the package resources of an npm package directory.
276
+
277
+ What `lawspec learn` serves: learn/, the gzipped compiler and the glue.
278
+ core.wasm is not among them: the executable only compares the archive with
279
+ it when it is there, and serves the archive alone otherwise.
280
+ """
281
+ for name in RESOURCE_FILES:
282
+ path = os.path.join(directory, name)
283
+ if not os.path.isfile(path):
284
+ raise PackageError(
285
+ "%s has no %s; build the npm package first" % (directory, name)
286
+ )
287
+ yield NATIVE + "/resources/" + name, path, False
288
+ learn = os.path.join(directory, "learn")
289
+ if not os.path.isdir(learn):
290
+ raise PackageError("%s has no learn/" % directory)
291
+ yield from _walk(learn, NATIVE + "/resources/learn")
292
+
293
+
294
+ def _python_sources():
295
+ source = os.path.join(python_package_dir(), "src", "lawspec")
296
+ for name in sorted(os.listdir(source)):
297
+ if name.endswith(".py"):
298
+ yield "lawspec/" + name, os.path.join(source, name), False
299
+
300
+
301
+ def metadata_text(version, readme):
302
+ """Returns the METADATA file's text."""
303
+ lines = [
304
+ "Metadata-Version: 2.1",
305
+ "Name: " + NAME,
306
+ "Version: " + version,
307
+ "Summary: " + SUMMARY,
308
+ "Home-page: " + HOMEPAGE,
309
+ "License: " + LICENSE_NAME,
310
+ ]
311
+ lines += ["Classifier: " + c for c in CLASSIFIERS]
312
+ lines += [
313
+ "Requires-Python: " + REQUIRES_PYTHON,
314
+ "Description-Content-Type: text/markdown",
315
+ "",
316
+ readme,
317
+ ]
318
+ return "\n".join(lines)
319
+
320
+
321
+ def check_version(version):
322
+ """Fails unless the version is a plain MAJOR.MINOR.PATCH."""
323
+ if not re.fullmatch(r"\d+\.\d+\.\d+", version or ""):
324
+ raise PackageError("not a MAJOR.MINOR.PATCH version: %s" % version)
325
+
326
+
327
+ def _zipinfo(name, epoch, mode):
328
+ info = zipfile.ZipInfo(name, time.gmtime(epoch)[:6])
329
+ info.create_system = 3
330
+ info.compress_type = zipfile.ZIP_DEFLATED
331
+ info.external_attr = (stat.S_IFREG | mode) << 16
332
+ return info
333
+
334
+
335
+ def wheel_filename(version, tags):
336
+ """Returns the wheel's file name; compound tags are joined by dots."""
337
+ return "%s-%s-py3-none-%s.whl" % (NAME, version, ".".join(tags))
338
+
339
+
340
+ def build_wheel(
341
+ version, out, binary, tags, windows, canon=None, resources=None, epoch=None
342
+ ):
343
+ """Writes the wheel and returns its path.
344
+
345
+ Args:
346
+ version: MAJOR.MINOR.PATCH.
347
+ out: The directory to write into.
348
+ binary: The executable to bundle.
349
+ tags: The platform tags, such as ["win_amd64"].
350
+ windows: Whether the executable is `lawspec.exe`.
351
+ canon: The native Canon bundle directory, or None.
352
+ resources: The built npm package directory (npm/), or None.
353
+ epoch: The timestamp of every entry; source_epoch() by default.
354
+
355
+ Returns:
356
+ The path of the wheel written.
357
+ """
358
+ check_version(version)
359
+ epoch = source_epoch() if epoch is None else epoch
360
+ package = python_package_dir()
361
+ with open(os.path.join(package, "README.md"), encoding="utf-8") as handle:
362
+ readme = handle.read()
363
+ license_path = first_file(
364
+ os.path.join(here(), "LICENSE"),
365
+ os.path.join(os.path.dirname(here()), "LICENSE"),
366
+ )
367
+ dist_info = "%s-%s.dist-info" % (NAME, version)
368
+ entries = list(_python_sources())
369
+ entries.append(
370
+ (NATIVE + "/" + ("lawspec.exe" if windows else "lawspec"), binary, True)
371
+ )
372
+ if canon:
373
+ entries += list(_walk(canon, NATIVE + "/canon"))
374
+ if resources:
375
+ entries += list(_resources(resources))
376
+ generated = {
377
+ dist_info + "/METADATA": metadata_text(version, readme),
378
+ dist_info + "/WHEEL": "".join(
379
+ "%s: %s\n" % pair
380
+ for pair in [
381
+ ("Wheel-Version", "1.0"),
382
+ ("Generator", "lawspec-package-wheel"),
383
+ ("Root-Is-Purelib", "false"),
384
+ ]
385
+ + [("Tag", "py3-none-" + tag) for tag in tags]
386
+ ),
387
+ dist_info + "/entry_points.txt": ENTRY_POINTS,
388
+ }
389
+ names = [e[0] for e in entries]
390
+ if len(set(names)) != len(names):
391
+ raise PackageError("duplicate wheel entries")
392
+ os.makedirs(out, exist_ok=True)
393
+ path = os.path.join(out, wheel_filename(version, tags))
394
+ partial = path + ".partial"
395
+ records = []
396
+ with zipfile.ZipFile(
397
+ partial, "w", zipfile.ZIP_DEFLATED, compresslevel=9
398
+ ) as archive:
399
+ files = [(n, p, x) for n, p, x in entries]
400
+ files.append((dist_info + "/LICENSE", license_path, False))
401
+ for name, text in generated.items():
402
+ files.append((name, text.encode("utf-8"), False))
403
+ for name, source, executable in sorted(files, key=lambda f: f[0]):
404
+ info = _zipinfo(name, epoch, 0o755 if executable else 0o644)
405
+ if isinstance(source, bytes):
406
+ digest = hashlib.sha256(source).digest()
407
+ size = len(source)
408
+ archive.writestr(info, source, zipfile.ZIP_DEFLATED, 9)
409
+ else:
410
+ digest, size = _digest(source)
411
+ with (
412
+ open(source, "rb") as handle,
413
+ archive.open(info, "w", force_zip64=True) as sink,
414
+ ):
415
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
416
+ sink.write(chunk)
417
+ records.append(record_entry(name, digest, size))
418
+ records.append(dist_info + "/RECORD,,")
419
+ archive.writestr(
420
+ _zipinfo(dist_info + "/RECORD", epoch, 0o644),
421
+ "\n".join(records) + "\n",
422
+ )
423
+ os.replace(partial, path)
424
+ return path
425
+
426
+
427
+ # ---- the source distribution ---------------------------------------------
428
+
429
+
430
+ def sdist_files():
431
+ """Returns [(archive path, source path)] of the sdist, sorted."""
432
+ package = python_package_dir()
433
+ toolchain = os.path.join(here(), "go-toolchain.json")
434
+ files = {
435
+ "pyproject.toml": os.path.join(package, "pyproject.toml"),
436
+ "README.md": os.path.join(package, "README.md"),
437
+ "build_backend.py": os.path.join(package, "build_backend.py"),
438
+ "package-wheel.py": os.path.abspath(__file__),
439
+ "go-toolchain.json": toolchain,
440
+ "LICENSE": first_file(
441
+ os.path.join(here(), "LICENSE"),
442
+ os.path.join(os.path.dirname(here()), "LICENSE"),
443
+ ),
444
+ }
445
+ for name, path, _ in _python_sources():
446
+ files["src/" + name] = path
447
+ return sorted(files.items())
448
+
449
+
450
+ def build_sdist(version, out, epoch=None):
451
+ """Writes lawspec-<version>.tar.gz and returns its path."""
452
+ check_version(version)
453
+ epoch = source_epoch() if epoch is None else epoch
454
+ root = "%s-%s" % (NAME, version)
455
+ with open(
456
+ os.path.join(python_package_dir(), "README.md"), encoding="utf-8"
457
+ ) as handle:
458
+ readme = handle.read()
459
+ os.makedirs(out, exist_ok=True)
460
+ path = os.path.join(out, root + ".tar.gz")
461
+ partial = path + ".partial"
462
+ with (
463
+ open(partial, "wb") as raw,
464
+ gzip.GzipFile(
465
+ filename="", mode="wb", fileobj=raw, mtime=0, compresslevel=9
466
+ ) as zipped,
467
+ tarfile.open(
468
+ fileobj=zipped, mode="w", format=tarfile.PAX_FORMAT
469
+ ) as archive,
470
+ ):
471
+ entries = [("PKG-INFO", metadata_text(version, readme).encode())]
472
+ for name, source in sdist_files():
473
+ with open(source, "rb") as handle:
474
+ data = handle.read()
475
+ if name == "pyproject.toml":
476
+ text, count = re.subn(
477
+ r'(?m)^version = "[^"]*"$',
478
+ 'version = "%s"' % version,
479
+ data.decode("utf-8"),
480
+ )
481
+ if count != 1:
482
+ raise PackageError("pyproject.toml has no version line")
483
+ data = text.encode("utf-8")
484
+ entries.append((name, data))
485
+ for name, data in sorted(entries):
486
+ info = tarfile.TarInfo(root + "/" + name)
487
+ info.size = len(data)
488
+ info.mtime = epoch
489
+ info.mode = 0o644
490
+ info.uid = info.gid = 0
491
+ info.uname = info.gname = ""
492
+ info.pax_headers = {}
493
+ archive.addfile(info, io.BytesIO(data))
494
+ os.replace(partial, path)
495
+ return path
496
+
497
+
498
+ # ---- command line --------------------------------------------------------
499
+
500
+
501
+ def parse_arguments(argv):
502
+ """Parses the command line."""
503
+ parser = argparse.ArgumentParser(
504
+ prog="package-wheel.py", description=__doc__.split("\n")[0]
505
+ )
506
+ parser.add_argument("--platform", choices=sorted(PLATFORMS))
507
+ parser.add_argument("--binary", help="lawspec-native, or lawspec.exe")
508
+ parser.add_argument("--canon", help="the native Canon bundle directory")
509
+ parser.add_argument("--resources", help="the built npm package directory")
510
+ parser.add_argument(
511
+ "--macos-min",
512
+ metavar="MAJOR.MINOR",
513
+ help="the macOS minimum, instead of the binaries'",
514
+ )
515
+ parser.add_argument("--version", required=True)
516
+ parser.add_argument("--out", required=True)
517
+ parser.add_argument(
518
+ "--sdist",
519
+ action="store_true",
520
+ help="write the source distribution instead",
521
+ )
522
+ return parser.parse_args(argv)
523
+
524
+
525
+ def main(argv=None):
526
+ """Writes the wheel or sdist the command line asks for."""
527
+ args = parse_arguments(sys.argv[1:] if argv is None else argv)
528
+ try:
529
+ if args.sdist:
530
+ print(build_sdist(args.version, args.out))
531
+ return 0
532
+ if not args.platform or not args.binary:
533
+ raise PackageError("--platform and --binary are required")
534
+ if not os.path.isfile(args.binary):
535
+ raise PackageError("no such binary: " + args.binary)
536
+ check_executable(args.platform, args.binary)
537
+ kind = PLATFORMS[args.platform][0]
538
+ binaries = [args.binary]
539
+ if args.canon:
540
+ canon_binary = os.path.join(args.canon, "canon")
541
+ if not os.path.isfile(canon_binary):
542
+ raise PackageError("no canon executable in " + args.canon)
543
+ check_executable(args.platform, canon_binary)
544
+ binaries.append(canon_binary)
545
+ if args.resources and not os.path.isdir(args.resources):
546
+ raise PackageError("no such directory: " + args.resources)
547
+ override = None
548
+ if args.macos_min:
549
+ override = tuple(int(p) for p in args.macos_min.split("."))
550
+ tags = platform_tags(
551
+ args.platform, binaries if kind == "macho" else (), override
552
+ )
553
+ print(
554
+ build_wheel(
555
+ args.version,
556
+ args.out,
557
+ args.binary,
558
+ tags,
559
+ args.platform.startswith("windows"),
560
+ args.canon,
561
+ args.resources,
562
+ )
563
+ )
564
+ return 0
565
+ except PackageError as error:
566
+ sys.stderr.write("package-wheel: %s\n" % error)
567
+ return 2
568
+
569
+
570
+ if __name__ == "__main__":
571
+ sys.exit(main())
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = []
3
+ build-backend = "build_backend"
4
+ backend-path = ["."]
5
+
6
+ [project]
7
+ name = "lawspec"
8
+ version = "0.36.5"
9
+ description = "Portable executable laws"
10
+ readme = "README.md"
11
+ requires-python = ">=3.9"
12
+ license = { text = "MIT" }
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Topic :: Software Development :: Compilers",
17
+ ]
18
+
19
+ [project.scripts]
20
+ lawspec = "lawspec._launcher:main"
@@ -0,0 +1,6 @@
1
+ """LawSpec: portable executable laws.
2
+
3
+ This package only carries the platform's `lawspec` executable and starts
4
+ it; `python -m lawspec` and the `lawspec` console script do the same. It has
5
+ no LawSpec logic of its own.
6
+ """
@@ -0,0 +1,6 @@
1
+ """Runs `python -m lawspec`, the same as the `lawspec` command."""
2
+
3
+ from lawspec._launcher import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,100 @@
1
+ """Finds the bundled `lawspec` executable and runs it.
2
+
3
+ The wheel holds, under `lawspec/_native/`, the platform's executable
4
+ (`lawspec`, or `lawspec.exe` on Windows), the native Canon bundle (`canon/`)
5
+ and the package resources `lawspec learn` serves (`resources/`), each only
6
+ where the platform has it. The launcher sets `LAWSPEC_CANON` and
7
+ `LAWSPEC_RESOURCES` to those, unless they are already set, and replaces
8
+ itself with the executable (a child process on Windows, where there is no
9
+ exec), passing the arguments, the working directory, the environment, the
10
+ standard streams and the exit code through.
11
+ """
12
+
13
+ import os
14
+ import subprocess
15
+ import sys
16
+
17
+ NATIVE_DIRECTORY = "_native"
18
+
19
+
20
+ class LaunchError(Exception):
21
+ """The bundled executable is missing."""
22
+
23
+
24
+ class Layout:
25
+ """Where the bundled files are, for one platform's path rules."""
26
+
27
+ def __init__(self, root, windows, path=None):
28
+ """Describes the bundle under `root`.
29
+
30
+ Args:
31
+ root: The package's `_native` directory.
32
+ windows: Whether the executable is `lawspec.exe`.
33
+ path: The path module to join with, `os.path` by default; tests
34
+ pass `ntpath` to check Windows rules from any platform.
35
+ """
36
+ path = path or os.path
37
+ self.executable = path.join(
38
+ root, "lawspec.exe" if windows else "lawspec"
39
+ )
40
+ self.canon = path.join(root, "canon")
41
+ self.resources = path.join(root, "resources")
42
+
43
+
44
+ def native_root(package_file=None):
45
+ """Returns the directory the wheel keeps the bundled files in."""
46
+ package_file = package_file or __file__
47
+ return os.path.join(
48
+ os.path.dirname(os.path.abspath(package_file)), NATIVE_DIRECTORY
49
+ )
50
+
51
+
52
+ def environment(layout, current, isdir=os.path.isdir):
53
+ """Returns the variables to add to the inherited environment.
54
+
55
+ Args:
56
+ layout: The `Layout` of the bundle.
57
+ current: The environment the process has.
58
+ isdir: Tells whether a directory exists.
59
+
60
+ Returns:
61
+ A dict with `LAWSPEC_CANON` and `LAWSPEC_RESOURCES`, each only when its
62
+ directory is bundled and the variable is not already set.
63
+ """
64
+ added = {}
65
+ if "LAWSPEC_CANON" not in current and isdir(layout.canon):
66
+ added["LAWSPEC_CANON"] = layout.canon
67
+ if "LAWSPEC_RESOURCES" not in current and isdir(layout.resources):
68
+ added["LAWSPEC_RESOURCES"] = layout.resources
69
+ return added
70
+
71
+
72
+ def command(layout, arguments):
73
+ """Returns the argument vector that runs the executable."""
74
+ return [layout.executable] + list(arguments)
75
+
76
+
77
+ def main(argv=None, windows=None, native=None):
78
+ """Runs `lawspec` with the arguments and exits with its code.
79
+
80
+ Args:
81
+ argv: The arguments after the program name; `sys.argv[1:]` by default.
82
+ windows: Whether this is Windows; detected by default.
83
+ native: The directory holding the bundle; the package's by default.
84
+ """
85
+ arguments = sys.argv[1:] if argv is None else argv
86
+ windows = os.name == "nt" if windows is None else windows
87
+ layout = Layout(native or native_root(), windows)
88
+ if not os.path.isfile(layout.executable):
89
+ sys.stderr.write(
90
+ "lawspec: the bundled executable %s is missing; reinstall the "
91
+ "package, or install a wheel for this platform.\n"
92
+ % layout.executable
93
+ )
94
+ sys.exit(127)
95
+ env = dict(os.environ)
96
+ env.update(environment(layout, env))
97
+ argv_vector = command(layout, arguments)
98
+ if windows:
99
+ sys.exit(subprocess.call(argv_vector, env=env))
100
+ os.execve(layout.executable, argv_vector, env)