docstate 0.2.3__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.
docstate/config.py ADDED
@@ -0,0 +1,550 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import tomllib
5
+ from dataclasses import dataclass
6
+ from pathlib import Path, PurePosixPath
7
+
8
+ from .errors import DocstateError, fail
9
+
10
+ ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
11
+ FIELD_RE = re.compile(r"^[A-Za-z0-9_-]+$")
12
+ DIALECTS = {"scalar-v1", "scalar-v2"}
13
+ BUILTIN_EXCLUDES = {".git", "node_modules", ".venv", "dist", "build"}
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Fact:
18
+ id: str
19
+ path: Path
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Block:
24
+ id: str
25
+ file: Path
26
+ file_rel: str
27
+ fact_id: str
28
+ template: Path
29
+ template_rel: str
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class OwnerRule:
34
+ owner: Path
35
+ owner_rel: str
36
+ field: str
37
+ applies_to: list[Path]
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class FrontmatterRule:
42
+ files: list[Path]
43
+ status_field: str
44
+ status_values: list[str]
45
+ require: list[str]
46
+ bom: str
47
+ status_review: str
48
+ updated_field: str
49
+ owners: list[OwnerRule]
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class FreshnessRule:
54
+ doc: Path
55
+ doc_rel: str
56
+ field: str
57
+ changelog: Path
58
+ changelog_rel: str
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class AnchorRule:
63
+ files: list[Path]
64
+ repo: Path
65
+ repo_rel: str
66
+ paths: list[str]
67
+ pattern: re.Pattern[str]
68
+ require: bool
69
+ severity: str
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ForbiddenRule:
74
+ files: list[Path]
75
+ patterns: list[re.Pattern[str]]
76
+ allow: list[Path]
77
+ allow_rel: list[str]
78
+ severity: str
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Config:
83
+ path: Path
84
+ base: Path
85
+ dialect: str
86
+ facts: dict[str, Fact]
87
+ blocks: list[Block]
88
+ check_files: list[Path]
89
+ exclude: list[str]
90
+ frontmatter: FrontmatterRule | None
91
+ freshness: list[FreshnessRule]
92
+ anchors: list[AnchorRule]
93
+ forbidden: list[ForbiddenRule]
94
+
95
+
96
+ def _read_toml(path: Path) -> dict:
97
+ try:
98
+ raw = path.read_bytes()
99
+ except OSError as exc:
100
+ fail("CFG_READ", f"cannot read config: {exc}", path=str(path))
101
+ try:
102
+ text = raw.decode("utf-8")
103
+ except UnicodeDecodeError as exc:
104
+ fail("CFG_READ", f"config is not UTF-8: {exc}", path=str(path))
105
+ try:
106
+ return tomllib.loads(text)
107
+ except tomllib.TOMLDecodeError as exc:
108
+ fail("CFG_PARSE", str(exc), path=str(path))
109
+
110
+
111
+ def _reject_unknown(mapping: dict, allowed: set[str], where: str) -> None:
112
+ unknown = set(mapping) - allowed
113
+ if unknown:
114
+ names = ", ".join(sorted(unknown))
115
+ fail("CFG_SCHEMA", f"unknown key(s) in {where}: {names}")
116
+
117
+
118
+ def _resolve_file(base: Path, raw: object, *, suffix: str, where: str) -> Path:
119
+ if not isinstance(raw, str) or not raw:
120
+ fail("CFG_SCHEMA", f"{where} must be a non-empty string")
121
+ candidate = Path(raw)
122
+ if candidate.is_absolute():
123
+ fail("CFG_PATH", f"{where} must be relative: {raw}")
124
+ unresolved = base / candidate
125
+ if unresolved.is_symlink():
126
+ fail("CFG_PATH", f"{where} must not be a symlink: {raw}")
127
+ resolved = unresolved.resolve()
128
+ if resolved != base and base not in resolved.parents:
129
+ fail("CFG_PATH", f"{where} escapes the config directory: {raw}")
130
+ if resolved.suffix != suffix:
131
+ fail("CFG_SCHEMA", f"{where} must end with {suffix}: {raw}")
132
+ if not resolved.is_file():
133
+ fail("CFG_PATH", f"{where} does not exist or is not a file: {raw}")
134
+ return resolved
135
+
136
+
137
+ def _resolve_fact(base: Path, raw: object, *, where: str) -> Path:
138
+ """Facts are read-only and may live outside the config directory."""
139
+
140
+ if not isinstance(raw, str) or not raw:
141
+ fail("CFG_SCHEMA", f"{where} must be a non-empty string")
142
+ candidate = Path(raw)
143
+ if candidate.is_absolute():
144
+ fail("CFG_PATH", f"{where} must be relative: {raw}")
145
+ unresolved = base / candidate
146
+ if unresolved.is_symlink():
147
+ fail("CFG_PATH", f"{where} must not be a symlink: {raw}")
148
+ resolved = unresolved.resolve()
149
+ if resolved.suffix != ".json":
150
+ fail("CFG_SCHEMA", f"{where} must end with .json: {raw}")
151
+ if not resolved.is_file():
152
+ fail("CFG_PATH", f"{where} does not exist or is not a file: {raw}")
153
+ return resolved
154
+
155
+
156
+ def _relative(base: Path, path: Path) -> str:
157
+ return path.relative_to(base).as_posix()
158
+
159
+
160
+ def _validate_id(raw: object, where: str) -> str:
161
+ if not isinstance(raw, str) or not ID_RE.fullmatch(raw):
162
+ fail("CFG_SCHEMA", f"{where} must match {ID_RE.pattern}")
163
+ return raw
164
+
165
+
166
+ def _list_of_strings(raw: object, where: str) -> list[str]:
167
+ if raw is None:
168
+ return []
169
+ if not isinstance(raw, list) or any(not isinstance(item, str) for item in raw):
170
+ fail("CFG_SCHEMA", f"{where} must be an array of strings")
171
+ return list(raw)
172
+
173
+
174
+ def _check_pattern(pattern: str, where: str) -> None:
175
+ if not pattern:
176
+ fail("CFG_SCHEMA", f"{where} contains an empty pattern")
177
+ pure = PurePosixPath(pattern)
178
+ if pure.is_absolute() or ".." in pure.parts:
179
+ fail("CFG_PATH", f"{where} must be relative and must not contain '..': {pattern}")
180
+
181
+
182
+ def _expand_check_files(
183
+ base: Path,
184
+ patterns: list[str] | None,
185
+ default_files: list[Path],
186
+ exclude: list[str],
187
+ ) -> list[Path]:
188
+ if patterns is None:
189
+ candidates = list(default_files)
190
+ elif not patterns:
191
+ candidates = []
192
+ else:
193
+ candidates = []
194
+ for pattern in patterns:
195
+ _check_pattern(pattern, "check.files")
196
+ candidates.extend(sorted(base.glob(pattern)))
197
+
198
+ result: list[Path] = []
199
+ seen: set[Path] = set()
200
+ for path in candidates:
201
+ if path.is_symlink() or not path.is_file():
202
+ continue
203
+ resolved = path.resolve()
204
+ if resolved in seen:
205
+ continue
206
+ rel = _relative(base, resolved)
207
+ parts = PurePosixPath(rel).parts
208
+ if any(part in BUILTIN_EXCLUDES for part in parts):
209
+ continue
210
+ if any(PurePosixPath(rel).match(pattern) for pattern in exclude):
211
+ continue
212
+ seen.add(resolved)
213
+ result.append(resolved)
214
+ return sorted(result, key=lambda item: _relative(base, item))
215
+
216
+
217
+ def _validate_field(raw: object, where: str) -> str:
218
+ if not isinstance(raw, str) or not FIELD_RE.fullmatch(raw):
219
+ fail("CFG_SCHEMA", f"{where} must match {FIELD_RE.pattern}")
220
+ return raw
221
+
222
+
223
+ def _enum(raw: object, allowed: set[str], where: str, default: str) -> str:
224
+ if raw is None:
225
+ return default
226
+ if not isinstance(raw, str) or raw not in allowed:
227
+ fail("CFG_SCHEMA", f"{where} must be one of: {', '.join(sorted(allowed))}")
228
+ return raw
229
+
230
+
231
+ def _parse_frontmatter_rule(base: Path, raw: object) -> FrontmatterRule:
232
+ if not isinstance(raw, dict):
233
+ fail("CFG_SCHEMA", "check.frontmatter must be a table")
234
+ _reject_unknown(
235
+ raw,
236
+ {"files", "require", "status_field", "status_values", "bom", "status_review", "updated_field", "owners"},
237
+ "check.frontmatter",
238
+ )
239
+ files_raw = raw.get("files")
240
+ if files_raw is None:
241
+ fail("CFG_SCHEMA", "check.frontmatter.files is required")
242
+ patterns = _list_of_strings(files_raw, "check.frontmatter.files")
243
+ if not patterns:
244
+ fail("CFG_SCHEMA", "check.frontmatter.files must not be empty")
245
+ files = _expand_check_files(base, patterns, [], [])
246
+
247
+ status_field = _validate_field(raw.get("status_field", "status"), "check.frontmatter.status_field")
248
+ updated_field = _validate_field(raw.get("updated_field", "updated"), "check.frontmatter.updated_field")
249
+ status_values = _list_of_strings(raw.get("status_values"), "check.frontmatter.status_values")
250
+ require = _list_of_strings(raw.get("require"), "check.frontmatter.require")
251
+ for field_name in require:
252
+ _validate_field(field_name, "check.frontmatter.require")
253
+ bom = _enum(raw.get("bom"), {"ignore", "warn", "error"}, "check.frontmatter.bom", "warn")
254
+ status_review = _enum(
255
+ raw.get("status_review"), {"off", "warn", "error"}, "check.frontmatter.status_review", "off"
256
+ )
257
+
258
+ owners_raw = raw.get("owners", [])
259
+ if not isinstance(owners_raw, list):
260
+ fail("CFG_SCHEMA", "check.frontmatter.owners must be an array of tables")
261
+ owners: list[OwnerRule] = []
262
+ for index, item in enumerate(owners_raw):
263
+ if not isinstance(item, dict):
264
+ fail("CFG_SCHEMA", f"check.frontmatter.owners[{index}] must be a table")
265
+ _reject_unknown(item, {"owner", "field", "applies_to"}, f"check.frontmatter.owners[{index}]")
266
+ owner = _resolve_file(
267
+ base, item.get("owner"), suffix=".md", where=f"check.frontmatter.owners[{index}].owner"
268
+ )
269
+ field_name = _validate_field(item.get("field"), f"check.frontmatter.owners[{index}].field")
270
+ applies = _list_of_strings(item.get("applies_to"), f"check.frontmatter.owners[{index}].applies_to")
271
+ if not applies:
272
+ fail("CFG_SCHEMA", f"check.frontmatter.owners[{index}].applies_to must not be empty")
273
+ owners.append(
274
+ OwnerRule(
275
+ owner=owner,
276
+ owner_rel=_relative(base, owner),
277
+ field=field_name,
278
+ applies_to=_expand_check_files(base, applies, [], []),
279
+ )
280
+ )
281
+
282
+ return FrontmatterRule(
283
+ files=files,
284
+ status_field=status_field,
285
+ status_values=status_values,
286
+ require=require,
287
+ bom=bom,
288
+ status_review=status_review,
289
+ updated_field=updated_field,
290
+ owners=owners,
291
+ )
292
+
293
+
294
+ def _parse_freshness_rules(base: Path, raw: object) -> list[FreshnessRule]:
295
+ if raw is None:
296
+ return []
297
+ if not isinstance(raw, list):
298
+ fail("CFG_SCHEMA", "check.freshness must be an array of tables")
299
+ rules: list[FreshnessRule] = []
300
+ for index, item in enumerate(raw):
301
+ if not isinstance(item, dict):
302
+ fail("CFG_SCHEMA", f"check.freshness[{index}] must be a table")
303
+ _reject_unknown(item, {"doc", "field", "changelog"}, f"check.freshness[{index}]")
304
+ doc = _resolve_file(base, item.get("doc"), suffix=".md", where=f"check.freshness[{index}].doc")
305
+ changelog = _resolve_file(
306
+ base, item.get("changelog"), suffix=".md", where=f"check.freshness[{index}].changelog"
307
+ )
308
+ field_name = _validate_field(item.get("field"), f"check.freshness[{index}].field")
309
+ rules.append(
310
+ FreshnessRule(
311
+ doc=doc,
312
+ doc_rel=_relative(base, doc),
313
+ field=field_name,
314
+ changelog=changelog,
315
+ changelog_rel=_relative(base, changelog),
316
+ )
317
+ )
318
+ return rules
319
+
320
+
321
+ def _resolve_dir(base: Path, raw: object, where: str) -> Path:
322
+ if not isinstance(raw, str) or not raw:
323
+ fail("CFG_SCHEMA", f"{where} must be a non-empty string")
324
+ candidate = Path(raw)
325
+ if candidate.is_absolute():
326
+ fail("CFG_PATH", f"{where} must be relative: {raw}")
327
+ resolved = (base / candidate).resolve()
328
+ if not resolved.is_dir():
329
+ fail("CFG_PATH", f"{where} does not exist or is not a directory: {raw}")
330
+ return resolved
331
+
332
+
333
+ def _compile_pattern(raw: object, where: str) -> re.Pattern[str]:
334
+ if not isinstance(raw, str) or not raw:
335
+ fail("CFG_SCHEMA", f"{where} must be a non-empty string")
336
+ try:
337
+ return re.compile(raw)
338
+ except re.error as exc:
339
+ fail("CFG_SCHEMA", f"{where} is not a valid regular expression: {exc}")
340
+
341
+
342
+ def _parse_anchor_rules(base: Path, raw: object) -> list[AnchorRule]:
343
+ if raw is None:
344
+ return []
345
+ if not isinstance(raw, list):
346
+ fail("CFG_SCHEMA", "check.anchors must be an array of tables")
347
+ rules: list[AnchorRule] = []
348
+ for index, item in enumerate(raw):
349
+ if not isinstance(item, dict):
350
+ fail("CFG_SCHEMA", f"check.anchors[{index}] must be a table")
351
+ _reject_unknown(
352
+ item,
353
+ {"files", "repo", "paths", "pattern", "require", "severity"},
354
+ f"check.anchors[{index}]",
355
+ )
356
+ files_raw = item.get("files")
357
+ if files_raw is None:
358
+ fail("CFG_SCHEMA", f"check.anchors[{index}].files is required")
359
+ patterns = _list_of_strings(files_raw, f"check.anchors[{index}].files")
360
+ if not patterns:
361
+ fail("CFG_SCHEMA", f"check.anchors[{index}].files must not be empty")
362
+ repo = _resolve_dir(base, item.get("repo"), f"check.anchors[{index}].repo")
363
+ paths = _list_of_strings(item.get("paths"), f"check.anchors[{index}].paths")
364
+ pattern = _compile_pattern(
365
+ item.get("pattern", r"external HEAD[==]\s*`?([0-9a-f]{7,40})`?"),
366
+ f"check.anchors[{index}].pattern",
367
+ )
368
+ if pattern.groups != 1:
369
+ fail("CFG_SCHEMA", f"check.anchors[{index}].pattern must contain exactly one capture group")
370
+ require = item.get("require", True)
371
+ if not isinstance(require, bool):
372
+ fail("CFG_SCHEMA", f"check.anchors[{index}].require must be a boolean")
373
+ severity = _enum(
374
+ item.get("severity"), {"warn", "error"}, f"check.anchors[{index}].severity", "error"
375
+ )
376
+ rules.append(
377
+ AnchorRule(
378
+ files=_expand_check_files(base, patterns, [], []),
379
+ repo=repo,
380
+ repo_rel=(
381
+ repo.relative_to(base).as_posix()
382
+ if repo == base or base in repo.parents
383
+ else str(repo)
384
+ ),
385
+ paths=paths,
386
+ pattern=pattern,
387
+ require=require,
388
+ severity=severity,
389
+ )
390
+ )
391
+ return rules
392
+
393
+
394
+ def _parse_forbidden_rules(base: Path, raw: object) -> list[ForbiddenRule]:
395
+ if raw is None:
396
+ return []
397
+ if not isinstance(raw, list):
398
+ fail("CFG_SCHEMA", "check.forbidden must be an array of tables")
399
+ rules: list[ForbiddenRule] = []
400
+ for index, item in enumerate(raw):
401
+ if not isinstance(item, dict):
402
+ fail("CFG_SCHEMA", f"check.forbidden[{index}] must be a table")
403
+ _reject_unknown(
404
+ item, {"files", "patterns", "allow", "exclude", "severity"}, f"check.forbidden[{index}]"
405
+ )
406
+ files_raw = item.get("files")
407
+ if files_raw is None:
408
+ fail("CFG_SCHEMA", f"check.forbidden[{index}].files is required")
409
+ file_patterns = _list_of_strings(files_raw, f"check.forbidden[{index}].files")
410
+ if not file_patterns:
411
+ fail("CFG_SCHEMA", f"check.forbidden[{index}].files must not be empty")
412
+ patterns_raw = _list_of_strings(item.get("patterns"), f"check.forbidden[{index}].patterns")
413
+ if not patterns_raw:
414
+ fail("CFG_SCHEMA", f"check.forbidden[{index}].patterns must not be empty")
415
+ patterns = [
416
+ _compile_pattern(value, f"check.forbidden[{index}].patterns")
417
+ for value in patterns_raw
418
+ ]
419
+ allow_raw = _list_of_strings(item.get("allow"), f"check.forbidden[{index}].allow")
420
+ exclude = _list_of_strings(item.get("exclude"), f"check.forbidden[{index}].exclude")
421
+ for value in exclude:
422
+ _check_pattern(value, f"check.forbidden[{index}].exclude")
423
+ allow: list[Path] = []
424
+ for value in allow_raw:
425
+ allow.append(_resolve_file(base, value, suffix=".md", where=f"check.forbidden[{index}].allow"))
426
+ severity = _enum(
427
+ item.get("severity"), {"warn", "error"}, f"check.forbidden[{index}].severity", "error"
428
+ )
429
+ rules.append(
430
+ ForbiddenRule(
431
+ files=_expand_check_files(base, file_patterns, [], exclude),
432
+ patterns=patterns,
433
+ allow=allow,
434
+ allow_rel=[_relative(base, path) for path in allow],
435
+ severity=severity,
436
+ )
437
+ )
438
+ return rules
439
+
440
+
441
+ def load_config(path: str | Path) -> Config:
442
+ config_path = Path(path).resolve()
443
+ data = _read_toml(config_path)
444
+ base = config_path.parent
445
+
446
+ _reject_unknown(data, {"version", "dialect", "facts", "blocks", "check"}, "config")
447
+
448
+ version = data.get("version")
449
+ if type(version) is not int or version != 1:
450
+ fail("CFG_VERSION", "version must be 1", path=str(config_path))
451
+
452
+ dialect = data.get("dialect")
453
+ if not isinstance(dialect, str) or dialect not in DIALECTS:
454
+ fail(
455
+ "CFG_DIALECT",
456
+ f"dialect must be one of: {', '.join(sorted(DIALECTS))}",
457
+ path=str(config_path),
458
+ )
459
+
460
+ facts_raw = data.get("facts", [])
461
+ blocks_raw = data.get("blocks", [])
462
+ if not isinstance(facts_raw, list) or not isinstance(blocks_raw, list):
463
+ fail("CFG_SCHEMA", "facts and blocks must be arrays of tables", path=str(config_path))
464
+ facts: dict[str, Fact] = {}
465
+ for index, item in enumerate(facts_raw):
466
+ if not isinstance(item, dict):
467
+ fail("CFG_SCHEMA", f"facts[{index}] must be a table")
468
+ _reject_unknown(item, {"id", "path"}, f"facts[{index}]")
469
+ fact_id = _validate_id(item.get("id"), f"facts[{index}].id")
470
+ if fact_id in facts:
471
+ fail("CFG_SCHEMA", f"duplicate facts id: {fact_id}")
472
+ fact_path = _resolve_fact(base, item.get("path"), where=f"facts[{index}].path")
473
+ facts[fact_id] = Fact(id=fact_id, path=fact_path)
474
+
475
+ blocks: list[Block] = []
476
+ block_ids: set[str] = set()
477
+ for index, item in enumerate(blocks_raw):
478
+ if not isinstance(item, dict):
479
+ fail("CFG_SCHEMA", f"blocks[{index}] must be a table")
480
+ _reject_unknown(item, {"id", "file", "facts", "template"}, f"blocks[{index}]")
481
+ block_id = _validate_id(item.get("id"), f"blocks[{index}].id")
482
+ if block_id in block_ids:
483
+ fail("CFG_SCHEMA", f"duplicate blocks id: {block_id}")
484
+ block_ids.add(block_id)
485
+ file_path = _resolve_file(base, item.get("file"), suffix=".md", where=f"blocks[{index}].file")
486
+ fact_id = item.get("facts")
487
+ if not isinstance(fact_id, str) or fact_id not in facts:
488
+ fail("CFG_SCHEMA", f"blocks[{index}].facts must reference a facts id")
489
+ template_path = _resolve_file(
490
+ base, item.get("template"), suffix=".md", where=f"blocks[{index}].template"
491
+ )
492
+ blocks.append(
493
+ Block(
494
+ id=block_id,
495
+ file=file_path,
496
+ file_rel=_relative(base, file_path),
497
+ fact_id=fact_id,
498
+ template=template_path,
499
+ template_rel=_relative(base, template_path),
500
+ )
501
+ )
502
+
503
+ check_raw = data.get("check", {})
504
+ if check_raw is None:
505
+ check_raw = {}
506
+ if not isinstance(check_raw, dict):
507
+ fail("CFG_SCHEMA", "check must be a table", path=str(config_path))
508
+ _reject_unknown(
509
+ check_raw, {"files", "exclude", "frontmatter", "freshness", "anchors", "forbidden"}, "check"
510
+ )
511
+ files_raw = check_raw.get("files")
512
+ patterns = None if files_raw is None else _list_of_strings(files_raw, "check.files")
513
+ exclude = _list_of_strings(check_raw.get("exclude"), "check.exclude")
514
+ for pattern in exclude:
515
+ _check_pattern(pattern, "check.exclude")
516
+
517
+ default_files: list[Path] = []
518
+ for block in blocks:
519
+ if block.file not in default_files:
520
+ default_files.append(block.file)
521
+ check_files = _expand_check_files(base, patterns, default_files, exclude)
522
+ frontmatter = (
523
+ _parse_frontmatter_rule(base, check_raw.get("frontmatter"))
524
+ if check_raw.get("frontmatter") is not None
525
+ else None
526
+ )
527
+ freshness = _parse_freshness_rules(base, check_raw.get("freshness"))
528
+ anchors = _parse_anchor_rules(base, check_raw.get("anchors"))
529
+ forbidden = _parse_forbidden_rules(base, check_raw.get("forbidden"))
530
+ if not facts and not blocks and frontmatter is None and not freshness and not anchors and not forbidden:
531
+ fail(
532
+ "CFG_SCHEMA",
533
+ "config needs at least one facts/block pair or a check rule",
534
+ path=str(config_path),
535
+ )
536
+
537
+ return Config(
538
+ path=config_path,
539
+ base=base,
540
+ dialect=dialect,
541
+ facts=facts,
542
+ blocks=blocks,
543
+ check_files=check_files,
544
+ exclude=exclude,
545
+ frontmatter=frontmatter,
546
+ freshness=freshness,
547
+ anchors=anchors,
548
+ forbidden=forbidden,
549
+ )
550
+
docstate/errors.py ADDED
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class DocstateError(Exception):
5
+ """A user-facing error with a stable code and optional location."""
6
+
7
+ def __init__(
8
+ self,
9
+ code: str,
10
+ message: str,
11
+ *,
12
+ path: str | None = None,
13
+ line: int | None = None,
14
+ ) -> None:
15
+ super().__init__(message)
16
+ self.code = code
17
+ self.message = message
18
+ self.path = path
19
+ self.line = line
20
+
21
+ def __str__(self) -> str:
22
+ location = self.path or ""
23
+ if self.path and self.line is not None:
24
+ location = f"{self.path}:{self.line}"
25
+ prefix = f"{location}: " if location else ""
26
+ return f"{prefix}error[{self.code}]: {self.message}"
27
+
28
+
29
+ def fail(
30
+ code: str,
31
+ message: str,
32
+ *,
33
+ path: str | None = None,
34
+ line: int | None = None,
35
+ ) -> None:
36
+ raise DocstateError(code, message, path=path, line=line)
37
+
docstate/facts.py ADDED
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from .config import Config, Fact
7
+ from .errors import fail
8
+
9
+
10
+ class _DuplicateKey(ValueError):
11
+ def __init__(self, key: str) -> None:
12
+ super().__init__(key)
13
+ self.key = key
14
+
15
+
16
+ def _pairs(pairs: list[tuple[str, object]]) -> dict:
17
+ result: dict = {}
18
+ for key, value in pairs:
19
+ if key in result:
20
+ raise _DuplicateKey(key)
21
+ result[key] = value
22
+ return result
23
+
24
+
25
+ def _reject_constant(value: str) -> None:
26
+ raise ValueError(f"non-finite number: {value}")
27
+
28
+
29
+ def load_fact(fact: Fact) -> dict:
30
+ try:
31
+ raw = fact.path.read_bytes()
32
+ except OSError as exc:
33
+ fail("FACTS_READ", f"cannot read facts: {exc}", path=str(fact.path))
34
+ try:
35
+ text = raw.decode("utf-8")
36
+ except UnicodeDecodeError as exc:
37
+ fail("FACTS_ENCODING", f"facts file is not UTF-8: {exc}", path=str(fact.path))
38
+ try:
39
+ data = json.loads(
40
+ text,
41
+ object_pairs_hook=_pairs,
42
+ parse_constant=_reject_constant,
43
+ )
44
+ except _DuplicateKey as exc:
45
+ fail("FACTS_DUPLICATE_KEY", f"duplicate JSON key: {exc.key}", path=str(fact.path))
46
+ except (json.JSONDecodeError, ValueError) as exc:
47
+ fail("FACTS_JSON", str(exc), path=str(fact.path))
48
+ if not isinstance(data, dict):
49
+ fail("FACTS_TYPE", "facts JSON must be an object at the top level", path=str(fact.path))
50
+ return data
51
+
52
+
53
+ def load_all_facts(config: Config) -> dict[str, dict]:
54
+ return {fact_id: load_fact(fact) for fact_id, fact in config.facts.items()}
55
+