Coverage for packages/workshop/src/livery/workshop/_envfile.py: 91%

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_variables.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_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.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_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/cpp/tests/test_extensions_cpp.py ran.

1r"""The one dotenv implementation: parsing, substitution, the cascade.
2
3Every ``.repo.env`` in the wild is written against these rules:
4
5- **Precedence** (highest first, kind-major): the pre-existing
6 process environment, ``.repo.env.local`` files (nearest to
7 farthest), ``.repo.shared.env`` in the runner's config directory,
8 committed ``.repo.env`` files (nearest to farthest).
9- **Values**: ``~`` expands at the start of a raw value; double
10 quotes strip and allow substitution; single quotes strip and are
11 literal; an unquoted value loses inline ``#`` comments and
12 trailing whitespace.
13- **Substitution**: ``$VAR`` and ``${VAR}`` resolve from the stack
14 first, then the pre-existing environment, else empty; ``\$``
15 stays a literal dollar; iterated until stable.
16- **Provenance** is tracked per key (which extension supplied the
17 value); the display and the agent emission select on it.
18"""
19
20from __future__ import annotations
21
22import os
23import re
24from dataclasses import dataclass, field
25from enum import IntEnum
26from pathlib import Path
27
28#: Name suffixes whose values are masked in display output.
29SECRET_SUFFIXES = ("_TOKEN", "_SECRET", "_PASSWORD", "_KEY", "_API_KEY")
30
31#: The prefix under which the emitted entry step carries each declared
32#: key's non-secret CI variable; the emission strips it when it writes
33#: the shared slot.
34RUNG_PREFIX = "RUNG_"
35
36#: Matches a ``KEY=value`` assignment line in an env file.
37KEY_RE = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)")
38
39_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
40
41_LITERAL = "\x00literal\x00"
42_ESCAPED_DOLLAR = "\x00dollar\x00"
43
44
45class Source(IntEnum):
46 """Where a stack value came from (lower is higher precedence)."""
47
48 environment = 0
49 """The pre-existing process environment: always wins."""
50 local = 1
51 """``.repo.env.local`` (per machine, gitignored)."""
52 shared = 2
53 """``.repo.shared.env`` in the runner's config directory."""
54 repo = 3
55 """``.repo.env`` (committed repo config)."""
56
57
58def is_secret_name(key: str) -> bool:
59 """Whether *key* names a secret by the suffix convention."""
60 return any(key.endswith(suffix) for suffix in SECRET_SUFFIXES)
61
62
63def _expand_tilde(value: str) -> str:
64 if value.startswith("~"):64 ↛ 65line 64 didn't jump to line 65 because the condition on line 64 was never true
65 return os.path.expanduser("~") + value[1:]
66 return value
67
68
69def _parse_raw(raw: str) -> str:
70 """Quote and comment handling for one raw value."""
71 double = re.match(r'^"(.*)"\s*(#.*)?$', raw)
72 if double:
73 return double.group(1)
74 single = re.match(r"^'(.*)'\s*(#.*)?$", raw)
75 if single:
76 return _LITERAL + single.group(1)
77 value = raw.split("#", 1)[0]
78 return value.rstrip()
79
80
81def parse_env_file(path: Path) -> dict[str, str]:
82 """Parse an env file into ``key -> raw value`` pairs.
83
84 Comments and blank lines are skipped, surrounding quotes
85 stripped, ``${VAR}`` left raw. The membership-only readers use
86 this; full resolution goes through
87 ``livery.workshop._envfile.load_cascade``. A missing file
88 answers an empty dict.
89 """
90 result: dict[str, str] = {}
91 if not path.is_file():
92 return result
93 for raw in path.read_text(encoding="utf-8").splitlines():
94 line = raw.strip()
95 if not line or line.startswith("#"):
96 continue
97 match = KEY_RE.match(line)
98 if match:98 ↛ 93line 98 didn't jump to line 93 because the condition on line 98 was always true
99 key = match.group(1)
100 value = match.group(2).strip()
101 if (value.startswith('"') and value.endswith('"')) or (
102 value.startswith("'") and value.endswith("'")
103 ):
104 value = value[1:-1]
105 result[key] = value
106 return result
107
108
109@dataclass
110class EnvStack:
111 """The resolved env-file stack: values plus per-key provenance."""
112
113 values: dict[str, str] = field(default_factory=dict)
114 sources: dict[str, Source] = field(default_factory=dict)
115
116 def managed(self) -> dict[str, str]:
117 """The keys the files supplied (everything not pre-existing)."""
118 return {
119 key: value
120 for key, value in self.values.items()
121 if self.sources[key] is not Source.environment
122 }
123
124
125def _substitute(value: str, lookup: dict[str, str], environ: dict[str, str]) -> str:
126 """One substitution pass over *value* (``$VAR`` and ``${VAR}``)."""
127 out: list[str] = []
128 i = 0
129 while i < len(value):
130 ch = value[i]
131 if ch == "\\" and i + 1 < len(value) and value[i + 1] == "$":
132 out.append(_ESCAPED_DOLLAR)
133 i += 2
134 continue
135 if ch != "$":
136 out.append(ch)
137 i += 1
138 continue
139 rest = value[i + 1 :]
140 if rest.startswith("{"):140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true
141 match = _NAME_RE.match(rest, 1)
142 if match and rest[match.end() : match.end() + 1] == "}":
143 name = match.group(0)
144 out.append(lookup.get(name, environ.get(name, "")))
145 i += 2 + len(name) + 1
146 continue
147 out.append("${")
148 i += 2
149 continue
150 match = _NAME_RE.match(rest)
151 if match:151 ↛ 156line 151 didn't jump to line 156 because the condition on line 151 was always true
152 name = match.group(0)
153 out.append(lookup.get(name, environ.get(name, "")))
154 i += 1 + len(name)
155 continue
156 out.append("$")
157 i += 1
158 return "".join(out)
159
160
161def load_extension(
162 path: Path,
163 source: Source,
164 stack: EnvStack,
165 environ: dict[str, str],
166) -> None:
167 """Fold one file into *stack*; pre-existing environment wins."""
168 if not path.is_file():
169 return
170 for line in path.read_text(encoding="utf-8").splitlines():
171 stripped = line.strip()
172 if not stripped or stripped.startswith("#"):172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true
173 continue
174 match = KEY_RE.match(stripped)
175 if match is None:175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true
176 continue
177 key, raw = match.group(1), match.group(2)
178 env_value = environ.get(key, "")
179 if env_value:
180 stack.values[key] = _expand_tilde(env_value)
181 stack.sources[key] = Source.environment
182 continue
183 # Later loads override earlier ones; the caller feeds files
184 # from lowest precedence (repo) to highest (local).
185 stack.values[key] = _parse_raw(_expand_tilde(raw))
186 stack.sources[key] = source
187
188
189MAX_SUBSTITUTION_PASSES = 16
190"""How many times one value may be re-substituted before it is given up.
191
192Each pass resolves one level of reference, so a legitimate chain
193settles in a handful. Two keys referring to each other (``A=$B``
194beside ``B=$A``) never settle: the value alternates, so it never
195equals its own one-step predecessor and an unbounded loop runs
196forever. That loop is inside the cascade every ``fm`` command loads,
197so the bound is what keeps a mistyped pair from hanging the whole
198toolchain.
199"""
200
201
202def resolve_all(stack: EnvStack, environ: dict[str, str]) -> None:
203 """Substitute every value until stable; honour literals and escapes.
204
205 A value that has not settled within
206 ``livery.workshop._envfile.MAX_SUBSTITUTION_PASSES`` keeps
207 its raw text, unexpanded: showing ``$B`` is the answer a reader
208 can act on, and half an expansion would look like a resolved
209 value.
210 """
211 for key, value in list(stack.values.items()):
212 if value.startswith(_LITERAL):
213 stack.values[key] = value[len(_LITERAL) :]
214 continue
215 raw = value
216 previous = None
217 for _ in range(MAX_SUBSTITUTION_PASSES):
218 if value == previous:
219 break
220 previous = value
221 value = _substitute(value, stack.values, environ)
222 else:
223 value = raw.replace("\\$", "$")
224 stack.values[key] = value.replace(_ESCAPED_DOLLAR, "$")
225
226
227def cascade_dirs(repo_root: Path, cwd: Path) -> list[Path]:
228 """Directories from the repo ceiling down to *cwd*, farthest first.
229
230 Farthest first, so folding with later-wins gives the nearest
231 file precedence within its kind.
232 """
233 root = repo_root.resolve()
234 cur = cwd.resolve()
235 if root != cur and root not in cur.parents:
236 return [root]
237 dirs: list[Path] = []
238 while True:
239 dirs.append(cur)
240 if cur == root:
241 break
242 cur = cur.parent
243 dirs.reverse()
244 return dirs
245
246
247def load_cascade(
248 repo_root: Path,
249 cwd: Path,
250 *,
251 shared_dir: Path | None = None,
252 environ: dict[str, str] | None = None,
253) -> EnvStack:
254 """Load the multi-level env-file cascade, the one config mechanism.
255
256 ``.repo.env`` (committed) and ``.repo.env.local`` (machine,
257 secrets, gitignored) at every level from the repo ceiling down
258 to *cwd*. Precedence is kind-major: real environment, then
259 ``.local`` files nearest to farthest, then the shared file, then
260 committed files nearest to farthest, so a machine override beats
261 committed config at any depth.
262
263 *shared_dir* is where ``.repo.shared.env`` lives; None means the
264 runner's own config directory, asked of footman. Under CI the
265 entry's emission points ``WORKSHOP_SHARED_ENV_FILE`` at a
266 runner-local file it wrote from the job's secrets, and that file
267 IS the shared slot: same precedence, same masking, gone with the
268 runner. *environ*
269 defaults to ``os.environ`` and is injectable for tests.
270 """
271 env = dict(os.environ) if environ is None else environ
272 dirs = cascade_dirs(repo_root, cwd)
273 committed = [d / ".repo.env" for d in dirs]
274 local = [d / ".repo.env.local" for d in dirs]
275
276 stack = EnvStack()
277 for path in committed:
278 load_extension(path, Source.repo, stack, env)
279 load_extension(shared_file(shared_dir, env), Source.shared, stack, env)
280 for path in local:
281 load_extension(path, Source.local, stack, env)
282 resolve_all(stack, env)
283 return stack
284
285
286def quote_value(value: str) -> str:
287 """*value* spelled so the parser reads it back unchanged.
288
289 An unquoted value loses everything from its first ``#`` onward
290 and all trailing whitespace, so a value carrying either is
291 written inside double quotes, which the parser strips again. A
292 line break cannot be spelled on one line at all, the value would
293 read back as several lines with the second silently discarded,
294 so it is refused rather than written.
295
296 Raises:
297 ValueError: *value* contains a line break.
298 """
299 if "\n" in value or "\r" in value:
300 raise ValueError("a line break cannot be stored in an env file")
301 if "#" in value or value != value.strip():
302 return f'"{value}"'
303 return value
304
305
306def set_value(path: Path, key: str, value: str) -> None:
307 """Set ``key=value`` in *path*, preserving the file's other content.
308
309 The stack's one write primitive: creates the file and parents
310 when missing, replaces the key's line in place when present,
311 appends with a blank separator otherwise. The value is spelled
312 by ``livery.workshop._envfile.quote_value``, so what is read
313 back is what was set.
314 """
315 lines = path.read_text(encoding="utf-8").splitlines() if path.is_file() else []
316 new_line = f"{key}={quote_value(value)}"
317 for index, line in enumerate(lines):
318 match = KEY_RE.match(line)
319 if match and match.group(1) == key:
320 lines[index] = new_line
321 break
322 else:
323 if lines and lines[-1].strip():
324 lines.append("")
325 lines.append(new_line)
326 path.parent.mkdir(parents=True, exist_ok=True)
327 path.write_text("\n".join(lines) + "\n", encoding="utf-8")
328
329
330def shared_file(shared_dir: Path | None, environ: dict[str, str]) -> Path:
331 """The shared rung's file: the CI rung when the runner set one.
332
333 ``WORKSHOP_SHARED_ENV_FILE`` names a runner-local file the
334 entry's emission materialised from the repository's secrets; when
335 it is unset the rung is ``.repo.shared.env`` in *shared_dir*
336 (the runner's config directory when None).
337 """
338 override = environ.get("WORKSHOP_SHARED_ENV_FILE", "")
339 if override:
340 return Path(override)
341 if shared_dir is None:
342 import livery.footman as footman
343
344 shared_dir = footman.config_dir()
345 return shared_dir / ".repo.shared.env"
346
347
348def member_keys(repo_root: Path, cwd: Path, shared_dir: Path) -> set[str]:
349 """Every key the cascade's files define (membership, no values).
350
351 The one definition of which files make up the stack, for the
352 membership consumers (the agent emission, ``env.show``): the
353 same files ``livery.workshop._envfile.load_cascade`` folds
354 for a run from *cwd*.
355 """
356 keys: set[str] = set()
357 for directory in cascade_dirs(repo_root, cwd):
358 keys |= set(parse_env_file(directory / ".repo.env"))
359 keys |= set(parse_env_file(directory / ".repo.env.local"))
360 keys |= set(parse_env_file(shared_file(shared_dir, dict(os.environ))))
361 return keys