casekit 0.9.1__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.
- casekit/__init__.py +8 -0
- casekit/caps.py +60 -0
- casekit/decision_log.py +237 -0
- casekit/evidence.py +29 -0
- casekit/export.py +146 -0
- casekit/fetch.py +229 -0
- casekit/jsonschema/case-1.0.json +274 -0
- casekit/narrative.py +76 -0
- casekit/py.typed +0 -0
- casekit/schema.py +187 -0
- casekit/scoring.py +60 -0
- casekit/text.py +161 -0
- casekit-0.9.1.dist-info/METADATA +49 -0
- casekit-0.9.1.dist-info/RECORD +16 -0
- casekit-0.9.1.dist-info/WHEEL +4 -0
- casekit-0.9.1.dist-info/licenses/LICENSE +21 -0
casekit/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""casekit: building blocks for evidence-backed security case tools.
|
|
2
|
+
|
|
3
|
+
Data-source neutral: source clients, field semantics and narrative prompts stay in each
|
|
4
|
+
component. No dependency on `mcp` (tests/test_guards.py).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.9.1"
|
|
8
|
+
SCHEMA_VERSION = "1.0"
|
casekit/caps.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Response budgets: every tool response fits in a character budget, paginating beyond it.
|
|
2
|
+
|
|
3
|
+
House rule: default 20,000 characters, with `truncated: true` + `next_cursor` when a page had
|
|
4
|
+
to be cut. Plain dicts in, plain dicts out, so this works under any MCP SDK (or none).
|
|
5
|
+
Extracted from the buildkit component template (caps.py).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
|
|
13
|
+
DEFAULT_MAX_CHARS = 20_000
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def size(obj: object) -> int:
|
|
17
|
+
"""Characters of the canonical JSON form, the measure every budget uses."""
|
|
18
|
+
return len(json.dumps(obj, ensure_ascii=False, sort_keys=True))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OverBudget(ValueError):
|
|
22
|
+
"""A single item does not fit the budget; the caller must summarize it instead."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def fit_page(
|
|
26
|
+
items: Sequence[dict],
|
|
27
|
+
start: int,
|
|
28
|
+
limit: int,
|
|
29
|
+
build: Callable[[list[dict]], dict],
|
|
30
|
+
max_chars: int = DEFAULT_MAX_CHARS,
|
|
31
|
+
) -> dict:
|
|
32
|
+
"""Largest page of items[start:start+limit] whose built response fits the budget.
|
|
33
|
+
|
|
34
|
+
Invariants: the page is non-empty when items remain (the cursor always advances), and
|
|
35
|
+
`truncated` is True exactly when `next_cursor` is set (more items exist). `build`'s
|
|
36
|
+
result is never modified; a new dict is returned.
|
|
37
|
+
"""
|
|
38
|
+
if limit < 1:
|
|
39
|
+
raise ValueError("limit must be at least 1, or the cursor can never advance")
|
|
40
|
+
page = list(items[start : start + limit])
|
|
41
|
+
while True:
|
|
42
|
+
nxt = start + len(page)
|
|
43
|
+
more = nxt < len(items)
|
|
44
|
+
response = {**build(page), "truncated": more, "next_cursor": str(nxt) if more else None}
|
|
45
|
+
used = size(response)
|
|
46
|
+
if used <= max_chars:
|
|
47
|
+
return response
|
|
48
|
+
if len(page) <= 1:
|
|
49
|
+
raise OverBudget(f"one item needs {used} characters; the budget is {max_chars}")
|
|
50
|
+
page = page[: max(1, min(len(page) - 1, len(page) * max_chars // used))]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_cursor(cursor: str | None, total: int) -> int:
|
|
54
|
+
"""Offset for a cursor from `fit_page`; None/"" is the start. Anything else is rejected."""
|
|
55
|
+
if cursor in (None, ""):
|
|
56
|
+
return 0
|
|
57
|
+
text = str(cursor)
|
|
58
|
+
if not (text.isascii() and text.isdecimal()) or int(text) > total:
|
|
59
|
+
raise ValueError(f"invalid cursor: {cursor!r}")
|
|
60
|
+
return int(text)
|
casekit/decision_log.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Append-only JSONL decision log behind an explicit confirm flag.
|
|
2
|
+
|
|
3
|
+
- Nothing is written unless `confirm is True` (a tool layer passes the human's confirmation
|
|
4
|
+
through; casekit cannot verify it, so treat the log as a worklog, not an audit trail).
|
|
5
|
+
- One line per record: sorted-key JSON (no NaN/Infinity), raw UTF-8, LF, at most
|
|
6
|
+
MAX_RECORD_BYTES; the file is capped at `max_bytes` including the new line. Writers take a
|
|
7
|
+
lock (a sidecar `<log>.lock`), so concurrent appends never fork the chain.
|
|
8
|
+
- By default each line carries `prev_sha256`, the sha256 of the previous line's exact bytes
|
|
9
|
+
(GENESIS for the first). `verify_chain` finds edits, insertions and deletions *before* the
|
|
10
|
+
last line. It cannot see a truncated tail or an edited last line, and anyone who can write
|
|
11
|
+
the file can rewrite the whole chain: store `head()` somewhere else and compare it.
|
|
12
|
+
`chain=False` writes the record unchanged, for logs that predate the chain.
|
|
13
|
+
|
|
14
|
+
Extracted from exposure-case-builder (disposition).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
24
|
+
from contextlib import contextmanager
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from .schema import Decision
|
|
29
|
+
|
|
30
|
+
CHAIN_KEY = "prev_sha256"
|
|
31
|
+
GENESIS = "0" * 64
|
|
32
|
+
DEFAULT_MAX_BYTES = 5 * 1024 * 1024 # a worklog, not a database
|
|
33
|
+
MAX_RECORD_BYTES = 64 * 1024
|
|
34
|
+
MAX_READ_BYTES = 4 * DEFAULT_MAX_BYTES
|
|
35
|
+
LOCK_TIMEOUT_S = 10.0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DecisionLogError(ValueError):
|
|
39
|
+
"""The log could not be written or read; messages never include record contents."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Head:
|
|
44
|
+
"""Anchor for the tail: store it outside the log and compare later."""
|
|
45
|
+
|
|
46
|
+
lines: int
|
|
47
|
+
sha256: str # of the last line; GENESIS for an empty log
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def line_hash(raw_line: bytes) -> str:
|
|
51
|
+
"""sha256 of one line's exact bytes, without its terminating LF."""
|
|
52
|
+
return hashlib.sha256(raw_line).hexdigest()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@contextmanager
|
|
56
|
+
def _locked(target: Path) -> Iterator[None]:
|
|
57
|
+
lock_path = target.with_name(target.name + ".lock")
|
|
58
|
+
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
59
|
+
try:
|
|
60
|
+
if os.name == "nt":
|
|
61
|
+
import msvcrt
|
|
62
|
+
|
|
63
|
+
deadline = time.monotonic() + LOCK_TIMEOUT_S
|
|
64
|
+
while True:
|
|
65
|
+
try:
|
|
66
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
67
|
+
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
|
|
68
|
+
break
|
|
69
|
+
except OSError:
|
|
70
|
+
if time.monotonic() > deadline:
|
|
71
|
+
raise DecisionLogError("the log is locked by another writer") from None
|
|
72
|
+
time.sleep(0.01)
|
|
73
|
+
try:
|
|
74
|
+
yield
|
|
75
|
+
finally:
|
|
76
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
77
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
78
|
+
else:
|
|
79
|
+
import fcntl
|
|
80
|
+
|
|
81
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
82
|
+
try:
|
|
83
|
+
yield
|
|
84
|
+
finally:
|
|
85
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
86
|
+
finally:
|
|
87
|
+
os.close(fd)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _size(path: Path) -> int:
|
|
91
|
+
try:
|
|
92
|
+
return path.stat().st_size
|
|
93
|
+
except FileNotFoundError:
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _raw_lines(path: Path, max_bytes: int = MAX_READ_BYTES) -> list[bytes]:
|
|
98
|
+
"""Every line (LF-split, the empty piece after a final LF dropped)."""
|
|
99
|
+
if _size(path) > max_bytes:
|
|
100
|
+
raise DecisionLogError(f"the log is too large to read (limit {max_bytes} bytes)")
|
|
101
|
+
try:
|
|
102
|
+
data = path.read_bytes() if path.exists() else b""
|
|
103
|
+
except OSError as exc:
|
|
104
|
+
raise DecisionLogError(f"cannot read the log: {type(exc).__name__}") from None
|
|
105
|
+
lines = data.split(b"\n")
|
|
106
|
+
return lines[:-1] if lines and lines[-1] == b"" else lines
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _last_line(path: Path) -> bytes | None:
|
|
110
|
+
"""The last non-blank line, read from the tail only (O(record), not O(file))."""
|
|
111
|
+
size = _size(path)
|
|
112
|
+
if size == 0:
|
|
113
|
+
return None
|
|
114
|
+
window = min(size, MAX_RECORD_BYTES + 1024)
|
|
115
|
+
with path.open("rb") as fh:
|
|
116
|
+
fh.seek(size - window)
|
|
117
|
+
tail = fh.read(window)
|
|
118
|
+
lines = [ln for ln in tail.split(b"\n") if ln.strip()]
|
|
119
|
+
if not lines:
|
|
120
|
+
return None
|
|
121
|
+
if window < size and b"\n" not in tail.rstrip(b"\n"):
|
|
122
|
+
raise DecisionLogError("the last log line is longer than a record may be")
|
|
123
|
+
return lines[-1]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _encode(line: Mapping[str, object]) -> bytes:
|
|
127
|
+
try:
|
|
128
|
+
text = json.dumps(line, sort_keys=True, ensure_ascii=False, allow_nan=False)
|
|
129
|
+
return (text + "\n").encode("utf-8")
|
|
130
|
+
except (TypeError, ValueError, UnicodeError):
|
|
131
|
+
raise DecisionLogError("the record is not valid JSON-serializable data") from None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def append(
|
|
135
|
+
path: str | Path,
|
|
136
|
+
record: Mapping[str, object],
|
|
137
|
+
*,
|
|
138
|
+
confirm: bool,
|
|
139
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
140
|
+
chain: bool = True,
|
|
141
|
+
) -> dict:
|
|
142
|
+
"""Validate, then append exactly one line; returns the dict that was written."""
|
|
143
|
+
if confirm is not True:
|
|
144
|
+
raise DecisionLogError("writing to the decision log requires confirm=True")
|
|
145
|
+
if chain and CHAIN_KEY in record:
|
|
146
|
+
raise DecisionLogError(f"{CHAIN_KEY!r} is reserved for the hash chain")
|
|
147
|
+
target = Path(path)
|
|
148
|
+
_encode(record) # reject bad data before touching the disk
|
|
149
|
+
try:
|
|
150
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
with _locked(target):
|
|
152
|
+
line = dict(record)
|
|
153
|
+
if chain:
|
|
154
|
+
previous = _last_line(target)
|
|
155
|
+
line[CHAIN_KEY] = line_hash(previous) if previous is not None else GENESIS
|
|
156
|
+
data = _encode(line)
|
|
157
|
+
if len(data) > MAX_RECORD_BYTES:
|
|
158
|
+
raise DecisionLogError(f"the record is too large (limit {MAX_RECORD_BYTES} bytes)")
|
|
159
|
+
if _size(target) + len(data) > max_bytes:
|
|
160
|
+
raise DecisionLogError("the decision log is full; archive or trim it first")
|
|
161
|
+
flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0)
|
|
162
|
+
fd = os.open(target, flags, 0o600)
|
|
163
|
+
try:
|
|
164
|
+
os.write(fd, data) # one write of one complete line
|
|
165
|
+
finally:
|
|
166
|
+
os.close(fd)
|
|
167
|
+
except OSError as exc:
|
|
168
|
+
raise DecisionLogError(f"cannot write the log: {type(exc).__name__}") from None
|
|
169
|
+
return line
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def record_decision(
|
|
173
|
+
path: str | Path, decision: Decision, *, confirm: bool, max_bytes: int = DEFAULT_MAX_BYTES
|
|
174
|
+
) -> dict:
|
|
175
|
+
"""Append a schema-validated Decision (chained)."""
|
|
176
|
+
return append(path, decision.model_dump(mode="json"), confirm=confirm, max_bytes=max_bytes)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _parse(raw: bytes, number: int) -> dict:
|
|
180
|
+
try:
|
|
181
|
+
data = json.loads(raw.decode("utf-8"))
|
|
182
|
+
except (ValueError, RecursionError):
|
|
183
|
+
raise DecisionLogError(f"corrupt log entry at line {number}") from None
|
|
184
|
+
if not isinstance(data, dict):
|
|
185
|
+
raise DecisionLogError(f"corrupt log entry at line {number}")
|
|
186
|
+
return data
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _numbered(path: str | Path, max_bytes: int) -> Iterable[tuple[int, bytes]]:
|
|
190
|
+
for number, raw in enumerate(_raw_lines(Path(path), max_bytes), start=1):
|
|
191
|
+
if raw.strip():
|
|
192
|
+
yield number, raw
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def read(path: str | Path, max_bytes: int = MAX_READ_BYTES) -> tuple[dict, ...]:
|
|
196
|
+
"""All entries in file order; a missing file has none. A corrupt line raises."""
|
|
197
|
+
return tuple(_parse(raw, n) for n, raw in _numbered(path, max_bytes))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def read_lenient(
|
|
201
|
+
path: str | Path, max_bytes: int = MAX_READ_BYTES
|
|
202
|
+
) -> tuple[tuple[dict, ...], tuple[int, ...]]:
|
|
203
|
+
"""Valid entries plus the numbers of skipped lines, so one bad line can't stop a tool."""
|
|
204
|
+
entries: list[dict] = []
|
|
205
|
+
bad: list[int] = []
|
|
206
|
+
for number, raw in _numbered(path, max_bytes):
|
|
207
|
+
try:
|
|
208
|
+
entries.append(_parse(raw, number))
|
|
209
|
+
except DecisionLogError:
|
|
210
|
+
bad.append(number)
|
|
211
|
+
return tuple(entries), tuple(bad)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def verify_chain(path: str | Path, max_bytes: int = MAX_READ_BYTES) -> tuple[int, ...]:
|
|
215
|
+
"""Line numbers that break the chain: a `prev_sha256` that doesn't match the line before,
|
|
216
|
+
or a blank line (append never writes one). See the module docstring for what it can't see."""
|
|
217
|
+
broken: list[int] = []
|
|
218
|
+
expected = GENESIS
|
|
219
|
+
for number, raw in enumerate(_raw_lines(Path(path), max_bytes), start=1):
|
|
220
|
+
try:
|
|
221
|
+
data = _parse(raw, number) if raw.strip() else {}
|
|
222
|
+
except DecisionLogError:
|
|
223
|
+
data = {}
|
|
224
|
+
if data.get(CHAIN_KEY) != expected:
|
|
225
|
+
broken.append(number)
|
|
226
|
+
expected = line_hash(raw)
|
|
227
|
+
return tuple(broken)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def head(path: str | Path, max_bytes: int = MAX_READ_BYTES) -> Head:
|
|
231
|
+
lines = _raw_lines(Path(path), max_bytes)
|
|
232
|
+
return Head(len(lines), line_hash(lines[-1]) if lines else GENESIS)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def latest_by(entries: Iterable[Mapping[str, object]], key: str) -> dict[object, Mapping]:
|
|
236
|
+
"""The most recent entry per value of `key` (later lines win)."""
|
|
237
|
+
return {e[key]: e for e in entries if key in e}
|
casekit/evidence.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Stable identifiers and content hashes for evidence.
|
|
2
|
+
|
|
3
|
+
Canonical JSON = sorted keys, no whitespace, raw UTF-8. Its definition is pinned by a golden
|
|
4
|
+
test: changing it would silently change every stored hash and ID.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
ID_HASH_CHARS = 24 # 96 bits: IDs may be built from attacker-influenced scanner data
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def canonical_json(obj: object) -> str:
|
|
16
|
+
"""Raises ValueError for NaN/Infinity (not JSON). Note 1 and 1.0 hash differently."""
|
|
17
|
+
return json.dumps(
|
|
18
|
+
obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sha256_of(obj: object) -> str:
|
|
23
|
+
return hashlib.sha256(canonical_json(obj).encode("utf-8")).hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def stable_id(prefix: str, *parts: str) -> str:
|
|
27
|
+
"""`<prefix>-<24 hex>` from the parts; parts are hashed as a JSON list, so they can't
|
|
28
|
+
run together ("ab", "c" differs from "a", "bc")."""
|
|
29
|
+
return f"{prefix}-{sha256_of(list(parts))[:ID_HASH_CHARS]}"
|
casekit/export.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Deterministic JSON/CSV rendering and atomic, confined file exports.
|
|
2
|
+
|
|
3
|
+
- `write_files` needs confirm=True and writes only strictly safe plain names
|
|
4
|
+
(`[A-Za-z0-9][A-Za-z0-9._-]{0,127}`, no Windows device names, no trailing dot) directly inside
|
|
5
|
+
`out_dir`. Names that would alias on a case-insensitive file system are refused. Every name is
|
|
6
|
+
checked before anything is written; each file is replaced atomically (unique temp file +
|
|
7
|
+
os.replace, which replaces a symlink instead of following it). If the OS fails midway, earlier
|
|
8
|
+
files may already be replaced: the error says so. CSV files get a UTF-8 BOM.
|
|
9
|
+
- Output never contains wall-clock time; the same input gives the same bytes. NaN/Infinity
|
|
10
|
+
are refused (not valid JSON).
|
|
11
|
+
|
|
12
|
+
Extracted from exposure-case-builder (export).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import csv
|
|
18
|
+
import hashlib
|
|
19
|
+
import io
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import tempfile
|
|
24
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
from .text import csv_cell
|
|
28
|
+
|
|
29
|
+
MAX_STEM_CHARS = 60
|
|
30
|
+
STEM_HASH_CHARS = 16 # 64 bits; exposure-case-builder passes 8 to keep its existing file names
|
|
31
|
+
_SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
|
32
|
+
_DEVICE = re.compile(r"^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$", re.IGNORECASE)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ExportError(ValueError):
|
|
36
|
+
"""An export could not be written."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def to_json(data: object) -> str:
|
|
40
|
+
return json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _cell(value: object) -> object:
|
|
44
|
+
"""Numbers and bools pass through; everything else is text and is formula-defused."""
|
|
45
|
+
if isinstance(value, (bool, int, float)):
|
|
46
|
+
return value
|
|
47
|
+
return csv_cell(value if isinstance(value, str) else str(value))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def to_csv(header: Sequence[str], rows: Iterable[Sequence[object]]) -> str:
|
|
51
|
+
out = io.StringIO()
|
|
52
|
+
writer = csv.writer(out, lineterminator="\n")
|
|
53
|
+
writer.writerow([_cell(h) for h in header])
|
|
54
|
+
for row in rows:
|
|
55
|
+
writer.writerow([_cell(v) for v in row])
|
|
56
|
+
return out.getvalue()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def slugify(text: str) -> str:
|
|
60
|
+
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def safe_stem(
|
|
64
|
+
identifier: str,
|
|
65
|
+
fallback: str,
|
|
66
|
+
max_chars: int = MAX_STEM_CHARS,
|
|
67
|
+
hash_chars: int = STEM_HASH_CHARS,
|
|
68
|
+
) -> str:
|
|
69
|
+
"""Readable, bounded file stem: slug plus a hash of the exact id (collisions are refused by
|
|
70
|
+
write_files within one call, but across calls a short hash can collide: keep the default)."""
|
|
71
|
+
slug = slugify(identifier)[:max_chars].strip("-") or fallback
|
|
72
|
+
digest = hashlib.sha1(identifier.encode("utf-8", "replace"), usedforsecurity=False)
|
|
73
|
+
return f"{slug}-{digest.hexdigest()[:hash_chars]}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _encoding(name: str) -> str:
|
|
77
|
+
return "utf-8-sig" if name.lower().endswith(".csv") else "utf-8"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def atomic_write(path: str | Path, content: str, *, encoding: str = "utf-8") -> Path:
|
|
81
|
+
"""Write one file via a temp file in the same directory and os.replace. No confinement:
|
|
82
|
+
the caller chooses the path."""
|
|
83
|
+
target = Path(path)
|
|
84
|
+
try:
|
|
85
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
86
|
+
fd, tmp = tempfile.mkstemp(dir=str(target.parent), prefix=".tmp-", suffix=".part")
|
|
87
|
+
try:
|
|
88
|
+
with os.fdopen(fd, "w", encoding=encoding, newline="\n") as handle:
|
|
89
|
+
handle.write(content)
|
|
90
|
+
os.replace(tmp, target)
|
|
91
|
+
finally:
|
|
92
|
+
if os.path.exists(tmp):
|
|
93
|
+
os.unlink(tmp)
|
|
94
|
+
except (OSError, ValueError) as exc:
|
|
95
|
+
raise ExportError(f"cannot write {target.name}: {type(exc).__name__}") from None
|
|
96
|
+
return target
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _validate_names(names: Iterable[str]) -> None:
|
|
100
|
+
seen: dict[str, str] = {}
|
|
101
|
+
for name in names:
|
|
102
|
+
if not isinstance(name, str) or not _SAFE_NAME.match(name) or name.endswith("."):
|
|
103
|
+
raise ExportError(f"unsafe export file name: {name!r}")
|
|
104
|
+
if _DEVICE.match(name):
|
|
105
|
+
raise ExportError(f"unsafe export file name (a Windows device name): {name!r}")
|
|
106
|
+
key = name.casefold()
|
|
107
|
+
if key in seen:
|
|
108
|
+
raise ExportError(f"export file names collide: {seen[key]!r} and {name!r}")
|
|
109
|
+
seen[key] = name
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def write_files(
|
|
113
|
+
files: Mapping[str, str], out_dir: str | Path, *, confirm: bool
|
|
114
|
+
) -> tuple[Path, ...]:
|
|
115
|
+
"""Write every file; returns the final paths in order."""
|
|
116
|
+
if confirm is not True:
|
|
117
|
+
raise ExportError("writing export files requires confirm=True")
|
|
118
|
+
_validate_names(files)
|
|
119
|
+
try:
|
|
120
|
+
directory = Path(out_dir)
|
|
121
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
root = directory.resolve()
|
|
123
|
+
except OSError as exc:
|
|
124
|
+
raise ExportError(f"cannot use the export directory: {type(exc).__name__}") from None
|
|
125
|
+
for name in files:
|
|
126
|
+
if (root / name).is_dir():
|
|
127
|
+
raise ExportError(f"a directory already exists at {name}")
|
|
128
|
+
temps: list[tuple[str, Path]] = []
|
|
129
|
+
done: list[Path] = []
|
|
130
|
+
try:
|
|
131
|
+
for name, content in files.items():
|
|
132
|
+
fd, tmp = tempfile.mkstemp(dir=str(root), prefix=".tmp-", suffix=".part")
|
|
133
|
+
temps.append((tmp, root / name))
|
|
134
|
+
with os.fdopen(fd, "w", encoding=_encoding(name), newline="\n") as handle:
|
|
135
|
+
handle.write(content)
|
|
136
|
+
for tmp, final in temps:
|
|
137
|
+
os.replace(tmp, final)
|
|
138
|
+
done.append(final)
|
|
139
|
+
except OSError as exc:
|
|
140
|
+
partial = f"; {len(done)} of {len(files)} files were already replaced" if done else ""
|
|
141
|
+
raise ExportError(f"export failed: {type(exc).__name__}{partial}") from None
|
|
142
|
+
finally:
|
|
143
|
+
for tmp, _ in temps:
|
|
144
|
+
if os.path.exists(tmp):
|
|
145
|
+
os.unlink(tmp)
|
|
146
|
+
return tuple(done)
|