stringforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ # Copyright 2026 Andreas Schachner
2
+ #
3
+ # This file is part of StringForge.
4
+ #
5
+ # StringForge is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+
10
+ r"""
11
+ Run-ID template engine for Vulcan.
12
+
13
+ A ``run_id`` is the per-write identifier carried on every row of a
14
+ Vulcan shard. Templates are ordinary Python format strings with
15
+ ``{name}`` placeholders; an additional ``{name?}`` form marks an
16
+ optional placeholder that falls back to ``"na"`` when the substitution
17
+ is not provided.
18
+
19
+ The rendered string must satisfy
20
+ :data:`stringforge.vacuavault.schema.LABEL_SLUG_RE`, so a Vulcan
21
+ run_id is admissible as a vault label after future promotion. The
22
+ constraints are: the first character must be in ``[A-Za-z0-9]``;
23
+ subsequent characters must be in ``[A-Za-z0-9_-]``; and an optional
24
+ trailing ``_v\d+`` version suffix is permitted. Substitution values
25
+ are coerced via :func:`_slugify` before insertion. Note that
26
+ :func:`_slugify` strips leading and trailing ``-`` but does *not*
27
+ strip a leading ``_``, so a substitution rendering with a leading
28
+ ``_`` will fail validation.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import re
33
+ import uuid
34
+ from datetime import datetime, timezone
35
+ from string import Formatter
36
+ from typing import Any, Callable, Mapping, Optional, Union
37
+
38
+ from .schema import is_safe_run_id
39
+
40
+ # Per the plan: default template carries date, project, Hodge numbers,
41
+ # KS+triang IDs, and seed. Optional placeholders are marked with `?`
42
+ # so they fall back to "na" when an upstream caller has nothing to put
43
+ # in them (e.g. a CICY model has no ks_id).
44
+ DEFAULT_TEMPLATE: str = (
45
+ "{date}_{project}_h11-{h11?}_h12-{h12?}_"
46
+ "ks-{ks_id?}_triang-{triang_id?}_seed-{seed?}"
47
+ )
48
+
49
+ #: Sentinel used to render an optional placeholder when no value is
50
+ #: available. Chosen to be slug-safe and visually distinct.
51
+ OPTIONAL_PLACEHOLDER_FALLBACK: str = "na"
52
+
53
+ _OPTIONAL_SUFFIX_RE = re.compile(r"^(.*)\?$")
54
+
55
+ # Vulcan templates accept plain placeholders only -- attribute access
56
+ # (``{x.y}``) and item access (``{x[0]}``) lead to format errors that
57
+ # do not name the offending placeholder. We reject them upfront so the
58
+ # error message points to the actual problem.
59
+ _FORBIDDEN_FIELD_CHARS_RE = re.compile(r"[.\[\]]")
60
+
61
+ # Slug coercion: collapse anything outside [A-Za-z0-9_-] into "-".
62
+ # Leading/trailing "-" are stripped so we never produce "-foo" or
63
+ # "foo--bar".
64
+ _SLUGIFY_RE = re.compile(r"[^A-Za-z0-9_\-]+")
65
+
66
+
67
+ def _slugify(value: Any) -> str:
68
+ r"""
69
+ Coerce ``value`` into a slug-safe string. Returns
70
+ :data:`OPTIONAL_PLACEHOLDER_FALLBACK` for ``None``.
71
+ """
72
+ if value is None:
73
+ return OPTIONAL_PLACEHOLDER_FALLBACK
74
+ text = str(value).strip()
75
+ if not text:
76
+ return OPTIONAL_PLACEHOLDER_FALLBACK
77
+ text = _SLUGIFY_RE.sub("-", text)
78
+ text = text.strip("-")
79
+ return text or OPTIONAL_PLACEHOLDER_FALLBACK
80
+
81
+
82
+ def _utc_date_slug(now: Optional[datetime] = None) -> str:
83
+ r"""
84
+ Return ``YYYY-MM-DD-HHMMSS`` for the current UTC moment.
85
+ The format is intentionally slug-safe -- no dots, colons, or
86
+ timezone suffixes.
87
+ """
88
+ dt = now if now is not None else datetime.now(tz=timezone.utc)
89
+ if dt.tzinfo is None:
90
+ dt = dt.replace(tzinfo=timezone.utc)
91
+ else:
92
+ dt = dt.astimezone(timezone.utc)
93
+ return dt.strftime("%Y-%m-%d-%H%M%S")
94
+
95
+
96
+ def _split_optional_keys(template: str) -> tuple[str, set[str]]:
97
+ r"""
98
+ **Description:**
99
+ Convert ``{name?}`` markers into ``{name}`` and return the cleaned
100
+ template plus the set of names that were marked optional.
101
+
102
+ Reject placeholders that use attribute access (``{x.y}``) or item
103
+ access (``{x[0]}``) -- those are technically valid Python format
104
+ syntax but produce confusing errors when paired with the slugify
105
+ pipeline. Vulcan templates accept plain identifiers only.
106
+
107
+ Args:
108
+ template: A run-id template string.
109
+
110
+ Returns:
111
+ tuple[str, set[str]]: ``(cleaned_template, optional_names)``.
112
+
113
+ Raises:
114
+ ValueError: If the template contains an attribute- or
115
+ item-access placeholder.
116
+ """
117
+ cleaned_parts: list[str] = []
118
+ optional: set[str] = set()
119
+ for literal, field_name, format_spec, conversion in Formatter().parse(template):
120
+ cleaned_parts.append(literal)
121
+ if field_name is None:
122
+ continue
123
+ match = _OPTIONAL_SUFFIX_RE.match(field_name)
124
+ name = match.group(1) if match is not None else field_name
125
+ if _FORBIDDEN_FIELD_CHARS_RE.search(name):
126
+ raise ValueError(
127
+ f"Vulcan run_id template does not support attribute or "
128
+ f"item access in placeholders: {{{field_name}}}. "
129
+ f"Use a plain identifier and pass nested data via "
130
+ f"extra_kwargs."
131
+ )
132
+ if match is not None:
133
+ optional.add(name)
134
+ # Rebuild the field spec.
135
+ spec = ""
136
+ if conversion:
137
+ spec += f"!{conversion}"
138
+ if format_spec:
139
+ spec += f":{format_spec}"
140
+ cleaned_parts.append("{" + name + spec + "}")
141
+ return "".join(cleaned_parts), optional
142
+
143
+
144
+ def render(
145
+ template: Optional[Union[str, Callable[..., str]]] = None,
146
+ *,
147
+ project: str = "",
148
+ now: Optional[datetime] = None,
149
+ **substitutions: Any,
150
+ ) -> str:
151
+ r"""
152
+ **Description:**
153
+ Render a Vulcan ``run_id`` from a template and a set of
154
+ substitutions.
155
+
156
+ The rendered identifier is guaranteed to satisfy
157
+ :data:`stringforge.vacuavault.schema.LABEL_SLUG_RE` so it is
158
+ admissible as a vault label after a future promotion step. Non
159
+ slug-safe substitution values are coerced via :func:`_slugify`
160
+ before insertion; trailing whitespace and disallowed punctuation
161
+ collapse into single dashes.
162
+
163
+ Args:
164
+ template:
165
+ * ``str`` -- format string with ``{name}`` and/or
166
+ ``{name?}`` placeholders. Plain identifiers only;
167
+ attribute access (``{x.y}``) and item access
168
+ (``{x[0]}``) are rejected.
169
+ * Callable -- invoked with ``**substitutions``; the
170
+ returned string is used verbatim and must satisfy
171
+ :data:`~stringforge.vacuavault.schema.LABEL_SLUG_RE`.
172
+ * ``None`` -- fall back to :func:`uuid.uuid4`'s ``.hex``.
173
+ project: Default value for ``{project}`` when not present in
174
+ ``substitutions``.
175
+ now: Override the wall-clock for tests. Defaults to
176
+ :func:`datetime.datetime.now` in UTC.
177
+ **substitutions: Values to interpolate. Standard keys include
178
+ ``h11``, ``h12``, ``ks_id``, ``triang_id``, ``conifold_id``,
179
+ ``cicy_id``, ``seed``, ``solver``. Unknown keys are
180
+ forwarded to the template engine.
181
+
182
+ Returns:
183
+ str: A slug-safe run identifier.
184
+
185
+ Raises:
186
+ KeyError: A required (non-``?``) placeholder is unsupplied.
187
+ ValueError: The rendered string is not a valid run_id, or
188
+ the template uses attribute / item access.
189
+ """
190
+ if template is None:
191
+ return uuid.uuid4().hex
192
+
193
+ if callable(template):
194
+ # Callable templates are expected to produce the final form
195
+ # themselves -- we validate but do not transform. This is the
196
+ # contract that lets a callable enforce a stricter naming
197
+ # scheme than slugify would; the template-string path applies
198
+ # slugify because positional substitutions are the only way
199
+ # for plain users to guarantee a valid output.
200
+ rendered = template(**substitutions)
201
+ if not isinstance(rendered, str) or not is_safe_run_id(rendered):
202
+ raise ValueError(
203
+ f"callable run_id_template returned an invalid slug: "
204
+ f"{rendered!r}. Returned value must satisfy LABEL_SLUG_RE; "
205
+ f"slugify is not applied to callable results."
206
+ )
207
+ return rendered
208
+
209
+ cleaned_template, optional_names = _split_optional_keys(template)
210
+
211
+ # Build the substitution map: always inject {date} and {project};
212
+ # callers may override either.
213
+ env: dict[str, Any] = {
214
+ "date": _utc_date_slug(now=now),
215
+ "project": project,
216
+ }
217
+ env.update(substitutions)
218
+
219
+ # Slugify every substitution. This is also what fills optional
220
+ # placeholders with the fallback when their value is missing.
221
+ slug_env = {k: _slugify(v) for k, v in env.items()}
222
+ for opt in optional_names:
223
+ slug_env.setdefault(opt, OPTIONAL_PLACEHOLDER_FALLBACK)
224
+
225
+ try:
226
+ rendered = cleaned_template.format(**slug_env)
227
+ except KeyError as exc:
228
+ missing = exc.args[0]
229
+ raise KeyError(
230
+ f"Vulcan run_id template requires placeholder {missing!r}; "
231
+ f"pass it via extra_kwargs= or mark it optional as "
232
+ f"{{{missing}?}}"
233
+ ) from None
234
+
235
+ if not is_safe_run_id(rendered):
236
+ raise ValueError(
237
+ f"rendered run_id is not a valid slug: {rendered!r}. "
238
+ f"LABEL_SLUG_RE requires the first character to be in "
239
+ f"[A-Za-z0-9], subsequent characters in [A-Za-z0-9_-], "
240
+ f"with an optional trailing _v\\d+ version suffix. Note "
241
+ f"that _slugify strips leading/trailing '-' but does NOT "
242
+ f"strip a leading '_', so a substitution rendering with a "
243
+ f"leading '_' will fail this check. Check that no "
244
+ f"template literals or substitutions introduce disallowed "
245
+ f"characters."
246
+ )
247
+
248
+ return rendered