Coverage for packages/workshop/src/livery/workshop/_new_project.py: 87%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_extensions_conan.py ran.

1"""``fm new.project``: birth, end to end, one idempotent verb.
2
3Seed the contract, write the project's seeds, lock and sync, deliver
4the extension content, generate the CI files, initialise git, then the
5forge half: create the repository, assert its configuration, push,
6and open the unarmed setup pull request. Every step detects done
7and walks past it, so re-running is the recovery procedure and a
8kill between any two steps costs nothing. ``--local`` is everything
9that stays on the machine and nothing that leaves it.
10
11The task lives above any repository, so the workspace it makes never
12needed one. The workspace's extensions are the stock list
13(``birth_extensions``) unless ``--extensions`` names them, and the
14birth writes them as their canonical list.
15"""
16
17from __future__ import annotations
18
19import datetime
20import re
21import tempfile
22from pathlib import Path
23from typing import TYPE_CHECKING, Annotated
24
25import livery.footman as footman
26from livery import git
27from livery.footman import Arg, doc, fail, group, hidden
28from livery.forge import Forge, ForgeError, Repository
29from livery.workshop._contract import toml_string
30from livery.workshop._templates import NEW_HELP, PACKAGE_HELP
31
32new_group = group("new", help=NEW_HELP)
33
34#: The group of the templates' verbs: ``fm new.package.<template>``.
35package = new_group.group("package", help=PACKAGE_HELP)
36
37if TYPE_CHECKING:
38 from livery.toolroom.tools import Result
39
40#: The web host each kind means when the contract carries no URL.
41_PUBLIC_HOSTS = {"github": "https://github.com", "gitlab": "https://gitlab.com"}
42
43
44#: The catalogue a newborn resolves its tools against: this extension's own
45#: published index, a strongroom store served as static files under the
46#: site the extension publishes. Hardcoded, and it moves when the site does.
47PUBLISHED_INDEX = "https://livery.willem.net/tools/"
48
49
50def _sync_tools(root: Path) -> None:
51 """Write the newborn's first `toolroom.lock` and install what it names.
52
53 Without this a newborn's own gate reaches for checkers the store
54 never installed: the lock says what to install and nothing writes
55 one for a project that has never had one. Idempotent, like every
56 other step of the birth. The engine takes the newborn's root as a
57 value: this runs inside the birth's own task, and a task may not
58 change the process directory.
59 """
60 from livery.workshop._tool_tasks import sync_tools
61
62 sync_tools(root)
63
64
65def _hand_off(
66 root: Path,
67 *,
68 forge: str = "",
69 owner: str = "",
70 url: str = "",
71 local: bool = False,
72 extension: str = "",
73) -> None:
74 """Finish the birth with the runner *root*'s environment holds, inside *root*.
75
76 Run as ``new.project --resume`` from the project's own directory,
77 where the project's extensions are mounted at the versions it
78 locked: its tools, its composed and generated files and its forge
79 half come from them, which a process started elsewhere cannot
80 promise. The answers ride in the contract; the flags pass what it
81 does not hold. The child shares the console and its failure is the
82 birth's.
83
84 Raises:
85 Failed: when the environment has no runner, naming it.
86 """
87 from livery.workshop._pythons import runner_script
88
89 prog = footman.prog()
90 runner = runner_script(root / ".venv")
91 if not runner.is_file():
92 fail(
93 f"{runner} is missing: {root}'s environment has no {prog} to finish"
94 f" the birth with. `uv sync` in {root} installs it; then run"
95 f" `{prog} new.project --resume` there"
96 )
97 argv = [str(runner), "new.project", "--resume"]
98 argv += [
99 f"--{key}={value}"
100 for key, value in (
101 ("forge", forge),
102 ("owner", owner),
103 ("url", url),
104 ("extension", extension),
105 )
106 if value
107 ]
108 if local:108 ↛ 110line 108 didn't jump to line 110 because the condition on line 108 was always true
109 argv.append("--local")
110 print(f" environment: the birth continues with {runner}")
111 footman.run(argv, cwd=root, capture=False)
112
113
114def _git(root: Path, *args: str) -> str:
115 """Run git under *root*; stdout, or fail with git's own words."""
116 try:
117 return git.run(root, *args)
118 except git.GitError as error:
119 fail(str(error))
120
121
122def _git_outside(*args: str) -> Result:
123 """Run git where no repository is implied; the result, never a refusal.
124
125 The birth verb runs above any repository, and several of its
126 questions must not be answered by whatever repository the
127 person happens to stand in. The temporary directory is that
128 nowhere. Every caller reads the exit code itself.
129 """
130 return git.call(Path(tempfile.gettempdir()), *args)
131
132
133def _git_config(name: str) -> str:
134 """A global git config value, empty when unset."""
135 result = _git_outside("config", "--global", "--get", name)
136 return result.stdout.strip() if result.code == 0 else ""
137
138
139def _clone_url(kind: str, url: str, owner: str, name: str) -> str:
140 """The remote the newborn pushes to, credential-free."""
141 web = (url or _PUBLIC_HOSTS.get(kind, "")).rstrip("/")
142 if not web:
143 fail("the forge needs a URL: pass --url (gitea has no public default)")
144 return f"{web}/{owner}/{name}.git"
145
146
147def _remote_is_foreign(clone_url: str) -> bool:
148 """Whether the remote already has commits (foreign, never adopted)."""
149 listing = _git_outside("ls-remote", clone_url)
150 return listing.code == 0 and bool(listing.stdout.strip())
151
152
153def _connect(kind: str, url: str) -> tuple[Forge, str]:
154 """The target forge on the everyday token ladder, and the token.
155
156 The token rides back so the pushes can authenticate with it: the
157 committed remote stays credential-free (a human's pushes ride
158 their credential helper), and automation pushes to a
159 token-carrying URL instead, the way the emitted GitLab lane and
160 the stamp transport already do.
161 """
162 from livery.workshop._forge_lane import _connect as connect
163 from livery.workshop._tokens import forge_token
164
165 token, _ = forge_token(kind, url)
166 forge = connect(kind, url, token or None)
167 if not token:
168 # The connection resolved its own dialect variable; the push
169 # credential mirrors that resolution or automation cannot
170 # push at all.
171 token = forge.token
172 return forge, token
173
174
175def _push_target(clone_url: str, token: str) -> str:
176 """Where pushes go: the token-embedded URL when one resolved.
177
178 Only http(s) URLs can carry the credential; anything else pushes
179 to the remote as-is. The token-embedded URL is a
180 [livery.footman.Secret][]: a profile trace and every other place
181 a command line is shown carry ``***`` in its place, and git alone
182 receives the value. The caller passes it to git unchanged, since
183 any string operation on it returns a plain `str`, which is shown
184 in the clear.
185 """
186 if token and clone_url.startswith(("http://", "https://")):
187 scheme, _, rest = clone_url.partition("://")
188 return footman.Secret(f"{scheme}://oauth2:{token}@{rest}")
189 return "origin"
190
191
192#: The extensions a stock App's birth lists, as their canonical list:
193#: the type checker's, the changelog's, coverage's, the site's API
194#: reference, which requires the site's, the test runner's, python and
195#: the python formatter's. python is the language of the workspace's own
196#: tests and ``tasks.py``: those tests hold the root's set, and run while
197#: it holds python. An agent's files are a choice the project makes, so
198#: no agent's extension is among them.
199STOCK = (
200 "basedpyright",
201 "changelog",
202 "coverage",
203 "mkdocstrings",
204 "pytest",
205 "python",
206 "ruff",
207)
208
209
210def birth_extensions(builtin: list[str] | tuple[str, ...]) -> list[str]:
211 """The extensions a birth lists, from the running App's builtin providers.
212
213 Footman's own providers and the base are never listed. A stock App
214 (the base among its builtins) lists the stock list (``STOCK``), and
215 a branded App its own extensions beside them, all as their
216 canonical list (``canonical_extensions``). A brand's extension
217 takes another's file or step by requiring it and declaring the
218 replacement, never by where it is listed.
219 """
220 kept = [entry for entry in builtin if not entry.startswith("footman.")]
221 kept = kept or ["livery.workshop"]
222 listed = [entry for entry in kept if entry != "livery.workshop"]
223 if "livery.workshop" in kept:
224 listed[:0] = STOCK
225 return canonical_extensions(listed)
226
227
228def canonical_extensions(names: list[str] | tuple[str, ...]) -> list[str]:
229 """*names* as the canonical list a birth writes.
230
231 The minimal list of their set in composition order, as the installed
232 declarations compose it: an extension another one requires is left
233 out, and a name no installed distribution declares requires
234 nothing.
235
236 Raises:
237 Failed: when the set's declared order has no start, naming the
238 cycle.
239 """
240 from livery.workshop._composition import OrderCycle, canonical
241 from livery.workshop._extensions import installed_declaration
242
243 try:
244 return list(canonical(names, installed_declaration))
245 except OrderCycle as error:
246 fail(f"the extensions cannot be listed: {error}")
247
248
249@new_group.task(name="project", expose="always", interactive=True, cwd="asinvoked")
250def new_project(
251 folder: Annotated[
252 Arg[str],
253 doc("where the project is born, an empty or new folder; this one by default"),
254 ] = "",
255 name: Annotated[
256 str, doc("the workspace's name, also the repository's; the folder's by default")
257 ] = "",
258 forge: Annotated[str, doc("github, gitea, or gitlab; github by default")] = "",
259 owner: Annotated[
260 str, doc("the owner or organisation the repository lives under")
261 ] = "",
262 url: Annotated[
263 str, doc("the forge server (empty for github.com and gitlab.com)")
264 ] = "",
265 description: Annotated[str, doc("one sentence for the virtual root")] = "",
266 author: Annotated[str, doc("the authors entry's name (default: git config)")] = "",
267 email: Annotated[str, doc("the authors entry's email (default: git config)")] = "",
268 namespace: Annotated[str, doc("dotted namespace packages live in")] = "",
269 extension: Annotated[
270 str,
271 doc(
272 "also scaffold this named extension package, with its branded App,"
273 " and self-host it: the workspace becomes the extension's home"
274 ),
275 ] = "",
276 local: Annotated[
277 bool, doc("everything that stays on the machine, nothing that leaves it")
278 ] = False,
279 extensions: Annotated[
280 str,
281 doc(
282 "the extensions the workspace lists, comma-separated, each by name,"
283 " written as their canonical list; the stock list by default, which"
284 " names python for the workspace's own tests"
285 ),
286 ] = "",
287 resume: Annotated[bool, hidden] = False,
288) -> None:
289 """Create a workspace in an empty or new folder, end to end, as one verb.
290
291 The birth seeds the contract, whose ``[workspace] extensions`` is
292 the stock list or the one ``--extensions`` names, written as its
293 canonical list: no extension another one requires, in composition
294 order. The stock list names python: the workspace's own tests hold
295 the root's set, and run while it holds python. It writes the
296 project's files, locks and syncs its environment, then hands the
297 rest to the runner that environment holds, run as
298 ``new.project --resume`` inside the project. There the project's
299 own extensions are mounted, so its
300 tools, its composed and generated files and its forge half come
301 from them at the versions it locked. A folder that holds a project
302 refuses, naming ``--resume``, which finishes that project's birth:
303 every step of it detects done and walks past it, so it is also
304 the recovery after a birth that stopped part way. Headless runs
305 never hang; a missing required answer is a refusal listing what to
306 pass.
307 """
308 # The task's directory is the launch directory (`asinvoked`), not
309 # the directory of whichever tasks file mounted the verb: the folder
310 # means where the caller stands.
311 here = footman.cwd()
312 root = (here / folder).resolve() if folder else here
313 prog = footman.prog()
314 held = (root / "workshop.toml").is_file()
315 if resume:
316 if not held:
317 fail(
318 f"{root} holds no project to resume: `{prog} new.project`"
319 " births one into an empty or new folder"
320 )
321 from livery.workshop._extensions import workspace_root
322
323 # Inside the project this process is its own runner; elsewhere
324 # the project's runner finishes it.
325 finish = _finish if workspace_root() == root else _hand_off
326 finish(
327 root, forge=forge, owner=owner, url=url, local=local, extension=extension
328 )
329 return
330 if held:
331 fail(
332 f"{root} holds a project already; `{prog} new.project --resume`"
333 " finishes its birth"
334 )
335 if root.exists() and any(root.iterdir()):
336 fail(f"{root} is not empty: a project is born into an empty or new folder")
337 name = name or root.name
338 forge = forge or "github"
339 _check_answers(name, forge=forge, owner=owner, url=url, local=local)
340 # The contract: a birth-time seed the render never touches. The
341 # list is the running App's own builtin providers, minus footman's
342 # and the base, which is never listed (contract 19): a branded App's
343 # children carry its extensions. Stock fm's carry the stock list,
344 # whose distributions the newborn's sync installs.
345 # footman.BUILTIN is an import-time snapshot of the stock brand;
346 # the running App's own list lives in _paths.builtin() (a public
347 # runtime accessor is footman#536's family). It is composed before
348 # the folder is made, so a list that cannot be written leaves none.
349 from livery.footman import builtins
350
351 named = [e.strip() for e in extensions.split(",") if e.strip()]
352 listed = canonical_extensions(named) if named else birth_extensions(builtins())
353 root.mkdir(parents=True, exist_ok=True)
354 contract = root / "workshop.toml"
355 spelled = ", ".join(f'"{entry}"' for entry in listed)
356 year = str(datetime.datetime.now(tz=datetime.UTC).year)
357 author_name = author or _git_config("user.name") or f"{name} authors"
358 author_email = email or _git_config("user.email")
359 person = f"{{ name = {toml_string(author_name)}"
360 if author_email:360 ↛ 362line 360 didn't jump to line 362 because the condition on line 360 was always true
361 person += f", email = {toml_string(author_email)}"
362 person += " }"
363 lines = [
364 "[workspace]",
365 f"name = {toml_string(name)}",
366 "description = "
367 + toml_string(description or f"The {name} monorepo (virtual root)."),
368 f"namespace = {toml_string(namespace or name.replace('-', '_'))}",
369 f"authors = [{person}]",
370 f'copyright-year = "{year}"',
371 f"extensions = [{spelled}]",
372 ]
373 lines += ["", "[forge]", f'kind = "{forge}"']
374 if owner:
375 lines.append(f'owner = "{owner}"')
376 if url:
377 lines.append(f'url = "{url}"')
378 lines += [
379 "",
380 "[toolroom]",
381 f'index = "{PUBLISHED_INDEX}"',
382 "",
383 "[ci]",
384 'runners = ["ubuntu-latest"]',
385 'required-context = "gate"',
386 ]
387 contract.write_text("\n".join(lines) + "\n", encoding="utf-8")
388 print(" workshop.toml: seeded")
389
390 _prepare(root)
391 _hand_off(root, local=local, extension=extension)
392
393
394def _check_answers(name: str, *, forge: str, owner: str, url: str, local: bool) -> None:
395 """Refuse answers no birth can use, listing what to pass."""
396 if not re.fullmatch(r"[a-z][a-z0-9-]*", name):
397 fail(
398 f"project name {name!r}: use lowercase letters, digits, hyphens"
399 " (the folder's name, unless --name gives one)"
400 )
401 if forge not in ("github", "gitea", "gitlab"):401 ↛ 402line 401 didn't jump to line 402 because the condition on line 401 was never true
402 fail(f"unknown forge kind {forge!r}: use github, gitea, or gitlab")
403 if not local and not owner:
404 fail(
405 "answers missing for the forge half: pass --owner (and --url"
406 " for a self-hosted server), or --local for everything that"
407 " stays on the machine"
408 )
409 if forge == "gitea" and not local and not url:
410 fail("gitea has no public default server: pass --url")
411
412
413def _prepare(root: Path) -> None:
414 """Write what a newborn starts with, then lock and sync its environment.
415
416 The seeds are the files a workspace starts with, its own from then
417 on: one that exists is never touched, so a resumed birth writes
418 only what a stopped one did not. The project file is composed from
419 the answers and the lock reads it, so the composed files are
420 written before the first lock.
421 """
422 from livery.workshop._identity import project_facts
423 from livery.workshop._seeds import PROJECT, create
424 from livery.workshop._shipped_files import deliver
425 from livery.workshop._templates import package_injections
426 from livery.workshop._uv import run_uv
427
428 seeded = create(
429 root, root, PROJECT, {**project_facts(root), **package_injections(root)}
430 )
431 print(f" seeds: {len(seeded)} written" if seeded else " seeds: already written")
432 for line in deliver(root):
433 print(line)
434 run_uv("lock", root=root)
435 run_uv("sync", root=root)
436 print(" environment: locked and synced")
437
438
439def _finish(
440 root: Path,
441 *,
442 forge: str = "",
443 owner: str = "",
444 url: str = "",
445 local: bool = False,
446 extension: str = "",
447) -> None:
448 """Finish *root*'s birth from inside it: everything after its environment.
449
450 The answers come from the contract the birth seeded; a flag passes
451 what it does not hold, the owner a local birth left out, say.
452 """
453 from livery.workshop._contract import load_contract
454
455 contract = load_contract(root / "workshop.toml")
456 workspace = contract.get("workspace") or {}
457 seeded = contract.get("forge") or {}
458 name = str(workspace.get("name", root.name))
459 description = str(workspace.get("description", ""))
460 forge = forge or str(seeded.get("kind", "github"))
461 owner = owner or str(seeded.get("owner", ""))
462 url = url or str(seeded.get("url", ""))
463 _check_answers(name, forge=forge, owner=owner, url=url, local=local)
464 _prepare(root)
465
466 _sync_tools(root)
467
468 from livery.workshop._sync import sync_workspace
469
470 for line in sync_workspace(root):470 ↛ 471line 470 didn't jump to line 471 because the loop on line 470 never started
471 print(line)
472
473 from livery.workshop._templates import apply_project
474
475 for changed in apply_project(root):
476 print(f" rendered: {changed}")
477
478 if extension:
479 _add_extension(root, extension)
480
481 if not (root / ".git").is_dir():
482 _git(root, "init", "-q", "--initial-branch=main")
483 print(" git: initialised")
484 else:
485 print(" git: already initialised")
486 if not git.has_commits(root):
487 _git(root, "add", "-A")
488 _git(root, "commit", "-q", "-m", "chore: birth")
489 print(" git: birth committed")
490 else:
491 _git(root, "add", "-A")
492 status = _git(root, "status", "--porcelain")
493 if status.strip():493 ↛ 494line 493 didn't jump to line 494 because the condition on line 493 was never true
494 _git(root, "commit", "-q", "-m", "chore: birth aftercare")
495 print(" git: aftercare committed")
496
497 if local:
498 print(
499 " --local: done. Skipped, because they leave the machine:"
500 " repo.create, the repository configuration, the push, and"
501 f" the setup PR. `{footman.prog()} new.project --resume"
502 " --owner=...` here finishes the forge half."
503 )
504 return
505
506 clone_url = _clone_url(forge, url, owner, name)
507 target, push_token = _connect(forge, url)
508 push_to = _push_target(clone_url, push_token)
509 existing = target.get_repo(owner, name)
510 created_now = False
511 if existing is None:
512 target.create_repo(
513 owner,
514 name,
515 private=True,
516 description=description or f"The {name} monorepo (virtual root).",
517 )
518 created_now = True
519 print(f" repository: created {owner}/{name}")
520 elif _remote_is_foreign(clone_url) and not _pushed_by_us(root, clone_url):
521 fail(
522 f"{owner}/{name} already exists on the forge with its own"
523 " history: pick another name, or delete the foreign"
524 " repository first. Nothing was pushed."
525 )
526 else:
527 print(f" repository: {owner}/{name} already exists; adopting")
528
529 remotes = _git(root, "remote")
530 if "origin" in remotes.split():
531 _git(root, "remote", "set-url", "origin", clone_url)
532 else:
533 _git(root, "remote", "add", "origin", clone_url)
534 if created_now:
535 # The protocol initialises a created repository with a default
536 # branch, so the birth history replaces that init commit; the
537 # repository is seconds old and this checkout is its author.
538 _git(root, "push", "-q", "--force", "-u", push_to, "main")
539 print(" pushed: main")
540 else:
541 pushed = git.call(root, "push", "-q", "-u", push_to, "main")
542 if pushed.code == 0:542 ↛ 544line 542 didn't jump to line 544 because the condition on line 542 was always true
543 print(" pushed: main")
544 elif "protected branch" in f"{pushed.stdout}{pushed.stderr}":
545 # The resumed repository already governs itself: main
546 # moves through pull requests now, so local aftercare
547 # stays here and rides the next submitted branch.
548 print(
549 " main is protected (the birth already configured it):"
550 " the local commits stay here; submit them as a pull"
551 f" request with `{footman.prog()} submit`"
552 )
553 else:
554 fail(f"git push exited {pushed.code}:\n{pushed.stdout}{pushed.stderr}")
555
556 from livery.workshop._workflow_tasks import assert_configuration
557
558 assert_configuration(root)
559
560 _open_setup_pr(root, target.repository(owner, name), push_to)
561 print(
562 " done: merge the setup PR to prove the gate; the repository"
563 " is protected and live"
564 )
565 print(
566 " secrets: place CI tokens in protected scopes with"
567 f" `{footman.prog()} workflow.secret.set <NAME>` and verify with"
568 f" `{footman.prog()} security.check`"
569 )
570
571
572def _add_extension(root: Path, extension: str) -> None:
573 """Scaffold *extension* and self-host it: the workspace becomes its home.
574
575 The extension package is born from the ``workshop-extension``
576 template with its branded App, a script named after the extension's
577 directory, and the contract's list gains its import path, written
578 again as its canonical list, so the home composes with its own
579 extension at HEAD from the first commit. Idempotent: an
580 already-listed extension walks past.
581 """
582 from livery.workshop._sync import sync_workspace
583 from livery.workshop._templates import render_member
584
585 if (root / "packages" / extension).exists():
586 print(f" extension: packages/{extension} already scaffolded")
587 return
588 app = extension.rsplit("/", 1)[-1]
589 import_path = render_member(root, extension, "workshop-extension", {"app": app})
590 # Wired in the birth's own process: the template needs python, which
591 # the root's list holds, so this process mounted it already, and a
592 # list without python refused the render above.
593 wire_member(root, extension)
594 contract = root / "workshop.toml"
595 text = contract.read_text("utf-8")
596 if f'"{import_path}"' not in text:596 ↛ 614line 596 didn't jump to line 614 because the condition on line 596 was always true
597 import tomllib
598
599 match = re.search(r"^extensions = \[(.*)\]$", text, flags=re.M)
600 if match is None:600 ↛ 601line 600 didn't jump to line 601 because the condition on line 600 was never true
601 fail(
602 f"cannot self-host {import_path}: the contract has no"
603 " extensions line; add it by hand"
604 )
605 workspace = tomllib.loads(text).get("workspace", {})
606 named = [str(entry) for entry in workspace.get("extensions", [])]
607 listed = canonical_extensions([*named, import_path])
608 written = ", ".join(f'"{entry}"' for entry in listed)
609 text = text[: match.start()] + f"extensions = [{written}]" + text[match.end() :]
610 contract.write_text(text, encoding="utf-8")
611 print(f" extensions: {import_path} self-hosted")
612 # The stack changed: re-deliver content and re-render through the
613 # composed source, so the home's files carry its own overlay.
614 from livery.workshop._templates import apply_project as reapply
615
616 for line in sync_workspace(root):616 ↛ 617line 616 didn't jump to line 617 because the loop on line 616 never started
617 print(line)
618 for changed in reapply(root):618 ↛ 619line 618 didn't jump to line 619 because the loop on line 618 never started
619 print(f" rendered: {changed}")
620
621
622def _pushed_by_us(root: Path, clone_url: str) -> bool:
623 """Whether the remote's main is this checkout's history (a resume)."""
624 try:
625 sha = git.ls_remote(root, "refs/heads/main", remote=clone_url).get(
626 "refs/heads/main", ""
627 )
628 except git.GitError:
629 sha = ""
630 if not sha:630 ↛ 631line 630 didn't jump to line 631 because the condition on line 630 was never true
631 return True # exists but empty: get-or-create proceeds
632 return git.tracks(root, sha)
633
634
635#: The setup branch: a trivial change whose PR proves the gate wires
636#: end to end before any real work rides it.
637_SETUP_BRANCH = "chore/setup-check"
638
639
640def _open_setup_pr(root: Path, repo: Repository, push_to: str) -> None:
641 """Open the unarmed setup PR; find it instead when it exists."""
642 found = repo.pr.find_by_head(_SETUP_BRANCH)
643 if found is not None:
644 print(f" setup PR: already open (#{found.number})")
645 return
646 branches = _git(root, "branch", "--list", _SETUP_BRANCH)
647 if not branches.strip():647 ↛ 649line 647 didn't jump to line 649 because the condition on line 647 was always true
648 _git(root, "branch", _SETUP_BRANCH, "main")
649 _git(root, "push", "-q", push_to, _SETUP_BRANCH)
650 # The branch needs a diff or some forges refuse the PR; an empty
651 # commit rides it, evaporating in the squash.
652 tip = _git(root, "rev-parse", _SETUP_BRANCH).strip()
653 main = _git(root, "rev-parse", "main").strip()
654 if tip == main:654 ↛ 659line 654 didn't jump to line 659 because the condition on line 654 was always true
655 _git(root, "switch", "-q", _SETUP_BRANCH)
656 _git(root, "commit", "-q", "--allow-empty", "-m", "chore: setup check")
657 _git(root, "push", "-q", push_to, _SETUP_BRANCH)
658 _git(root, "switch", "-q", "main")
659 try:
660 opened = repo.pr.open(
661 _SETUP_BRANCH,
662 "main",
663 "chore: setup check",
664 "The birth verb's proof: CI runs, the gate reports, branch"
665 " protection holds. Merge when green; the squash evaporates"
666 " the empty commit.",
667 )
668 except ForgeError as error:
669 fail(f"the setup PR did not open:\n{error}")
670 print(f" setup PR: opened #{opened.number}, unarmed")
671
672
673@new_group.task(name="wire", hidden=True)
674def new_wire(
675 name: Annotated[str, doc("the package's path under packages/")],
676) -> None:
677 """Wire the package under packages/<name> into the workspace.
678
679 Writes the project files again, so every per-package list picks the
680 member up, then locks and syncs the environment and the tools. A
681 template's verb runs it in the runner the workspace's environment
682 holds once the member is written, and it is the recovery after a
683 wiring that stopped part way. A member that does not hold the
684 runtime language joins the roster without a dev-group entry: there
685 is no distribution to install.
686 """
687 from livery.workshop._templates import _root
688
689 wire_member(_root(), name)
690
691
692def wire_member(root: Path, name: str) -> None:
693 """Wire the package under ``packages/<name>`` into *root*.
694
695 Writes the composed and generated files again, so every
696 per-package list picks the member up, then locks and syncs the
697 environment and the tools. ``fm new.wire`` runs it in the runner
698 the workspace's environment holds, after a template's verb wrote the
699 member.
700
701 Raises:
702 Failed: when *name* breaks the package naming rule, or
703 ``packages/<name>`` holds no package.
704 """
705 from livery.workshop._templates import _check_member_name, apply_project
706 from livery.workshop._tool_tasks import sync_tools
707 from livery.workshop._uv import run_uv
708
709 _check_member_name(name)
710 if not (root / "packages" / name / "workshop.toml").is_file():
711 fail(
712 f"packages/{name} holds no package to wire:"
713 f" `{footman.prog()} new.package.<template> {name}` creates one"
714 )
715 for changed in apply_project(root):
716 print(f" rendered: {changed}")
717 run_uv("lock", root=root)
718 run_uv("sync", root=root)
719 # A member's extensions bring tools of their own (a native
720 # member's build tools and the steps that judge it), so the tool
721 # lock moves with the member and the store supplies what it names:
722 # the gate that follows finds them, as it does after a birth.
723 sync_tools(root)
724 print(f" packages/{name}: seeded, wired, and installed")