1"""Write the files a birth starts with, which are the workspace's own afterwards.
3A workspace's birth writes the seed tree ``project``. A package's birth
4writes the seed tree ``package-base``, then the files of the template
5the package is born from. A seed is a file an extension ships under
6``content/seeds/<tree>/``, and every extension of the workspace's stack
7adds the seeds it ships for the tree: the base's ``package-base`` holds
8the docs page and its nav, and a listed extension such as the
9changelog's adds its own.
11A template is declared under ``[templates.<name>]`` by an installed
12extension's ``extension.toml``, or by the base's ``contract.toml``: its
13``doc``, the ``extensions`` a package born from it lists, and
14``extends``, the template whose files the birth writes first. Its files
15live under ``content/templates/<name>/`` beside the file that declares
16it.
18A template declares creation options under
19``[templates.<name>.options.<option>]``: a ``doc``, either ``choices`` or
20a ``type``, and a ``default``; one without a default is required. A
21template that extends another takes the other's options too, and its
22``fixes`` table gives an answer to an option of a template it extends,
23which a birth from it then takes no answer for. ``fm
24new.package.<template> <name> --<option>=<answer>`` answers them
25(`livery.workshop._templates.generate_template_verbs` makes the
26verb), and every answer is checked before anything is written
27(`answered`). Each answer renders the
28files as a template variable, the option's name with its hyphens as
29underscores (``--package-type`` is ``package_type``). Nothing stores the
30answers: a later step that needs one reads the file the answer wrote.
32A workspace offers the base's templates and those of the extensions
33its installed set holds. A birth needs every extension the template's
34chain names in the installed set and installed, and it refuses
35otherwise, naming what to list or that ``fm sync`` installs it: a
36creation installs nothing. Each template of the chain lists only
37extensions that compose something in a package, as a package's list
38does, or the birth refuses naming the entry. A template is read at a
39birth alone: nothing records which one a package came from.
41`create` writes a ``.jinja`` file rendered with minijinja, its suffix
42dropped, and any other file byte for byte; path names render too
43(``src/{{ source_path }}/...``). A ``.jinja`` file that renders to
44whitespace alone is not written, so a file depends on an answer by
45wrapping its whole body in ``{% if <variable> %}`` and ``{% endif %}``.
46A file that exists is never touched, and nothing is receipted: once
47written, a file belongs to the workspace, and no step judges it.
49For one path, a template's file wins over the seeds and over the files
50of the template it extends. Two extensions seeding one path of a tree
51follow the shipped files' rule instead: the one later in composition
52order, which requires the other, declares the other's under
53``[replaces]`` or ``[deletes]`` in its ``extension.toml``, or the birth
54refuses naming both. The fragment
55engine keeps the composed files current; this module writes these once.
56"""
58from __future__ import annotations
60import functools
61from collections.abc import Mapping, Sequence
62from pathlib import Path
63from typing import TYPE_CHECKING, Any, cast
65from livery.footman import Failed, fail, prog
66from livery.workshop._extensions import extension_content, stack_names
67from livery.workshop._fragment_engine import Fragment
69if TYPE_CHECKING:
70 from livery.workshop._declaration import Answer, DeclaredTemplate, TemplateOption
72SEEDS = "seeds"
73"""The `content/` subdirectory an extension's seeds live under."""
75TEMPLATES = "templates"
76"""The `content/` subdirectory a template's files live under, by its name."""
78TEMPLATE = ".jinja"
79"""The suffix of a file rendered with minijinja; any other is copied."""
81PROJECT = "project"
82"""The tree a workspace's birth writes."""
84PACKAGE_BASE = "package-base"
85"""The tree every package's birth writes before its template's files.
87The base's own holds the docs page and its nav, and a listed extension
88may ship seeds of its own under the same tree.
89"""
91#: The base's project seeds, which `fm explain` names as seeds.
92PROJECT_SEEDS = ("docs/index.md", "README.md", "LICENSE")
95def derived(facts: Mapping[str, Any]) -> dict[str, str]:
96 """The names a package's seeds derive from its name and its namespace.
98 The distribution name decides the import path, as it does in this
99 repository: each hyphen after the namespace's own prefix is one
100 namespace level (`acme-tools-store` in `acme` imports as
101 `acme.tools.store`). The directory decides nothing, so a package
102 in a group directory (`extensions/widgets`, named
103 `acme-extensions-widgets`) imports as `acme.extensions.widgets`.
104 `project_slug` is the last level, `source_path` the directory
105 under `src/` and `tests/`, and `import_path` the dotted import.
106 """
107 namespace = str(facts.get("namespace_package", ""))
108 name = str(facts.get("package_name", ""))
109 prefix = namespace.replace(".", "-") + "-" if namespace else ""
110 levels = name.removeprefix(prefix).split("-")
111 if not namespace:
112 # A workspace without a namespace keeps one top-level module.
113 levels = ["_".join(levels)]
114 module = [*namespace.split("."), *levels] if namespace else levels
115 return {
116 "project_slug": levels[-1],
117 "source_path": "/".join(module),
118 "import_path": ".".join(module),
119 }
122def template_files(template: DeclaredTemplate) -> Path:
123 """The directory *template*'s files live in, beside the file declaring it."""
124 return template.path.resolve().parent / "content" / TEMPLATES / template.name
127@functools.cache
128def base_templates() -> dict[str, DeclaredTemplate]:
129 """The templates the base declares in its contract file, by name.
131 Read from the one parse of the file its other readers share.
133 Raises:
134 Failed: for a template off its shape, naming the file and the key.
135 """
136 from livery.workshop._contract_keys import BASE_FILE, base_contract
137 from livery.workshop._declaration import DeclarationError, template_specs_of
138 from livery.workshop._extensions import SELF
140 try:
141 return template_specs_of(base_contract(), BASE_FILE, extension=SELF)
142 except DeclarationError as error:
143 fail(str(error))
146def available_templates() -> dict[str, DeclaredTemplate]:
147 """Every template the base or an installed distribution declares, by name.
149 Read from the declaration files alone, without judging the rest of
150 an extension's file or importing anything, and whatever the
151 workspace lists: a birth from a template the workspace does not
152 offer names the extension that declares it. `installed_templates`
153 is the ones a workspace offers.
155 Raises:
156 Failed: for a template two extensions declare, naming both, and
157 for a template off its shape, naming the file and the key.
158 """
159 from livery.workshop._declaration import (
160 DeclarationError,
161 template_declarations,
162 )
163 from livery.workshop._extensions import (
164 extension_package,
165 installed_extensions,
166 )
168 found = list(base_templates().values())
169 try:
170 for extension in installed_extensions():
171 found += template_declarations(extension, extension_package(extension))
172 except DeclarationError as error:
173 fail(str(error))
174 by_name: dict[str, list[DeclaredTemplate]] = {}
175 for template in found:
176 by_name.setdefault(template.name, []).append(template)
177 for name, held in sorted(by_name.items()):
178 if len(held) > 1:
179 owners = sorted(template.extension for template in held)
180 named = (
181 f"both {owners[0]} and {owners[1]}"
182 if len(owners) == 2
183 else f"{', '.join(owners[:-1])} and {owners[-1]}"
184 )
185 fail(
186 f"the template {name} is declared by {named}; one extension"
187 " declares a template, so one of them renames it"
188 )
189 return {name: held[0] for name, held in sorted(by_name.items())}
192def installed_templates(start: Path | None = None) -> dict[str, DeclaredTemplate]:
193 """The templates the workspace at or above *start* offers, by name.
195 The base's, and those of each extension the workspace's installed
196 set holds that an installed distribution declares. Outside a
197 workspace, the base's alone. Each has a verb,
198 ``fm new.package.<template>``, which the mount makes from the
199 declarations it reads, and a refusal naming the installed templates
200 names these.
202 Raises:
203 Failed: as `available_templates` does.
204 """
205 from livery.workshop._extensions import SELF, installed_set
207 held = {SELF, *installed_set(start)}
208 return {
209 name: template
210 for name, template in available_templates().items()
211 if template.extension in held
212 }
215def described(templates: Mapping[str, DeclaredTemplate]) -> str:
216 """Each of *templates* on a line of its own, its name then its doc."""
217 return "\n".join(
218 f" {name}: {template.doc}" for name, template in sorted(templates.items())
219 )
222def template_chain(
223 name: str,
224 templates: Mapping[str, DeclaredTemplate] | None = None,
225 *,
226 offered: Mapping[str, DeclaredTemplate] | None = None,
227) -> tuple[DeclaredTemplate, ...]:
228 """The templates a birth from *name* writes, in order: the one extended first.
230 *name* is last, after the template it extends and that template's
231 own chain. The chain is read from *templates*, every available one
232 when None, and a refusal names *offered* as the installed
233 templates, *templates* when None.
235 Raises:
236 Failed: for a name no installed extension declares, an
237 ``extends`` that names one, and an ``extends`` that leads
238 back to a template of the chain; each refusal names the
239 installed templates or the cycle.
240 """
241 known = available_templates() if templates is None else templates
242 listed = known if offered is None else offered
243 if name not in known:
244 fail(
245 f"no installed template is named {name}; the installed templates"
246 f" are:\n{described(listed)}"
247 )
248 chain: list[DeclaredTemplate] = []
249 current = name
250 while current:
251 names = [template.name for template in chain]
252 if current in names:
253 loop = [*names[names.index(current) :], current]
254 fail(
255 f"the template {name} reaches an extends cycle:"
256 f" {' extends '.join(loop)}; each template extends one that does"
257 " not lead back to it"
258 )
259 template = known.get(current)
260 if template is None:
261 fail(
262 f"the template {chain[-1].name} extends {current}, which no"
263 " installed extension declares; the installed templates are:"
264 f"\n{described(listed)}"
265 )
266 chain.append(template)
267 current = template.extends
268 return tuple(reversed(chain))
271def chain_needs(chain: Sequence[DeclaredTemplate]) -> tuple[str, ...]:
272 """The extensions a birth from *chain* needs, first met first.
274 Each template's ``extensions``, then the extension that declares
275 it, the base aside, from the template extended first to the one
276 born: a workspace offers a template while its installed set holds
277 the extension that declares it, and the template it extends with
278 it.
279 """
280 from livery.workshop._extensions import SELF
282 found: dict[str, None] = {}
283 for template in chain:
284 found.update(dict.fromkeys(template.extensions))
285 if template.extension != SELF:
286 found[template.extension] = None
287 return tuple(found)
290def chain_options(
291 chain: Sequence[DeclaredTemplate],
292) -> tuple[dict[str, TemplateOption], dict[str, Answer]]:
293 """The options a birth from *chain* takes, and the answers its templates fix.
295 Each template of the chain, the one extended first, adds the options
296 it declares and fixes the answers its ``fixes`` names: a fixed option
297 is no longer one the birth takes.
299 Returns:
300 The options by name, in declaration order, and the fixed answers
301 by option name.
303 Raises:
304 Failed: for a template that fixes an option no template it
305 extends declares, a fixed answer that does not answer the
306 option, and an option a template of the chain declares again.
307 """
308 options: dict[str, TemplateOption] = {}
309 owners: dict[str, str] = {}
310 fixed: dict[str, Answer] = {}
311 for template in chain:
312 for name, answer in template.fixes:
313 option = options.pop(name, None)
314 if option is None:
315 fail(
316 f"the template {template.name} fixes {name}, which no template"
317 f" it extends declares as an option; it fixes only those"
318 )
319 if refusal := option.refusal(answer):
320 fail(
321 f"the template {template.name} fixes an answer the option"
322 f" refuses: {refusal}"
323 )
324 fixed[name] = answer
325 for option in template.options:
326 owner = owners.get(option.name)
327 if owner is not None:
328 fail(
329 f"the template {template.name} declares the option"
330 f" {option.name}, which {owner} declares; a template takes"
331 " the options of the one it extends, and fixes an answer"
332 " with fixes"
333 )
334 options[option.name] = option
335 owners[option.name] = template.name
336 return options, fixed
339def described_options(options: Mapping[str, TemplateOption]) -> str:
340 """Each of *options* as ``--<option>``, for a refusal; ``none`` for none."""
341 return ", ".join(f"--{name}" for name in options) or "none"
344def answered(
345 chain: Sequence[DeclaredTemplate], answers: Mapping[str, object]
346) -> dict[str, Answer]:
347 """The template variables a birth from *chain* renders with, each answer checked.
349 *answers* holds an answer by each option's variable (`package_type`
350 for ``--package-type``), as the template's verb passes them. An option
351 without an answer takes its default, and a fixed option the answer
352 its template fixes.
354 Raises:
355 Failed: for an answer to an option the born template does not
356 take, a required option without an answer, and an answer
357 outside an option's choices or of the wrong type; each
358 refusal names the option and what it takes.
359 """
360 options, fixed = chain_options(chain)
361 born = chain[-1].name
362 by_variable = {option.variable: option for option in options.values()}
363 for key in answers:
364 if key not in by_variable:
365 fail(
366 f"the template {born} takes no option --{key.replace('_', '-')};"
367 f" it takes: {described_options(options)}"
368 )
369 variables: dict[str, Answer] = {}
370 for option in options.values():
371 if option.variable not in answers:
372 if option.default is None:
373 takes = (
374 f"one of {', '.join(option.choices)}"
375 if option.choices
376 else f"a {option.type}"
377 )
378 fail(
379 f"the template {born} needs --{option.name}, {option.doc}:"
380 f" give `--{option.name}=<answer>`, {takes}"
381 )
382 variables[option.variable] = option.default
383 continue
384 answer = answers[option.variable]
385 if refusal := option.refusal(answer):
386 fail(f"the template {born} takes no such answer: {refusal}")
387 variables[option.variable] = cast("Answer", answer)
388 for name, answer in fixed.items():
389 variables[name.replace("-", "_")] = answer
390 return variables
393def verb_options(
394 name: str, templates: Mapping[str, DeclaredTemplate]
395) -> tuple[TemplateOption, ...]:
396 """The options the verb of the template *name* offers, read from *templates*.
398 The options of its chain less the answers the chain fixes, as a
399 birth takes them (`chain_options`). A chain that *templates* do not
400 resolve, or whose options disagree, offers the options *name*
401 declares itself: its verb exists all the same, and running it
402 refuses as a birth from it refuses.
403 """
404 try:
405 return tuple(chain_options(template_chain(name, templates))[0].values())
406 except Failed:
407 return templates[name].options
410def resolved_chain(root: Path, name: str) -> tuple[DeclaredTemplate, ...]:
411 """The chain of *name* in the workspace at *root*, from the installed declarations.
413 Refuses as `birth_chain` does for a template no installed extension
414 declares, and for a chain that does not resolve; the extensions the
415 chain needs are `birth_chain`'s to judge.
417 A template that extends one no installed extension declares, while
418 the part of its chain that resolves needs an extension the
419 workspace's lists do not hold, refuses naming that extension: listed
420 and synced, its distribution may declare the template extended, as
421 python's declares the ``python-library`` the base's
422 ``workshop-extension`` extends.
424 Raises:
425 Failed: for a template, or a template it extends, that no
426 installed extension declares, naming ``fm sync`` while the
427 installed set holds an extension no installed distribution
428 declares yet, each extension the resolved part of the chain
429 needs that the lists do not hold, and the installed templates
430 otherwise, and for an ``extends`` cycle.
431 """
432 from livery.workshop._extensions import installed_extensions, installed_set
434 available = available_templates()
435 unknown = _first_unknown(name, available)
436 held = installed_set(root)
437 present = set(installed_extensions())
438 waiting = [extension for extension in held if extension not in present]
439 if unknown and waiting:
440 what = (
441 f"no installed extension declares the template {name}"
442 if unknown == name
443 else f"the template {name} extends {unknown}, which no installed"
444 " extension declares"
445 )
446 fail(
447 f"{what}, and the workspace's lists hold {_with_distributions(waiting)},"
448 f" which no installed distribution declares yet: {_sync(waiting)}"
449 )
450 if unknown and unknown != name:
451 outside = [
452 extension
453 for extension in chain_needs(_resolved_part(name, available))
454 if extension not in held
455 ]
456 if outside:
457 them = "it" if len(outside) == 1 else "them"
458 fail(
459 f"the template {name} extends {unknown}, which no installed"
460 f" extension declares, and needs {_with_distributions(outside)},"
461 f" which the workspace's lists do not hold: list {them} in"
462 f" [workspace] extensions and run `{prog()} sync`, then create"
463 " the package again"
464 )
465 return template_chain(name, available, offered=installed_templates(root))
468def birth_chain(root: Path, name: str) -> tuple[DeclaredTemplate, ...]:
469 """The chain a birth from *name* writes in the workspace at *root*, once judged.
471 A birth needs every extension the chain names (`chain_needs`) in
472 the workspace's installed set, and each of them, with what it
473 requires, installed: a creation installs nothing, so a refusal
474 says what to list, and that ``fm sync`` installs it. This writes
475 nothing.
477 Raises:
478 Failed: in this order: for a template, or a template it
479 extends, that no installed extension declares while the
480 installed set holds an extension no installed distribution
481 declares yet, naming each and ``fm sync``; for a template
482 that extends one no installed extension declares while the
483 resolved part of its chain needs an extension the lists do
484 not hold, naming each with its distribution; for a template
485 no installed extension declares, naming the installed
486 templates; for a chain that does not resolve; for an
487 extension the chain needs that the installed set does not
488 hold, naming each with its distribution, ``[workspace]
489 extensions`` and ``fm sync``; and for one it holds that no
490 installed distribution declares yet, naming each and ``fm
491 sync``.
492 """
493 from livery.workshop._composition import closure
494 from livery.workshop._extensions import (
495 installed_declaration,
496 installed_extensions,
497 installed_set,
498 )
500 chain = resolved_chain(root, name)
501 held = installed_set(root)
502 present = set(installed_extensions())
503 needs = chain_needs(chain)
504 outside = [extension for extension in needs if extension not in held]
505 if outside:
506 them = "it" if len(outside) == 1 else "them"
507 fail(
508 f"the template {name} needs {_with_distributions(outside)}, which the"
509 f" workspace's lists do not hold: list {them} in [workspace] extensions"
510 f" and run `{prog()} sync`, then create the package again"
511 )
512 missing = [
513 extension
514 for extension in closure(needs, installed_declaration)
515 if extension not in present
516 ]
517 if missing:
518 fail(
519 f"the template {name} needs {_with_distributions(missing)}, which no"
520 f" installed distribution declares yet: {_sync(missing)}"
521 )
522 return chain
525def _resolved_part(
526 name: str, known: Mapping[str, DeclaredTemplate]
527) -> tuple[DeclaredTemplate, ...]:
528 """The templates of *name*'s chain that *known* holds, up to the first it lacks.
530 From *name* down the ``extends`` it names, in that order; a template
531 met twice ends the walk.
532 """
533 found: list[DeclaredTemplate] = []
534 current = name
535 while current and current not in {template.name for template in found}:535 ↛ 541line 535 didn't jump to line 541 because the condition on line 535 was always true
536 template = known.get(current)
537 if template is None:
538 break
539 found.append(template)
540 current = template.extends
541 return tuple(found)
544def _first_unknown(name: str, known: Mapping[str, DeclaredTemplate]) -> str:
545 """The first template of *name*'s chain that *known* lacks; empty for none.
547 A chain that leads back to a template of it ends the walk, and
548 `template_chain` names the cycle.
549 """
550 seen: set[str] = set()
551 current = name
552 while current and current not in seen:
553 seen.add(current)
554 template = known.get(current)
555 if template is None:
556 return current
557 current = template.extends
558 return ""
561def _with_distributions(extensions: Sequence[str]) -> str:
562 """*extensions*, each with its distribution, as a sentence lists them."""
563 from livery.workshop._extensions import (
564 _spoken, # pyright: ignore[reportPrivateUsage]
565 distribution_of,
566 )
568 return _spoken([f"{name} ({distribution_of(name)})" for name in extensions])
571def _sync(extensions: Sequence[str]) -> str:
572 """The end of a refusal while *extensions* are held and not installed yet."""
573 them = "it" if len(extensions) == 1 else "them"
574 return f"run `{prog()} sync`, which installs {them}, then create the package again"
577def _judged(chain: Sequence[DeclaredTemplate]) -> tuple[str, ...]:
578 """The canonical list of the born template, the last of *chain*, once judged.
580 Each template of the chain lists only extensions that compose
581 something in a package, itself or through what it requires: a
582 package's list refuses any other, so a birth from such a template
583 refuses instead of writing a list the gate refuses. An entry
584 another entry requires is left out of the list, and not judged.
586 Raises:
587 Failed: for a template of the chain whose directory of files is
588 missing, for a list whose requirements order no start, and
589 for a template of the chain listing an extension that
590 composes nothing in a package, naming what it does instead.
591 """
592 from livery.workshop._composition import OrderCycle, canonical, closure, implied
593 from livery.workshop._declaration import DeclarationError
594 from livery.workshop._extensions import installed_declaration, why_inert
596 for template in chain:
597 files = template_files(template)
598 if not files.is_dir():
599 fail(
600 f"the template {template.name} has no files: {files} is missing"
601 f" beside {template.path.name}, which declares it"
602 )
603 born = chain[-1]
604 try:
605 listed = canonical(born.extensions, installed_declaration)
606 except (DeclarationError, OrderCycle) as error:
607 fail(f"the template {born.name}: {error}")
608 # The birth's judges read every declaration the chain names already.
609 for template in chain:
610 members = closure(template.extensions, installed_declaration)
611 required = implied(members, installed_declaration)
612 for name in dict.fromkeys(template.extensions):
613 why = "" if name in required else why_inert(name)
614 if why:
615 fail(
616 f"the template {template.name} lists {name}, which composes"
617 f" nothing in a package: {why}; a package's list refuses it,"
618 f" so {template.extension}, which declares the template, drops"
619 " it from the template's extensions"
620 )
621 return listed
624def _shipped(order: Sequence[str], tree: str) -> list[Fragment]:
625 """Each listed extension's seeds in *tree*, one fragment each."""
626 found: list[Fragment] = []
627 for extension in order:
628 content = extension_content(extension)
629 if content is None:
630 continue
631 found += _fragments(extension, content / SEEDS / tree, f"{SEEDS}/{tree}")
632 return found
635def _fragments(owner: str, base: Path, named: str) -> list[Fragment]:
636 """Each file under *base*, a fragment of *owner* named under *named*."""
637 if not base.is_dir():
638 return []
639 found: list[Fragment] = []
640 for source in sorted(base.rglob("*")):
641 if not source.is_file() or "__pycache__" in source.parts:
642 continue
643 relative = source.relative_to(base).as_posix().removesuffix(TEMPLATE)
644 found.append(Fragment(owner, f"{named}/{relative}", relative, source=source))
645 return found
648def plan(
649 root: Path,
650 tree: str,
651 data: Mapping[str, Any],
652 *,
653 templates: Sequence[DeclaredTemplate] = (),
654) -> dict[str, Fragment]:
655 """Each file's path, rendered, to the fragment that writes it.
657 The seeds of *tree* that the stack ships come first, then each of
658 *templates* in order; a template's file takes a path from the seeds
659 and from the templates before it.
661 Raises:
662 Failed: for two extensions seeding one path with no declaration
663 between them, a declaration naming a seed no listed extension
664 ships, and one naming a seed of an extension the declaring
665 one does not require.
666 """
667 from livery.workshop._fragment_engine import (
668 _render, # pyright: ignore[reportPrivateUsage]
669 _resolve, # pyright: ignore[reportPrivateUsage]
670 )
671 from livery.workshop._shipped_files import declared
673 def rendered(fragment: Fragment) -> str:
674 return _render(
675 Fragment(fragment.owner, f"{fragment.name} (path)", "", fragment.target),
676 data,
677 )
679 order = list(stack_names(root))
680 rank = {name: index for index, name in enumerate(order)}
681 chosen: dict[str, Fragment] = {}
682 seeds = _shipped(order, tree)
683 for fragment in _resolve(declared(seeds, order, seeds=True), order):
684 path = rendered(fragment)
685 held = chosen.get(path)
686 if held is not None and held.owner != fragment.owner:686 ↛ 687line 686 didn't jump to line 687 because the condition on line 686 was never true
687 low, high = sorted((held, fragment), key=lambda f: rank[f.owner])
688 fail(
689 f"{path} is seeded by both {low.ref} and {high.ref}: {high.owner}"
690 f' declares [replaces] "{low.ref}" = "<reason>" in its'
691 " extension.toml to take it, or [deletes] to drop it"
692 )
693 chosen[path] = fragment
694 for template in templates:
695 named = f"{TEMPLATES}/{template.name}"
696 for fragment in _fragments(template.extension, template_files(template), named):
697 chosen[rendered(fragment)] = fragment
698 return chosen
701def create(
702 root: Path,
703 destination: Path,
704 tree: str,
705 data: Mapping[str, Any],
706 *,
707 templates: Sequence[DeclaredTemplate] = (),
708) -> list[str]:
709 """Write the seeds of *tree*, then *templates*' files, into *destination*.
711 Args:
712 root: The workspace whose stack ships the seeds.
713 destination: Where the files land: the root for a project, the
714 member's directory for a package.
715 tree: The seed tree, ``project`` or ``package-base``.
716 data: What the files read when they render.
717 templates: The templates whose files come after the seeds, in
718 order: a later one wins for a path.
720 Returns:
721 The paths written, relative to *destination*. A path that
722 already exists is left alone and is not listed, and so is a
723 ``.jinja`` file that renders to whitespace alone.
724 """
725 from livery.workshop._fragment_engine import (
726 _render, # pyright: ignore[reportPrivateUsage]
727 )
729 written: list[str] = []
730 for path, fragment in sorted(plan(root, tree, data, templates=templates).items()):
731 target = destination / path
732 if target.exists():
733 continue
734 source = fragment.source
735 if source is not None and not source.name.endswith(TEMPLATE):
736 body = source.read_bytes()
737 else:
738 text = _render(fragment, data)
739 if not text.strip():
740 continue # the file depends on an answer that rendered it away
741 body = text.encode("utf-8")
742 target.parent.mkdir(parents=True, exist_ok=True)
743 target.write_bytes(body)
744 written.append(path)
745 return written
748def create_package(
749 root: Path,
750 destination: Path,
751 template: str,
752 data: Mapping[str, Any],
753 answers: Mapping[str, object] | None = None,
754) -> list[str]:
755 """Write a package born from *template* into *destination*; the paths written.
757 The ``package-base`` seeds come first, then the files of each
758 template of the chain, the one extended first and *template* last
759 (`template_chain`). The files read the born template's
760 ``extensions``, in their canonical form, as ``package_extensions``,
761 spelled as a contract spells the list: the contract writes it. They
762 read the answers to the chain's options as variables, *answers*
763 holding each by its variable (`answered`). Nothing is written until
764 every template of the chain and every answer is judged, and nothing
765 is installed: the workspace at *root* holds and has installed every
766 extension the chain needs (`birth_chain`).
768 Raises:
769 Failed: for a template the workspace cannot take
770 (`birth_chain`), a template whose files are missing, a born
771 template whose list's requirements order no start, a
772 template of the chain listing an extension that composes
773 nothing in a package, an answer the chain's options refuse
774 (`answered`), and an option whose variable *data* holds
775 already; each refusal names what to change.
776 """
777 from livery.workshop._contract import spelled_list
779 chain = birth_chain(root, template)
780 listed = _judged(chain)
781 variables = answered(chain, answers or {})
782 for variable in variables:
783 if variable in data or variable == "package_extensions":
784 fail(
785 f"the template {template} has an option whose variable is"
786 f" {variable}, which every birth sets already; the extension"
787 " that declares it renames the option"
788 )
789 full = {**data, **variables, "package_extensions": spelled_list(listed)}
790 return create(root, destination, PACKAGE_BASE, full, templates=chain)