Coverage for packages/workshop/src/livery/workshop/_templates.py: 92%

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_walk.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_locked.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_skip_marks.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_schema.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runtime_language.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_decide.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_phases.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_package_level_fragments.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_fragments.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_cpp_kind.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_composition.py, packages/workshop/tests/test_workshop_claims.py, packages/workshop/tests/test_workshop_categories.py, packages/workshop/tests/test_workshop_affected_legs.py, packages/extensions/ty/tests/test_ty.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/pyrefly/tests/test_pyrefly.py, packages/extensions/nanobind/tests/test_nanobind_kind.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mypy/tests/test_mypy.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_affected_legs.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_conan_kind.py, packages/extensions/cmake/tests/test_cpp_kind.py, packages/extensions/cmake/tests/test_coverage_parts.py, packages/extensions/cmake/tests/test_cmake.py, packages/extensions/clang-tidy/tests/test_clang_tidy.py, packages/extensions/clang-format/tests/test_clang_format.py, packages/extensions/changelog/tests/test_changelog.py, packages/extensions/basedpyright/tests/test_basedpyright.py, packages/extensions/agents/tests/test_agents.py ran.

1"""The workspace's generated files: the drift check, the writer, new members.
2
3The listed extensions' files are composed by the fragment engine
4(`livery.workshop._shipped_files`); the CI files and the codeowners file
5are generated from the contract. `drift_check` judges both against the
6repository as the gate's `fm drift.check`; `apply_project` writes both,
7and `fm sync` runs it, which is the recovery for drift.
8
9Each installed template is a verb, ``fm new.package.<template> <name>
10--<option>=<answer>``, made from its declaration by
11`generate_template_verbs` when the plugin loads. It writes a member
12born from the template into ``packages/<name>`` through
13`render_member` (`livery.workshop._seeds`), the one function every
14creation calls, and a fresh runner adds the member to the project
15files.
16"""
17
18from __future__ import annotations
19
20import inspect
21import re
22import weakref
23from collections.abc import Callable, Mapping, Sequence
24from pathlib import Path
25from typing import TYPE_CHECKING, Annotated, Any, Literal, cast
26
27import livery.footman as footman
28from livery.footman import Group, doc, fail
29from livery.workshop._contract import load_contract
30from livery.workshop._extensions import (
31 stack_entries,
32 workspace_root,
33)
34from livery.workshop._identity import default_description, identity, python_dirs
35from livery.workshop._pythons import python_floor, runner_script
36
37if TYPE_CHECKING:
38 from livery.workshop._declaration import DeclaredTemplate, TemplateOption
39
40#: What ``fm new`` does, and what ``fm new.package`` does.
41NEW_HELP = "Create a project from the extensions' seeds, or a package from a template"
42PACKAGE_HELP = "Create a package from an installed template: one task per template"
43
44
45def _root() -> Path:
46 """The workspace root, or fail."""
47 root = workspace_root()
48 if root is None:48 ↛ 49line 48 didn't jump to line 49 because the condition on line 48 was never true
49 fail("no workspace: no workshop.toml above the working directory")
50 return root
51
52
53def _requirement_name(spec: str) -> str:
54 """The distribution a requirement spec names, extras and floors cut."""
55 return re.split(r"[\[<>=!~; ]", spec.strip(), maxsplit=1)[0]
56
57
58def registry_injections(root: Path) -> dict[str, str]:
59 """The contract's python registry, as render inputs.
60
61 Only the committed ``[registries]`` table feeds a render: the
62 resolution ladder's environment rung is machine truth, and a
63 rendered file must derive from the repository alone or the drift
64 check would judge each machine differently. Nothing declared
65 renders nothing, and uv resolves from the ecosystem default.
66 """
67 contract = load_contract(root / "workshop.toml")
68 table = contract.get("registries") or {}
69 entry = table.get("python") if isinstance(table, dict) else None
70 url, prerelease = "", ""
71 if isinstance(entry, str):
72 url = entry
73 elif isinstance(entry, dict):
74 url = str(entry.get("url", ""))
75 prerelease = str(entry.get("prerelease", ""))
76 return {"python_registry": url, "python_prerelease": prerelease}
77
78
79def render_injections(root: Path, answers: dict[str, Any]) -> dict[str, Any]:
80 """The render-time values no answer stores.
81
82 Identity is answered, configuration is declared: the runner's
83 name belongs to the process, the Python floor to the root
84 ``pyproject.toml``, the extensions and the registry to
85 ``workshop.toml``. Every project render mixes these in, so the
86 answers hold identity and the ``packages`` roster alone.
87 """
88 entries = stack_entries(root)
89 if not entries:89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 fail(
91 "workshop.toml declares no [workspace] extensions: the render"
92 " needs the stack (the base extension is livery.workshop)"
93 )
94 members = {
95 _requirement_name(str(entry.get("dev", "")))
96 for entry in answers.get("packages", [])
97 if isinstance(entry, dict)
98 }
99 from livery.workshop._queries import EDITOR_EXTENSIONS, answer, workspace_answers
100
101 injected: dict[str, Any] = {
102 "runner_prog": footman.prog(),
103 "python_floor": python_floor(root),
104 # The workspace's own tests directory, which the checkers and
105 # the test runner read only while it exists: a newborn has none.
106 "root_tests": ["tests"] if (root / "tests").is_dir() else [],
107 # Each python member's src and tests that hold a python file: a
108 # checker such as mypy refuses a named directory with none, and
109 # an extension's src may hold data alone.
110 "python_dirs": python_dirs(root),
111 # The workspace-level queries' answers, by name, each answered
112 # when a template reads it: the dev group's tool lines, the docs
113 # group's lines, pytest's addopts. A listed extension's answer
114 # lands here, and an unlisted one's leaves with it.
115 "queries": workspace_answers(root),
116 "extension_imports": [import_path for import_path, _ in entries],
117 # One line per distribution: a wheel may ship several extensions.
118 "extension_requirements": _extension_requirements(entries, members),
119 # The editor extension ids the listed extensions answer.
120 "extensions": list(answer(root, EDITOR_EXTENSIONS)),
121 **registry_injections(root),
122 }
123 injected["fragments"] = compose_fragments({**answers, **injected})
124 return injected
125
126
127def _extension_requirements(
128 entries: tuple[tuple[str, str], ...], members: set[str]
129) -> list[str]:
130 """The dev group's line for each stack distribution that is not a member.
131
132 One line per distribution, since a wheel may ship several
133 extensions.
134 """
135 found = [dist for _name, dist in entries if _requirement_name(dist) not in members]
136 return list(dict.fromkeys(found))
137
138
139def compose_fragments(data: dict[str, Any]) -> dict[str, str]:
140 """The step records' fragments composed per rendered file over *data*."""
141 from livery.workshop._fragments import compose_project
142
143 return compose_project(fragment_data(data))
144
145
146def fragment_data(data: dict[str, Any]) -> dict[str, Any]:
147 """*data* with what the step records' fragments read beside it.
148
149 The roster is split the way the project file splits it, ``py`` for
150 the members with a dev entry and ``native`` for the rest, and the
151 per-file ignores the claims render are added for the sets of
152 extensions the members hold, each entry's ``extensions``. A roster
153 with no member renders the ignores of the
154 workspace's own unit alone. The fragment engine reads the step
155 records' fragments through this.
156 """
157 from livery.workshop._steps import per_file_ignores
158
159 roster = [entry for entry in data.get("packages", []) if isinstance(entry, dict)]
160 held = {
161 tuple(str(name) for name in entry.get("extensions", ())) for entry in roster
162 }
163 return {
164 **data,
165 "py": [entry for entry in roster if entry.get("dev")],
166 "native": [entry for entry in roster if not entry.get("dev")],
167 # The per-file ignores the claims render, for the sets present.
168 "per_file_ignores": per_file_ignores(sorted(held)),
169 }
170
171
172def package_injections(root: Path) -> dict[str, Any]:
173 """The render-time values a package render takes from the contract.
174
175 The forge facts feed the changelog's link bases; asking them per
176 package would let one workspace's packages disagree about where
177 they live.
178 """
179 contract = load_contract(root / "workshop.toml")
180 forge_table = contract.get("forge") or {}
181
182 return {
183 "runner_prog": footman.prog(),
184 "python_floor": python_floor(root),
185 "forge_kind": str(forge_table.get("kind", "github")),
186 "forge_owner": str(forge_table.get("owner", "")),
187 "forge_url": str(forge_table.get("url", "")),
188 "project_name": identity(root)["project_name"],
189 }
190
191
192def _lf(data: bytes) -> bytes:
193 """The bytes with LF endings, whatever the platform wrote.
194
195 Git holds LF, and a file written on Windows may carry CRLF, so both
196 sides normalise before any compare or write. Without this the
197 Windows gate drifts on every file.
198 """
199 return data.replace(b"\r\n", b"\n")
200
201
202def project_drift(root: Path) -> list[str]:
203 """The drift report: generated files (CI, codeowners) that disagree with *root*.
204
205 Empty when every generated file matches the repository byte for
206 byte.
207 """
208 drift: list[str] = []
209 from livery.workshop._ci_generate import generated_files
210 from livery.workshop._governance import codeowners_file
211
212 generated = dict(generated_files(root))
213 rendered_owners = codeowners_file(root)
214 if rendered_owners is not None:214 ↛ 215line 214 didn't jump to line 215 because the condition on line 214 was never true
215 from livery.workshop._provenance import generated_header
216
217 generated[root / rendered_owners.path] = (
218 generated_header("#") + rendered_owners.content
219 )
220 for path, content in generated.items():
221 relative_generated = path.relative_to(root).as_posix()
222 if not path.is_file():
223 drift.append(
224 f"{relative_generated}: generated, but missing from the repository"
225 )
226 elif _lf(path.read_bytes()) != _lf(content.encode()):226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 drift.append(f"{relative_generated}: differs from its generation")
228 from livery.workshop._ci_generate import retired_files
229
230 for path in retired_files(root):230 ↛ 231line 230 didn't jump to line 231 because the loop on line 230 never started
231 drift.append(
232 f"{path.relative_to(root).as_posix()}: retired, still present;"
233 " the apply deletes it"
234 )
235 return drift
236
237
238def _release_baseline(directory: Path) -> str:
239 """The [release] baseline a package's contract declares, or empty.
240
241 A migrated distribution's version line predates this workspace;
242 the baseline names the version it continues from, and a package
243 template reads it as ``release_baseline`` to anchor the first
244 release on it.
245 """
246 contract = directory / "workshop.toml"
247 if not contract.is_file():
248 return ""
249 data = load_contract(contract)
250 return str((data.get("release") or {}).get("baseline", ""))
251
252
253def _release_exclude(directory: Path) -> tuple[str, ...]:
254 """The [release] exclude paths a package's contract declares, or empty."""
255 contract = directory / "workshop.toml"
256 if not contract.is_file():256 ↛ 257line 256 didn't jump to line 257 because the condition on line 256 was never true
257 return ()
258 data = load_contract(contract)
259 raw = (data.get("release") or {}).get("exclude", [])
260 if not isinstance(raw, list):260 ↛ 261line 260 didn't jump to line 261 because the condition on line 260 was never true
261 return ()
262 return tuple(str(path).strip("/") for path in raw if str(path).strip("/"))
263
264
265def apply_project(root: Path) -> list[str]:
266 """Write the composed and generated files over *root*; the files that changed.
267
268 The fragment engine composes the project file, the editor files, the
269 ignore and attribute lines, so a new member reaches `pyproject.toml`
270 here; the CI files and the codeowners file are generated after.
271 """
272 changed: list[str] = []
273 from livery.workshop._shipped_files import deliver
274
275 for line in deliver(root):
276 verb, _, rest = line.strip().partition(" ")
277 path = rest.partition(":")[0].split(" ")[0]
278 if path.startswith((".workshop/", ".claude/", ".agents/")):
279 continue # this checkout's own, not the project's render
280 if verb in ("wrote", "updated", "removed"):280 ↛ 283line 280 didn't jump to line 283 because the condition on line 280 was always true
281 changed.append(path)
282 else:
283 print(line)
284 changed.extend(apply_generated(root))
285 return changed
286
287
288def apply_generated(root: Path) -> list[str]:
289 """Write the emitted artifacts (CI files, codeowners); what changed.
290
291 The fragment engine's delivery and this together are apply_project,
292 which an update runs, so an instance's generated workflows move
293 with its workshop.
294 """
295 changed: list[str] = []
296 from livery.workshop._ci_generate import generated_files
297 from livery.workshop._governance import codeowners_file
298
299 generated = dict(generated_files(root))
300 rendered_owners = codeowners_file(root)
301 if rendered_owners is not None:301 ↛ 302line 301 didn't jump to line 302 because the condition on line 301 was never true
302 from livery.workshop._provenance import generated_header
303
304 generated[root / rendered_owners.path] = (
305 generated_header("#") + rendered_owners.content
306 )
307 for path, content in generated.items():
308 body = _lf(content.encode())
309 if not path.is_file() or _lf(path.read_bytes()) != body:
310 path.parent.mkdir(parents=True, exist_ok=True)
311 path.write_bytes(body)
312 changed.append(path.relative_to(root).as_posix())
313 from livery.workshop._ci_generate import retired_files
314
315 for path in retired_files(root):
316 path.unlink()
317 changed.append(f"{path.relative_to(root).as_posix()} (retired)")
318 return changed
319
320
321def drift_check(files: frozenset[str] | None = None) -> None:
322 """Fail when a composed or generated file drifts from what writes it.
323
324 The gate's drift check, `fm drift.check`. `fm sync` writes both
325 kinds of file, so it is the recovery for every line this names.
326 *files* keeps the findings to those root-relative files: the tree
327 a change is measured from was judged already, so only a file the
328 change touched can have drifted since, unless an input of every
329 file changed, and then the caller passes None.
330 """
331 from livery.workshop._shipped_files import shipped_drift
332
333 root = _root()
334 drift = shipped_drift(root) + project_drift(root)
335 if files is not None:
336 drift = [line for line in drift if line.split(":", 1)[0] in files]
337 if not drift:
338 return
339 fail(
340 "committed files drift from what writes them:\n "
341 + "\n ".join(drift)
342 + f"\n run `{footman.prog()} sync`, which writes them again"
343 )
344
345
346#: The package's name, which every template's verb takes first. Module
347#: level, where footman reads a task's annotations.
348_Name = Annotated[str, doc("directory name under packages/ (e.g. scratch)")]
349
350#: Each verb the generator made, to what it was made from: the template
351#: and the options its verb offers.
352_MADE: weakref.WeakKeyDictionary[
353 Callable[..., None], tuple[DeclaredTemplate, tuple[TemplateOption, ...]]
354] = weakref.WeakKeyDictionary()
355
356
357def generate_template_verbs(
358 templates: Mapping[str, DeclaredTemplate], into: Group | None = None
359) -> None:
360 """Make a verb per template, ``fm new.package.<template>``, from *templates*.
361
362 *templates* are the installed ones by name: the base's, and those
363 of each extension of the installed set an installed distribution
364 declares, as the mount read them. Each verb takes the package's
365 name, then each option the template's chain offers as a keyword
366 option (`livery.workshop._seeds.verb_options`): choices as a
367 `Literal`, the doc as its help line, the default as its default,
368 and an option without a default required. Nothing else is read, so
369 the command line, its help and its completion follow from the
370 declarations alone.
371
372 Run again after the installed set changed, it makes the verb of a
373 new template, remakes a verb whose template or options changed, and
374 removes the verb of a template that is gone. A task at a template's
375 address that the generator did not make is left alone.
376 """
377 from livery.footman import root_group
378 from livery.workshop._seeds import verb_options
379
380 parent = _package_group(into if into is not None else root_group)
381 for key, task in list(parent.tasks.items()):
382 if _made(task) is not None and key not in templates:
383 del parent.tasks[key]
384 for name, template in templates.items():
385 options = verb_options(name, templates)
386 existing = parent.tasks.get(name)
387 if existing is not None:
388 made = _made(existing)
389 if made is None or made == (template, options):
390 continue
391 del parent.tasks[name]
392 parent.task(name=name)(_template_verb(template, options))
393
394
395def _package_group(target: Group) -> Group:
396 """The ``new.package`` group under *target*, made when it is missing."""
397 held = target.groups.get("new")
398 if held is None:
399 held = target.group("new", help=NEW_HELP)
400 found = held.groups.get("package")
401 if found is None:
402 found = held.group("package", help=PACKAGE_HELP)
403 return found
404
405
406def _made(
407 task: Callable[..., object],
408) -> tuple[DeclaredTemplate, tuple[TemplateOption, ...]] | None:
409 """What the generator made *task* from; None for a task it did not make."""
410 return _MADE.get(inspect.unwrap(task))
411
412
413def _template_verb(
414 template: DeclaredTemplate, options: Sequence[TemplateOption]
415) -> Callable[..., None]:
416 """The verb that creates a package from *template*, offering *options*."""
417 born = template.name
418
419 def verb(name: str, **answers: object) -> None:
420 _create(born, name, answers)
421
422 parameters = [
423 inspect.Parameter(
424 "name", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=_Name
425 ),
426 *(_parameter(option) for option in options),
427 ]
428 # footman reads a verb's parameters through inspect.signature, which
429 # answers with __signature__ when a function carries one: the options
430 # are data, so the signature is built here.
431 vars(verb)["__signature__"] = inspect.Signature(parameters, return_annotation=None)
432 verb.__doc__ = _verb_doc(template)
433 _MADE[verb] = (template, tuple(options))
434 return verb
435
436
437def _parameter(option: TemplateOption) -> inspect.Parameter:
438 """*option* as a keyword option of its template's verb."""
439 from livery.workshop._declaration import OPTION_TYPES
440
441 answer: Any = OPTION_TYPES[option.type]
442 if option.choices:
443 # The choices are data, so the Literal is built at run time.
444 answer = cast("Any", Literal)[option.choices]
445 return inspect.Parameter(
446 option.variable,
447 inspect.Parameter.KEYWORD_ONLY,
448 default=inspect.Parameter.empty if option.default is None else option.default,
449 annotation=cast("Any", Annotated)[answer, doc(option.doc)],
450 )
451
452
453def _verb_doc(template: DeclaredTemplate) -> str:
454 """The help of *template*'s verb: its doc first, then what a creation does.
455
456 The first line is the summary listings show, so it stays one line;
457 the paragraphs after it are wrapped as a docstring is, since footman
458 prints a verb's help as written.
459 """
460 import textwrap
461
462 extends = (
463 f", after the files of {template.extends} and each template it extends"
464 if template.extends
465 else ""
466 )
467 paragraphs = (
468 "Writes the package-base seeds, then the files of the template"
469 f" {template.name}{extends}, into packages/<name>, with the"
470 " distribution named <namespace>-<name> and the contract listing"
471 " the template's extensions. Each option's answer is checked"
472 " before anything is written, and renders the files; nothing"
473 " stores it.",
474 "A creation installs nothing: a template that needs an extension"
475 " the workspace's lists do not hold, or that no installed"
476 " distribution declares yet, refuses before anything is written,"
477 " naming each. Then the runner the workspace's environment holds"
478 " wires the member, run as `new.wire <name>`: it writes the"
479 " project files again, and locks and syncs the environment and"
480 " the tools.",
481 )
482 wrapped = (
483 textwrap.fill(paragraph, 72, break_on_hyphens=False) for paragraph in paragraphs
484 )
485 return "\n\n".join((f"Create {template.doc}.", *wrapped))
486
487
488def _create(template: str, name: str, answers: Mapping[str, object]) -> None:
489 """Create ``packages/<name>`` from *template* with *answers*, then wire it.
490
491 The body of every template's verb: the render (`render_member`),
492 then the wiring in the runner the workspace's environment holds, a
493 fresh process whose mount holds the member's extensions.
494 """
495 root = _root()
496 render_member(root, name, template, answers)
497 prog = footman.prog()
498 runner = runner_script(root / ".venv")
499 if not runner.is_file():
500 fail(
501 f"{runner} is missing: {root}'s environment has no {prog} to wire"
502 f" packages/{name} with. `uv sync` in {root} installs it; then run"
503 f" `{prog} new.wire {name}` there"
504 )
505 print(f" packages/{name}: seeded; the wiring continues with {runner}")
506 footman.run([str(runner), "new.wire", name], cwd=root, capture=False)
507
508
509def _check_member_name(name: str) -> None:
510 """Refuse a package name ``packages/<name>`` cannot hold."""
511 if not re.fullmatch(r"([a-z][a-z0-9-]*/)?[a-z][a-z0-9-]*", name):
512 fail(
513 f"package name {name!r}: use lowercase letters, digits, hyphens,"
514 " and at most one group directory (extensions/widgets)"
515 )
516
517
518def render_member(
519 root: Path,
520 name: str,
521 template: str,
522 answers: Mapping[str, object] | None = None,
523) -> str:
524 """Write a member born from *template* into ``packages/<name>``; the import path.
525
526 The one function behind every creation: each template's verb, ``fm
527 ci.scale``, and ``fm new.project --extension`` call it. Writes the
528 ``package-base`` seeds and the files of the template's chain
529 (`livery.workshop._seeds.create_package`), rendered with *answers*,
530 each answer to one of the chain's options by its variable, and the
531 files the records compose for the member. The member's own contract
532 is one of the template's files, and discovery finds the member
533 through it, so the roster needs no write. The project files, the
534 lock and the install are the caller's: `wire_member` runs them for
535 one member, and a caller adding many members runs them once after
536 the last. Refuses an existing directory, naming it, a template the
537 birth cannot take, and an answer the template's options refuse,
538 before anything is written.
539 """
540 _check_member_name(name)
541 destination = root / "packages" / name
542 if destination.exists():
543 fail(f"{destination} already exists")
544 group = destination.parent
545 if group.name != "packages" and (group / "workshop.toml").is_file():545 ↛ 546line 545 didn't jump to line 546 because the condition on line 545 was never true
546 fail(f"{group} is a package: a group directory has no workshop.toml")
547 facts = identity(root)
548 namespace = str(facts.get("namespace_package", ""))
549 prefix = namespace.replace(".", "-")
550 flat = name.replace("/", "-")
551 package_name = f"{prefix}-{flat}" if prefix else flat
552 data: dict[str, Any] = {
553 **facts,
554 # The forge facts ride the contract: a package's changelog
555 # links its own pull requests on the workspace's forge.
556 **package_injections(root),
557 "package_dir": name,
558 "package_name": package_name,
559 "package_description": default_description(
560 package_name, str(facts.get("project_name", ""))
561 ),
562 }
563 from livery.workshop._seeds import create_package, derived
564
565 data.update(derived(data))
566 create_package(root, destination, template, data, answers)
567 from livery.workshop._shipped_files import deliver
568
569 deliver(root)
570 return str(data["import_path"])