esys-tools 0.2.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.
- esys_tools/__init__.py +3 -0
- esys_tools/__main__.py +6 -0
- esys_tools/bootstrap.py +143 -0
- esys_tools/catalog.py +317 -0
- esys_tools/cli.py +472 -0
- esys_tools/commands/__init__.py +1 -0
- esys_tools/commands/doctor.py +395 -0
- esys_tools/commands/lifecycle.py +306 -0
- esys_tools/commands/list_versions.py +121 -0
- esys_tools/compat.py +198 -0
- esys_tools/conan.py +232 -0
- esys_tools/conan_env.py +215 -0
- esys_tools/exit_codes.py +17 -0
- esys_tools/path_install.py +213 -0
- esys_tools/process.py +114 -0
- esys_tools/python_env.py +346 -0
- esys_tools-0.2.0.dist-info/METADATA +101 -0
- esys_tools-0.2.0.dist-info/RECORD +21 -0
- esys_tools-0.2.0.dist-info/WHEEL +5 -0
- esys_tools-0.2.0.dist-info/entry_points.txt +3 -0
- esys_tools-0.2.0.dist-info/top_level.txt +1 -0
esys_tools/__init__.py
ADDED
esys_tools/__main__.py
ADDED
esys_tools/bootstrap.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Auto-bootstrap one named tool on update (ADR-0005).
|
|
2
|
+
|
|
3
|
+
``install`` stays explicit. ``list`` and ``version`` do not install a native CLI.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from esys_tools.catalog import CatalogEntry
|
|
13
|
+
from esys_tools.commands.lifecycle import (
|
|
14
|
+
WRAPPER_MARKER,
|
|
15
|
+
install_tool,
|
|
16
|
+
wrapper_bin_for_mode,
|
|
17
|
+
wrapper_filename,
|
|
18
|
+
)
|
|
19
|
+
from esys_tools.exit_codes import ExitCode
|
|
20
|
+
from esys_tools.python_env import ModeNotConfirmedError, PythonEnvMode, resolve_mode
|
|
21
|
+
|
|
22
|
+
_TRUTHY = {"1", "true", "yes", "on"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class EnsureResult:
|
|
27
|
+
"""Whether update may continue, and whether this call installed the tool."""
|
|
28
|
+
|
|
29
|
+
exit_code: ExitCode
|
|
30
|
+
bootstrapped: bool
|
|
31
|
+
error: str = ""
|
|
32
|
+
hint: str = ""
|
|
33
|
+
message: str = ""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def bootstrap_permitted(
|
|
37
|
+
*,
|
|
38
|
+
no_bootstrap: bool = False,
|
|
39
|
+
strict: bool = False,
|
|
40
|
+
environ: Mapping[str, str] | None = None,
|
|
41
|
+
) -> bool:
|
|
42
|
+
"""Implicit install is off for ``--no-bootstrap``, ``--strict``, and ``CI=true``."""
|
|
43
|
+
if no_bootstrap or strict:
|
|
44
|
+
return False
|
|
45
|
+
env = os.environ if environ is None else environ
|
|
46
|
+
if _truthy(env.get("ESYS_TOOLS_NO_BOOTSTRAP")) or _truthy(env.get("ESYS_TOOLS_STRICT")):
|
|
47
|
+
return False
|
|
48
|
+
return not _truthy(env.get("CI"))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def native_wrappers_present(
|
|
52
|
+
entry: CatalogEntry,
|
|
53
|
+
mode: PythonEnvMode,
|
|
54
|
+
*,
|
|
55
|
+
environ: Mapping[str, str] | None = None,
|
|
56
|
+
) -> bool:
|
|
57
|
+
"""Return whether every command wrapper for this entry is already in place."""
|
|
58
|
+
bin_dir = wrapper_bin_for_mode(mode, environ=environ)
|
|
59
|
+
if not bin_dir.is_dir():
|
|
60
|
+
return False
|
|
61
|
+
for command in entry.commands:
|
|
62
|
+
path = bin_dir / wrapper_filename(command)
|
|
63
|
+
if not path.is_file():
|
|
64
|
+
return False
|
|
65
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
66
|
+
if WRAPPER_MARKER not in text or f"tool={entry.id}" not in text:
|
|
67
|
+
return False
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def ensure_for_update(
|
|
72
|
+
entry: CatalogEntry,
|
|
73
|
+
*,
|
|
74
|
+
linkage: str | None = None,
|
|
75
|
+
channel: str | None = None,
|
|
76
|
+
dev: bool = False,
|
|
77
|
+
mode: str | None = None,
|
|
78
|
+
yes: bool = False,
|
|
79
|
+
no_bootstrap: bool = False,
|
|
80
|
+
strict: bool = False,
|
|
81
|
+
environ: Mapping[str, str] | None = None,
|
|
82
|
+
) -> EnsureResult:
|
|
83
|
+
"""Install ``entry`` when its wrappers are missing and bootstrap is allowed.
|
|
84
|
+
|
|
85
|
+
The confirm path runs first. A refused mode does not call Conan. Only this
|
|
86
|
+
tool id is installed.
|
|
87
|
+
"""
|
|
88
|
+
try:
|
|
89
|
+
resolved, _source = resolve_mode(explicit=mode, yes=yes, environ=environ)
|
|
90
|
+
present = native_wrappers_present(entry, resolved, environ=environ)
|
|
91
|
+
except ModeNotConfirmedError as exc:
|
|
92
|
+
return EnsureResult(
|
|
93
|
+
exit_code=ExitCode.ENVIRONMENT_ERROR,
|
|
94
|
+
bootstrapped=False,
|
|
95
|
+
error=str(exc),
|
|
96
|
+
)
|
|
97
|
+
except ValueError as exc:
|
|
98
|
+
return EnsureResult(
|
|
99
|
+
exit_code=ExitCode.ENVIRONMENT_ERROR,
|
|
100
|
+
bootstrapped=False,
|
|
101
|
+
error=f"error: {exc}",
|
|
102
|
+
)
|
|
103
|
+
if present:
|
|
104
|
+
return EnsureResult(exit_code=ExitCode.SUCCESS, bootstrapped=False)
|
|
105
|
+
if not bootstrap_permitted(no_bootstrap=no_bootstrap, strict=strict, environ=environ):
|
|
106
|
+
return EnsureResult(
|
|
107
|
+
exit_code=ExitCode.MISSING_NATIVE_CLI,
|
|
108
|
+
bootstrapped=False,
|
|
109
|
+
error=f"error: native CLI for '{entry.id}' is not installed",
|
|
110
|
+
hint=f"hint: esys-tools install {entry.id}",
|
|
111
|
+
)
|
|
112
|
+
installed = install_tool(
|
|
113
|
+
entry,
|
|
114
|
+
linkage=linkage,
|
|
115
|
+
channel=channel,
|
|
116
|
+
dev=dev,
|
|
117
|
+
mode=mode,
|
|
118
|
+
yes=yes,
|
|
119
|
+
environ=environ,
|
|
120
|
+
)
|
|
121
|
+
if installed.exit_code is ExitCode.SUCCESS:
|
|
122
|
+
return EnsureResult(
|
|
123
|
+
exit_code=ExitCode.SUCCESS,
|
|
124
|
+
bootstrapped=True,
|
|
125
|
+
message=installed.message,
|
|
126
|
+
)
|
|
127
|
+
if installed.exit_code in {ExitCode.USAGE_ERROR, ExitCode.ENVIRONMENT_ERROR}:
|
|
128
|
+
return EnsureResult(
|
|
129
|
+
exit_code=installed.exit_code,
|
|
130
|
+
bootstrapped=False,
|
|
131
|
+
error=installed.error,
|
|
132
|
+
hint=installed.hint,
|
|
133
|
+
)
|
|
134
|
+
return EnsureResult(
|
|
135
|
+
exit_code=ExitCode.BOOTSTRAP_FAILURE,
|
|
136
|
+
bootstrapped=False,
|
|
137
|
+
error=installed.error or f"error: auto-bootstrap failed for {entry.id}",
|
|
138
|
+
hint=installed.hint or f"hint: esys-tools install {entry.id}",
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _truthy(value: str | None) -> bool:
|
|
143
|
+
return bool(value) and value.strip().lower() in _TRUTHY
|
esys_tools/catalog.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Tool-catalog snapshot (ADR-0015).
|
|
2
|
+
|
|
3
|
+
An explicit ``ESYS_TOOLS_CATALOG`` directory is used as-is. When that variable
|
|
4
|
+
is unset, the Git catalog is cloned into the esys-tools data directory.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from esys_tools.process import run
|
|
16
|
+
from esys_tools.python_env import data_dir
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CatalogError(ValueError):
|
|
20
|
+
"""The catalog source or snapshot cannot be used."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class CatalogEntry:
|
|
25
|
+
"""One installable tool."""
|
|
26
|
+
|
|
27
|
+
id: str
|
|
28
|
+
summary: str
|
|
29
|
+
commands: tuple[str, ...]
|
|
30
|
+
static_package: str | None
|
|
31
|
+
shared_package: str | None
|
|
32
|
+
default_linkage: str
|
|
33
|
+
path: Path
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class InvalidCatalogFile:
|
|
38
|
+
"""A tool file that was skipped. ``doctor`` reports these later."""
|
|
39
|
+
|
|
40
|
+
path: Path
|
|
41
|
+
reason: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class CatalogSnapshot:
|
|
46
|
+
"""Tools offered for install, plus files that were skipped."""
|
|
47
|
+
|
|
48
|
+
root: Path
|
|
49
|
+
entries: tuple[CatalogEntry, ...]
|
|
50
|
+
invalid: tuple[InvalidCatalogFile, ...]
|
|
51
|
+
|
|
52
|
+
def get(self, tool_id: str) -> CatalogEntry | None:
|
|
53
|
+
for entry in self.entries:
|
|
54
|
+
if entry.id == tool_id:
|
|
55
|
+
return entry
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
DEFAULT_CATALOG_GIT_URL = "https://gitlab.com/libesys/tools/esys-tools-catalog.git"
|
|
60
|
+
ENV_CATALOG = "ESYS_TOOLS_CATALOG"
|
|
61
|
+
ENV_CATALOG_GIT = "ESYS_TOOLS_CATALOG_GIT"
|
|
62
|
+
_CLONE_TIMEOUT_SECONDS = 120.0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def catalog_root(environ: Mapping[str, str] | None = None) -> Path | None:
|
|
66
|
+
"""Return ``ESYS_TOOLS_CATALOG`` when it is set."""
|
|
67
|
+
env = os.environ if environ is None else environ
|
|
68
|
+
raw = env.get(ENV_CATALOG, "").strip()
|
|
69
|
+
if not raw:
|
|
70
|
+
return None
|
|
71
|
+
return Path(raw)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def catalog_git_url(environ: Mapping[str, str] | None = None) -> str:
|
|
75
|
+
"""Return ``ESYS_TOOLS_CATALOG_GIT`` or the LibESys catalog remote."""
|
|
76
|
+
env = os.environ if environ is None else environ
|
|
77
|
+
raw = env.get(ENV_CATALOG_GIT, "").strip()
|
|
78
|
+
return raw or DEFAULT_CATALOG_GIT_URL
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def default_catalog_dir(environ: Mapping[str, str] | None = None) -> Path:
|
|
82
|
+
"""Directory where the Git catalog is cloned when ``ESYS_TOOLS_CATALOG`` is unset."""
|
|
83
|
+
return data_dir(environ=environ) / "catalog"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def describe_paths(environ: Mapping[str, str] | None = None) -> list[str]:
|
|
87
|
+
"""Return data and catalog locations. This does not clone or refresh."""
|
|
88
|
+
env = os.environ if environ is None else environ
|
|
89
|
+
data = data_dir(environ=env)
|
|
90
|
+
explicit = catalog_root(env)
|
|
91
|
+
if explicit is not None:
|
|
92
|
+
catalog = explicit
|
|
93
|
+
origin = "explicit"
|
|
94
|
+
else:
|
|
95
|
+
catalog = default_catalog_dir(env)
|
|
96
|
+
origin = catalog_git_url(env)
|
|
97
|
+
present = "yes" if (catalog / "tools").is_dir() else "no"
|
|
98
|
+
return [
|
|
99
|
+
f"data: {data}",
|
|
100
|
+
f"catalog: {catalog}",
|
|
101
|
+
f"catalog-git: {origin}",
|
|
102
|
+
f"catalog-present: {present}",
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def resolve_catalog_root(environ: Mapping[str, str] | None = None) -> Path:
|
|
107
|
+
"""Return the explicit snapshot, or clone the Git catalog into the data directory."""
|
|
108
|
+
explicit = catalog_root(environ)
|
|
109
|
+
if explicit is not None:
|
|
110
|
+
return explicit
|
|
111
|
+
dest = default_catalog_dir(environ)
|
|
112
|
+
if (dest / "tools").is_dir():
|
|
113
|
+
return dest
|
|
114
|
+
sync_git_catalog(dest, environ=environ)
|
|
115
|
+
if not (dest / "tools").is_dir():
|
|
116
|
+
raise CatalogError(f"cloned catalog has no tools directory: {dest / 'tools'}")
|
|
117
|
+
return dest
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def sync_git_catalog(dest: Path, *, environ: Mapping[str, str] | None = None) -> str:
|
|
121
|
+
"""Clone ``dest`` or fast-forward it when it is already a Git checkout."""
|
|
122
|
+
url = catalog_git_url(environ)
|
|
123
|
+
if (dest / ".git").is_dir():
|
|
124
|
+
result = run(["git", "-C", str(dest), "pull", "--ff-only"], timeout=_CLONE_TIMEOUT_SECONDS)
|
|
125
|
+
action = "updated"
|
|
126
|
+
else:
|
|
127
|
+
if dest.exists() and any(dest.iterdir()):
|
|
128
|
+
raise CatalogError(f"catalog directory is not a git checkout: {dest}")
|
|
129
|
+
if dest.exists():
|
|
130
|
+
dest.rmdir()
|
|
131
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
132
|
+
result = run(["git", "clone", url, str(dest)], timeout=_CLONE_TIMEOUT_SECONDS)
|
|
133
|
+
action = "cloned"
|
|
134
|
+
if result.ok:
|
|
135
|
+
return action
|
|
136
|
+
detail = (result.stderr or result.stdout).strip()
|
|
137
|
+
if result.executable_missing:
|
|
138
|
+
raise CatalogError("git is not installed")
|
|
139
|
+
verb = "pull" if action == "updated" else "clone"
|
|
140
|
+
message = f"git {verb} failed for {url}"
|
|
141
|
+
if detail:
|
|
142
|
+
message = f"{message}\n{detail}"
|
|
143
|
+
raise CatalogError(message)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def load_catalog(root: Path) -> CatalogSnapshot:
|
|
147
|
+
"""Load ``root/tools/*.yaml``. Invalid files are skipped, not raised."""
|
|
148
|
+
tools_dir = root / "tools"
|
|
149
|
+
if not tools_dir.is_dir():
|
|
150
|
+
raise CatalogError(f"catalog snapshot has no tools directory: {tools_dir}")
|
|
151
|
+
|
|
152
|
+
entries: list[CatalogEntry] = []
|
|
153
|
+
invalid: list[InvalidCatalogFile] = []
|
|
154
|
+
for path in sorted(tools_dir.glob("*.yaml")):
|
|
155
|
+
try:
|
|
156
|
+
text = path.read_text(encoding="utf-8")
|
|
157
|
+
data = parse_yaml_subset(text)
|
|
158
|
+
entries.append(_entry_from_mapping(data, path))
|
|
159
|
+
except (OSError, ValueError) as exc:
|
|
160
|
+
invalid.append(InvalidCatalogFile(path=path, reason=str(exc)))
|
|
161
|
+
entries.sort(key=lambda item: item.id)
|
|
162
|
+
return CatalogSnapshot(root=root, entries=tuple(entries), invalid=tuple(invalid))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def format_entries(snapshot: CatalogSnapshot) -> list[str]:
|
|
166
|
+
"""One human line per tool: id, summary, and command names."""
|
|
167
|
+
lines: list[str] = []
|
|
168
|
+
for entry in snapshot.entries:
|
|
169
|
+
commands = ", ".join(entry.commands)
|
|
170
|
+
lines.append(f"{entry.id} | {entry.summary} | {commands}")
|
|
171
|
+
return lines
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def refresh_local(source: Path, dest: Path) -> int:
|
|
175
|
+
"""Copy ``source/tools/*.yaml`` into ``dest/tools``, replacing yaml files there."""
|
|
176
|
+
src_tools = source / "tools"
|
|
177
|
+
if not src_tools.is_dir():
|
|
178
|
+
raise CatalogError(f"catalog source has no tools directory: {src_tools}")
|
|
179
|
+
dst_tools = dest / "tools"
|
|
180
|
+
dst_tools.mkdir(parents=True, exist_ok=True)
|
|
181
|
+
wanted = {path.name: path for path in src_tools.glob("*.yaml")}
|
|
182
|
+
for old in dst_tools.glob("*.yaml"):
|
|
183
|
+
if old.name not in wanted:
|
|
184
|
+
old.unlink()
|
|
185
|
+
for name, src in sorted(wanted.items()):
|
|
186
|
+
shutil.copyfile(src, dst_tools / name)
|
|
187
|
+
return len(wanted)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def parse_yaml_subset(text: str) -> dict[str, object]:
|
|
191
|
+
"""Parse the small YAML subset used by catalog entries.
|
|
192
|
+
|
|
193
|
+
Supported forms are scalars (``key: value``), flow lists (``key: [a, b]``),
|
|
194
|
+
and nested mappings indented with spaces. Unknown keys are kept so the
|
|
195
|
+
caller can ignore them.
|
|
196
|
+
"""
|
|
197
|
+
root: dict[str, object] = {}
|
|
198
|
+
stack: list[tuple[int, dict[str, object]]] = [(-1, root)]
|
|
199
|
+
for line_number, raw in enumerate(text.splitlines(), start=1):
|
|
200
|
+
if not raw.strip() or raw.lstrip().startswith("#"):
|
|
201
|
+
continue
|
|
202
|
+
if "\t" in raw[: len(raw) - len(raw.lstrip(" \t"))]:
|
|
203
|
+
raise ValueError(f"line {line_number}: tabs are not allowed in indentation")
|
|
204
|
+
indent = len(raw) - len(raw.lstrip(" "))
|
|
205
|
+
line = _strip_comment(raw.strip())
|
|
206
|
+
if ":" not in line:
|
|
207
|
+
raise ValueError(f"line {line_number}: expected 'key: value'")
|
|
208
|
+
key, _, rest = line.partition(":")
|
|
209
|
+
key = key.strip()
|
|
210
|
+
if not key:
|
|
211
|
+
raise ValueError(f"line {line_number}: missing key")
|
|
212
|
+
while stack and indent <= stack[-1][0]:
|
|
213
|
+
stack.pop()
|
|
214
|
+
if not stack:
|
|
215
|
+
raise ValueError(f"line {line_number}: invalid indentation")
|
|
216
|
+
parent = stack[-1][1]
|
|
217
|
+
if rest.strip() == "":
|
|
218
|
+
child: dict[str, object] = {}
|
|
219
|
+
parent[key] = child
|
|
220
|
+
stack.append((indent, child))
|
|
221
|
+
continue
|
|
222
|
+
parent[key] = _parse_scalar(rest.strip(), line_number)
|
|
223
|
+
return root
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _entry_from_mapping(data: dict[str, object], path: Path) -> CatalogEntry:
|
|
227
|
+
tool_id = _require_str(data, "id")
|
|
228
|
+
if tool_id != path.stem:
|
|
229
|
+
raise ValueError(f"id {tool_id!r} does not match filename {path.name}")
|
|
230
|
+
summary = _require_str(data, "summary")
|
|
231
|
+
if any(char in summary for char in "\n\r"):
|
|
232
|
+
raise ValueError("summary must be one line")
|
|
233
|
+
commands = _require_commands(data.get("commands"))
|
|
234
|
+
conan = data.get("conan")
|
|
235
|
+
if not isinstance(conan, dict):
|
|
236
|
+
raise ValueError("conan mapping is required")
|
|
237
|
+
static_package = _optional_str(conan.get("static"))
|
|
238
|
+
shared_package = _optional_str(conan.get("shared"))
|
|
239
|
+
if static_package is None and shared_package is None:
|
|
240
|
+
raise ValueError("conan.static or conan.shared is required")
|
|
241
|
+
default_linkage = _optional_str(conan.get("default_linkage"))
|
|
242
|
+
if static_package and shared_package:
|
|
243
|
+
if default_linkage not in {"static", "shared"}:
|
|
244
|
+
raise ValueError(
|
|
245
|
+
"conan.default_linkage must be static or shared when both packages are set"
|
|
246
|
+
)
|
|
247
|
+
elif default_linkage is None:
|
|
248
|
+
default_linkage = "static" if static_package else "shared"
|
|
249
|
+
elif default_linkage != ("static" if static_package else "shared"):
|
|
250
|
+
raise ValueError("conan.default_linkage does not match the declared package")
|
|
251
|
+
if default_linkage not in {"static", "shared"}:
|
|
252
|
+
raise ValueError("conan.default_linkage must be static or shared")
|
|
253
|
+
return CatalogEntry(
|
|
254
|
+
id=tool_id,
|
|
255
|
+
summary=summary,
|
|
256
|
+
commands=commands,
|
|
257
|
+
static_package=static_package,
|
|
258
|
+
shared_package=shared_package,
|
|
259
|
+
default_linkage=default_linkage,
|
|
260
|
+
path=path,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _require_str(data: Mapping[str, object], key: str) -> str:
|
|
265
|
+
value = data.get(key)
|
|
266
|
+
if not isinstance(value, str) or not value.strip():
|
|
267
|
+
raise ValueError(f"{key} is required")
|
|
268
|
+
return value.strip()
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _optional_str(value: object) -> str | None:
|
|
272
|
+
if value is None:
|
|
273
|
+
return None
|
|
274
|
+
if not isinstance(value, str) or not value.strip():
|
|
275
|
+
raise ValueError("expected a string")
|
|
276
|
+
return value.strip()
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _require_commands(value: object) -> tuple[str, ...]:
|
|
280
|
+
if not isinstance(value, list) or not value:
|
|
281
|
+
raise ValueError("commands must be a non-empty list")
|
|
282
|
+
commands: list[str] = []
|
|
283
|
+
for item in value:
|
|
284
|
+
if not isinstance(item, str) or not item.strip():
|
|
285
|
+
raise ValueError("commands must be strings")
|
|
286
|
+
commands.append(item.strip())
|
|
287
|
+
return tuple(commands)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _parse_scalar(text: str, line_number: int) -> str | list[str]:
|
|
291
|
+
if text.startswith("["):
|
|
292
|
+
if not text.endswith("]"):
|
|
293
|
+
raise ValueError(f"line {line_number}: unclosed list")
|
|
294
|
+
inner = text[1:-1].strip()
|
|
295
|
+
if not inner:
|
|
296
|
+
return []
|
|
297
|
+
return [_unquote(part.strip()) for part in inner.split(",")]
|
|
298
|
+
return _unquote(text)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _unquote(text: str) -> str:
|
|
302
|
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
|
|
303
|
+
return text[1:-1]
|
|
304
|
+
return text
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _strip_comment(line: str) -> str:
|
|
308
|
+
in_single = False
|
|
309
|
+
in_double = False
|
|
310
|
+
for index, char in enumerate(line):
|
|
311
|
+
if char == "'" and not in_double:
|
|
312
|
+
in_single = not in_single
|
|
313
|
+
elif char == '"' and not in_single:
|
|
314
|
+
in_double = not in_double
|
|
315
|
+
elif char == "#" and not in_single and not in_double:
|
|
316
|
+
return line[:index].rstrip()
|
|
317
|
+
return line
|