wolfdocx 0.1.0__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.
- wolfdocx/__init__.py +25 -0
- wolfdocx/_cache_root.py +24 -0
- wolfdocx/_comment_threads.py +278 -0
- wolfdocx/_inspection_cache.py +374 -0
- wolfdocx/_version.py +3 -0
- wolfdocx/admission.py +163 -0
- wolfdocx/assembly.py +463 -0
- wolfdocx/authoring.py +2773 -0
- wolfdocx/canonical.py +267 -0
- wolfdocx/content.py +963 -0
- wolfdocx/document.py +215 -0
- wolfdocx/errors.py +169 -0
- wolfdocx/find_replace.py +1210 -0
- wolfdocx/formatting.py +3160 -0
- wolfdocx/inspect.py +3999 -0
- wolfdocx/model.py +1038 -0
- wolfdocx/numbering_authoring.py +1422 -0
- wolfdocx/output.py +13 -0
- wolfdocx/package.py +2313 -0
- wolfdocx/package_profile.py +128 -0
- wolfdocx/page_setup.py +2483 -0
- wolfdocx/paragraph_authoring.py +1842 -0
- wolfdocx/properties.py +2728 -0
- wolfdocx/protection.py +1909 -0
- wolfdocx/regions.py +1993 -0
- wolfdocx/render_warnings.py +106 -0
- wolfdocx/reporting.py +943 -0
- wolfdocx/review.py +2862 -0
- wolfdocx/run_text.py +117 -0
- wolfdocx/section_break.py +1810 -0
- wolfdocx/session_ops/__init__.py +45 -0
- wolfdocx/session_ops/_bridge.py +151 -0
- wolfdocx/session_ops/lists.py +104 -0
- wolfdocx/session_ops/paragraphs.py +39 -0
- wolfdocx/session_ops/rich_objects.py +2598 -0
- wolfdocx/session_ops/run_edits.py +70 -0
- wolfdocx/session_ops/runs.py +313 -0
- wolfdocx/session_ops/sections.py +109 -0
- wolfdocx/session_ops/styling.py +99 -0
- wolfdocx/session_ops/tables.py +247 -0
- wolfdocx/styles_authoring.py +2822 -0
- wolfdocx/table_cell_properties.py +1458 -0
- wolfdocx/table_column.py +1501 -0
- wolfdocx/table_delete.py +942 -0
- wolfdocx/table_insert.py +1114 -0
- wolfdocx/table_merge.py +1863 -0
- wolfdocx/table_properties.py +2429 -0
- wolfdocx/table_row_properties.py +1095 -0
- wolfdocx/table_structure.py +1044 -0
- wolfdocx/text_effects.py +1438 -0
- wolfdocx-0.1.0.dist-info/METADATA +127 -0
- wolfdocx-0.1.0.dist-info/RECORD +54 -0
- wolfdocx-0.1.0.dist-info/WHEEL +4 -0
- wolfdocx-0.1.0.dist-info/licenses/LICENSE +21 -0
wolfdocx/reporting.py
ADDED
|
@@ -0,0 +1,943 @@
|
|
|
1
|
+
"""Atomic, source-bound report editing across DOCX body, headers, and footers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import hashlib
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import tempfile
|
|
11
|
+
import zipfile
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
from xml.etree import ElementTree as ET
|
|
17
|
+
|
|
18
|
+
from .authoring import (
|
|
19
|
+
_MAX_TEXT_CHARACTERS,
|
|
20
|
+
_PUBLISHED,
|
|
21
|
+
_REFUSED,
|
|
22
|
+
_cell_structure_fingerprint,
|
|
23
|
+
_effective_xml_space_by_element,
|
|
24
|
+
_has_unsupported_ancestor,
|
|
25
|
+
_patch_xml_texts,
|
|
26
|
+
_sha256_file,
|
|
27
|
+
_simple_text_node,
|
|
28
|
+
_span_text_nodes,
|
|
29
|
+
_span_text_occurrences,
|
|
30
|
+
_SpanTextNode,
|
|
31
|
+
_text_replacements_preserve_whitespace,
|
|
32
|
+
_unsupported_context_by_element,
|
|
33
|
+
_word_namespace,
|
|
34
|
+
)
|
|
35
|
+
from .canonical import sha256_bytes
|
|
36
|
+
from .inspect import PackageLimits, Q, _inspect_bytes, _Inspection
|
|
37
|
+
from .package import PackageError, PackageGraph
|
|
38
|
+
|
|
39
|
+
_DOCUMENT_PART = "word/document.xml"
|
|
40
|
+
_HEADER_CONTENT_TYPE = (
|
|
41
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"
|
|
42
|
+
)
|
|
43
|
+
_FOOTER_CONTENT_TYPE = (
|
|
44
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class ReportEdit:
|
|
50
|
+
"""One text replacement resolved only against the original source package."""
|
|
51
|
+
|
|
52
|
+
kind: str
|
|
53
|
+
part: str
|
|
54
|
+
expected_old_text: str
|
|
55
|
+
structure_fingerprint_sha256: str
|
|
56
|
+
text: str
|
|
57
|
+
table: int | None = None
|
|
58
|
+
row: int | None = None
|
|
59
|
+
cell: int | None = None
|
|
60
|
+
paragraph: int | None = None
|
|
61
|
+
|
|
62
|
+
def target_dict(self) -> dict[str, Any]:
|
|
63
|
+
if self.kind == "cell":
|
|
64
|
+
return {
|
|
65
|
+
"kind": self.kind,
|
|
66
|
+
"part": self.part,
|
|
67
|
+
"target": {"table": self.table, "row": self.row, "cell": self.cell},
|
|
68
|
+
}
|
|
69
|
+
return {"kind": self.kind, "part": self.part, "paragraph": self.paragraph}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class ReportRequest:
|
|
74
|
+
source: Path
|
|
75
|
+
destination: Path
|
|
76
|
+
source_sha256: str
|
|
77
|
+
edits: tuple[ReportEdit, ...]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class ReportAuthoringReport:
|
|
82
|
+
status: str
|
|
83
|
+
code: str | None
|
|
84
|
+
source_sha256: str
|
|
85
|
+
edit_targets: list[dict[str, Any]]
|
|
86
|
+
destination_sha256: str | None = None
|
|
87
|
+
target_change_reports: list[dict[str, Any]] | None = None
|
|
88
|
+
unselected_parts_preserved: bool | None = None
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def passed(self) -> bool:
|
|
92
|
+
return self.status == _PUBLISHED
|
|
93
|
+
|
|
94
|
+
def to_dict(self) -> dict[str, Any]:
|
|
95
|
+
return {
|
|
96
|
+
"schema_version": 1,
|
|
97
|
+
"operation": "report",
|
|
98
|
+
"passed": self.passed,
|
|
99
|
+
"status": self.status,
|
|
100
|
+
"code": self.code,
|
|
101
|
+
"source_sha256": self.source_sha256,
|
|
102
|
+
"edit_targets": self.edit_targets,
|
|
103
|
+
"destination_sha256": self.destination_sha256,
|
|
104
|
+
"target_change_reports": self.target_change_reports,
|
|
105
|
+
"unselected_parts_preserved": self.unselected_parts_preserved,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class _TextRegion:
|
|
111
|
+
node: ET.Element
|
|
112
|
+
start: int
|
|
113
|
+
end: int
|
|
114
|
+
text: str
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class _ResolvedEdit:
|
|
119
|
+
edit: ReportEdit
|
|
120
|
+
element: ET.Element
|
|
121
|
+
source_text: str
|
|
122
|
+
start: int
|
|
123
|
+
end: int
|
|
124
|
+
regions: tuple[_TextRegion, ...]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _require_sha256(value: Any, label: str) -> str:
|
|
128
|
+
if not isinstance(value, str) or len(value) != 64:
|
|
129
|
+
raise ValueError(f"{label}_invalid")
|
|
130
|
+
try:
|
|
131
|
+
int(value, 16)
|
|
132
|
+
except ValueError as error:
|
|
133
|
+
raise ValueError(f"{label}_invalid") from error
|
|
134
|
+
return value.lower()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _coordinate(value: Any, label: str) -> int:
|
|
138
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
139
|
+
raise ValueError(f"{label}_invalid")
|
|
140
|
+
return value
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _parse_edit(value: Any) -> ReportEdit:
|
|
144
|
+
if not isinstance(value, Mapping):
|
|
145
|
+
raise TypeError("report_edit_invalid")
|
|
146
|
+
kind = value.get("kind")
|
|
147
|
+
if kind not in {"cell", "text"}:
|
|
148
|
+
raise ValueError("report_edit_kind_invalid")
|
|
149
|
+
common = {"kind", "expected_old_text", "structure_fingerprint_sha256", "text"}
|
|
150
|
+
allowed = common | ({"target", "part"} if kind == "cell" else {"paragraph", "part"})
|
|
151
|
+
if set(value) - allowed or not common <= set(value):
|
|
152
|
+
raise ValueError("report_edit_fields_invalid")
|
|
153
|
+
part = value.get("part", _DOCUMENT_PART)
|
|
154
|
+
if not isinstance(part, str) or not part:
|
|
155
|
+
raise ValueError("report_part_invalid")
|
|
156
|
+
expected_old_text = value["expected_old_text"]
|
|
157
|
+
text = value["text"]
|
|
158
|
+
if not isinstance(expected_old_text, str) or not isinstance(text, str):
|
|
159
|
+
raise TypeError("report_text_invalid")
|
|
160
|
+
if not expected_old_text:
|
|
161
|
+
raise ValueError("report_expected_old_text_empty")
|
|
162
|
+
if len(expected_old_text) > _MAX_TEXT_CHARACTERS:
|
|
163
|
+
raise ValueError("report_expected_old_text_character_limit")
|
|
164
|
+
if len(text) > _MAX_TEXT_CHARACTERS:
|
|
165
|
+
raise ValueError("report_text_character_limit")
|
|
166
|
+
fingerprint = _require_sha256(
|
|
167
|
+
value["structure_fingerprint_sha256"], "report_structure_fingerprint_sha256"
|
|
168
|
+
)
|
|
169
|
+
if kind == "cell":
|
|
170
|
+
target = value.get("target")
|
|
171
|
+
if not isinstance(target, Mapping) or set(target) != {"table", "row", "cell"}:
|
|
172
|
+
raise ValueError("report_cell_target_invalid")
|
|
173
|
+
return ReportEdit(
|
|
174
|
+
kind=kind,
|
|
175
|
+
part=part,
|
|
176
|
+
expected_old_text=expected_old_text,
|
|
177
|
+
structure_fingerprint_sha256=fingerprint,
|
|
178
|
+
text=text,
|
|
179
|
+
table=_coordinate(target["table"], "report_cell_table"),
|
|
180
|
+
row=_coordinate(target["row"], "report_cell_row"),
|
|
181
|
+
cell=_coordinate(target["cell"], "report_cell_cell"),
|
|
182
|
+
)
|
|
183
|
+
if "paragraph" not in value:
|
|
184
|
+
raise ValueError("report_text_paragraph_missing")
|
|
185
|
+
return ReportEdit(
|
|
186
|
+
kind=kind,
|
|
187
|
+
part=part,
|
|
188
|
+
expected_old_text=expected_old_text,
|
|
189
|
+
structure_fingerprint_sha256=fingerprint,
|
|
190
|
+
text=text,
|
|
191
|
+
paragraph=_coordinate(value["paragraph"], "report_text_paragraph"),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def parse_report_request(value: Any) -> ReportRequest:
|
|
196
|
+
"""Parse the strict JSON request for one atomic, report-wide authoring operation."""
|
|
197
|
+
|
|
198
|
+
if not isinstance(value, Mapping) or set(value) != {
|
|
199
|
+
"source",
|
|
200
|
+
"destination",
|
|
201
|
+
"source_sha256",
|
|
202
|
+
"edits",
|
|
203
|
+
}:
|
|
204
|
+
raise ValueError("report_request_fields_invalid")
|
|
205
|
+
source, destination, edits = value["source"], value["destination"], value["edits"]
|
|
206
|
+
if (
|
|
207
|
+
not isinstance(source, str)
|
|
208
|
+
or not source
|
|
209
|
+
or not isinstance(destination, str)
|
|
210
|
+
or not destination
|
|
211
|
+
):
|
|
212
|
+
raise ValueError("report_path_invalid")
|
|
213
|
+
if not isinstance(edits, list) or not edits:
|
|
214
|
+
raise ValueError("report_edits_invalid")
|
|
215
|
+
return ReportRequest(
|
|
216
|
+
source=Path(source),
|
|
217
|
+
destination=Path(destination),
|
|
218
|
+
source_sha256=_require_sha256(value["source_sha256"], "report_source_sha256"),
|
|
219
|
+
edits=tuple(_parse_edit(item) for item in edits),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def load_report_request(path: str | Path) -> ReportRequest:
|
|
224
|
+
with Path(path).open(encoding="utf-8") as stream:
|
|
225
|
+
return parse_report_request(json.load(stream))
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _report_refusal(request: ReportRequest, code: str) -> ReportAuthoringReport:
|
|
229
|
+
return ReportAuthoringReport(
|
|
230
|
+
status=_REFUSED,
|
|
231
|
+
code=code,
|
|
232
|
+
source_sha256=request.source_sha256,
|
|
233
|
+
edit_targets=[edit.target_dict() for edit in request.edits],
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _select_cell(
|
|
238
|
+
root: ET.Element, edit: ReportEdit, namespace: str
|
|
239
|
+
) -> ET.Element | None:
|
|
240
|
+
assert edit.table is not None and edit.row is not None and edit.cell is not None
|
|
241
|
+
def word(local):
|
|
242
|
+
return Q(namespace, local)
|
|
243
|
+
tables = list(root.iter(word("tbl")))
|
|
244
|
+
if edit.table > len(tables):
|
|
245
|
+
return None
|
|
246
|
+
rows = tables[edit.table - 1].findall(word("tr"))
|
|
247
|
+
if edit.row > len(rows):
|
|
248
|
+
return None
|
|
249
|
+
cells = rows[edit.row - 1].findall(word("tc"))
|
|
250
|
+
return cells[edit.cell - 1] if edit.cell <= len(cells) else None
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _select_paragraph(
|
|
254
|
+
root: ET.Element, edit: ReportEdit, namespace: str
|
|
255
|
+
) -> ET.Element | None:
|
|
256
|
+
assert edit.paragraph is not None
|
|
257
|
+
paragraphs = list(root.iter(Q(namespace, "p")))
|
|
258
|
+
return paragraphs[edit.paragraph - 1] if edit.paragraph <= len(paragraphs) else None
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _supported_part(graph: PackageGraph, part: str) -> bool:
|
|
262
|
+
package_part = graph.part(part)
|
|
263
|
+
if package_part is None:
|
|
264
|
+
return False
|
|
265
|
+
if part == _DOCUMENT_PART:
|
|
266
|
+
return True
|
|
267
|
+
if part.startswith("word/header") and part.endswith(".xml"):
|
|
268
|
+
expected_type, relationship_kind, reference_kind = (
|
|
269
|
+
_HEADER_CONTENT_TYPE,
|
|
270
|
+
"header",
|
|
271
|
+
"headerReference",
|
|
272
|
+
)
|
|
273
|
+
elif part.startswith("word/footer") and part.endswith(".xml"):
|
|
274
|
+
expected_type, relationship_kind, reference_kind = (
|
|
275
|
+
_FOOTER_CONTENT_TYPE,
|
|
276
|
+
"footer",
|
|
277
|
+
"footerReference",
|
|
278
|
+
)
|
|
279
|
+
else:
|
|
280
|
+
return False
|
|
281
|
+
if package_part.content_type != expected_type:
|
|
282
|
+
return False
|
|
283
|
+
relationship_ids = {
|
|
284
|
+
relationship.id
|
|
285
|
+
for relationship in graph.relationships_for(_DOCUMENT_PART)
|
|
286
|
+
if not relationship.is_external
|
|
287
|
+
and relationship.resolved_target() == part
|
|
288
|
+
and relationship.type.rsplit("/", 1)[-1] == relationship_kind
|
|
289
|
+
}
|
|
290
|
+
if not relationship_ids:
|
|
291
|
+
return False
|
|
292
|
+
try:
|
|
293
|
+
document_root = ET.fromstring(graph.read_part_bytes(_DOCUMENT_PART))
|
|
294
|
+
except (ET.ParseError, PackageError):
|
|
295
|
+
return False
|
|
296
|
+
return any(
|
|
297
|
+
element.tag.rsplit("}", 1)[-1] == reference_kind
|
|
298
|
+
and any(
|
|
299
|
+
attribute.rsplit("}", 1)[-1] == "id" and value in relationship_ids
|
|
300
|
+
for attribute, value in element.attrib.items()
|
|
301
|
+
)
|
|
302
|
+
for element in document_root.iter()
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _regions_for_text(
|
|
307
|
+
nodes: list[Any], *, start: int, end: int, replacement: str
|
|
308
|
+
) -> tuple[_TextRegion, ...]:
|
|
309
|
+
regions: list[_TextRegion] = []
|
|
310
|
+
for node in nodes:
|
|
311
|
+
if node.start >= end or start >= node.end:
|
|
312
|
+
continue
|
|
313
|
+
local_start = max(start, node.start) - node.start
|
|
314
|
+
local_end = min(end, node.end) - node.start
|
|
315
|
+
regions.append(
|
|
316
|
+
_TextRegion(
|
|
317
|
+
node=node.node,
|
|
318
|
+
start=local_start,
|
|
319
|
+
end=local_end,
|
|
320
|
+
text=replacement if node.start <= start < node.end else "",
|
|
321
|
+
)
|
|
322
|
+
)
|
|
323
|
+
return tuple(regions)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _resolve_edit(
|
|
327
|
+
root: ET.Element, edit: ReportEdit, namespace: str
|
|
328
|
+
) -> tuple[_ResolvedEdit | None, str | None]:
|
|
329
|
+
if edit.kind == "cell":
|
|
330
|
+
cell = _select_cell(root, edit, namespace)
|
|
331
|
+
if cell is None:
|
|
332
|
+
return None, "cell_coordinate_missing"
|
|
333
|
+
if _cell_structure_fingerprint(cell) != edit.structure_fingerprint_sha256:
|
|
334
|
+
return None, "cell_structure_mismatch"
|
|
335
|
+
if _has_unsupported_ancestor(root, cell, namespace):
|
|
336
|
+
return None, "cell_context_unsupported"
|
|
337
|
+
text_node = _simple_text_node(cell, namespace)
|
|
338
|
+
if text_node is None:
|
|
339
|
+
return None, "cell_structure_unsupported"
|
|
340
|
+
node, old_text = text_node
|
|
341
|
+
if old_text != edit.expected_old_text:
|
|
342
|
+
return None, "expected_old_text_mismatch"
|
|
343
|
+
if old_text == edit.text:
|
|
344
|
+
return None, "replacement_unchanged"
|
|
345
|
+
return _ResolvedEdit(
|
|
346
|
+
edit,
|
|
347
|
+
cell,
|
|
348
|
+
old_text,
|
|
349
|
+
0,
|
|
350
|
+
len(old_text),
|
|
351
|
+
(_TextRegion(node, 0, len(old_text), edit.text),),
|
|
352
|
+
), None
|
|
353
|
+
|
|
354
|
+
paragraph = _select_paragraph(root, edit, namespace)
|
|
355
|
+
if paragraph is None:
|
|
356
|
+
return None, "paragraph_coordinate_missing"
|
|
357
|
+
if _cell_structure_fingerprint(paragraph) != edit.structure_fingerprint_sha256:
|
|
358
|
+
return None, "paragraph_structure_mismatch"
|
|
359
|
+
if _has_unsupported_ancestor(root, paragraph, namespace):
|
|
360
|
+
return None, "paragraph_context_unsupported"
|
|
361
|
+
nodes = _span_text_nodes(paragraph, namespace)
|
|
362
|
+
if nodes is None:
|
|
363
|
+
return None, "text_structure_unsupported"
|
|
364
|
+
source_text = "".join(node.text for node in nodes)
|
|
365
|
+
start = source_text.find(edit.expected_old_text)
|
|
366
|
+
if start < 0:
|
|
367
|
+
return None, "expected_old_text_mismatch"
|
|
368
|
+
if source_text.find(edit.expected_old_text, start + 1) >= 0:
|
|
369
|
+
return None, "text_occurrence_ambiguous"
|
|
370
|
+
end = start + len(edit.expected_old_text)
|
|
371
|
+
if edit.expected_old_text == edit.text:
|
|
372
|
+
return None, "replacement_unchanged"
|
|
373
|
+
return _ResolvedEdit(
|
|
374
|
+
edit,
|
|
375
|
+
paragraph,
|
|
376
|
+
source_text,
|
|
377
|
+
start,
|
|
378
|
+
end,
|
|
379
|
+
_regions_for_text(nodes, start=start, end=end, replacement=edit.text),
|
|
380
|
+
), None
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _parents(root: ET.Element) -> dict[int, ET.Element]:
|
|
384
|
+
return {id(child): parent for parent in root.iter() for child in parent}
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _is_ancestor(
|
|
388
|
+
ancestor: ET.Element, element: ET.Element, parents: Mapping[int, ET.Element]
|
|
389
|
+
) -> bool:
|
|
390
|
+
current: ET.Element | None = element
|
|
391
|
+
while current is not None:
|
|
392
|
+
if current is ancestor:
|
|
393
|
+
return True
|
|
394
|
+
current = parents.get(id(current))
|
|
395
|
+
return False
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _has_overlapping_targets(
|
|
399
|
+
resolved: list[_ResolvedEdit], roots: Mapping[str, ET.Element]
|
|
400
|
+
) -> bool:
|
|
401
|
+
# Parent maps cost one whole-tree walk, so build them only for parts holding a pair.
|
|
402
|
+
parents: dict[str, dict[int, ET.Element]] = {}
|
|
403
|
+
for index, current in enumerate(resolved):
|
|
404
|
+
for previous in resolved[:index]:
|
|
405
|
+
if current.edit.part != previous.edit.part:
|
|
406
|
+
continue
|
|
407
|
+
if (
|
|
408
|
+
current.edit.kind == previous.edit.kind == "text"
|
|
409
|
+
and current.element is previous.element
|
|
410
|
+
):
|
|
411
|
+
if current.start >= previous.end or previous.start >= current.end:
|
|
412
|
+
continue
|
|
413
|
+
return True
|
|
414
|
+
part = current.edit.part
|
|
415
|
+
if part not in parents:
|
|
416
|
+
parents[part] = _parents(roots[part])
|
|
417
|
+
part_parents = parents[part]
|
|
418
|
+
if _is_ancestor(
|
|
419
|
+
current.element, previous.element, part_parents
|
|
420
|
+
) or _is_ancestor(previous.element, current.element, part_parents):
|
|
421
|
+
return True
|
|
422
|
+
return False
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _replacement_texts(resolved: list[_ResolvedEdit]) -> dict[int, str] | None:
|
|
426
|
+
by_node: dict[int, tuple[ET.Element, list[_TextRegion]]] = {}
|
|
427
|
+
for item in resolved:
|
|
428
|
+
for region in item.regions:
|
|
429
|
+
node, regions = by_node.setdefault(id(region.node), (region.node, []))
|
|
430
|
+
assert node is region.node
|
|
431
|
+
regions.append(region)
|
|
432
|
+
replacements: dict[int, str] = {}
|
|
433
|
+
for node_id, (node, regions) in by_node.items():
|
|
434
|
+
cursor = 0
|
|
435
|
+
pieces: list[str] = []
|
|
436
|
+
for region in sorted(regions, key=lambda item: (item.start, item.end)):
|
|
437
|
+
if region.start < cursor or region.end < region.start:
|
|
438
|
+
return None
|
|
439
|
+
pieces.extend((node.text or "")[cursor : region.start])
|
|
440
|
+
pieces.append(region.text)
|
|
441
|
+
cursor = region.end
|
|
442
|
+
pieces.append((node.text or "")[cursor:])
|
|
443
|
+
replacements[node_id] = "".join(pieces)
|
|
444
|
+
return replacements
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _patch_part(
|
|
448
|
+
root: ET.Element,
|
|
449
|
+
part_bytes: bytes,
|
|
450
|
+
namespace: str,
|
|
451
|
+
replacements: Mapping[int, str],
|
|
452
|
+
nodes: Mapping[int, ET.Element],
|
|
453
|
+
) -> bytes | None:
|
|
454
|
+
selected: list[_SpanTextNode] = []
|
|
455
|
+
for node_id in replacements:
|
|
456
|
+
node = nodes.get(node_id)
|
|
457
|
+
if node is None:
|
|
458
|
+
return None
|
|
459
|
+
selected.append(_SpanTextNode(node=node, text="", start=0, end=0))
|
|
460
|
+
# The occurrence walk refuses any selected node that is not inside ``root``.
|
|
461
|
+
try:
|
|
462
|
+
occurrences = _span_text_occurrences(root, selected)
|
|
463
|
+
except ValueError:
|
|
464
|
+
return None
|
|
465
|
+
return _patch_xml_texts(
|
|
466
|
+
part_bytes,
|
|
467
|
+
word_namespace=namespace,
|
|
468
|
+
replacements={
|
|
469
|
+
occurrences[node_id]: text for node_id, text in replacements.items()
|
|
470
|
+
},
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _write_staged_package(
|
|
475
|
+
source: Path, staged: Path, replacements: Mapping[str, bytes]
|
|
476
|
+
) -> None:
|
|
477
|
+
with (
|
|
478
|
+
zipfile.ZipFile(source) as baseline,
|
|
479
|
+
zipfile.ZipFile(staged, "w", compression=zipfile.ZIP_DEFLATED) as rewritten,
|
|
480
|
+
):
|
|
481
|
+
for info in baseline.infolist():
|
|
482
|
+
rewritten.writestr(
|
|
483
|
+
copy.copy(info),
|
|
484
|
+
replacements.get(info.filename, baseline.read(info.filename)),
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _unselected_part_bytes_preserved(
|
|
489
|
+
source: Path,
|
|
490
|
+
candidate: Path,
|
|
491
|
+
selected_parts: set[str],
|
|
492
|
+
*,
|
|
493
|
+
allowed_additions: frozenset[str] = frozenset(),
|
|
494
|
+
) -> bool:
|
|
495
|
+
with zipfile.ZipFile(source) as baseline, zipfile.ZipFile(candidate) as rewritten:
|
|
496
|
+
baseline_names = set(baseline.namelist())
|
|
497
|
+
candidate_names = set(rewritten.namelist())
|
|
498
|
+
if baseline_names - candidate_names:
|
|
499
|
+
return False
|
|
500
|
+
if candidate_names - baseline_names - allowed_additions:
|
|
501
|
+
return False
|
|
502
|
+
return all(
|
|
503
|
+
baseline.read(name) == rewritten.read(name)
|
|
504
|
+
for name in baseline_names
|
|
505
|
+
if name not in selected_parts
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _report_unselected_preserved(
|
|
510
|
+
source_bytes: bytes,
|
|
511
|
+
baseline: _Inspection,
|
|
512
|
+
staged_bytes: bytes,
|
|
513
|
+
candidate: _Inspection,
|
|
514
|
+
selected_parts: set[str],
|
|
515
|
+
) -> bool:
|
|
516
|
+
"""Prove every unselected entry kept its bytes, from digests both inspections hold.
|
|
517
|
+
|
|
518
|
+
Each inspection hashed every package part from the bytes it validated, so equal
|
|
519
|
+
SHA-256 digests prove equal bytes without decompressing either archive again.
|
|
520
|
+
Entries the inspections did not hash (non-part members) are compared directly.
|
|
521
|
+
"""
|
|
522
|
+
with (
|
|
523
|
+
zipfile.ZipFile(io.BytesIO(source_bytes)) as source_zip,
|
|
524
|
+
zipfile.ZipFile(io.BytesIO(staged_bytes)) as staged_zip,
|
|
525
|
+
):
|
|
526
|
+
names = set(source_zip.namelist())
|
|
527
|
+
if names != set(staged_zip.namelist()):
|
|
528
|
+
return False
|
|
529
|
+
before, after = baseline.part_sha256, candidate.part_sha256
|
|
530
|
+
for name in names - selected_parts:
|
|
531
|
+
source_digest, staged_digest = before.get(name), after.get(name)
|
|
532
|
+
if source_digest is not None and staged_digest is not None:
|
|
533
|
+
if source_digest != staged_digest:
|
|
534
|
+
return False
|
|
535
|
+
elif source_zip.read(name) != staged_zip.read(name):
|
|
536
|
+
return False
|
|
537
|
+
return True
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _bound_source_bytes(source: Path, source_sha256: str) -> bytes | str:
|
|
541
|
+
"""Read the source once, or the refusal code for an oversized or unbound source."""
|
|
542
|
+
if source.stat().st_size > PackageLimits().max_archive_size:
|
|
543
|
+
# Never materialize an oversized package; its inspection refuses it unread.
|
|
544
|
+
if _sha256_file(source) != source_sha256:
|
|
545
|
+
return "source_hash_mismatch"
|
|
546
|
+
return "source_inspection_invalid"
|
|
547
|
+
data = source.read_bytes()
|
|
548
|
+
return data if sha256_bytes(data) == source_sha256 else "source_hash_mismatch"
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _candidate_target_reports(
|
|
552
|
+
candidate_roots: Mapping[str, ET.Element],
|
|
553
|
+
resolved: list[_ResolvedEdit],
|
|
554
|
+
expected_texts: Mapping[int, str],
|
|
555
|
+
) -> list[dict[str, Any]] | None:
|
|
556
|
+
"""Re-read every target from the staged inspection's read-only trees."""
|
|
557
|
+
reports: list[dict[str, Any]] = []
|
|
558
|
+
for item in resolved:
|
|
559
|
+
root = candidate_roots.get(item.edit.part)
|
|
560
|
+
if root is None:
|
|
561
|
+
return None
|
|
562
|
+
namespace = _word_namespace(root)
|
|
563
|
+
if namespace is None:
|
|
564
|
+
return None
|
|
565
|
+
if item.edit.kind == "cell":
|
|
566
|
+
element = _select_cell(root, item.edit, namespace)
|
|
567
|
+
text_node = (
|
|
568
|
+
_simple_text_node(element, namespace) if element is not None else None
|
|
569
|
+
)
|
|
570
|
+
actual = text_node[1] if text_node is not None else None
|
|
571
|
+
else:
|
|
572
|
+
element = _select_paragraph(root, item.edit, namespace)
|
|
573
|
+
nodes = _span_text_nodes(element, namespace) if element is not None else None
|
|
574
|
+
actual = "".join(node.text for node in nodes) if nodes is not None else None
|
|
575
|
+
expected = expected_texts[id(item)]
|
|
576
|
+
structure_ok = (
|
|
577
|
+
element is not None
|
|
578
|
+
and _cell_structure_fingerprint(element)
|
|
579
|
+
== item.edit.structure_fingerprint_sha256
|
|
580
|
+
)
|
|
581
|
+
reports.append(
|
|
582
|
+
{
|
|
583
|
+
"target": item.edit.target_dict(),
|
|
584
|
+
"expected_text_sha256": hashlib.sha256(
|
|
585
|
+
expected.encode("utf-8")
|
|
586
|
+
).hexdigest(),
|
|
587
|
+
"candidate_text_sha256": hashlib.sha256(
|
|
588
|
+
actual.encode("utf-8")
|
|
589
|
+
).hexdigest()
|
|
590
|
+
if actual is not None
|
|
591
|
+
else None,
|
|
592
|
+
"structure_preserved": structure_ok,
|
|
593
|
+
"passed": actual == expected and structure_ok,
|
|
594
|
+
}
|
|
595
|
+
)
|
|
596
|
+
return reports
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def report_target_structure_fingerprint(
|
|
600
|
+
source: str | Path,
|
|
601
|
+
*,
|
|
602
|
+
kind: str,
|
|
603
|
+
target: Mapping[str, Any] | int,
|
|
604
|
+
part: str = _DOCUMENT_PART,
|
|
605
|
+
) -> str | None:
|
|
606
|
+
"""Return a text-masked bound fingerprint for a supported report target."""
|
|
607
|
+
|
|
608
|
+
document = Path(source)
|
|
609
|
+
if kind not in {"cell", "text"} or not isinstance(part, str):
|
|
610
|
+
return None
|
|
611
|
+
try:
|
|
612
|
+
graph = PackageGraph.from_file(document)
|
|
613
|
+
if not _supported_part(graph, part):
|
|
614
|
+
return None
|
|
615
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
616
|
+
except (ET.ParseError, PackageError):
|
|
617
|
+
return None
|
|
618
|
+
namespace = _word_namespace(root)
|
|
619
|
+
if namespace is None:
|
|
620
|
+
return None
|
|
621
|
+
if kind == "cell":
|
|
622
|
+
if not isinstance(target, Mapping) or set(target) != {"table", "row", "cell"}:
|
|
623
|
+
return None
|
|
624
|
+
try:
|
|
625
|
+
edit = ReportEdit(
|
|
626
|
+
"cell",
|
|
627
|
+
part,
|
|
628
|
+
"x",
|
|
629
|
+
"0" * 64,
|
|
630
|
+
"y",
|
|
631
|
+
**{key: _coordinate(target[key], key) for key in target},
|
|
632
|
+
)
|
|
633
|
+
except (TypeError, ValueError):
|
|
634
|
+
return None
|
|
635
|
+
element = _select_cell(root, edit, namespace)
|
|
636
|
+
else:
|
|
637
|
+
if isinstance(target, bool) or not isinstance(target, int) or target <= 0:
|
|
638
|
+
return None
|
|
639
|
+
element = _select_paragraph(
|
|
640
|
+
root,
|
|
641
|
+
ReportEdit("text", part, "x", "0" * 64, "y", paragraph=target),
|
|
642
|
+
namespace,
|
|
643
|
+
)
|
|
644
|
+
return _cell_structure_fingerprint(element) if element is not None else None
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def discover_report_targets(
|
|
648
|
+
source: str | Path, *, part: str = _DOCUMENT_PART
|
|
649
|
+
) -> dict[str, Any]:
|
|
650
|
+
"""List source-bound targets supported by the read-only report authoring surface."""
|
|
651
|
+
|
|
652
|
+
document = Path(source)
|
|
653
|
+
if not document.is_file():
|
|
654
|
+
return {
|
|
655
|
+
"schema_version": 1,
|
|
656
|
+
"operation": "report-targets",
|
|
657
|
+
"passed": False,
|
|
658
|
+
"status": _REFUSED,
|
|
659
|
+
"code": "source_missing",
|
|
660
|
+
}
|
|
661
|
+
try:
|
|
662
|
+
graph = PackageGraph.from_file(document)
|
|
663
|
+
source_sha256 = graph.file_sha256
|
|
664
|
+
if not _supported_part(graph, part):
|
|
665
|
+
return {
|
|
666
|
+
"schema_version": 1,
|
|
667
|
+
"operation": "report-targets",
|
|
668
|
+
"passed": False,
|
|
669
|
+
"status": _REFUSED,
|
|
670
|
+
"code": "report_part_unsupported",
|
|
671
|
+
"source_sha256": source_sha256,
|
|
672
|
+
"part": part,
|
|
673
|
+
}
|
|
674
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
675
|
+
except (ET.ParseError, PackageError):
|
|
676
|
+
return {
|
|
677
|
+
"schema_version": 1,
|
|
678
|
+
"operation": "report-targets",
|
|
679
|
+
"passed": False,
|
|
680
|
+
"status": _REFUSED,
|
|
681
|
+
"code": "source_part_invalid",
|
|
682
|
+
"part": part,
|
|
683
|
+
}
|
|
684
|
+
namespace = _word_namespace(root)
|
|
685
|
+
if namespace is None:
|
|
686
|
+
return {
|
|
687
|
+
"schema_version": 1,
|
|
688
|
+
"operation": "report-targets",
|
|
689
|
+
"passed": False,
|
|
690
|
+
"status": _REFUSED,
|
|
691
|
+
"code": "source_word_namespace_unsupported",
|
|
692
|
+
"source_sha256": source_sha256,
|
|
693
|
+
"part": part,
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
targets: list[dict[str, Any]] = []
|
|
697
|
+
effective_spaces = _effective_xml_space_by_element(root)
|
|
698
|
+
unsupported_contexts = _unsupported_context_by_element(root, namespace)
|
|
699
|
+
def word(local):
|
|
700
|
+
return Q(namespace, local)
|
|
701
|
+
for table_index, table in enumerate(root.iter(word("tbl")), start=1):
|
|
702
|
+
for row_index, row in enumerate(table.findall(word("tr")), start=1):
|
|
703
|
+
for cell_index, cell in enumerate(row.findall(word("tc")), start=1):
|
|
704
|
+
if unsupported_contexts.get(id(cell), True):
|
|
705
|
+
continue
|
|
706
|
+
simple = _simple_text_node(cell, namespace)
|
|
707
|
+
if simple is None:
|
|
708
|
+
continue
|
|
709
|
+
node, old_text = simple
|
|
710
|
+
if not old_text or not _text_replacements_preserve_whitespace(
|
|
711
|
+
root, {id(node): old_text}, effective_spaces=effective_spaces
|
|
712
|
+
):
|
|
713
|
+
continue
|
|
714
|
+
targets.append(
|
|
715
|
+
{
|
|
716
|
+
"kind": "cell",
|
|
717
|
+
"part": part,
|
|
718
|
+
"target": {
|
|
719
|
+
"table": table_index,
|
|
720
|
+
"row": row_index,
|
|
721
|
+
"cell": cell_index,
|
|
722
|
+
},
|
|
723
|
+
"expected_old_text": old_text,
|
|
724
|
+
"structure_fingerprint_sha256": _cell_structure_fingerprint(
|
|
725
|
+
cell
|
|
726
|
+
),
|
|
727
|
+
}
|
|
728
|
+
)
|
|
729
|
+
for paragraph_index, paragraph in enumerate(root.iter(word("p")), start=1):
|
|
730
|
+
if unsupported_contexts.get(id(paragraph), True):
|
|
731
|
+
continue
|
|
732
|
+
nodes = _span_text_nodes(paragraph, namespace)
|
|
733
|
+
if nodes is None:
|
|
734
|
+
continue
|
|
735
|
+
old_text = "".join(node.text for node in nodes)
|
|
736
|
+
node_texts = {id(node.node): node.text for node in nodes}
|
|
737
|
+
if not old_text or not _text_replacements_preserve_whitespace(
|
|
738
|
+
root, node_texts, effective_spaces=effective_spaces
|
|
739
|
+
):
|
|
740
|
+
continue
|
|
741
|
+
targets.append(
|
|
742
|
+
{
|
|
743
|
+
"kind": "text",
|
|
744
|
+
"part": part,
|
|
745
|
+
"paragraph": paragraph_index,
|
|
746
|
+
"expected_old_text": old_text,
|
|
747
|
+
"structure_fingerprint_sha256": _cell_structure_fingerprint(paragraph),
|
|
748
|
+
}
|
|
749
|
+
)
|
|
750
|
+
return {
|
|
751
|
+
"schema_version": 1,
|
|
752
|
+
"operation": "report-targets",
|
|
753
|
+
"passed": True,
|
|
754
|
+
"status": "discovered",
|
|
755
|
+
"code": None,
|
|
756
|
+
"source_sha256": source_sha256,
|
|
757
|
+
"part": part,
|
|
758
|
+
"targets": targets,
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def author_report(request: ReportRequest) -> ReportAuthoringReport:
|
|
763
|
+
"""Resolve every edit on the immutable source, verify once, then publish once."""
|
|
764
|
+
|
|
765
|
+
source = request.source.resolve()
|
|
766
|
+
destination = request.destination.resolve()
|
|
767
|
+
if source == destination:
|
|
768
|
+
return _report_refusal(request, "source_destination_same")
|
|
769
|
+
if not source.is_file():
|
|
770
|
+
return _report_refusal(request, "source_missing")
|
|
771
|
+
if not destination.parent.is_dir():
|
|
772
|
+
return _report_refusal(request, "destination_parent_missing")
|
|
773
|
+
source_bytes = _bound_source_bytes(source, request.source_sha256)
|
|
774
|
+
if isinstance(source_bytes, str):
|
|
775
|
+
return _report_refusal(request, source_bytes)
|
|
776
|
+
# Inspection, graph, and part reads all bind to these exact hashed bytes.
|
|
777
|
+
baseline = _inspect_bytes(
|
|
778
|
+
source_bytes, display_path=str(source), file_sha256=request.source_sha256
|
|
779
|
+
)
|
|
780
|
+
if not baseline.valid:
|
|
781
|
+
return _report_refusal(request, "source_inspection_invalid")
|
|
782
|
+
try:
|
|
783
|
+
graph = PackageGraph.from_bytes(
|
|
784
|
+
source_bytes, path=source, file_sha256=request.source_sha256
|
|
785
|
+
)
|
|
786
|
+
except PackageError:
|
|
787
|
+
return _report_refusal(request, "source_package_invalid")
|
|
788
|
+
|
|
789
|
+
source_parts: dict[str, bytes] = {}
|
|
790
|
+
roots: dict[str, ET.Element] = {}
|
|
791
|
+
namespaces: dict[str, str] = {}
|
|
792
|
+
resolved: list[_ResolvedEdit] = []
|
|
793
|
+
for edit in request.edits:
|
|
794
|
+
if not _supported_part(graph, edit.part):
|
|
795
|
+
return _report_refusal(request, "report_part_unsupported")
|
|
796
|
+
if edit.part not in roots:
|
|
797
|
+
try:
|
|
798
|
+
source_parts[edit.part] = graph.read_part_bytes(edit.part)
|
|
799
|
+
# The inspection above parsed these same bound bytes; its trees are
|
|
800
|
+
# shared, so this function only reads them.
|
|
801
|
+
root = baseline.parsed_xml.get(edit.part)
|
|
802
|
+
roots[edit.part] = (
|
|
803
|
+
root if root is not None else ET.fromstring(source_parts[edit.part])
|
|
804
|
+
)
|
|
805
|
+
except PackageError:
|
|
806
|
+
return _report_refusal(request, "report_part_missing")
|
|
807
|
+
except ET.ParseError:
|
|
808
|
+
return _report_refusal(request, "report_part_invalid")
|
|
809
|
+
namespace = _word_namespace(roots[edit.part])
|
|
810
|
+
if namespace is None:
|
|
811
|
+
return _report_refusal(request, "source_word_namespace_unsupported")
|
|
812
|
+
namespaces[edit.part] = namespace
|
|
813
|
+
item, code = _resolve_edit(roots[edit.part], edit, namespaces[edit.part])
|
|
814
|
+
if item is None:
|
|
815
|
+
return _report_refusal(request, code or "report_target_invalid")
|
|
816
|
+
resolved.append(item)
|
|
817
|
+
if _has_overlapping_targets(resolved, roots):
|
|
818
|
+
return _report_refusal(request, "report_edit_overlap")
|
|
819
|
+
|
|
820
|
+
expected_texts: dict[int, str] = {}
|
|
821
|
+
for item in resolved:
|
|
822
|
+
expected_texts[id(item)] = (
|
|
823
|
+
item.source_text[: item.start]
|
|
824
|
+
+ item.edit.text
|
|
825
|
+
+ item.source_text[item.end :]
|
|
826
|
+
)
|
|
827
|
+
for part, root in roots.items():
|
|
828
|
+
text_items = [
|
|
829
|
+
item
|
|
830
|
+
for item in resolved
|
|
831
|
+
if item.edit.part == part and item.edit.kind == "text"
|
|
832
|
+
]
|
|
833
|
+
by_paragraph: dict[int, list[_ResolvedEdit]] = {}
|
|
834
|
+
for item in text_items:
|
|
835
|
+
by_paragraph.setdefault(id(item.element), []).append(item)
|
|
836
|
+
for items in by_paragraph.values():
|
|
837
|
+
source_text = items[0].source_text
|
|
838
|
+
updated = source_text
|
|
839
|
+
for item in sorted(items, key=lambda value: value.start, reverse=True):
|
|
840
|
+
updated = updated[: item.start] + item.edit.text + updated[item.end :]
|
|
841
|
+
for item in items:
|
|
842
|
+
expected_texts[id(item)] = updated
|
|
843
|
+
replacements = _replacement_texts(resolved)
|
|
844
|
+
if replacements is None:
|
|
845
|
+
return _report_refusal(request, "report_edit_overlap")
|
|
846
|
+
for part, root in roots.items():
|
|
847
|
+
part_replacements = {
|
|
848
|
+
node_id: text
|
|
849
|
+
for node_id, text in replacements.items()
|
|
850
|
+
if any(
|
|
851
|
+
id(region.node) == node_id
|
|
852
|
+
for item in resolved
|
|
853
|
+
if item.edit.part == part
|
|
854
|
+
for region in item.regions
|
|
855
|
+
)
|
|
856
|
+
}
|
|
857
|
+
if not _text_replacements_preserve_whitespace(root, part_replacements):
|
|
858
|
+
return _report_refusal(request, "replacement_whitespace_unsupported")
|
|
859
|
+
|
|
860
|
+
patched_parts: dict[str, bytes] = {}
|
|
861
|
+
for part, root in roots.items():
|
|
862
|
+
part_replacements = {
|
|
863
|
+
node_id: text
|
|
864
|
+
for node_id, text in replacements.items()
|
|
865
|
+
if any(
|
|
866
|
+
id(region.node) == node_id
|
|
867
|
+
for item in resolved
|
|
868
|
+
if item.edit.part == part
|
|
869
|
+
for region in item.regions
|
|
870
|
+
)
|
|
871
|
+
}
|
|
872
|
+
part_nodes = {
|
|
873
|
+
id(region.node): region.node
|
|
874
|
+
for item in resolved
|
|
875
|
+
if item.edit.part == part
|
|
876
|
+
for region in item.regions
|
|
877
|
+
}
|
|
878
|
+
patched = _patch_part(
|
|
879
|
+
root, source_parts[part], namespaces[part], part_replacements, part_nodes
|
|
880
|
+
)
|
|
881
|
+
if patched is None:
|
|
882
|
+
return _report_refusal(request, "report_text_patch_unsupported")
|
|
883
|
+
patched_parts[part] = patched
|
|
884
|
+
|
|
885
|
+
staged_path: Path | None = None
|
|
886
|
+
try:
|
|
887
|
+
with tempfile.NamedTemporaryFile(
|
|
888
|
+
dir=destination.parent,
|
|
889
|
+
prefix=f".{destination.name}.",
|
|
890
|
+
suffix=".tmp",
|
|
891
|
+
delete=False,
|
|
892
|
+
) as staged:
|
|
893
|
+
staged_path = Path(staged.name)
|
|
894
|
+
_write_staged_package(source, staged_path, patched_parts)
|
|
895
|
+
staged_bytes = staged_path.read_bytes()
|
|
896
|
+
candidate = _inspect_bytes(staged_bytes, display_path=str(staged_path), reuse=baseline)
|
|
897
|
+
target_change_reports = (
|
|
898
|
+
_candidate_target_reports(candidate.parsed_xml, resolved, expected_texts)
|
|
899
|
+
if candidate.valid
|
|
900
|
+
else None
|
|
901
|
+
)
|
|
902
|
+
unselected_parts_preserved = _report_unselected_preserved(
|
|
903
|
+
source_bytes, baseline, staged_bytes, candidate, set(patched_parts)
|
|
904
|
+
)
|
|
905
|
+
try:
|
|
906
|
+
candidate_graph = PackageGraph.from_bytes(
|
|
907
|
+
staged_bytes, path=staged_path, file_sha256=candidate.file_sha256
|
|
908
|
+
)
|
|
909
|
+
selected_parts_exact = all(
|
|
910
|
+
candidate_graph.read_part_bytes(part) == patched
|
|
911
|
+
for part, patched in patched_parts.items()
|
|
912
|
+
)
|
|
913
|
+
except PackageError:
|
|
914
|
+
selected_parts_exact = False
|
|
915
|
+
source_still_bound = _sha256_file(source) == request.source_sha256
|
|
916
|
+
if not (
|
|
917
|
+
candidate.valid
|
|
918
|
+
and target_change_reports is not None
|
|
919
|
+
and all(item["passed"] for item in target_change_reports)
|
|
920
|
+
and unselected_parts_preserved
|
|
921
|
+
and selected_parts_exact
|
|
922
|
+
and source_still_bound
|
|
923
|
+
):
|
|
924
|
+
return _report_refusal(
|
|
925
|
+
request,
|
|
926
|
+
"staged_verification_failed"
|
|
927
|
+
if source_still_bound
|
|
928
|
+
else "source_hash_changed",
|
|
929
|
+
)
|
|
930
|
+
os.replace(staged_path, destination)
|
|
931
|
+
staged_path = None
|
|
932
|
+
return ReportAuthoringReport(
|
|
933
|
+
status=_PUBLISHED,
|
|
934
|
+
code=None,
|
|
935
|
+
source_sha256=request.source_sha256,
|
|
936
|
+
edit_targets=[edit.target_dict() for edit in request.edits],
|
|
937
|
+
destination_sha256=candidate.file_sha256,
|
|
938
|
+
target_change_reports=target_change_reports,
|
|
939
|
+
unselected_parts_preserved=True,
|
|
940
|
+
)
|
|
941
|
+
finally:
|
|
942
|
+
if staged_path is not None:
|
|
943
|
+
staged_path.unlink(missing_ok=True)
|