basedpython 0.0.1a9__py3-none-win32.whl → 0.0.1b2__py3-none-win32.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.
basedpython/build.py ADDED
@@ -0,0 +1,749 @@
1
+ """The PEP 517 build backend for basedpython projects.
2
+
3
+ [build-system]
4
+ requires = ["basedpython"]
5
+ build-backend = "basedpython.build"
6
+
7
+ A basedpython project is python once it is built, so this backend does the one
8
+ thing that makes it so — run `by build`, which transpiles the `.by` sources and
9
+ carries everything else across unchanged — and then hands the resulting tree to
10
+ `uv_build` to package. Splitting it there is deliberate: everything above the
11
+ transpile (core metadata, RECORD, wheel tags, entry points, editable installs) is
12
+ ordinary python packaging with nothing basedpython about it, and a backend that
13
+ reimplemented it would only be a second place for it to be subtly wrong.
14
+
15
+ The wheel is plain python: the transpiled `.py` for python to import, the `.by`
16
+ sources beside them, and a `by.typed` marker saying the `.by` are the
17
+ authoritative surface. A python consumer sees a python library; a basedpython
18
+ consumer sees the declarations that have no python spelling.
19
+
20
+ The source distribution keeps the `.by` untranspiled — it is the source — and is
21
+ written here rather than delegated, because no python backend knows that a `.by`
22
+ file is a source file.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import base64
28
+ import hashlib
29
+ import io
30
+ import os
31
+ import re
32
+ import shutil
33
+ import subprocess
34
+ import sys
35
+ import sysconfig
36
+ import tarfile
37
+ import tempfile
38
+ import zipfile
39
+ from contextlib import contextmanager
40
+ from pathlib import Path
41
+ from typing import TYPE_CHECKING, Any
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Generator, Mapping, Sequence
45
+
46
+ # the backend `uv_build` version this was written against. it is requested at
47
+ # build time rather than depended on outright: `by check` and `by run` are the
48
+ # overwhelming majority of what this distribution is used for, and neither of
49
+ # them packages anything
50
+ UV_BUILD_REQUIREMENT = "uv_build>=0.9,<10"
51
+
52
+ # the config setting that asks for a wheel lowered to one python rather than to
53
+ # the floor of what the project supports
54
+ TARGET_VERSION_SETTING = "python-version"
55
+
56
+ # where `build_editable` stages the project. it is `by build`'s own default
57
+ # output directory on purpose: an editable install points python at this tree, so
58
+ # a plain `by build` is what refreshes an editable install. the two have to be
59
+ # renamed together — an install left pointing at a directory `by build` no longer
60
+ # writes goes stale with nothing said about it
61
+ EDITABLE_STAGING_DIRECTORY = "build"
62
+
63
+
64
+ class BuildError(Exception):
65
+ """A build that cannot proceed, reported without a traceback into it."""
66
+
67
+
68
+ # ── PEP 517 / PEP 660 hooks ──────────────────────────────────────────────────
69
+
70
+
71
+ def get_requires_for_build_wheel(
72
+ config_settings: Mapping[str, Any] | None = None,
73
+ ) -> list[str]:
74
+ return _requirements()
75
+
76
+
77
+ def get_requires_for_build_sdist(
78
+ config_settings: Mapping[str, Any] | None = None,
79
+ ) -> list[str]:
80
+ return _requirements()
81
+
82
+
83
+ def get_requires_for_build_editable(
84
+ config_settings: Mapping[str, Any] | None = None,
85
+ ) -> list[str]:
86
+ return _requirements()
87
+
88
+
89
+ def prepare_metadata_for_build_wheel(
90
+ metadata_directory: str,
91
+ config_settings: Mapping[str, Any] | None = None,
92
+ ) -> str:
93
+ with _staged() as staging:
94
+ return _delegate(
95
+ "prepare_metadata_for_build_wheel",
96
+ staging,
97
+ metadata_directory,
98
+ config_settings,
99
+ )
100
+
101
+
102
+ def prepare_metadata_for_build_editable(
103
+ metadata_directory: str,
104
+ config_settings: Mapping[str, Any] | None = None,
105
+ ) -> str:
106
+ with _staged() as staging:
107
+ return _delegate(
108
+ "prepare_metadata_for_build_editable",
109
+ staging,
110
+ metadata_directory,
111
+ config_settings,
112
+ )
113
+
114
+
115
+ def build_wheel(
116
+ wheel_directory: str,
117
+ config_settings: Mapping[str, Any] | None = None,
118
+ metadata_directory: str | None = None,
119
+ ) -> str:
120
+ target = _target_version(config_settings)
121
+ with _staged(target) as staging:
122
+ built = _delegate("build_wheel", staging, wheel_directory, config_settings)
123
+ if target is None:
124
+ return built
125
+ # a wheel lowered for one python says so, so that a newer interpreter can be
126
+ # given a better one. see `_retag`
127
+ return _retag(Path(wheel_directory) / built, target)
128
+
129
+
130
+ def build_editable(
131
+ wheel_directory: str,
132
+ config_settings: Mapping[str, Any] | None = None,
133
+ metadata_directory: str | None = None,
134
+ ) -> str:
135
+ # an editable install is a pointer at a directory, so the directory has to
136
+ # outlive the build. it is the same one `by build` writes, which is what
137
+ # makes the install editable at all: transpiled python is what gets imported,
138
+ # and re-running the build is what updates it
139
+ staging = Path.cwd() / EDITABLE_STAGING_DIRECTORY
140
+ target = _target_version(config_settings)
141
+ built = _stage(staging, target)
142
+ _write_staged_pyproject(staging, built)
143
+ editable = _delegate("build_editable", staging, wheel_directory, config_settings)
144
+ if target is None:
145
+ return editable
146
+ # an editable wheel is a pointer, but it is still selected on its tag, so it
147
+ # is tagged for the python it was lowered for like any other
148
+ return _retag(Path(wheel_directory) / editable, target)
149
+
150
+
151
+ def build_sdist(
152
+ sdist_directory: str,
153
+ config_settings: Mapping[str, Any] | None = None,
154
+ ) -> str:
155
+ project_root = Path.cwd()
156
+ metadata = _read_project_metadata(project_root)
157
+ name = _normalized_name(metadata["name"])
158
+ version = metadata["version"]
159
+ directory_name = f"{name}-{version}"
160
+
161
+ with tempfile.TemporaryDirectory() as scratch:
162
+ staging = Path(scratch) / "build"
163
+ # one build answers both halves of a source distribution: what the
164
+ # project is made of, and — through the metadata the wheel would carry —
165
+ # what to say about it
166
+ built = _stage(staging)
167
+ _write_staged_pyproject(staging, built)
168
+ metadata_directory = Path(scratch) / "metadata"
169
+ metadata_directory.mkdir()
170
+ dist_info = _delegate(
171
+ "prepare_metadata_for_build_wheel", staging, str(metadata_directory), None
172
+ )
173
+ pkg_info = (metadata_directory / dist_info / "METADATA").read_bytes()
174
+
175
+ sdist = Path(sdist_directory)
176
+ sdist.mkdir(parents=True, exist_ok=True)
177
+ target = sdist / f"{directory_name}.tar.gz"
178
+ with tarfile.open(target, "w:gz", format=tarfile.PAX_FORMAT) as archive:
179
+ for source in built.sources:
180
+ if not (project_root / source).is_file():
181
+ continue
182
+ archive.add(
183
+ project_root / source,
184
+ arcname=f"{directory_name}/{source}",
185
+ recursive=False,
186
+ )
187
+ info = tarfile.TarInfo(f"{directory_name}/PKG-INFO")
188
+ info.size = len(pkg_info)
189
+ archive.addfile(info, io.BytesIO(pkg_info))
190
+
191
+ return target.name
192
+
193
+
194
+ # ── staging ──────────────────────────────────────────────────────────────────
195
+
196
+
197
+ @contextmanager
198
+ def _staged(python_version: str | None = None) -> Generator[Path, None, None]:
199
+ """The project, built as python, in a directory that lasts for one hook."""
200
+ with tempfile.TemporaryDirectory() as directory:
201
+ staging = Path(directory) / "build"
202
+ built = _stage(staging, python_version)
203
+ _write_staged_pyproject(staging, built)
204
+ yield staging
205
+
206
+
207
+ def _target_version(config_settings: Mapping[str, Any] | None) -> str | None:
208
+ """The python this wheel is being lowered for, if one was asked for.
209
+
210
+ Without it the build targets what the project declares it supports, which is
211
+ the wheel that runs everywhere. With it, the wheel is for one python and is
212
+ tagged so that only that python — or the next one up with no wheel of its own
213
+ — will choose it.
214
+ """
215
+ if not config_settings:
216
+ return None
217
+ target = config_settings.get(TARGET_VERSION_SETTING)
218
+ if target is None:
219
+ return None
220
+ target = str(target).strip()
221
+ if not re.fullmatch(r"3\.\d+", target):
222
+ raise BuildError(
223
+ f"`{TARGET_VERSION_SETTING}` has to be a python version like `3.12`, not `{target}`"
224
+ )
225
+ return target
226
+
227
+
228
+ class Staged:
229
+ """What a build read, what it produced, and what the result needs to run."""
230
+
231
+ __slots__ = ("packages", "requires", "sources")
232
+
233
+ def __init__(
234
+ self,
235
+ sources: list[str],
236
+ packages: list[str],
237
+ requires: list[str] | None = None,
238
+ ) -> None:
239
+ self.sources = sources
240
+ self.packages = packages
241
+ self.requires = requires or []
242
+
243
+
244
+ def _stage(staging: Path, python_version: str | None = None) -> Staged:
245
+ """Build the project into `staging`, and report what came of it.
246
+
247
+ Which files the project is made of, and which packages it builds into, are
248
+ both the build's answers rather than this backend's. Reading a staged tree
249
+ back to guess at them would be a second answer to keep in step — and it would
250
+ guess wrong, since a directory in the output is not necessarily something the
251
+ project ships.
252
+ """
253
+ arguments = ["build", "--out", str(staging), "--print-manifest"]
254
+ if python_version:
255
+ arguments += ["--min-version", python_version]
256
+
257
+ sources: list[str] = []
258
+ packages: list[str] = []
259
+ requires: list[str] = []
260
+ for line in _run_by(*arguments).splitlines():
261
+ kind, _, value = line.strip().partition(" ")
262
+ if kind == "input":
263
+ sources.append(value)
264
+ elif kind == "package":
265
+ packages.append(value)
266
+ elif kind == "requires":
267
+ requires.append(value)
268
+ return Staged(sorted(set(sources)), sorted(set(packages)), sorted(set(requires)))
269
+
270
+
271
+ def _write_staged_pyproject(staging: Path, built: Staged) -> None:
272
+ """Describe the staged tree to the backend that packages it.
273
+
274
+ The project's own `pyproject.toml` was copied across by the build, and it
275
+ names *this* backend — handing it back unchanged would build the project
276
+ again, forever. So it is replaced by one describing what the staged tree
277
+ actually is: plain python, packages at the top level, and a version that is
278
+ settled rather than dynamic.
279
+ """
280
+ project_root = Path.cwd()
281
+ metadata = _read_project_metadata(project_root)
282
+ if not built.packages:
283
+ raise BuildError(
284
+ "this project has no package to build a wheel from — a wheel needs at "
285
+ "least one importable package, so a top-level module like `app.by` has "
286
+ "to become `app/__init__.by`"
287
+ )
288
+
289
+ metadata["dependencies"] = _merged_dependencies(metadata, built.requires)
290
+
291
+ document = {
292
+ "build-system": {
293
+ "requires": [UV_BUILD_REQUIREMENT],
294
+ "build-backend": "uv_build",
295
+ },
296
+ "project": metadata,
297
+ "tool": {
298
+ "uv": {
299
+ "build-backend": {
300
+ # the staged tree *is* the module root: `by build` already
301
+ # resolved the project's layout, so `src/pkg` arrives as `pkg`
302
+ "module-root": "",
303
+ "module-name": built.packages,
304
+ }
305
+ }
306
+ },
307
+ }
308
+ (staging / "pyproject.toml").write_text(_toml(document), encoding="utf-8")
309
+
310
+
311
+ # ── tagging a wheel for the python it was lowered for ────────────────────────
312
+
313
+
314
+ def _retag(wheel: Path, python_version: str) -> str:
315
+ """Re-tag `wheel` for one python, and return its new name.
316
+
317
+ A wheel's tag is what an installer selects on. Left as `py3-none-any`, every
318
+ wheel of a release looks equally good and the first one found wins — so a
319
+ 3.13 user could be handed code lowered for 3.9, with a `typing_extensions`
320
+ dependency they have no use for. Tagged `py313-none-any`, that same user gets
321
+ the wheel built for them, and a python with no wheel of its own falls back to
322
+ the newest one below it.
323
+
324
+ The backend that built it has no option for this, so the tag is rewritten
325
+ here: in the archive's `WHEEL`, in the `RECORD` line that carries that file's
326
+ hash, and in the file name itself.
327
+ """
328
+ tag = _python_tag(python_version)
329
+ entries = _read_wheel(wheel)
330
+
331
+ wheel_metadata = _dist_info_entry(entries, "WHEEL")
332
+ metadata_info, metadata = entries[wheel_metadata]
333
+ entries[wheel_metadata] = (metadata_info, _replace_tag(metadata, tag))
334
+
335
+ record = _dist_info_entry(entries, "RECORD")
336
+ record_info, recorded = entries[record]
337
+ entries[record] = (
338
+ record_info,
339
+ _rerecord(recorded, wheel_metadata, entries[wheel_metadata][1]),
340
+ )
341
+
342
+ renamed = wheel.with_name(_retagged_name(wheel.name, tag))
343
+ _write_wheel(renamed, entries)
344
+ if renamed != wheel:
345
+ wheel.unlink()
346
+ return renamed.name
347
+
348
+
349
+ def _python_tag(python_version: str) -> str:
350
+ return "py" + python_version.replace(".", "")
351
+
352
+
353
+ def _retagged_name(name: str, tag: str) -> str:
354
+ """`thing-1.0-py3-none-any.whl` under a new python tag.
355
+
356
+ The three tag fields are the last three before the extension, whatever the
357
+ name and version in front of them contain.
358
+ """
359
+ stem, _, extension = name.rpartition(".")
360
+ parts = stem.split("-")
361
+ if len(parts) < 4:
362
+ raise BuildError(f"`{name}` is not a wheel name this can re-tag")
363
+ parts[-3] = tag
364
+ return "-".join(parts) + "." + extension
365
+
366
+
367
+ def _read_wheel(wheel: Path) -> dict[str, tuple[zipfile.ZipInfo, bytes]]:
368
+ with zipfile.ZipFile(wheel) as archive:
369
+ return {
370
+ info.filename: (info, archive.read(info)) for info in archive.infolist()
371
+ }
372
+
373
+
374
+ def _write_wheel(
375
+ wheel: Path, entries: Mapping[str, tuple[zipfile.ZipInfo, bytes]]
376
+ ) -> None:
377
+ """Write the entries back, each as it arrived but for what changed.
378
+
379
+ The original `ZipInfo` is reused rather than rebuilt, because it carries what
380
+ a wheel means by it: the mode, and so whether a file in `.data/scripts/` is
381
+ still executable once installed. Building a fresh one silently made every
382
+ entry `0o644`.
383
+ """
384
+ with zipfile.ZipFile(wheel, "w", zipfile.ZIP_DEFLATED) as archive:
385
+ for info, payload in entries.values():
386
+ archive.writestr(info, payload)
387
+
388
+
389
+ def _dist_info_entry(
390
+ entries: Mapping[str, tuple[zipfile.ZipInfo, bytes]], name: str
391
+ ) -> str:
392
+ matches = [
393
+ entry
394
+ for entry in entries
395
+ if entry.endswith(f".dist-info/{name}") and entry.count("/") == 1
396
+ ]
397
+ if len(matches) != 1:
398
+ raise BuildError(f"the wheel does not hold exactly one `{name}` to rewrite")
399
+ return matches[0]
400
+
401
+
402
+ def _replace_tag(wheel_metadata: bytes, tag: str) -> bytes:
403
+ """Rewrite every `Tag:` line to name `tag`.
404
+
405
+ A pure-python wheel carries one; rewriting all of them means a wheel that
406
+ somehow carried several is either re-tagged wholly or not at all.
407
+ """
408
+ lines = wheel_metadata.decode("utf-8").splitlines(keepends=True)
409
+ rewritten = []
410
+ seen = False
411
+ for line in lines:
412
+ if line.startswith("Tag:"):
413
+ seen = True
414
+ _, _, rest = line.partition(":")
415
+ fields = rest.strip().split("-")
416
+ fields[0] = tag
417
+ rewritten.append("Tag: " + "-".join(fields) + "\n")
418
+ else:
419
+ rewritten.append(line)
420
+ if not seen:
421
+ raise BuildError("the wheel's `WHEEL` has no `Tag:` to rewrite")
422
+ return "".join(rewritten).encode("utf-8")
423
+
424
+
425
+ def _rerecord(record: bytes, path: str, payload: bytes) -> bytes:
426
+ """Restate `path`'s hash and size in `RECORD`.
427
+
428
+ `RECORD` is what an installer verifies the archive against, so a file
429
+ rewritten without it is a wheel that reports itself as corrupt.
430
+ """
431
+ digest = base64.urlsafe_b64encode(hashlib.sha256(payload).digest()).rstrip(b"=")
432
+ line = f"{path},sha256={digest.decode('ascii')},{len(payload)}\n"
433
+
434
+ rewritten = []
435
+ seen = False
436
+ for existing in record.decode("utf-8").splitlines(keepends=True):
437
+ if existing.split(",")[0] == path:
438
+ seen = True
439
+ rewritten.append(line)
440
+ else:
441
+ rewritten.append(existing)
442
+ if not seen:
443
+ raise BuildError(f"`RECORD` does not mention `{path}`")
444
+ return "".join(rewritten).encode("utf-8")
445
+
446
+
447
+ # ── delegation ───────────────────────────────────────────────────────────────
448
+
449
+
450
+ def _delegate(
451
+ hook_name: str,
452
+ staging: Path,
453
+ out_directory: str,
454
+ config_settings: Mapping[str, Any] | None,
455
+ ) -> str:
456
+ try:
457
+ import uv_build
458
+ except ImportError as error: # pragma: no cover - only without build isolation
459
+ raise BuildError(
460
+ f"packaging a basedpython project needs `{UV_BUILD_REQUIREMENT}`, which "
461
+ "is normally installed into the build environment automatically. it is "
462
+ "missing, which usually means the build was run with isolation disabled"
463
+ ) from error
464
+
465
+ hook = getattr(uv_build, hook_name)
466
+ # the settings are this backend's, not the one it delegates to: `uv_build`
467
+ # supports none of its own and warns about every one it is handed
468
+ config_settings = None
469
+ out = os.path.abspath(out_directory)
470
+ Path(out).mkdir(parents=True, exist_ok=True)
471
+ previous = Path.cwd()
472
+ os.chdir(staging)
473
+ try:
474
+ with _scripts_on_path():
475
+ return hook(out, config_settings)
476
+ finally:
477
+ os.chdir(previous)
478
+
479
+
480
+ @contextmanager
481
+ def _scripts_on_path() -> Generator[None, None, None]:
482
+ """Make this environment's console scripts findable by name.
483
+
484
+ `uv_build` shells out to a `uv-build` executable it finds on `PATH`. A
485
+ frontend is supposed to put the build environment's scripts there, and they
486
+ all do — but the cost of not relying on it is one line.
487
+ """
488
+ scripts = sysconfig.get_path("scripts")
489
+ previous = os.environ.get("PATH", "")
490
+ os.environ["PATH"] = os.pathsep.join(filter(None, (scripts, previous)))
491
+ try:
492
+ yield
493
+ finally:
494
+ os.environ["PATH"] = previous
495
+
496
+
497
+ def _requirements() -> list[str]:
498
+ requirements = [UV_BUILD_REQUIREMENT]
499
+ if sys.version_info < (3, 11):
500
+ requirements.append("tomli>=2")
501
+ return requirements
502
+
503
+
504
+ # ── the project's own metadata ───────────────────────────────────────────────
505
+
506
+
507
+ def _merged_dependencies(
508
+ metadata: Mapping[str, Any], introduced: Sequence[str]
509
+ ) -> list[str]:
510
+ """The project's dependencies, plus what lowering needs at run time.
511
+
512
+ Building for an older python can put a name in the output that only
513
+ `typing_extensions` has there, and the project never asked for it, so it
514
+ cannot have declared it. A wheel that shipped without it would install
515
+ cleanly and fail on the first import of the module that needs it.
516
+
517
+ A project that already names the distribution keeps its own constraint: it
518
+ knows something about the version it wants that this does not.
519
+ """
520
+ declared = list(metadata.get("dependencies", []))
521
+ already = {_requirement_name(requirement) for requirement in declared}
522
+ return declared + [
523
+ requirement
524
+ for requirement in introduced
525
+ if _requirement_name(requirement) not in already
526
+ ]
527
+
528
+
529
+ def _requirement_name(requirement: str) -> str:
530
+ """The distribution a requirement names, normalized."""
531
+ name = re.split(r"[\s<>=!~;\[(]", requirement.strip(), maxsplit=1)[0]
532
+ return _normalized_name(name)
533
+
534
+
535
+ def _read_project_metadata(project_root: Path) -> dict[str, Any]:
536
+ """The `[project]` table, with anything dynamic settled.
537
+
538
+ It is carried into the staged tree verbatim, because it is what becomes the
539
+ wheel's core metadata. The one thing that cannot be carried is a dynamic
540
+ version: the backend downstream has no way to compute one, and the place the
541
+ version actually lives — a `.by` module — is not something it can read. So it
542
+ is resolved here, from the python that module was transpiled into.
543
+ """
544
+ pyproject = project_root / "pyproject.toml"
545
+ if not pyproject.is_file():
546
+ raise BuildError("a basedpython project needs a `pyproject.toml`")
547
+
548
+ document = _parse_toml(pyproject.read_bytes())
549
+ metadata = dict(document.get("project", {}))
550
+ if not metadata:
551
+ raise BuildError("`pyproject.toml` has no `[project]` table to build from")
552
+
553
+ dynamic = list(metadata.get("dynamic", []))
554
+ if "version" in dynamic:
555
+ metadata["version"] = _dynamic_version(project_root, document)
556
+ dynamic.remove("version")
557
+ if dynamic:
558
+ raise BuildError(
559
+ "this backend cannot resolve dynamic metadata "
560
+ f"{', '.join(sorted(dynamic))} — declare it in `[project]` instead"
561
+ )
562
+ metadata.pop("dynamic", None)
563
+ if "version" not in metadata:
564
+ raise BuildError("`[project]` has neither a `version` nor a dynamic one")
565
+ return metadata
566
+
567
+
568
+ def _dynamic_version(project_root: Path, document: Mapping[str, Any]) -> str:
569
+ """Read `__version__` out of the module the project points at."""
570
+ configured = (
571
+ document.get("tool", {})
572
+ .get("basedpython", {})
573
+ .get("build", {})
574
+ .get("version-from")
575
+ )
576
+ if not configured:
577
+ raise BuildError(
578
+ '`[project] dynamic = ["version"]` needs somewhere to read the version '
579
+ 'from — set `[tool.basedpython.build] version-from = "src/pkg/__init__.by"`'
580
+ )
581
+ source = project_root / configured
582
+ if not source.is_file():
583
+ raise BuildError(
584
+ f"`build.version-from` points at `{configured}`, which is not a file"
585
+ )
586
+
587
+ for line in source.read_text(encoding="utf-8").splitlines():
588
+ stripped = line.strip()
589
+ # `__version__ = "1.2.3"`, however it is spelled around the assignment.
590
+ # reading the text rather than importing keeps this from executing a
591
+ # module that has not been transpiled yet
592
+ if stripped.startswith("__version__"):
593
+ _, _, value = stripped.partition("=")
594
+ value = value.strip().split("#")[0].strip()
595
+ if len(value) >= 2 and value[0] in "\"'" and value[-1] == value[0]:
596
+ return value[1:-1]
597
+ raise BuildError(f"`{configured}` has no `__version__` to read the version from")
598
+
599
+
600
+ def _parse_toml(contents: bytes) -> dict[str, Any]:
601
+ try:
602
+ import tomllib
603
+ except ImportError: # python < 3.11
604
+ import tomli as tomllib # type: ignore[no-redef]
605
+ return tomllib.loads(contents.decode("utf-8"))
606
+
607
+
608
+ def _normalized_name(name: str) -> str:
609
+ return re.sub(r"[-_.]+", "_", name).lower()
610
+
611
+
612
+ # ── writing the staged pyproject ─────────────────────────────────────────────
613
+
614
+
615
+ def _toml(document: Mapping[str, Any]) -> str:
616
+ """Render a mapping as TOML.
617
+
618
+ Only what a `[project]` table holds has to survive this: strings, numbers,
619
+ booleans, arrays, tables, and arrays of tables. That is the whole of PEP 621,
620
+ and rendering it here is what lets the project's metadata reach the packaging
621
+ backend unaltered.
622
+ """
623
+ lines: list[str] = []
624
+ _render_table(document, [], lines)
625
+ return "\n".join(lines) + "\n"
626
+
627
+
628
+ def _render_table(
629
+ table: Mapping[str, Any], path: Sequence[str], lines: list[str]
630
+ ) -> None:
631
+ scalars = {key: value for key, value in table.items() if not _is_table_like(value)}
632
+ tables = {key: value for key, value in table.items() if _is_table_like(value)}
633
+
634
+ if path and (scalars or not tables):
635
+ lines.append(f"[{_render_key_path(path)}]")
636
+ for key, value in scalars.items():
637
+ lines.append(f"{_render_key(key)} = {_render_value(value)}")
638
+ if path and (scalars or not tables):
639
+ lines.append("")
640
+
641
+ for key, value in tables.items():
642
+ nested = [*path, key]
643
+ if isinstance(value, dict):
644
+ _render_table(value, nested, lines)
645
+ else:
646
+ for element in value:
647
+ lines.append(f"[[{_render_key_path(nested)}]]")
648
+ for inner_key, inner_value in element.items():
649
+ lines.append(
650
+ f"{_render_key(inner_key)} = {_render_value(inner_value)}"
651
+ )
652
+ lines.append("")
653
+
654
+
655
+ def _is_table_like(value: Any) -> bool:
656
+ if isinstance(value, dict):
657
+ return True
658
+ # an array of tables is rendered as `[[name]]` blocks; an array of anything
659
+ # else is an ordinary inline array
660
+ return (
661
+ isinstance(value, list)
662
+ and len(value) > 0
663
+ and all(isinstance(element, dict) for element in value)
664
+ )
665
+
666
+
667
+ def _render_key_path(path: Sequence[str]) -> str:
668
+ return ".".join(_render_key(part) for part in path)
669
+
670
+
671
+ def _render_key(key: str) -> str:
672
+ if key and all(character.isalnum() or character in "-_" for character in key):
673
+ return key
674
+ return _render_string(key)
675
+
676
+
677
+ def _render_value(value: Any) -> str:
678
+ if isinstance(value, bool):
679
+ return "true" if value else "false"
680
+ if isinstance(value, str):
681
+ return _render_string(value)
682
+ if isinstance(value, (int, float)):
683
+ return repr(value)
684
+ if isinstance(value, dict):
685
+ rendered = ", ".join(
686
+ f"{_render_key(key)} = {_render_value(inner)}"
687
+ for key, inner in value.items()
688
+ )
689
+ return "{" + rendered + "}"
690
+ if isinstance(value, (list, tuple)):
691
+ rendered = ", ".join(_render_value(element) for element in value)
692
+ return "[" + rendered + "]"
693
+ raise BuildError(
694
+ f"`pyproject.toml` holds a value this backend cannot carry over: {value!r}"
695
+ )
696
+
697
+
698
+ def _render_string(value: str) -> str:
699
+ escaped = (
700
+ value.replace("\\", "\\\\")
701
+ .replace('"', '\\"')
702
+ .replace("\n", "\\n")
703
+ .replace("\r", "\\r")
704
+ .replace("\t", "\\t")
705
+ )
706
+ return f'"{escaped}"'
707
+
708
+
709
+ # ── the `by` executable ──────────────────────────────────────────────────────
710
+
711
+
712
+ def _run_by(*arguments: str) -> str:
713
+ executable = _by_executable()
714
+ completed = subprocess.run(
715
+ [executable, *arguments],
716
+ stdout=subprocess.PIPE,
717
+ check=False,
718
+ )
719
+ if completed.returncode != 0:
720
+ raise BuildError(
721
+ f"`by {' '.join(arguments)}` failed with exit code {completed.returncode}"
722
+ )
723
+ return completed.stdout.decode("utf-8")
724
+
725
+
726
+ def _by_executable() -> str:
727
+ """Find the `by` that belongs to this installation.
728
+
729
+ It ships in the same distribution as this module, so it is in this
730
+ environment's scripts directory. Looking there first rather than on `PATH`
731
+ means the build uses the transpiler it was installed with, not whichever one
732
+ happens to be earlier in the shell's path.
733
+ """
734
+ name = "by.exe" if os.name == "nt" else "by"
735
+ candidates = [
736
+ Path(sysconfig.get_path("scripts")) / name,
737
+ Path(sys.executable).parent / name,
738
+ ]
739
+ for candidate in candidates:
740
+ if candidate.is_file():
741
+ return str(candidate)
742
+ found = shutil.which(name)
743
+ if found:
744
+ return found
745
+ raise BuildError(
746
+ "could not find the `by` executable, which is what builds a basedpython "
747
+ "project. it is installed by the `basedpython` distribution — check that "
748
+ "`[build-system] requires` names it"
749
+ )