strata-python 0.2.0__py3-none-any.whl → 0.2.2__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.
- strata_python/__init__.py +2 -1
- strata_python/cli.py +99 -20
- strata_python/clients/__init__.py +2 -0
- strata_python/clients/models.py +780 -0
- strata_python/db/__init__.py +116 -0
- strata_python/db/__main__.py +5 -0
- strata_python/db/_alembic/env.py +24 -0
- strata_python/db/_alembic/script.py.mako +28 -0
- strata_python/db/cli.py +199 -0
- strata_python/db/config.py +85 -0
- strata_python/db/engine.py +53 -0
- strata_python/db/guard.py +159 -0
- strata_python/db/migrations.py +243 -0
- strata_python/db/models.py +62 -0
- strata_python/db/project.py +98 -0
- strata_python/db/pytest_plugin.py +205 -0
- strata_python/db/scratch.py +143 -0
- strata_python/db/settings.py +63 -0
- strata_python/db/testing.py +43 -0
- strata_python/db/testserver.py +205 -0
- strata_python/oslib.py +44 -5
- strata_python/pages/__init__.py +21 -0
- strata_python/pages/model.py +241 -0
- strata_python/pages/render.py +273 -0
- strata_python/public_check.py +54 -8
- strata_python/pytest_plugin.py +70 -1
- strata_python/settings.py +243 -42
- strata_python/testing.py +257 -0
- strata_python/web.py +15 -6
- strata_python-0.2.2.dist-info/METADATA +334 -0
- strata_python-0.2.2.dist-info/RECORD +38 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/entry_points.txt +2 -0
- strata_python-0.2.0.dist-info/METADATA +0 -82
- strata_python-0.2.0.dist-info/RECORD +0 -16
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/WHEEL +0 -0
- {strata_python-0.2.0.dist-info → strata_python-0.2.2.dist-info}/licenses/LICENSE +0 -0
strata_python/pytest_plugin.py
CHANGED
|
@@ -4,6 +4,8 @@ Configure it in the app's `[tool.pytest.ini_options]`:
|
|
|
4
4
|
|
|
5
5
|
strata_env_prefix = "MYAPP" # MYAPP_HOME and MYAPP_DATA are pointed into a tmp dir for every test
|
|
6
6
|
strata_tuning_vars = ["MYAPP_GREETING"] # removed from the environment for every test
|
|
7
|
+
strata_env = ["MYAPP_SWEEP_SECONDS=0", "MYAPP_PROJECTS={env}/projects"] # set for every test; {env} is isolated_env's dir
|
|
8
|
+
strata_auto_integration = true # tests under tests/integration get the `integration` marker (the default)
|
|
7
9
|
|
|
8
10
|
Without `strata_env_prefix` the plugin changes nothing but the no-network guard and the fixtures, so it is safe to have installed.
|
|
9
11
|
|
|
@@ -11,10 +13,18 @@ Without `strata_env_prefix` the plugin changes nothing but the no-network guard
|
|
|
11
13
|
developer's real settings or data; override variables are removed. Returns that dir.
|
|
12
14
|
no_network (autouse) an outbound connection fails the test at once; loopback and unix sockets are fine.
|
|
13
15
|
http_server a real scripted HTTP server on loopback (strata_python.http_server); fails the test at teardown if a request reached no route.
|
|
14
|
-
live_app `with live_app(app) as base_url:` runs a FastAPI app on a real loopback port (strata_python.live).
|
|
16
|
+
live_app `with live_app(app) as base_url:` runs a FastAPI app on a real loopback port (strata_python.live).
|
|
17
|
+
fake_urlopen `urllib.request.urlopen` scripted: `fake_urlopen.reply(http_error(429), {...})`, then assert on `.calls`.
|
|
18
|
+
fake_popen `subprocess.Popen` starts nothing; `.instances` lists what was asked (`.cmd`, `.kw`), fresh for each test.
|
|
19
|
+
fake_run `subprocess.run` / `check_output`: `.returns["ffprobe"] = b"..."` for output, `.code = 1` to fail, `.calls`.
|
|
20
|
+
no_sleep `time.sleep` returns at once; `.delays` records the waits.
|
|
21
|
+
The fakes are a last resort for a true external edge (strata_python.testing says when); prefer `http_server` and real programs."""
|
|
15
22
|
|
|
16
23
|
import contextlib
|
|
17
24
|
import socket
|
|
25
|
+
import subprocess
|
|
26
|
+
import time
|
|
27
|
+
import urllib.request
|
|
18
28
|
from collections.abc import Callable, Iterator
|
|
19
29
|
from pathlib import Path
|
|
20
30
|
from typing import Any, cast
|
|
@@ -23,6 +33,7 @@ import pytest
|
|
|
23
33
|
from fastapi import FastAPI
|
|
24
34
|
|
|
25
35
|
from strata_python import http_server as hs
|
|
36
|
+
from strata_python import testing
|
|
26
37
|
from strata_python.live import live_server
|
|
27
38
|
|
|
28
39
|
|
|
@@ -31,6 +42,30 @@ def pytest_addoption(parser: pytest.Parser) -> None:
|
|
|
31
42
|
"strata_env_prefix", "environment prefix of the app under test (APP -> APP_HOME, APP_DATA)", default=""
|
|
32
43
|
)
|
|
33
44
|
parser.addini("strata_tuning_vars", "environment variables removed for every test", type="args", default=[])
|
|
45
|
+
parser.addini(
|
|
46
|
+
"strata_env", "KEY=VALUE set for every test; {env} is the isolated environment's dir", type="args", default=[]
|
|
47
|
+
)
|
|
48
|
+
parser.addini(
|
|
49
|
+
"strata_auto_integration", "mark tests under tests/integration with `integration`", type="bool", default=True
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def pytest_configure(config: pytest.Config) -> None:
|
|
54
|
+
config.addinivalue_line("markers", "integration: runs processes or servers end to end (tests/integration)")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
|
|
58
|
+
if not config.getini("strata_auto_integration"):
|
|
59
|
+
return
|
|
60
|
+
for item in items:
|
|
61
|
+
# Relative to the pytest root: a checkout that happens to sit under a folder called "integration" must not
|
|
62
|
+
# mark every test (review finding)
|
|
63
|
+
try:
|
|
64
|
+
parts = item.path.parent.relative_to(config.rootpath).parts
|
|
65
|
+
except ValueError: # a test outside the root (an explicit path elsewhere): leave it as it is
|
|
66
|
+
continue
|
|
67
|
+
if "integration" in parts:
|
|
68
|
+
item.add_marker(pytest.mark.integration)
|
|
34
69
|
|
|
35
70
|
|
|
36
71
|
@pytest.fixture(autouse=True)
|
|
@@ -46,6 +81,11 @@ def isolated_env(
|
|
|
46
81
|
monkeypatch.setenv(f"{prefix}_DATA", str(base / "data"))
|
|
47
82
|
for k in request.config.getini("strata_tuning_vars"):
|
|
48
83
|
monkeypatch.delenv(k, raising=False)
|
|
84
|
+
for pair in request.config.getini("strata_env"):
|
|
85
|
+
key, sep, value = str(pair).partition("=")
|
|
86
|
+
if not sep:
|
|
87
|
+
raise pytest.UsageError(f"strata_env entries are KEY=VALUE, not {pair!r}")
|
|
88
|
+
monkeypatch.setenv(key, value.replace("{env}", str(base)))
|
|
49
89
|
return base
|
|
50
90
|
|
|
51
91
|
|
|
@@ -78,3 +118,32 @@ def http_server() -> Iterator[hs.ScriptedServer]:
|
|
|
78
118
|
@pytest.fixture
|
|
79
119
|
def live_app() -> Callable[[FastAPI], contextlib.AbstractContextManager[str]]:
|
|
80
120
|
return live_server
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@pytest.fixture
|
|
124
|
+
def fake_urlopen(monkeypatch: pytest.MonkeyPatch) -> testing.FakeUrlopen:
|
|
125
|
+
fake = testing.FakeUrlopen()
|
|
126
|
+
monkeypatch.setattr(urllib.request, "urlopen", fake)
|
|
127
|
+
return fake
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@pytest.fixture
|
|
131
|
+
def fake_popen(monkeypatch: pytest.MonkeyPatch) -> type[testing.FakePopen]:
|
|
132
|
+
fake = testing.FakePopen.fresh()
|
|
133
|
+
monkeypatch.setattr(subprocess, "Popen", fake)
|
|
134
|
+
return fake
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@pytest.fixture
|
|
138
|
+
def fake_run(monkeypatch: pytest.MonkeyPatch) -> testing.FakeRun:
|
|
139
|
+
fake = testing.FakeRun()
|
|
140
|
+
monkeypatch.setattr(subprocess, "run", fake)
|
|
141
|
+
monkeypatch.setattr(subprocess, "check_output", fake.check_output)
|
|
142
|
+
return fake
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@pytest.fixture
|
|
146
|
+
def no_sleep(monkeypatch: pytest.MonkeyPatch) -> testing.Sleeper:
|
|
147
|
+
sleeper = testing.Sleeper()
|
|
148
|
+
monkeypatch.setattr(time, "sleep", sleeper)
|
|
149
|
+
return sleeper
|
strata_python/settings.py
CHANGED
|
@@ -3,21 +3,30 @@
|
|
|
3
3
|
An app declares its settings once (`Setting`: key, default, optional normaliser) and gets the file handling, the override order and the validation:
|
|
4
4
|
|
|
5
5
|
SETTINGS = Settings("myapp", [Setting("data_dir", default=lambda: "/srv/data", normalise=absolute_path),
|
|
6
|
-
Setting("greeting", default="Hello", normalise=non_empty)
|
|
6
|
+
Setting("greeting", default="Hello", normalise=non_empty),
|
|
7
|
+
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
8
|
+
ListSetting("source_roots", item=absolute_path)])
|
|
7
9
|
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
10
|
+
SETTINGS.get_int("workers") # typed getters: get_int, get_float, get_bool, get_list
|
|
8
11
|
SETTINGS.save({"greeting": "Hi"}) # validated, written atomically; None resets to the default
|
|
9
12
|
|
|
10
|
-
Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the name given), then the
|
|
13
|
+
Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the name given), then the store, then the default. The folder holding the file is `~/.<app>`, moved
|
|
11
14
|
with `<APP>_HOME`. A stored or environment value that fails its normaliser is ignored (the default applies) rather than crashing the app at start; only `save` raises.
|
|
12
|
-
Values are strings: the file is edited by hand as well as by the app.
|
|
15
|
+
Values are canonical strings (a normaliser returns the one spelling it accepts), and lists of them: the file is edited by hand as well as by the app.
|
|
13
16
|
|
|
17
|
+
Where the values live is a `SettingsStore`: the JSON file by default; `Settings.bind(store)` moves an app onto another one at run time (its database's `settings` table,
|
|
18
|
+
`strata_python.db.settings.TableStore`), copying the file's values in once. The CLI and tests without a database keep the file."""
|
|
19
|
+
|
|
20
|
+
import datetime
|
|
14
21
|
import json
|
|
22
|
+
import math
|
|
15
23
|
import os
|
|
24
|
+
import re
|
|
16
25
|
import tempfile
|
|
17
26
|
import threading
|
|
18
27
|
from collections.abc import Callable, Mapping, Sequence
|
|
19
28
|
from dataclasses import dataclass
|
|
20
|
-
from typing import Any, cast
|
|
29
|
+
from typing import Any, Protocol, cast
|
|
21
30
|
|
|
22
31
|
from strata_python.oslib import file_lock
|
|
23
32
|
|
|
@@ -38,6 +47,73 @@ def absolute_path(value: str) -> str:
|
|
|
38
47
|
return os.path.abspath(p)
|
|
39
48
|
|
|
40
49
|
|
|
50
|
+
def number_between(lo: float, hi: float) -> Callable[[str], str]:
|
|
51
|
+
"""Normaliser: a finite number from `lo` to `hi` (GB of memory, a budget in dollars), written the shortest way (`"8"`, `"8.5"`)."""
|
|
52
|
+
|
|
53
|
+
def normalise(value: str) -> str:
|
|
54
|
+
try:
|
|
55
|
+
x = float(value.strip())
|
|
56
|
+
except ValueError:
|
|
57
|
+
raise ValueError("must be a number") from None
|
|
58
|
+
if not math.isfinite(x) or not lo <= x <= hi:
|
|
59
|
+
raise ValueError(f"must be a number from {_num(lo)} to {_num(hi)}")
|
|
60
|
+
return _num(x)
|
|
61
|
+
|
|
62
|
+
return normalise
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def whole_between(lo: int, hi: int) -> Callable[[str], str]:
|
|
66
|
+
"""Normaliser: a whole number from `lo` to `hi` (job slots, a port)."""
|
|
67
|
+
|
|
68
|
+
def normalise(value: str) -> str:
|
|
69
|
+
try:
|
|
70
|
+
x = int(value.strip())
|
|
71
|
+
except ValueError:
|
|
72
|
+
raise ValueError("must be a whole number") from None
|
|
73
|
+
if not lo <= x <= hi:
|
|
74
|
+
raise ValueError(f"must be a whole number from {lo} to {hi}")
|
|
75
|
+
return str(x)
|
|
76
|
+
|
|
77
|
+
return normalise
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def iso_date(allow_blank: bool = True) -> Callable[[str], str]:
|
|
84
|
+
"""Normaliser: a `YYYY-MM-DD` date; with `allow_blank`, `""` is a value too (no date: the setting is cleared but not reset)."""
|
|
85
|
+
|
|
86
|
+
def normalise(value: str) -> str:
|
|
87
|
+
v = value.strip()
|
|
88
|
+
if not v and allow_blank:
|
|
89
|
+
return ""
|
|
90
|
+
try:
|
|
91
|
+
if not _DATE.fullmatch(v):
|
|
92
|
+
raise ValueError
|
|
93
|
+
return datetime.date.fromisoformat(v).isoformat()
|
|
94
|
+
except ValueError:
|
|
95
|
+
raise ValueError("must be a date, YYYY-MM-DD") from None
|
|
96
|
+
|
|
97
|
+
return normalise
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_TRUE, _FALSE = {"1", "true", "yes", "on"}, {"0", "false", "no", "off"}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def boolean(value: str) -> str:
|
|
104
|
+
"""Normaliser: `true` or `false` (also accepts 1/0, yes/no, on/off, in any case)."""
|
|
105
|
+
v = value.strip().lower()
|
|
106
|
+
if v in _TRUE:
|
|
107
|
+
return "true"
|
|
108
|
+
if v in _FALSE:
|
|
109
|
+
return "false"
|
|
110
|
+
raise ValueError("must be true or false")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _num(x: float) -> str:
|
|
114
|
+
return str(int(x)) if float(x).is_integer() and abs(x) < 1e15 else repr(float(x))
|
|
115
|
+
|
|
116
|
+
|
|
41
117
|
def _identity(value: str) -> str:
|
|
42
118
|
return value
|
|
43
119
|
|
|
@@ -53,15 +129,117 @@ class Setting:
|
|
|
53
129
|
d = self.default
|
|
54
130
|
return d if isinstance(d, str) else d()
|
|
55
131
|
|
|
132
|
+
def parse(self, raw: object) -> str:
|
|
133
|
+
"""A stored, environment or saved value as its canonical string; ValueError when it is not acceptable."""
|
|
134
|
+
if not isinstance(raw, str):
|
|
135
|
+
raise ValueError("must be text") # str(5) would pass a hand-edited number off as a deliberate string
|
|
136
|
+
return self.normalise(raw)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _no_list() -> list[str]:
|
|
140
|
+
return []
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass(frozen=True)
|
|
144
|
+
class ListSetting:
|
|
145
|
+
"""A setting that is a list of strings (folders to scan, names to enable). The file holds a JSON list (a string there is split, so hand edits work); the
|
|
146
|
+
environment value is split on `sep` (`os.pathsep` by default, for folders; give `sep=","` for names). `item` normalises each entry, and blank entries are
|
|
147
|
+
dropped. `get_list` returns the list and `all()` (so GET /api/settings) the list as JSON; `get` and `strata set` show it joined by `sep`, and `save` takes a
|
|
148
|
+
list or a joined string."""
|
|
149
|
+
|
|
150
|
+
key: str
|
|
151
|
+
default: Sequence[str] | Callable[[], Sequence[str]] = _no_list
|
|
152
|
+
item: Callable[[str], str] = _identity
|
|
153
|
+
sep: str = os.pathsep
|
|
154
|
+
env: str | None = None
|
|
155
|
+
|
|
156
|
+
def default_value(self) -> list[str]:
|
|
157
|
+
d = self.default
|
|
158
|
+
return list(cast("Sequence[str]", d) if isinstance(d, Sequence) else d())
|
|
159
|
+
|
|
160
|
+
def parse(self, raw: object) -> list[str]:
|
|
161
|
+
if isinstance(raw, str):
|
|
162
|
+
items: list[object] = list(raw.split(self.sep))
|
|
163
|
+
elif isinstance(raw, list | tuple):
|
|
164
|
+
items = list(cast("Sequence[object]", raw))
|
|
165
|
+
else:
|
|
166
|
+
raise ValueError("must be a list")
|
|
167
|
+
out: list[str] = []
|
|
168
|
+
for i in items:
|
|
169
|
+
if not isinstance(i, str):
|
|
170
|
+
raise ValueError("must be a list of text")
|
|
171
|
+
if i.strip():
|
|
172
|
+
out.append(self.item(i.strip()))
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
AnySetting = Setting | ListSetting
|
|
177
|
+
Value = str | list[str]
|
|
178
|
+
|
|
179
|
+
IMPORTED = "_imported_from_file" # the marker bind() leaves in a store it copied the file into; not a setting
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class SettingsStore(Protocol):
|
|
183
|
+
"""Where the values live. `load` returns every stored value; `update` applies changes (already validated; None removes a key) as one atomic step, so two
|
|
184
|
+
saves of different keys never lose one, and returns what is stored afterwards."""
|
|
185
|
+
|
|
186
|
+
def load(self) -> dict[str, object]: ...
|
|
187
|
+
|
|
188
|
+
def update(self, changes: Mapping[str, object]) -> dict[str, object]: ...
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class JsonFileStore:
|
|
192
|
+
"""The default store: one JSON object in a file, written atomically under a lock (across threads and processes). `path` is called each time, so a
|
|
193
|
+
variable that moves the folder (`<APP>_HOME`) takes effect without a restart."""
|
|
194
|
+
|
|
195
|
+
def __init__(self, path: str | Callable[[], str]) -> None:
|
|
196
|
+
self._path = path
|
|
197
|
+
self._thread_lock = threading.Lock() # file_lock alone does not exclude threads on every platform
|
|
198
|
+
|
|
199
|
+
def path(self) -> str:
|
|
200
|
+
p = self._path
|
|
201
|
+
return p if isinstance(p, str) else p()
|
|
202
|
+
|
|
203
|
+
def load(self) -> dict[str, object]:
|
|
204
|
+
"""The file's contents ({} when it is missing, unreadable or not a JSON object)."""
|
|
205
|
+
try:
|
|
206
|
+
with open(self.path(), encoding="utf8") as f:
|
|
207
|
+
d = json.load(f)
|
|
208
|
+
except (OSError, ValueError):
|
|
209
|
+
return {}
|
|
210
|
+
return cast("dict[str, object]", d) if isinstance(d, dict) else {}
|
|
211
|
+
|
|
212
|
+
def update(self, changes: Mapping[str, object]) -> dict[str, object]:
|
|
213
|
+
path = self.path()
|
|
214
|
+
folder = os.path.dirname(path)
|
|
215
|
+
os.makedirs(folder, exist_ok=True)
|
|
216
|
+
# The whole read-merge-write is one critical section, across threads (the server's PUT handlers run in a pool) and processes (the CLI `set` beside a running server);
|
|
217
|
+
# otherwise two saves of different keys lose one update.
|
|
218
|
+
with self._thread_lock, open(path + ".lock", "a+") as lock, file_lock(lock):
|
|
219
|
+
d = self.load()
|
|
220
|
+
for k, v in changes.items():
|
|
221
|
+
if v is None:
|
|
222
|
+
d.pop(k, None)
|
|
223
|
+
else:
|
|
224
|
+
d[k] = v
|
|
225
|
+
fd, tmp = tempfile.mkstemp(dir=folder, prefix="settings.", suffix=".tmp")
|
|
226
|
+
with os.fdopen(fd, "w", encoding="utf8") as f:
|
|
227
|
+
json.dump(d, f, indent=1)
|
|
228
|
+
os.replace(tmp, path) # atomic: a reader never sees half a file
|
|
229
|
+
return d
|
|
230
|
+
|
|
56
231
|
|
|
57
232
|
class Settings:
|
|
58
|
-
def __init__(
|
|
233
|
+
def __init__(
|
|
234
|
+
self, app: str, settings: Sequence[AnySetting], *, prefix: str | None = None, store: SettingsStore | None = None
|
|
235
|
+
) -> None:
|
|
59
236
|
"""`prefix` names the environment variables (`<PREFIX>_HOME`, `<PREFIX>_<KEY>`); default the upper-cased app name with `-` as `_`.
|
|
60
|
-
Give it when an app's variables already have a short form that deployed services use."""
|
|
237
|
+
Give it when an app's variables already have a short form that deployed services use. `store` is where values live (default: the JSON file)."""
|
|
61
238
|
self.app = app
|
|
62
239
|
self.prefix = prefix or app.upper().replace("-", "_")
|
|
63
|
-
self._by_key = {s.key: s for s in settings}
|
|
64
|
-
self.
|
|
240
|
+
self._by_key: dict[str, AnySetting] = {s.key: s for s in settings}
|
|
241
|
+
self.file = JsonFileStore(self.path)
|
|
242
|
+
self.store: SettingsStore = store or self.file
|
|
65
243
|
|
|
66
244
|
@property
|
|
67
245
|
def keys(self) -> tuple[str, ...]:
|
|
@@ -77,53 +255,76 @@ class Settings:
|
|
|
77
255
|
def env_name(self, key: str) -> str:
|
|
78
256
|
return self._by_key[key].env or f"{self.prefix}_{key.upper()}"
|
|
79
257
|
|
|
258
|
+
def bind(self, store: SettingsStore, *, import_file: bool = True) -> None:
|
|
259
|
+
"""Keep the values in `store` from now on. The first time a store is bound (it has no import marker), the file's valid values are copied into it,
|
|
260
|
+
with the marker, so moving an app onto its database keeps what its people set. Two processes binding a new store at once both copy the same values."""
|
|
261
|
+
if import_file and IMPORTED not in store.load():
|
|
262
|
+
values: dict[str, object] = {}
|
|
263
|
+
for k, raw in self.file.load().items():
|
|
264
|
+
s = self._by_key.get(k)
|
|
265
|
+
if s is not None:
|
|
266
|
+
try:
|
|
267
|
+
values[k] = s.parse(raw)
|
|
268
|
+
except ValueError:
|
|
269
|
+
continue # a bad value would be ignored by get() too; it is not carried over
|
|
270
|
+
store.update({**values, IMPORTED: self.file.path()})
|
|
271
|
+
self.store = store
|
|
272
|
+
|
|
80
273
|
def load(self) -> dict[str, Any]:
|
|
81
|
-
"""The raw file contents
|
|
82
|
-
|
|
83
|
-
with open(self.path(), encoding="utf8") as f:
|
|
84
|
-
d = json.load(f)
|
|
85
|
-
except (OSError, ValueError):
|
|
86
|
-
return {}
|
|
87
|
-
return cast("dict[str, Any]", d) if isinstance(d, dict) else {}
|
|
274
|
+
"""The raw stored values (for the file: its contents; {} when it is missing, unreadable or not a JSON object)."""
|
|
275
|
+
return self.store.load()
|
|
88
276
|
|
|
89
277
|
def save(self, changes: Mapping[str, object]) -> dict[str, Any]:
|
|
90
|
-
"""Merge `changes` into the
|
|
91
|
-
(naming the key), and None removes the setting. All changes are checked before any is written."""
|
|
278
|
+
"""Merge `changes` into the store and return what is stored. Unknown keys raise KeyError, a value its normaliser refuses raises ValueError
|
|
279
|
+
(naming the key), and None removes the setting. All changes are checked before any is written. A list setting takes a list or a joined string."""
|
|
92
280
|
for k in changes:
|
|
93
281
|
if k not in self._by_key:
|
|
94
282
|
raise KeyError(f"unknown setting {k!r}")
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
d[k] = self._by_key[k].normalise(str(v))
|
|
106
|
-
except ValueError as e:
|
|
107
|
-
raise ValueError(f"{k}: {e}") from e
|
|
108
|
-
fd, tmp = tempfile.mkstemp(dir=self.home(), prefix="settings.", suffix=".tmp")
|
|
109
|
-
with os.fdopen(fd, "w", encoding="utf8") as f:
|
|
110
|
-
json.dump(d, f, indent=1)
|
|
111
|
-
os.replace(tmp, self.path()) # atomic: a reader never sees half a file
|
|
112
|
-
return d
|
|
283
|
+
clean: dict[str, object] = {}
|
|
284
|
+
for k, v in changes.items():
|
|
285
|
+
s = self._by_key[k]
|
|
286
|
+
try:
|
|
287
|
+
clean[k] = (
|
|
288
|
+
None if v is None else s.parse(v if isinstance(s, ListSetting) or isinstance(v, str) else str(v))
|
|
289
|
+
)
|
|
290
|
+
except ValueError as e:
|
|
291
|
+
raise ValueError(f"{k}: {e}") from e
|
|
292
|
+
return self.store.update(clean)
|
|
113
293
|
|
|
114
|
-
def
|
|
294
|
+
def value(self, key: str) -> Value:
|
|
295
|
+
"""The setting's value: a string, or a list of strings for a `ListSetting`."""
|
|
115
296
|
s = self._by_key[key]
|
|
116
|
-
|
|
117
|
-
for raw in (os.environ.get(self.env_name(key)), stored if isinstance(stored, str) else None):
|
|
297
|
+
for raw in (os.environ.get(self.env_name(key)), self.load().get(key)):
|
|
118
298
|
if raw is not None: # "" is a value; the normaliser decides whether it is acceptable
|
|
119
299
|
try:
|
|
120
|
-
return s.
|
|
300
|
+
return s.parse(raw)
|
|
121
301
|
except ValueError:
|
|
122
302
|
continue
|
|
123
|
-
return s.
|
|
303
|
+
return s.parse(s.default_value())
|
|
304
|
+
|
|
305
|
+
def get(self, key: str) -> str:
|
|
306
|
+
"""The value as a string (a list setting joined by its separator)."""
|
|
307
|
+
v = self.value(key)
|
|
308
|
+
s = self._by_key[key]
|
|
309
|
+
return s.sep.join(v) if isinstance(s, ListSetting) and isinstance(v, list) else cast("str", v)
|
|
310
|
+
|
|
311
|
+
def get_list(self, key: str) -> list[str]:
|
|
312
|
+
s = self._by_key[key]
|
|
313
|
+
if not isinstance(s, ListSetting):
|
|
314
|
+
raise TypeError(f"{key!r} is not a ListSetting")
|
|
315
|
+
return cast("list[str]", self.value(key))
|
|
316
|
+
|
|
317
|
+
def get_int(self, key: str) -> int:
|
|
318
|
+
return int(self.get(key))
|
|
319
|
+
|
|
320
|
+
def get_float(self, key: str) -> float:
|
|
321
|
+
return float(self.get(key))
|
|
322
|
+
|
|
323
|
+
def get_bool(self, key: str) -> bool:
|
|
324
|
+
return boolean(self.get(key)) == "true"
|
|
124
325
|
|
|
125
|
-
def all(self) -> dict[str,
|
|
126
|
-
return {k: self.
|
|
326
|
+
def all(self) -> dict[str, Value]:
|
|
327
|
+
return {k: self.value(k) for k in self._by_key}
|
|
127
328
|
|
|
128
329
|
def folder(self, key: str) -> str:
|
|
129
330
|
"""The setting `key` as a folder that exists (created when asked for)."""
|