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/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """docstate: keep Markdown status blocks in sync with JSON facts."""
2
+
3
+ __version__ = "0.2.3"
4
+
docstate/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
4
+
docstate/check.py ADDED
@@ -0,0 +1,510 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import subprocess
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from urllib.parse import unquote
8
+
9
+ from .config import AnchorRule, Config, ForbiddenRule, FreshnessRule, FrontmatterRule
10
+ from .errors import fail
11
+ from .frontmatter import parse_frontmatter
12
+ from .render import BlockRender, PreparedFile, prepare
13
+ from .scan import iter_scan_lines
14
+
15
+ LINK_RE = re.compile(r"!?\[[^\]]*\]\(([^)]*)\)")
16
+ INLINE_CODE_RE = re.compile(r"`[^`]*`")
17
+ SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
18
+ DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
19
+ CHANGELOG_DATE_RE = re.compile(r"^#{1,6}\s.*?(\d{4}-\d{2}-\d{2})", re.MULTILINE)
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Finding:
24
+ kind: str
25
+ path: str
26
+ line: int
27
+ block_id: str = ""
28
+ expected: str = ""
29
+ actual: str = ""
30
+ target: str = ""
31
+ severity: str = "error"
32
+ field: str = ""
33
+ message: str = ""
34
+
35
+ def format(self) -> str:
36
+ if self.kind == "drift":
37
+ return (
38
+ f'{self.path}:{self.line}: drift[{self.block_id}]: '
39
+ f'expected={self.expected!r}; actual={self.actual!r}'
40
+ )
41
+ if self.kind == "link":
42
+ return f"{self.path}:{self.line}: link: broken target {self.target}"
43
+ return f"{self.path}:{self.line}: {self.severity}[{self.kind}:{self.field}]: {self.message}"
44
+
45
+ def as_dict(self) -> dict:
46
+ return {
47
+ "severity": self.severity,
48
+ "kind": self.kind,
49
+ "path": self.path,
50
+ "line": self.line,
51
+ "field": self.field,
52
+ "message": self.message,
53
+ "block_id": self.block_id,
54
+ "expected": self.expected,
55
+ "actual": self.actual,
56
+ "target": self.target,
57
+ }
58
+
59
+
60
+ def _compare_block(item: BlockRender, display: str) -> Finding | None:
61
+ expected = item.expected.lines
62
+ actual = item.span.content_lines
63
+ if expected == actual:
64
+ return None
65
+ limit = min(len(expected), len(actual))
66
+ for index in range(limit):
67
+ if expected[index] != actual[index]:
68
+ return Finding(
69
+ kind="drift",
70
+ path=display,
71
+ line=item.span.content_start_line + index,
72
+ block_id=item.block.id,
73
+ expected=expected[index],
74
+ actual=actual[index],
75
+ )
76
+ if len(expected) > len(actual):
77
+ return Finding(
78
+ kind="drift",
79
+ path=display,
80
+ line=item.span.end_line,
81
+ block_id=item.block.id,
82
+ expected=expected[limit],
83
+ actual="",
84
+ )
85
+ return Finding(
86
+ kind="drift",
87
+ path=display,
88
+ line=item.span.content_start_line + limit,
89
+ block_id=item.block.id,
90
+ expected="",
91
+ actual=actual[limit],
92
+ )
93
+
94
+
95
+ def _link_target(raw: str) -> str:
96
+ value = raw.strip()
97
+ if not value:
98
+ return ""
99
+ if value.startswith("<"):
100
+ end = value.find(">")
101
+ if end == -1:
102
+ return ""
103
+ value = value[1:end]
104
+ else:
105
+ value = value.split()[0]
106
+ value = value.split("#", 1)[0].split("?", 1)[0]
107
+ return unquote(value)
108
+
109
+
110
+ def _scan_links(path: Path, display: str) -> list[Finding]:
111
+ try:
112
+ text = path.read_text(encoding="utf-8-sig")
113
+ except OSError as exc:
114
+ fail("FILE_READ", f"cannot read link file: {exc}", path=display)
115
+ except UnicodeDecodeError as exc:
116
+ fail("FILE_ENCODING", f"link file is not UTF-8: {exc}", path=display)
117
+
118
+ findings: list[Finding] = []
119
+ for line_number, line in iter_scan_lines(text.splitlines()):
120
+ cleaned = INLINE_CODE_RE.sub("", line)
121
+ for match in LINK_RE.finditer(cleaned):
122
+ target = _link_target(match.group(1))
123
+ if not target or target.startswith(("#", "/", "//")) or SCHEME_RE.match(target):
124
+ continue
125
+ if not (path.parent / target).exists():
126
+ findings.append(
127
+ Finding(kind="link", path=display, line=line_number, target=target)
128
+ )
129
+ return findings
130
+
131
+
132
+ def _severity(level: str) -> str:
133
+ return "warning" if level == "warn" else "error"
134
+
135
+
136
+ def _read_frontmatter(path: Path, display: str):
137
+ try:
138
+ text = path.read_text(encoding="utf-8")
139
+ except OSError as exc:
140
+ fail("FILE_READ", f"cannot read frontmatter file: {exc}", path=display)
141
+ except UnicodeDecodeError as exc:
142
+ fail("FILE_ENCODING", f"frontmatter file is not UTF-8: {exc}", path=display)
143
+ return parse_frontmatter(text)
144
+
145
+
146
+ def _frontmatter_findings(rule: FrontmatterRule, base: Path) -> list[Finding]:
147
+ findings: list[Finding] = []
148
+ cache: dict[Path, tuple[object, str]] = {}
149
+
150
+ def load(path: Path):
151
+ if path not in cache:
152
+ display = path.relative_to(base).as_posix()
153
+ cache[path] = (_read_frontmatter(path, display), display)
154
+ return cache[path]
155
+
156
+ for path in rule.files:
157
+ frontmatter, display = load(path)
158
+ if frontmatter.bom and rule.bom != "ignore":
159
+ findings.append(
160
+ Finding(
161
+ kind="frontmatter",
162
+ path=display,
163
+ line=1,
164
+ field="bom",
165
+ severity=_severity(rule.bom),
166
+ message="file starts with a UTF-8 BOM",
167
+ )
168
+ )
169
+ if not frontmatter.has_frontmatter:
170
+ if rule.require:
171
+ findings.append(
172
+ Finding(
173
+ kind="frontmatter",
174
+ path=display,
175
+ line=1,
176
+ field="frontmatter",
177
+ message="no YAML frontmatter",
178
+ )
179
+ )
180
+ continue
181
+ for name in rule.require:
182
+ if not frontmatter.value(name):
183
+ findings.append(
184
+ Finding(
185
+ kind="frontmatter",
186
+ path=display,
187
+ line=frontmatter.line(name),
188
+ field=name,
189
+ message=f"missing required field: {name}",
190
+ )
191
+ )
192
+ status = frontmatter.value(rule.status_field)
193
+ if rule.status_values and status is not None and status not in rule.status_values:
194
+ findings.append(
195
+ Finding(
196
+ kind="frontmatter",
197
+ path=display,
198
+ line=frontmatter.line(rule.status_field),
199
+ field=rule.status_field,
200
+ message=f"invalid value {status!r}; allowed: {', '.join(rule.status_values)}",
201
+ )
202
+ )
203
+
204
+ for owner in rule.owners:
205
+ owner_fm, owner_display = load(owner.owner)
206
+ owner_value = owner_fm.value(owner.field)
207
+ if owner_value is None:
208
+ findings.append(
209
+ Finding(
210
+ kind="frontmatter",
211
+ path=owner_display,
212
+ line=owner_fm.line(owner.field),
213
+ field=owner.field,
214
+ message=f"owner is missing field: {owner.field}",
215
+ )
216
+ )
217
+ continue
218
+ for path in owner.applies_to:
219
+ if path == owner.owner:
220
+ continue
221
+ frontmatter, display = load(path)
222
+ value = frontmatter.value(owner.field)
223
+ if value is not None and value != owner_value:
224
+ findings.append(
225
+ Finding(
226
+ kind="frontmatter",
227
+ path=display,
228
+ line=frontmatter.line(owner.field),
229
+ field=owner.field,
230
+ message=f"{value!r} does not match owner {owner_display} ({owner_value!r})",
231
+ )
232
+ )
233
+ return findings
234
+
235
+
236
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess[str]:
237
+ return subprocess.run(
238
+ ["git", "-C", str(root), *args],
239
+ capture_output=True,
240
+ text=True,
241
+ check=False,
242
+ )
243
+
244
+
245
+ def _repo_root(base: Path) -> Path | None:
246
+ result = _git(base, "rev-parse", "--show-toplevel")
247
+ if result.returncode != 0:
248
+ return None
249
+ return Path(result.stdout.strip())
250
+
251
+
252
+ def _git_show(root: Path, revision: str, relative: str) -> str | None:
253
+ result = _git(root, "show", f"{revision}:{relative}")
254
+ return result.stdout if result.returncode == 0 else None
255
+
256
+
257
+ def _git_dirty(root: Path, relative: str) -> bool | None:
258
+ result = _git(root, "diff", "--quiet", "HEAD", "--", relative)
259
+ if result.returncode not in (0, 1):
260
+ return None
261
+ return result.returncode == 1
262
+
263
+
264
+ def _status_findings(rule: FrontmatterRule, base: Path) -> list[Finding]:
265
+ if rule.status_review == "off":
266
+ return []
267
+ severity = _severity(rule.status_review)
268
+ root = _repo_root(base)
269
+ if root is None:
270
+ return [
271
+ Finding(
272
+ kind="status",
273
+ path=".",
274
+ line=1,
275
+ field=rule.status_field,
276
+ severity=severity,
277
+ message="status_review is enabled but this directory is not a git repository",
278
+ )
279
+ ]
280
+
281
+ findings: list[Finding] = []
282
+ for path in rule.files:
283
+ display = path.relative_to(base).as_posix()
284
+ current = _read_frontmatter(path, display)
285
+ if not current.has_frontmatter:
286
+ continue
287
+ try:
288
+ relative = path.relative_to(root).as_posix()
289
+ except ValueError:
290
+ continue
291
+ head_text = _git_show(root, "HEAD", relative)
292
+ if head_text is None:
293
+ continue
294
+ dirty = _git_dirty(root, relative)
295
+ if dirty is None:
296
+ continue
297
+ if dirty:
298
+ previous = parse_frontmatter(head_text)
299
+ where = "working tree"
300
+ else:
301
+ previous_text = _git_show(root, "HEAD~1", relative)
302
+ if previous_text is None:
303
+ continue
304
+ previous = parse_frontmatter(previous_text)
305
+ where = "last commit"
306
+ if not previous.has_frontmatter:
307
+ continue
308
+ body_changed = current.body != previous.body
309
+ status_changed = current.value(rule.status_field) != previous.value(rule.status_field)
310
+ updated_changed = current.value(rule.updated_field) != previous.value(rule.updated_field)
311
+ line = current.line(rule.status_field)
312
+ if body_changed and not status_changed and not updated_changed:
313
+ findings.append(
314
+ Finding(
315
+ kind="status",
316
+ path=display,
317
+ line=line,
318
+ field=rule.status_field,
319
+ severity=severity,
320
+ message=f"body changed in {where} but {rule.status_field} and {rule.updated_field} did not change",
321
+ )
322
+ )
323
+ if status_changed and not updated_changed:
324
+ findings.append(
325
+ Finding(
326
+ kind="status",
327
+ path=display,
328
+ line=line,
329
+ field=rule.updated_field,
330
+ message=f"{rule.status_field} changed but {rule.updated_field} did not",
331
+ )
332
+ )
333
+ return findings
334
+
335
+
336
+ def _freshness_findings(rule: FreshnessRule) -> list[Finding]:
337
+ frontmatter = _read_frontmatter(rule.doc, rule.doc_rel)
338
+ value = frontmatter.value(rule.field)
339
+ if value is None:
340
+ return [
341
+ Finding(
342
+ kind="freshness",
343
+ path=rule.doc_rel,
344
+ line=1,
345
+ field=rule.field,
346
+ message=f"missing field: {rule.field}",
347
+ )
348
+ ]
349
+ if not DATE_RE.match(value):
350
+ return [
351
+ Finding(
352
+ kind="freshness",
353
+ path=rule.doc_rel,
354
+ line=frontmatter.line(rule.field),
355
+ field=rule.field,
356
+ message=f"date must be YYYY-MM-DD: {value!r}",
357
+ )
358
+ ]
359
+ try:
360
+ text = rule.changelog.read_text(encoding="utf-8-sig")
361
+ except OSError as exc:
362
+ fail("FILE_READ", f"cannot read changelog: {exc}", path=rule.changelog_rel)
363
+ except UnicodeDecodeError as exc:
364
+ fail("FILE_ENCODING", f"changelog is not UTF-8: {exc}", path=rule.changelog_rel)
365
+ dates = CHANGELOG_DATE_RE.findall(text)
366
+ if not dates:
367
+ return [
368
+ Finding(
369
+ kind="freshness",
370
+ path=rule.changelog_rel,
371
+ line=1,
372
+ field=rule.field,
373
+ message="no dated heading found in changelog",
374
+ )
375
+ ]
376
+ newest = max(dates)
377
+ if value < newest:
378
+ return [
379
+ Finding(
380
+ kind="freshness",
381
+ path=rule.doc_rel,
382
+ line=frontmatter.line(rule.field),
383
+ field=rule.field,
384
+ message=f"{value} is older than changelog {newest}",
385
+ )
386
+ ]
387
+ return []
388
+
389
+
390
+ def _anchor_findings(rule: AnchorRule, base: Path) -> list[Finding]:
391
+ findings: list[Finding] = []
392
+ severity = _severity(rule.severity)
393
+ for path in rule.files:
394
+ display = path.relative_to(base).as_posix()
395
+ try:
396
+ text = path.read_text(encoding="utf-8-sig")
397
+ except OSError as exc:
398
+ fail("FILE_READ", f"cannot read anchor file: {exc}", path=display)
399
+ except UnicodeDecodeError as exc:
400
+ fail("FILE_ENCODING", f"anchor file is not UTF-8: {exc}", path=display)
401
+ matches = list(rule.pattern.finditer(text))
402
+ if not matches:
403
+ if rule.require:
404
+ findings.append(
405
+ Finding(
406
+ kind="anchor",
407
+ path=display,
408
+ line=1,
409
+ field="external HEAD",
410
+ severity=severity,
411
+ message="no anchor found",
412
+ )
413
+ )
414
+ continue
415
+ anchors = [match.group(1) for match in matches]
416
+ target_result = _git(rule.repo, "log", "-1", "--format=%H", "--", *rule.paths)
417
+ target = target_result.stdout.strip()
418
+ if target_result.returncode != 0 or not target:
419
+ findings.append(
420
+ Finding(
421
+ kind="anchor",
422
+ path=display,
423
+ line=1,
424
+ field="external HEAD",
425
+ severity=severity,
426
+ message="cannot resolve the repository HEAD",
427
+ )
428
+ )
429
+ continue
430
+ if any(target.startswith(anchor) or anchor.startswith(target) for anchor in anchors):
431
+ continue
432
+ last = anchors[-1]
433
+ behind_result = _git(rule.repo, "rev-list", "--count", f"{last}..HEAD", "--", *rule.paths)
434
+ behind = behind_result.stdout.strip() if behind_result.returncode == 0 else ""
435
+ line = text.count("\n", 0, matches[-1].start()) + 1
436
+ message = f"anchor {last} does not match HEAD {target[:12]}"
437
+ if behind:
438
+ message += f" (behind {behind})"
439
+ findings.append(
440
+ Finding(
441
+ kind="anchor",
442
+ path=display,
443
+ line=line,
444
+ field="external HEAD",
445
+ severity=severity,
446
+ message=message,
447
+ )
448
+ )
449
+ return findings
450
+
451
+
452
+ def _forbidden_findings(rule: ForbiddenRule, base: Path) -> list[Finding]:
453
+ findings: list[Finding] = []
454
+ severity = _severity(rule.severity)
455
+ allow = set(rule.allow)
456
+ for path in rule.files:
457
+ if path in allow:
458
+ continue
459
+ display = path.relative_to(base).as_posix()
460
+ try:
461
+ text = path.read_text(encoding="utf-8-sig")
462
+ except OSError as exc:
463
+ fail("FILE_READ", f"cannot read forbidden-scan file: {exc}", path=display)
464
+ except UnicodeDecodeError as exc:
465
+ fail("FILE_ENCODING", f"forbidden-scan file is not UTF-8: {exc}", path=display)
466
+ for line_number, line in enumerate(text.splitlines(), 1):
467
+ for pattern in rule.patterns:
468
+ if pattern.search(line):
469
+ findings.append(
470
+ Finding(
471
+ kind="forbidden",
472
+ path=display,
473
+ line=line_number,
474
+ field=pattern.pattern,
475
+ severity=severity,
476
+ message=f"forbidden phrase {pattern.pattern!r}",
477
+ )
478
+ )
479
+ break
480
+ return findings
481
+
482
+
483
+ def check_project(config: Config) -> tuple[list[Finding], int, int]:
484
+ prepared: list[PreparedFile] = prepare(config)
485
+ findings: list[Finding] = []
486
+ block_count = 0
487
+ for item in prepared:
488
+ for block_render in item.block_renders:
489
+ block_count += 1
490
+ finding = _compare_block(block_render, item.display)
491
+ if finding:
492
+ findings.append(finding)
493
+
494
+ for path in config.check_files:
495
+ display = path.relative_to(config.base).as_posix()
496
+ findings.extend(_scan_links(path, display))
497
+
498
+ if config.frontmatter:
499
+ findings.extend(_frontmatter_findings(config.frontmatter, config.base))
500
+ findings.extend(_status_findings(config.frontmatter, config.base))
501
+ for rule in config.freshness:
502
+ findings.extend(_freshness_findings(rule))
503
+ for rule in config.anchors:
504
+ findings.extend(_anchor_findings(rule, config.base))
505
+ for rule in config.forbidden:
506
+ findings.extend(_forbidden_findings(rule, config.base))
507
+
508
+ findings.sort(key=lambda item: (item.path, item.line, item.block_id))
509
+ return findings, len(prepared), block_count
510
+
docstate/cli.py ADDED
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from importlib import metadata
7
+
8
+ from .check import check_project
9
+ from .config import load_config
10
+ from .errors import DocstateError
11
+ from .render import render_project
12
+
13
+
14
+ def _version() -> str:
15
+ try:
16
+ return metadata.version("docstate")
17
+ except metadata.PackageNotFoundError:
18
+ from . import __version__
19
+
20
+ return __version__
21
+
22
+
23
+ def _parser() -> argparse.ArgumentParser:
24
+ parser = argparse.ArgumentParser(prog="docstate")
25
+ parser.add_argument("--version", action="store_true", help="print the package version")
26
+ subparsers = parser.add_subparsers(dest="command")
27
+
28
+ render_parser = subparsers.add_parser("render", help="rewrite generated blocks")
29
+ render_parser.add_argument("--config", default="docstate.toml", help="path to docstate.toml")
30
+
31
+ check_parser = subparsers.add_parser("check", help="check blocks and relative links")
32
+ check_parser.add_argument("--config", default="docstate.toml", help="path to docstate.toml")
33
+ check_parser.add_argument("--strict", action="store_true", help="exit 1 when findings exist")
34
+ check_parser.add_argument("--json", action="store_true", help="print findings as JSON")
35
+ return parser
36
+
37
+
38
+ def main(argv: list[str] | None = None) -> int:
39
+ parser = _parser()
40
+ args = parser.parse_args(argv)
41
+ if args.version:
42
+ print(_version())
43
+ return 0
44
+ if not args.command:
45
+ parser.print_help()
46
+ return 2
47
+
48
+ try:
49
+ config = load_config(args.config)
50
+ if args.command == "render":
51
+ changed, blocks = render_project(config)
52
+ print(f"render: {len(changed)} files changed, {blocks} blocks")
53
+ return 0
54
+
55
+ findings, files_count, blocks = check_project(config)
56
+ if args.json:
57
+ payload = {
58
+ "files": files_count,
59
+ "blocks": blocks,
60
+ "counts": {
61
+ "error": sum(1 for finding in findings if finding.severity == "error"),
62
+ "warning": sum(1 for finding in findings if finding.severity == "warning"),
63
+ },
64
+ "findings": [finding.as_dict() for finding in findings],
65
+ }
66
+ print(json.dumps(payload, ensure_ascii=False))
67
+ if args.strict and payload["counts"]["error"]:
68
+ return 1
69
+ return 0
70
+ for finding in findings:
71
+ print(finding.format())
72
+ print(f"check: {files_count} files, {blocks} blocks; {len(findings)} findings")
73
+ if args.strict and any(finding.severity == "error" for finding in findings):
74
+ return 1
75
+ return 0
76
+ except DocstateError as exc:
77
+ print(f"error: {exc}", file=sys.stderr)
78
+ return 2
79
+
80
+
81
+ if __name__ == "__main__":
82
+ raise SystemExit(main())