Coverage for packages/workshop/src/livery/workshop/_variables.py: 100%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""Set the environment variables the workspace's extensions declare.
2
3An extension declares each environment variable it needs in an
4``[env.<NAME>]`` table of its ``extension.toml``: the ``value``,
5``always`` when that value beats one the environment already carries,
6and ``doc``, what the variable is for. The value takes the placeholder
7grammar of a step in words, ``{name}`` with lower-case words joined by
8dashes, and answers one placeholder, ``{place}``: a directory of the
9variable's own. Every other brace form refuses when the declaration is
10read, so a placeholder added later changes the meaning of no declared
11value.
12
13Each place that sets the variables reads the declarations of the
14extensions of the workspace's installed set, and names the directory
15``{place}`` stands for:
16
17- every ``fm`` run, through the cascade's hook: on a CI job, the job's
18 own directory (`job_place`), where the job's environment carries
19 none yet; on a desk, none;
20- the entry script, ``setup.sh``, for the steps before ``fm``: the same
21 directory on a CI job, and none off one;
22- ``fm env.emit --github``, which persists the variables for a job's
23 later steps: the runner's temporary directory;
24- a pass of the loop: the directory of the development environment it
25 runs on;
26- the scale fixture: the fixture's directory.
27
28A value naming ``{place}`` is not set where nothing names a directory.
29A variable the environment already carries keeps its value, as the
30cascade's variables do, with one exception. Where an environment is
31formed for what runs inside it, a declaration's ``always`` makes its
32value beat the one the environment carries: a CI job's, in the entry
33script and ``fm env.emit --github``, where the value to beat is one the
34runner sets for every job it takes; and a loop pass's or the scale
35fixture's, for the processes they start. Everywhere else, every ``fm``
36run among them, the environment wins, so a job's later runs keep the
37value its entry placed and a nested run keeps the one its parent set.
38"""
39
40from __future__ import annotations
41
42import re
43from pathlib import Path
44from typing import TYPE_CHECKING
45
46from livery.footman import fail
47
48if TYPE_CHECKING:
49 from collections.abc import Iterable, Mapping
50
51 from livery.workshop._declaration import DeclaredVariable
52
53#: The one placeholder an ``[env]`` value answers: a directory of the
54#: variable's own.
55PLACE_WORD = "{place}"
56
57#: A name a shell exports: letters, digits and underscores, not starting
58#: with a digit.
59NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
60
61#: Any brace form in a value: a placeholder of any spelling, an opening
62#: brace with no close, or a closing brace alone.
63_BRACES = re.compile(r"\{[^{}]*\}?|\}")
64
65#: Where a CI job keeps its own directory, by the entry's mode: the
66#: variable the runner names it in, and the directory under it that
67#: ``{place}`` stands for, empty for the directory itself. A GitHub or
68#: Gitea job's is its temporary directory. A GitLab job's is
69#: ``.workshop`` under its checkout: GitLab clones each of the jobs
70#: running at once into a path of its own, and git ignores ``.workshop/``.
71JOB_DIRECTORIES: dict[str, tuple[str, str]] = {
72 "github": ("RUNNER_TEMP", ""),
73 "gitlab": ("CI_PROJECT_DIR", ".workshop"),
74}
75
76#: The variable each CI kind sets on its jobs, by the entry's mode.
77_JOB_MARKERS = {"github": "GITHUB_ACTIONS", "gitlab": "GITLAB_CI"}
78
79
80def unanswered(value: str) -> tuple[str, ...]:
81 """Each brace form in *value* other than ``{place}``, in order, once each."""
82 return tuple(
83 dict.fromkeys(form for form in _BRACES.findall(value) if form != PLACE_WORD)
84 )
85
86
87def declared_variables(extensions: Iterable[str]) -> tuple[DeclaredVariable, ...]:
88 """The variables the installed declarations of *extensions* declare, in their order.
89
90 An extension no installed distribution declares declares none.
91
92 Raises:
93 Failed: when two of the extensions declare one variable, naming
94 both, since the two values would race for it.
95 """
96 from livery.workshop._extensions import installed_declaration
97
98 found: dict[str, DeclaredVariable] = {}
99 for extension in extensions:
100 declared = installed_declaration(extension)
101 if declared is None:
102 continue
103 for variable in declared.env:
104 held = found.get(variable.name)
105 if held is not None:
106 fail(
107 f"{held.extension} and {variable.extension} both declare the"
108 f" environment variable {variable.name}; one extension"
109 " declares a variable"
110 )
111 found[variable.name] = variable
112 return tuple(found.values())
113
114
115def workspace_variables(root: Path) -> tuple[DeclaredVariable, ...]:
116 """The variables the extensions of *root*'s installed set declare.
117
118 Raises:
119 Failed: when two of them declare one variable, naming both.
120 """
121 from livery.workshop._extensions import installed_set
122
123 return declared_variables(installed_set(root))
124
125
126def placed(
127 variables: Iterable[DeclaredVariable],
128 place: str | None,
129 environ: Mapping[str, str],
130 *,
131 forming: bool = False,
132) -> dict[str, str]:
133 """The value each of *variables* takes against *environ*, by name.
134
135 A value naming ``{place}`` takes *place* there, and is left out
136 when *place* is None. A variable *environ* already carries keeps
137 that value. *forming* says the caller forms an environment for what
138 runs inside it, a CI job's, a loop pass's or the scale fixture's:
139 there an ``always`` variable takes the declared value whatever
140 *environ* carries. An empty value counts as none, as in the cascade.
141 """
142 found: dict[str, str] = {}
143 for variable in variables:
144 if variable.placed and place is None:
145 continue
146 held = environ.get(variable.name, "")
147 if held and not (forming and variable.always):
148 found[variable.name] = held
149 else:
150 found[variable.name] = variable.render(place or "")
151 return found
152
153
154def job_place(environ: Mapping[str, str]) -> str | None:
155 """The directory a CI job's variables take for ``{place}``; None off a CI job.
156
157 A GitHub or Gitea job, which sets ``GITHUB_ACTIONS``, takes its
158 temporary directory, ``RUNNER_TEMP``. A GitLab job, which sets
159 ``GITLAB_CI``, takes ``.workshop`` under its checkout,
160 ``CI_PROJECT_DIR`` (`JOB_DIRECTORIES`). None as well when the runner
161 names no such directory, or one that does not exist: the entry
162 script refuses that job before any ``fm`` runs.
163 """
164 for mode, marker in _JOB_MARKERS.items():
165 if environ.get(marker):
166 variable, under = JOB_DIRECTORIES[mode]
167 directory = environ.get(variable, "")
168 if not directory or not Path(directory).is_dir():
169 return None
170 return f"{directory}/{under}" if under else directory
171 return None
172
173
174def declarers(variables: Iterable[DeclaredVariable]) -> str:
175 """Who declares *variables*, for a message: ``acme declares ACME_HOME``."""
176 return " and ".join(
177 f"{variable.extension} declares {variable.name}" for variable in variables
178 )