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.
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass, field
5
+
6
+ KEY_RE = re.compile(r"^([A-Za-z0-9_-]+):\s*(.*)$")
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Frontmatter:
11
+ fields: dict[str, str] = field(default_factory=dict)
12
+ lines: dict[str, int] = field(default_factory=dict)
13
+ body: str = ""
14
+ has_frontmatter: bool = False
15
+ bom: bool = False
16
+
17
+ def value(self, key: str) -> str | None:
18
+ return self.fields.get(key)
19
+
20
+ def line(self, key: str) -> int:
21
+ return self.lines.get(key, 1)
22
+
23
+
24
+ def parse_frontmatter(text: str) -> Frontmatter:
25
+ """Parse a flat YAML frontmatter block without a YAML dependency.
26
+
27
+ Only scalar `key: value` lines are read. Lists, nested mappings, and
28
+ multi-line values are ignored; status, stage, and date fields are scalars.
29
+ """
30
+
31
+ bom = text.startswith("\ufeff")
32
+ if bom:
33
+ text = text[1:]
34
+ lines = text.splitlines(keepends=True)
35
+ if not lines or lines[0].strip() != "---":
36
+ return Frontmatter(body=text, bom=bom)
37
+ end = None
38
+ for index in range(1, len(lines)):
39
+ if lines[index].strip() in {"---", "..."}:
40
+ end = index
41
+ break
42
+ if end is None:
43
+ return Frontmatter(body=text, bom=bom)
44
+
45
+ fields: dict[str, str] = {}
46
+ numbers: dict[str, int] = {}
47
+ for index in range(1, end):
48
+ raw = lines[index].rstrip("\r\n")
49
+ match = KEY_RE.match(raw)
50
+ if not match:
51
+ continue
52
+ key, value = match.groups()
53
+ value = value.strip()
54
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
55
+ value = value[1:-1]
56
+ fields[key] = value
57
+ numbers[key] = index + 1
58
+ return Frontmatter(
59
+ fields=fields,
60
+ lines=numbers,
61
+ body="".join(lines[end + 1 :]),
62
+ has_frontmatter=True,
63
+ bom=bom,
64
+ )
docstate/render.py ADDED
@@ -0,0 +1,198 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import stat
5
+ import tempfile
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .config import Block, Config
10
+ from .errors import fail
11
+ from .facts import load_all_facts
12
+ from .scan import BlockSpan, parse_markers
13
+ from .template import RenderedTemplate, render_template
14
+
15
+
16
+ @dataclass
17
+ class BlockRender:
18
+ block: Block
19
+ span: BlockSpan
20
+ expected: RenderedTemplate
21
+
22
+
23
+ @dataclass
24
+ class PreparedFile:
25
+ path: Path
26
+ display: str
27
+ original_bytes: bytes
28
+ had_bom: bool
29
+ mode: int
30
+ old_text: str
31
+ new_text: str
32
+ block_renders: list[BlockRender]
33
+
34
+ @property
35
+ def changed(self) -> bool:
36
+ return self.new_text != self.old_text
37
+
38
+ @property
39
+ def new_bytes(self) -> bytes:
40
+ body = self.new_text.encode("utf-8")
41
+ return (b"\xef\xbb\xbf" + body) if self.had_bom else body
42
+
43
+
44
+ def _read_text(path: Path, display: str) -> tuple[bytes, bool, str, int]:
45
+ if path.is_symlink():
46
+ fail("FILE_SYMLINK", "refusing to read or write a symlink", path=display)
47
+ try:
48
+ raw = path.read_bytes()
49
+ mode = stat.S_IMODE(path.stat().st_mode)
50
+ except OSError as exc:
51
+ fail("FILE_READ", f"cannot read file: {exc}", path=display)
52
+ had_bom = raw.startswith(b"\xef\xbb\xbf")
53
+ body = raw[3:] if had_bom else raw
54
+ try:
55
+ text = body.decode("utf-8")
56
+ except UnicodeDecodeError as exc:
57
+ fail("FILE_ENCODING", f"file is not UTF-8: {exc}", path=display)
58
+ return raw, had_bom, text, mode
59
+
60
+
61
+ def _newline_for(text: str) -> str:
62
+ return "\r\n" if "\r\n" in text else "\n"
63
+
64
+
65
+ def _render_block(
66
+ block: Block,
67
+ span: BlockSpan,
68
+ facts: dict[str, dict],
69
+ cache: dict[Path, str],
70
+ dialect: str,
71
+ ) -> RenderedTemplate:
72
+ if block.template not in cache:
73
+ try:
74
+ cache[block.template] = block.template.read_text(encoding="utf-8-sig")
75
+ except OSError as exc:
76
+ fail("TPL_READ", f"cannot read template: {exc}", path=block.template_rel)
77
+ except UnicodeDecodeError as exc:
78
+ fail("TPL_READ", f"template is not UTF-8: {exc}", path=block.template_rel)
79
+ return render_template(cache[block.template], facts[block.fact_id], block.template_rel, dialect)
80
+
81
+
82
+ def prepare(config: Config) -> list[PreparedFile]:
83
+ facts = load_all_facts(config)
84
+ template_cache: dict[Path, str] = {}
85
+ blocks_by_file: dict[Path, list[Block]] = {}
86
+ for block in config.blocks:
87
+ blocks_by_file.setdefault(block.file, []).append(block)
88
+
89
+ prepared: list[PreparedFile] = []
90
+ for file_path, blocks in blocks_by_file.items():
91
+ display = file_path.relative_to(config.base).as_posix()
92
+ raw, had_bom, old_text, mode = _read_text(file_path, display)
93
+ spans = parse_markers(old_text, display)
94
+ by_id = {span.id: span for span in spans}
95
+ configured = {block.id for block in blocks}
96
+ unknown = set(by_id) - configured
97
+ if unknown:
98
+ fail("MARKER_UNKNOWN", f"unconfigured block id(s): {', '.join(sorted(unknown))}", path=display)
99
+
100
+ block_renders: list[BlockRender] = []
101
+ for block in blocks:
102
+ span = by_id.get(block.id)
103
+ if span is None:
104
+ fail("MARKER_MISSING", f"missing block: {block.id}", path=display)
105
+ expected = _render_block(block, span, facts, template_cache, config.dialect)
106
+ block_renders.append(BlockRender(block=block, span=span, expected=expected))
107
+
108
+ newline = _newline_for(old_text)
109
+ lines = old_text.splitlines(keepends=True)
110
+ for item in sorted(block_renders, key=lambda entry: entry.span.begin_index, reverse=True):
111
+ content = item.expected.text
112
+ if content:
113
+ generated = [line.replace("\n", newline) for line in content.splitlines(keepends=True)]
114
+ else:
115
+ generated = []
116
+ lines[item.span.begin_index + 1 : item.span.end_index] = generated
117
+ new_text = "".join(lines)
118
+ prepared.append(
119
+ PreparedFile(
120
+ path=file_path,
121
+ display=display,
122
+ original_bytes=raw,
123
+ had_bom=had_bom,
124
+ mode=mode,
125
+ old_text=old_text,
126
+ new_text=new_text,
127
+ block_renders=block_renders,
128
+ )
129
+ )
130
+ return prepared
131
+
132
+
133
+ def _write_temp(path: Path, data: bytes, mode: int) -> Path:
134
+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.docstate-", dir=str(path.parent))
135
+ temp_path = Path(temp_name)
136
+ try:
137
+ with os.fdopen(fd, "wb") as stream:
138
+ stream.write(data)
139
+ stream.flush()
140
+ os.fsync(stream.fileno())
141
+ os.chmod(temp_path, mode)
142
+ return temp_path
143
+ except OSError:
144
+ temp_path.unlink(missing_ok=True)
145
+ raise
146
+
147
+
148
+ def _replace_bytes(path: Path, data: bytes, mode: int) -> None:
149
+ temp_path = _write_temp(path, data, mode)
150
+ os.replace(temp_path, path)
151
+
152
+
153
+ def write_prepared(prepared: list[PreparedFile]) -> list[Path]:
154
+ changes = [item for item in prepared if item.changed]
155
+ if not changes:
156
+ return []
157
+
158
+ temps: list[tuple[PreparedFile, Path]] = []
159
+ try:
160
+ for item in changes:
161
+ temp_path = _write_temp(item.path, item.new_bytes, item.mode)
162
+ temps.append((item, temp_path))
163
+ except OSError as exc:
164
+ for _, temp_path in temps:
165
+ temp_path.unlink(missing_ok=True)
166
+ fail("FILE_WRITE", f"cannot write temporary file: {exc}")
167
+
168
+ replaced: list[PreparedFile] = []
169
+ try:
170
+ while temps:
171
+ item, temp_path = temps[0]
172
+ os.replace(temp_path, item.path)
173
+ replaced.append(item)
174
+ temps.pop(0)
175
+ except OSError as exc:
176
+ for _, temp_path in temps:
177
+ temp_path.unlink(missing_ok=True)
178
+ failed_restores: list[str] = []
179
+ for item in replaced:
180
+ try:
181
+ _replace_bytes(item.path, item.original_bytes, item.mode)
182
+ except OSError:
183
+ failed_restores.append(item.display)
184
+ if failed_restores:
185
+ fail(
186
+ "PARTIAL_WRITE",
187
+ f"replace failed: {exc}; rollback failed for: {', '.join(failed_restores)}",
188
+ )
189
+ fail("FILE_WRITE", f"replace failed and was rolled back: {exc}")
190
+ return [item.path for item in changes]
191
+
192
+
193
+ def render_project(config: Config) -> tuple[list[Path], int]:
194
+ prepared = prepare(config)
195
+ changed = write_prepared(prepared)
196
+ block_count = sum(len(item.block_renders) for item in prepared)
197
+ return changed, block_count
198
+
docstate/scan.py ADDED
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import Iterator
6
+
7
+ from .errors import fail
8
+
9
+ ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}"
10
+ BEGIN_RE = re.compile(rf"^<!-- BEGIN GENERATED: ({ID_PATTERN}) -->$")
11
+ END_RE = re.compile(rf"^<!-- END GENERATED: ({ID_PATTERN}) -->$")
12
+ FENCE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class BlockSpan:
17
+ id: str
18
+ begin_index: int
19
+ end_index: int
20
+ begin_line: int
21
+ end_line: int
22
+ content_start_line: int
23
+ content_lines: list[str]
24
+
25
+
26
+ def _fence_close_re(char: str, length: int) -> re.Pattern[str]:
27
+ return re.compile(rf"^ {{0,3}}{re.escape(char)}{{{length},}}\s*$")
28
+
29
+
30
+ def iter_scan_lines(lines: list[str]) -> Iterator[tuple[int, str]]:
31
+ """Yield 1-based line numbers outside YAML frontmatter and fenced code."""
32
+
33
+ in_frontmatter = bool(lines) and lines[0] == "---"
34
+ fence_char: str | None = None
35
+ fence_length = 0
36
+
37
+ for index, line in enumerate(lines, 1):
38
+ if index == 1 and in_frontmatter:
39
+ continue
40
+ if in_frontmatter:
41
+ if line in {"---", "..."}:
42
+ in_frontmatter = False
43
+ continue
44
+ if fence_char is not None:
45
+ if _fence_close_re(fence_char, fence_length).match(line):
46
+ fence_char = None
47
+ continue
48
+ fence = FENCE_RE.match(line)
49
+ if fence:
50
+ fence_char = fence.group(1)[0]
51
+ fence_length = len(fence.group(1))
52
+ continue
53
+ yield index, line
54
+
55
+
56
+ def parse_markers(text: str, path: str) -> list[BlockSpan]:
57
+ lines = text.splitlines()
58
+ spans: list[BlockSpan] = []
59
+ open_id: str | None = None
60
+ open_index = 0
61
+ open_line = 0
62
+ seen: set[str] = set()
63
+
64
+ for index, line in iter_scan_lines(lines):
65
+ begin = BEGIN_RE.match(line)
66
+ if begin:
67
+ if open_id is not None:
68
+ fail("MARKER_NESTED", f"nested block: {begin.group(1)}", path=path, line=index)
69
+ marker_id = begin.group(1)
70
+ if marker_id in seen:
71
+ fail("MARKER_DUPLICATE", f"duplicate block id: {marker_id}", path=path, line=index)
72
+ open_id = marker_id
73
+ open_index = index - 1
74
+ open_line = index
75
+ continue
76
+
77
+ end = END_RE.match(line)
78
+ if end:
79
+ if open_id is None:
80
+ fail("MARKER_UNPAIRED", f"end without begin: {end.group(1)}", path=path, line=index)
81
+ if end.group(1) != open_id:
82
+ fail(
83
+ "MARKER_UNPAIRED",
84
+ f"end id {end.group(1)} does not match begin id {open_id}",
85
+ path=path,
86
+ line=index,
87
+ )
88
+ seen.add(open_id)
89
+ spans.append(
90
+ BlockSpan(
91
+ id=open_id,
92
+ begin_index=open_index,
93
+ end_index=index - 1,
94
+ begin_line=open_line,
95
+ end_line=index,
96
+ content_start_line=open_line + 1,
97
+ content_lines=lines[open_index + 1 : index - 1],
98
+ )
99
+ )
100
+ open_id = None
101
+
102
+ if open_id is not None:
103
+ fail("MARKER_UNPAIRED", f"missing end marker for {open_id}", path=path, line=open_line)
104
+ return spans
105
+
docstate/template.py ADDED
@@ -0,0 +1,138 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ from .errors import fail
8
+
9
+ PLACEHOLDER_RE = re.compile(
10
+ r"\{\{\s*([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)\s*(?::\s*([^{}]+?))?\s*\}\}"
11
+ )
12
+ FOR_RE = re.compile(
13
+ r"^[ \t]*\{%[ \t]*for[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]+in[ \t]+"
14
+ r"([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)[ \t]*%\}[ \t]*$"
15
+ )
16
+ ENDFOR_RE = re.compile(r"^[ \t]*\{%[ \t]*endfor[ \t]*%\}[ \t]*$")
17
+ TAG_RE = re.compile(r"\{%")
18
+ DIALECTS = {"scalar-v1", "scalar-v2"}
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class RenderedTemplate:
23
+ text: str
24
+ lines: list[str]
25
+
26
+
27
+ def _resolve(data: dict[str, Any], path: str, template_path: str, line: int) -> Any:
28
+ current: Any = data
29
+ for part in path.split("."):
30
+ if not isinstance(current, dict) or part not in current:
31
+ fail("VALUE_MISSING", f"missing value: {path}", path=template_path, line=line)
32
+ current = current[part]
33
+ return current
34
+
35
+
36
+ def _lookup(data: dict[str, Any], path: str, template_path: str, line: int) -> Any:
37
+ current = _resolve(data, path, template_path, line)
38
+ if current is None:
39
+ fail("VALUE_NULL", f"value is null: {path}", path=template_path, line=line)
40
+ if isinstance(current, (list, dict)):
41
+ fail("VALUE_NOT_SCALAR", f"value is not scalar: {path}", path=template_path, line=line)
42
+ return current
43
+
44
+
45
+ def _format_value(value: Any, spec: str | None, path: str, template_path: str, line: int) -> str:
46
+ if spec is not None:
47
+ try:
48
+ return format(value, spec.strip())
49
+ except (ValueError, TypeError) as exc:
50
+ fail("FORMAT_INVALID", f"cannot format {path}: {exc}", path=template_path, line=line)
51
+ if isinstance(value, bool):
52
+ return "true" if value else "false"
53
+ if isinstance(value, (int, float, str)):
54
+ return str(value)
55
+ fail("VALUE_NOT_SCALAR", f"value is not scalar: {path}", path=template_path, line=line)
56
+
57
+
58
+ def _render_line(line: str, data: dict[str, Any], template_path: str, line_number: int) -> str:
59
+ matches = list(PLACEHOLDER_RE.finditer(line))
60
+ if line.count("{{") != len(matches):
61
+ fail("TPL_PLACEHOLDER", "unmatched '{{' in template", path=template_path, line=line_number)
62
+ parts: list[str] = []
63
+ cursor = 0
64
+ for match in matches:
65
+ parts.append(line[cursor : match.start()])
66
+ value = _lookup(data, match.group(1), template_path, line_number)
67
+ parts.append(_format_value(value, match.group(2), match.group(1), template_path, line_number))
68
+ cursor = match.end()
69
+ parts.append(line[cursor:])
70
+ return "".join(parts)
71
+
72
+
73
+ def _render_lines(
74
+ lines: list[str],
75
+ data: dict[str, Any],
76
+ template_path: str,
77
+ dialect: str,
78
+ *,
79
+ depth: int = 0,
80
+ offset: int = 0,
81
+ ) -> list[str]:
82
+ output: list[str] = []
83
+ index = 0
84
+ while index < len(lines):
85
+ line = lines[index]
86
+ line_number = offset + index + 1
87
+ loop = FOR_RE.match(line)
88
+ if loop:
89
+ if dialect != "scalar-v2":
90
+ fail("LOOP_UNSUPPORTED", "loop tags require dialect scalar-v2", path=template_path, line=line_number)
91
+ if depth:
92
+ fail("LOOP_NESTED", "nested loops are not supported", path=template_path, line=line_number)
93
+ variable, path = loop.groups()
94
+ end = None
95
+ for candidate in range(index + 1, len(lines)):
96
+ if ENDFOR_RE.match(lines[candidate]):
97
+ end = candidate
98
+ break
99
+ if FOR_RE.match(lines[candidate]):
100
+ fail("LOOP_NESTED", "nested loops are not supported", path=template_path, line=offset + candidate + 1)
101
+ if end is None:
102
+ fail("LOOP_UNPAIRED", f"missing endfor for {variable}", path=template_path, line=line_number)
103
+ value = _resolve(data, path, template_path, line_number)
104
+ if not isinstance(value, list):
105
+ fail("LOOP_NOT_LIST", f"value is not a list: {path}", path=template_path, line=line_number)
106
+ body = lines[index + 1 : end]
107
+ for item in value:
108
+ scoped = dict(data)
109
+ scoped[variable] = item
110
+ output.extend(_render_lines(body, scoped, template_path, dialect, depth=depth + 1, offset=offset + index + 1))
111
+ index = end + 1
112
+ continue
113
+ if ENDFOR_RE.match(line):
114
+ fail("LOOP_UNPAIRED", "endfor without for", path=template_path, line=line_number)
115
+ if TAG_RE.search(line):
116
+ fail("LOOP_SYNTAX", "loop tags must occupy a whole line", path=template_path, line=line_number)
117
+ output.append(_render_line(line, data, template_path, line_number))
118
+ index += 1
119
+ return output
120
+
121
+
122
+ def render_template(
123
+ text: str,
124
+ data: dict[str, Any],
125
+ template_path: str,
126
+ dialect: str = "scalar-v1",
127
+ ) -> RenderedTemplate:
128
+ normalized = text.replace("\r\n", "\n").replace("\r", "\n")
129
+ if dialect not in DIALECTS:
130
+ fail("CFG_DIALECT", f"unknown dialect: {dialect}", path=template_path)
131
+ if dialect == "scalar-v1" and TAG_RE.search(normalized):
132
+ fail("LOOP_UNSUPPORTED", "loop tags require dialect scalar-v2", path=template_path)
133
+ lines = normalized.split("\n")
134
+ output = "\n".join(_render_lines(lines, data, template_path, dialect)).rstrip("\n")
135
+
136
+ if output:
137
+ output += "\n"
138
+ return RenderedTemplate(text=output, lines=output.splitlines())