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.
Files changed (54) hide show
  1. wolfdocx/__init__.py +25 -0
  2. wolfdocx/_cache_root.py +24 -0
  3. wolfdocx/_comment_threads.py +278 -0
  4. wolfdocx/_inspection_cache.py +374 -0
  5. wolfdocx/_version.py +3 -0
  6. wolfdocx/admission.py +163 -0
  7. wolfdocx/assembly.py +463 -0
  8. wolfdocx/authoring.py +2773 -0
  9. wolfdocx/canonical.py +267 -0
  10. wolfdocx/content.py +963 -0
  11. wolfdocx/document.py +215 -0
  12. wolfdocx/errors.py +169 -0
  13. wolfdocx/find_replace.py +1210 -0
  14. wolfdocx/formatting.py +3160 -0
  15. wolfdocx/inspect.py +3999 -0
  16. wolfdocx/model.py +1038 -0
  17. wolfdocx/numbering_authoring.py +1422 -0
  18. wolfdocx/output.py +13 -0
  19. wolfdocx/package.py +2313 -0
  20. wolfdocx/package_profile.py +128 -0
  21. wolfdocx/page_setup.py +2483 -0
  22. wolfdocx/paragraph_authoring.py +1842 -0
  23. wolfdocx/properties.py +2728 -0
  24. wolfdocx/protection.py +1909 -0
  25. wolfdocx/regions.py +1993 -0
  26. wolfdocx/render_warnings.py +106 -0
  27. wolfdocx/reporting.py +943 -0
  28. wolfdocx/review.py +2862 -0
  29. wolfdocx/run_text.py +117 -0
  30. wolfdocx/section_break.py +1810 -0
  31. wolfdocx/session_ops/__init__.py +45 -0
  32. wolfdocx/session_ops/_bridge.py +151 -0
  33. wolfdocx/session_ops/lists.py +104 -0
  34. wolfdocx/session_ops/paragraphs.py +39 -0
  35. wolfdocx/session_ops/rich_objects.py +2598 -0
  36. wolfdocx/session_ops/run_edits.py +70 -0
  37. wolfdocx/session_ops/runs.py +313 -0
  38. wolfdocx/session_ops/sections.py +109 -0
  39. wolfdocx/session_ops/styling.py +99 -0
  40. wolfdocx/session_ops/tables.py +247 -0
  41. wolfdocx/styles_authoring.py +2822 -0
  42. wolfdocx/table_cell_properties.py +1458 -0
  43. wolfdocx/table_column.py +1501 -0
  44. wolfdocx/table_delete.py +942 -0
  45. wolfdocx/table_insert.py +1114 -0
  46. wolfdocx/table_merge.py +1863 -0
  47. wolfdocx/table_properties.py +2429 -0
  48. wolfdocx/table_row_properties.py +1095 -0
  49. wolfdocx/table_structure.py +1044 -0
  50. wolfdocx/text_effects.py +1438 -0
  51. wolfdocx-0.1.0.dist-info/METADATA +127 -0
  52. wolfdocx-0.1.0.dist-info/RECORD +54 -0
  53. wolfdocx-0.1.0.dist-info/WHEEL +4 -0
  54. wolfdocx-0.1.0.dist-info/licenses/LICENSE +21 -0
wolfdocx/content.py ADDED
@@ -0,0 +1,963 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import re
5
+ import zipfile
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import asdict, dataclass, field
8
+ from itertools import zip_longest
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Any, cast
11
+ from xml.etree import ElementTree as ET
12
+
13
+ from .inspect import (
14
+ InspectionReport,
15
+ PackageLimits,
16
+ _parse_bounded_xml,
17
+ _XmlSafetyError,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from .package import PackageGraph
22
+
23
+ ASSERTION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
24
+ CONTENT_OPERATORS = {"contains", "not_contains", "equals", "count"}
25
+ SCOPE_KINDS = {"document", "paragraph", "table_cell"}
26
+ PART_TEXT_PATTERN = re.compile(
27
+ r"^word/(?:header[1-9][0-9]*\.xml|footer[1-9][0-9]*\.xml|comments\.xml)$"
28
+ )
29
+ XML_ATTRIBUTE_PART_PATTERN = re.compile(
30
+ r"^word/(?:document|styles|numbering|header[1-9][0-9]*|"
31
+ r"footer[1-9][0-9]*|comments)\.xml$"
32
+ )
33
+ XML_LOCAL_NAME_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]{0,127}$")
34
+ SCOPE_KINDS.update({"part_text", "xml_attribute", "xml_text"})
35
+ MAX_CONTENT_ASSERTIONS = 100
36
+ MAX_TARGET_CHANGES = 100
37
+ MAX_ASSERTION_VALUE_CHARACTERS = 32_768
38
+ PROPOSABLE_TEXT_ELEMENT_NAMES = {"t", "instrText", "delText"}
39
+
40
+
41
+ class ContentPolicyError(ValueError):
42
+ def __init__(self, code: str, message: str) -> None:
43
+ super().__init__(message)
44
+ self.code = code
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ContentScope:
49
+ kind: str
50
+ index: int | None = None
51
+ table: int | None = None
52
+ row: int | None = None
53
+ cell: int | None = None
54
+ part: str | None = None
55
+ element_path: tuple[str, ...] | None = None
56
+ attribute: str | None = None
57
+ occurrence: int | None = None
58
+
59
+ @property
60
+ def location(self) -> str:
61
+ if self.kind == "paragraph":
62
+ return f"word/document.xml#paragraph[{self.index}]"
63
+ if self.kind == "table_cell":
64
+ return f"word/document.xml#table[{self.table}]/row[{self.row}]/cell[{self.cell}]"
65
+ if self.kind == "part_text":
66
+ assert self.part is not None
67
+ return self.part
68
+ if self.kind in {"xml_attribute", "xml_text"}:
69
+ assert self.part is not None
70
+ assert self.element_path is not None
71
+ location = f"{self.part}#{self.kind}[{'/'.join(self.element_path)}][{self.occurrence}]"
72
+ return f"{location}/@{self.attribute}" if self.kind == "xml_attribute" else location
73
+ return "word/document.xml"
74
+
75
+ def to_dict(self) -> dict[str, Any]:
76
+ payload = {key: value for key, value in asdict(self).items() if value is not None}
77
+ if self.element_path is not None:
78
+ payload["element_path"] = list(self.element_path)
79
+ return payload
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class ContentAssertion:
84
+ assertion_id: str
85
+ scope: ContentScope
86
+ operator: str
87
+ value: str
88
+ expected_count: int | None = None
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class ContentAssertionResult:
93
+ assertion_id: str
94
+ passed: bool
95
+ scope: dict[str, Any]
96
+ location: str
97
+ operator: str
98
+ value_sha256: str
99
+ value_characters: int
100
+ scope_found: bool
101
+ scope_text_sha256: str | None
102
+ scope_characters: int | None
103
+ observed_count: int | None
104
+ expected_count: int | None
105
+
106
+ def to_dict(self) -> dict[str, Any]:
107
+ return asdict(self)
108
+
109
+
110
+ @dataclass
111
+ class ContentAssertionReport:
112
+ results: list[ContentAssertionResult] = field(default_factory=list)
113
+
114
+ @property
115
+ def passed(self) -> bool:
116
+ return all(result.passed for result in self.results)
117
+
118
+ def to_dict(self) -> dict[str, Any]:
119
+ return {
120
+ "schema_version": 1,
121
+ "passed": self.passed,
122
+ "assertion_count": len(self.results),
123
+ "results": [result.to_dict() for result in self.results],
124
+ }
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class TargetChangeResult:
129
+ scope: dict[str, Any]
130
+ location: str
131
+ target_found: bool
132
+ target_changed: bool
133
+ baseline_value_sha256: str | None
134
+ candidate_value_sha256: str | None
135
+ remaining_part_equivalent: bool
136
+ passed: bool
137
+
138
+ def to_dict(self) -> dict[str, Any]:
139
+ return asdict(self)
140
+
141
+
142
+ @dataclass
143
+ class TargetChangeReport:
144
+ results: list[TargetChangeResult] = field(default_factory=list)
145
+ uncovered_changed_parts: list[str] = field(default_factory=list)
146
+
147
+ @property
148
+ def passed(self) -> bool:
149
+ return not self.uncovered_changed_parts and all(result.passed for result in self.results)
150
+
151
+ def to_dict(self) -> dict[str, Any]:
152
+ return {
153
+ "schema_version": 1,
154
+ "passed": self.passed,
155
+ "target_count": len(self.results),
156
+ "uncovered_changed_parts": self.uncovered_changed_parts,
157
+ "results": [result.to_dict() for result in self.results],
158
+ }
159
+
160
+
161
+ @dataclass
162
+ class TargetChangeProposalReport:
163
+ status: str
164
+ complete: bool
165
+ selectors: list[dict[str, Any]] = field(default_factory=list)
166
+ changed_word_parts: list[str] = field(default_factory=list)
167
+ changed_word_xml_parts: list[str] = field(default_factory=list)
168
+ covered_changed_parts: list[str] = field(default_factory=list)
169
+ unsupported_changed_parts: list[str] = field(default_factory=list)
170
+ structurally_incompatible_parts: list[str] = field(default_factory=list)
171
+ issues: list[str] = field(default_factory=list)
172
+ validation: TargetChangeReport | None = None
173
+
174
+ def to_dict(self) -> dict[str, Any]:
175
+ return {
176
+ "schema_version": 1,
177
+ "status": self.status,
178
+ "complete": self.complete,
179
+ "selector_count": len(self.selectors),
180
+ "changed_word_parts": self.changed_word_parts,
181
+ "changed_word_xml_parts": self.changed_word_xml_parts,
182
+ "covered_changed_parts": self.covered_changed_parts,
183
+ "unsupported_changed_parts": self.unsupported_changed_parts,
184
+ "structurally_incompatible_parts": self.structurally_incompatible_parts,
185
+ "issues": self.issues,
186
+ "validation": self.validation.to_dict() if self.validation else None,
187
+ }
188
+
189
+
190
+ def _unknown_fields(value: dict[str, Any], allowed: set[str], label: str) -> None:
191
+ unknown = set(value) - allowed
192
+ if unknown:
193
+ raise ContentPolicyError(
194
+ f"{label}_unknown_fields",
195
+ f"Unknown {label} fields: {', '.join(sorted(unknown))}.",
196
+ )
197
+
198
+
199
+ def _positive_index(value: Any, label: str) -> int:
200
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
201
+ raise ContentPolicyError(
202
+ "content_scope_index_invalid",
203
+ f"Content assertion {label} must be a positive 1-based integer.",
204
+ )
205
+ return value
206
+
207
+
208
+ def _parse_scope(value: Any) -> ContentScope:
209
+ if not isinstance(value, dict):
210
+ raise ContentPolicyError(
211
+ "content_scope_invalid",
212
+ "Content assertion scope must be a JSON object.",
213
+ )
214
+ kind = value.get("kind")
215
+ if not isinstance(kind, str) or kind not in SCOPE_KINDS:
216
+ raise ContentPolicyError(
217
+ "content_scope_kind_invalid",
218
+ "Content assertion scope kind must be document, paragraph, table_cell, "
219
+ "part_text, xml_attribute, or xml_text.",
220
+ )
221
+ if kind == "document":
222
+ _unknown_fields(value, {"kind"}, "content_scope")
223
+ return ContentScope(kind=kind)
224
+ if kind == "paragraph":
225
+ _unknown_fields(value, {"kind", "index"}, "content_scope")
226
+ return ContentScope(kind=kind, index=_positive_index(value.get("index"), "index"))
227
+ if kind == "part_text":
228
+ _unknown_fields(value, {"kind", "part"}, "content_scope")
229
+ part = value.get("part")
230
+ if not isinstance(part, str) or PART_TEXT_PATTERN.fullmatch(part) is None:
231
+ raise ContentPolicyError(
232
+ "content_scope_part_invalid",
233
+ "part_text scope must name a numbered Word header/footer or comments.xml.",
234
+ )
235
+ return ContentScope(kind=kind, part=part)
236
+ if kind in {"xml_attribute", "xml_text"}:
237
+ _unknown_fields(
238
+ value,
239
+ (
240
+ {"kind", "part", "element_path", "attribute", "occurrence"}
241
+ if kind == "xml_attribute"
242
+ else {"kind", "part", "element_path", "occurrence"}
243
+ ),
244
+ "content_scope",
245
+ )
246
+ part = value.get("part")
247
+ element_path = value.get("element_path")
248
+ attribute = value.get("attribute")
249
+ if not isinstance(part, str) or XML_ATTRIBUTE_PART_PATTERN.fullmatch(part) is None:
250
+ raise ContentPolicyError(
251
+ "content_scope_part_invalid",
252
+ f"{kind} scope must name a supported Word XML part.",
253
+ )
254
+ if (
255
+ not isinstance(element_path, list)
256
+ or not 1 <= len(element_path) <= 6
257
+ or any(
258
+ not isinstance(item, str) or XML_LOCAL_NAME_PATTERN.fullmatch(item) is None
259
+ for item in element_path
260
+ )
261
+ ):
262
+ raise ContentPolicyError(
263
+ "content_scope_element_path_invalid",
264
+ f"{kind} element_path must contain 1-6 XML local names.",
265
+ )
266
+ if kind == "xml_attribute" and (
267
+ not isinstance(attribute, str) or XML_LOCAL_NAME_PATTERN.fullmatch(attribute) is None
268
+ ):
269
+ raise ContentPolicyError(
270
+ "content_scope_attribute_invalid",
271
+ "xml_attribute attribute must be an XML local name.",
272
+ )
273
+ return ContentScope(
274
+ kind=kind,
275
+ part=part,
276
+ element_path=tuple(element_path),
277
+ attribute=attribute if kind == "xml_attribute" else None,
278
+ occurrence=_positive_index(value.get("occurrence"), "occurrence"),
279
+ )
280
+ _unknown_fields(value, {"kind", "table", "row", "cell"}, "content_scope")
281
+ return ContentScope(
282
+ kind=kind,
283
+ table=_positive_index(value.get("table"), "table"),
284
+ row=_positive_index(value.get("row"), "row"),
285
+ cell=_positive_index(value.get("cell"), "cell"),
286
+ )
287
+
288
+
289
+ def parse_content_assertions(value: Any) -> list[ContentAssertion]:
290
+ if not isinstance(value, list):
291
+ raise ContentPolicyError(
292
+ "content_assertions_invalid",
293
+ "content_assertions must be an array.",
294
+ )
295
+ if len(value) > MAX_CONTENT_ASSERTIONS:
296
+ raise ContentPolicyError(
297
+ "content_assertion_limit",
298
+ f"content_assertions cannot exceed {MAX_CONTENT_ASSERTIONS} entries.",
299
+ )
300
+ assertions: list[ContentAssertion] = []
301
+ identifiers: set[str] = set()
302
+ for position, item in enumerate(value, start=1):
303
+ if not isinstance(item, dict):
304
+ raise ContentPolicyError(
305
+ "content_assertion_invalid",
306
+ f"Content assertion {position} must be a JSON object.",
307
+ )
308
+ _unknown_fields(
309
+ item,
310
+ {"id", "scope", "operator", "value", "expected_count"},
311
+ "content_assertion",
312
+ )
313
+ assertion_id = item.get("id")
314
+ if (
315
+ not isinstance(assertion_id, str)
316
+ or ASSERTION_ID_PATTERN.fullmatch(assertion_id) is None
317
+ ):
318
+ raise ContentPolicyError(
319
+ "content_assertion_id_invalid",
320
+ "Content assertion id must be 1-64 portable identifier characters.",
321
+ )
322
+ if assertion_id in identifiers:
323
+ raise ContentPolicyError(
324
+ "content_assertion_id_duplicate",
325
+ f"Content assertion id is duplicated: {assertion_id}.",
326
+ )
327
+ identifiers.add(assertion_id)
328
+ operator = item.get("operator")
329
+ if not isinstance(operator, str) or operator not in CONTENT_OPERATORS:
330
+ raise ContentPolicyError(
331
+ "content_assertion_operator_invalid",
332
+ "Content assertion operator must be contains, not_contains, equals, or count.",
333
+ )
334
+ assertion_value = item.get("value")
335
+ if not isinstance(assertion_value, str):
336
+ raise ContentPolicyError(
337
+ "content_assertion_value_invalid",
338
+ "Content assertion value must be a string.",
339
+ )
340
+ if len(assertion_value) > MAX_ASSERTION_VALUE_CHARACTERS:
341
+ raise ContentPolicyError(
342
+ "content_assertion_value_limit",
343
+ "Content assertion value exceeds the character limit.",
344
+ )
345
+ if operator != "equals" and not assertion_value:
346
+ raise ContentPolicyError(
347
+ "content_assertion_value_empty",
348
+ "Only the equals operator can use an empty assertion value.",
349
+ )
350
+ expected_count = item.get("expected_count")
351
+ if operator == "count":
352
+ if (
353
+ isinstance(expected_count, bool)
354
+ or not isinstance(expected_count, int)
355
+ or expected_count < 0
356
+ ):
357
+ raise ContentPolicyError(
358
+ "content_assertion_count_invalid",
359
+ "The count operator requires a non-negative expected_count.",
360
+ )
361
+ elif "expected_count" in item:
362
+ raise ContentPolicyError(
363
+ "content_assertion_count_unexpected",
364
+ "expected_count is only valid with the count operator.",
365
+ )
366
+ assertions.append(
367
+ ContentAssertion(
368
+ assertion_id=assertion_id,
369
+ scope=_parse_scope(item.get("scope")),
370
+ operator=operator,
371
+ value=assertion_value,
372
+ expected_count=expected_count,
373
+ )
374
+ )
375
+ return assertions
376
+
377
+
378
+ def parse_target_changes(value: Any) -> list[ContentScope]:
379
+ if not isinstance(value, list):
380
+ raise ContentPolicyError(
381
+ "allowed_target_changes_invalid",
382
+ "allowed_target_changes must be an array.",
383
+ )
384
+ if len(value) > MAX_TARGET_CHANGES:
385
+ raise ContentPolicyError(
386
+ "allowed_target_change_limit",
387
+ f"allowed_target_changes cannot exceed {MAX_TARGET_CHANGES} entries.",
388
+ )
389
+ scopes: list[ContentScope] = []
390
+ locations: set[str] = set()
391
+ for position, item in enumerate(value, start=1):
392
+ scope = _parse_scope(item)
393
+ if scope.kind not in {"xml_attribute", "xml_text"}:
394
+ raise ContentPolicyError(
395
+ "allowed_target_change_scope_invalid",
396
+ f"Allowed target change {position} must use xml_attribute or xml_text.",
397
+ )
398
+ if scope.location in locations:
399
+ raise ContentPolicyError(
400
+ "allowed_target_change_duplicate",
401
+ f"Allowed target change is duplicated: {scope.location}.",
402
+ )
403
+ locations.add(scope.location)
404
+ scopes.append(scope)
405
+ return scopes
406
+
407
+
408
+ def _local_name(value: str) -> str:
409
+ return value.rsplit("}", 1)[-1]
410
+
411
+
412
+ def _current_file_sha256(path: Path) -> str:
413
+ digest = hashlib.sha256()
414
+ with path.open("rb") as stream:
415
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
416
+ digest.update(chunk)
417
+ return digest.hexdigest()
418
+
419
+
420
+ def _load_xml_root(report: InspectionReport, part: str) -> ET.Element | None:
421
+ path = Path(report.path)
422
+ expected_part = next((item for item in report.parts if item.name == part), None)
423
+ if expected_part is None or not path.is_file():
424
+ return None
425
+ try:
426
+ if _current_file_sha256(path) != report.file_sha256:
427
+ return None
428
+ with zipfile.ZipFile(path) as archive:
429
+ data = archive.read(part)
430
+ if hashlib.sha256(data).hexdigest() != expected_part.sha256:
431
+ return None
432
+ limits = PackageLimits(**report.limits)
433
+ root = _parse_bounded_xml(data, limits=limits, total_elements=[0], preserve_qnames=False)
434
+ if _current_file_sha256(path) != report.file_sha256:
435
+ return None
436
+ except (
437
+ OSError,
438
+ KeyError,
439
+ RuntimeError,
440
+ ValueError,
441
+ zipfile.BadZipFile,
442
+ ET.ParseError,
443
+ _XmlSafetyError,
444
+ ):
445
+ return None
446
+ return root
447
+
448
+
449
+ def _load_xml_root_from_graph(graph: PackageGraph, part: str) -> ET.Element | None:
450
+ from .package import PackageError
451
+
452
+ package_part = graph.part(part)
453
+ if package_part is None:
454
+ return None
455
+ try:
456
+ return cast(ET.Element, package_part.parsed_xml())
457
+ except PackageError:
458
+ return None
459
+
460
+
461
+ def _matches_element_path(current: tuple[str, ...], element_path: tuple[str, ...]) -> bool:
462
+ if current[-1] != element_path[-1]:
463
+ return False
464
+ position = 0
465
+ for name in current:
466
+ if name == element_path[position]:
467
+ position += 1
468
+ if position == len(element_path):
469
+ return True
470
+ return False
471
+
472
+
473
+ def _load_mutable_xml_root_from_graph(graph: PackageGraph, part: str) -> ET.Element | None:
474
+ from .package import PackageError
475
+
476
+ package_part = graph.part(part)
477
+ if package_part is None:
478
+ return None
479
+ try:
480
+ return package_part.parsed_xml().to_mutable_element()
481
+ except PackageError:
482
+ return None
483
+
484
+
485
+ def _matching_elements(root: ET.Element, scope: ContentScope) -> list[ET.Element]:
486
+ """Elements whose root-to-self local-name path matches ``scope.element_path``.
487
+
488
+ Equivalent to :func:`_matches_element_path` on each element's full path: the
489
+ greedy subsequence position is carried down the walk instead of rebuilding and
490
+ rescanning the path tuple at every element, and each distinct tag's local name
491
+ is computed once.
492
+ """
493
+ assert scope.element_path is not None
494
+ element_path = scope.element_path
495
+ length = len(element_path)
496
+ last = element_path[-1]
497
+ matches: list[ET.Element] = []
498
+ local_names: dict[object, str] = {}
499
+
500
+ def visit(element: ET.Element, position: int) -> None:
501
+ tag = element.tag
502
+ name = local_names.get(tag)
503
+ if name is None:
504
+ name = local_names[tag] = _local_name(tag)
505
+ if position < length and name == element_path[position]:
506
+ position += 1
507
+ if position == length and name == last:
508
+ matches.append(element)
509
+ for child in element:
510
+ visit(child, position)
511
+
512
+ visit(root, 0)
513
+ return matches
514
+
515
+
516
+ def _selected_xml_value(root: ET.Element, scope: ContentScope) -> str | None:
517
+ assert scope.occurrence is not None
518
+ matches = _matching_elements(root, scope)
519
+ if scope.occurrence > len(matches):
520
+ return None
521
+ element = matches[scope.occurrence - 1]
522
+ if scope.kind == "xml_text":
523
+ return element.text or ""
524
+ assert scope.attribute is not None
525
+ for name, value in element.attrib.items():
526
+ if _local_name(name) == scope.attribute:
527
+ return value
528
+ return None
529
+
530
+
531
+ _MaskUndo = tuple[ET.Element, str | None, str | None]
532
+
533
+
534
+ def _mask_xml_scope(
535
+ root: ET.Element, scope: ContentScope, undo: list[_MaskUndo]
536
+ ) -> tuple[bool, str | None]:
537
+ """Mask one scope's value in place, recording ``(element, attribute, original)``."""
538
+ assert scope.occurrence is not None
539
+ matches = _matching_elements(root, scope)
540
+ if scope.occurrence > len(matches):
541
+ return False, None
542
+ element = matches[scope.occurrence - 1]
543
+ if scope.kind == "xml_text":
544
+ undo.append((element, None, element.text))
545
+ value = element.text or ""
546
+ element.text = "[wolfdocx allowed target]"
547
+ return True, value
548
+ assert scope.attribute is not None
549
+ for name, value in element.attrib.items():
550
+ if _local_name(name) == scope.attribute:
551
+ undo.append((element, name, value))
552
+ element.attrib[name] = "[wolfdocx allowed target]"
553
+ return True, value
554
+ return False, None
555
+
556
+
557
+ def _xml_trees_equal(left: ET.Element, right: ET.Element) -> bool:
558
+ """Compare two trees node by node without materializing either.
559
+
560
+ Equal tags, attribute mappings, text, tails and child counts along both pre-order
561
+ walks prove the trees are identical, because a pre-order walk annotated with child
562
+ counts determines the tree shape.
563
+ """
564
+ for left_node, right_node in zip_longest(left.iter(), right.iter()):
565
+ if (
566
+ left_node is None
567
+ or right_node is None
568
+ or left_node.tag != right_node.tag
569
+ or left_node.text != right_node.text
570
+ or left_node.tail != right_node.tail
571
+ or len(left_node) != len(right_node)
572
+ or left_node.attrib != right_node.attrib
573
+ ):
574
+ return False
575
+ return True
576
+
577
+
578
+ def _value_sha256(value: str | None) -> str | None:
579
+ return hashlib.sha256(value.encode("utf-8")).hexdigest() if value is not None else None
580
+
581
+
582
+ def _part_hashes(report: InspectionReport) -> dict[str, str]:
583
+ return {part.name: part.sha256 for part in report.parts}
584
+
585
+
586
+ def _evaluate_target_changes(
587
+ scopes: list[ContentScope],
588
+ baseline_parts: Mapping[str, str],
589
+ candidate_parts: Mapping[str, str],
590
+ *,
591
+ load_baseline_root: Callable[[str], ET.Element | None],
592
+ load_candidate_root: Callable[[str], ET.Element | None],
593
+ ) -> TargetChangeReport:
594
+ """Verify each scope changed and nothing else in its part did.
595
+
596
+ Scopes are masked in place for the comparison and restored before returning, so
597
+ the loaders may return shared trees that nothing else mutates concurrently.
598
+ """
599
+ changed_word_xml_parts = {
600
+ name
601
+ for name in baseline_parts.keys() | candidate_parts.keys()
602
+ if name.startswith("word/")
603
+ and name.endswith(".xml")
604
+ and baseline_parts.get(name) != candidate_parts.get(name)
605
+ }
606
+ declared_parts = {scope.part for scope in scopes if scope.part is not None}
607
+ uncovered = sorted(changed_word_xml_parts - declared_parts)
608
+ results: list[TargetChangeResult] = []
609
+ for part in sorted(declared_parts):
610
+ assert part is not None
611
+ part_scopes = [scope for scope in scopes if scope.part == part]
612
+ baseline_root = load_baseline_root(part)
613
+ candidate_root = load_candidate_root(part)
614
+ part_values: list[tuple[ContentScope, bool, str | None, bool, str | None]] = []
615
+ if baseline_root is not None and candidate_root is not None:
616
+ undo: list[_MaskUndo] = []
617
+ try:
618
+ for scope in part_scopes:
619
+ baseline_found, baseline_value = _mask_xml_scope(baseline_root, scope, undo)
620
+ candidate_found, candidate_value = _mask_xml_scope(candidate_root, scope, undo)
621
+ part_values.append(
622
+ (
623
+ scope,
624
+ baseline_found,
625
+ baseline_value,
626
+ candidate_found,
627
+ candidate_value,
628
+ )
629
+ )
630
+ remaining_equivalent = _xml_trees_equal(baseline_root, candidate_root)
631
+ finally:
632
+ # Undo in reverse so a value masked twice regains its original.
633
+ for element, attribute, original in reversed(undo):
634
+ if attribute is None:
635
+ element.text = original
636
+ else:
637
+ element.attrib[attribute] = original # type: ignore[assignment]
638
+ else:
639
+ remaining_equivalent = False
640
+ part_values = [(scope, False, None, False, None) for scope in part_scopes]
641
+ for (
642
+ scope,
643
+ baseline_found,
644
+ baseline_value,
645
+ candidate_found,
646
+ candidate_value,
647
+ ) in part_values:
648
+ found = baseline_found and candidate_found
649
+ changed = found and baseline_value != candidate_value
650
+ results.append(
651
+ TargetChangeResult(
652
+ scope=scope.to_dict(),
653
+ location=scope.location,
654
+ target_found=found,
655
+ target_changed=changed,
656
+ baseline_value_sha256=_value_sha256(baseline_value),
657
+ candidate_value_sha256=_value_sha256(candidate_value),
658
+ remaining_part_equivalent=remaining_equivalent,
659
+ passed=found and changed and remaining_equivalent,
660
+ )
661
+ )
662
+ return TargetChangeReport(results=results, uncovered_changed_parts=uncovered)
663
+
664
+
665
+ def evaluate_target_changes(
666
+ scopes: list[ContentScope],
667
+ baseline: InspectionReport,
668
+ candidate: InspectionReport,
669
+ ) -> TargetChangeReport:
670
+ return _evaluate_target_changes(
671
+ scopes,
672
+ _part_hashes(baseline),
673
+ _part_hashes(candidate),
674
+ load_baseline_root=lambda part: _load_xml_root(baseline, part),
675
+ load_candidate_root=lambda part: _load_xml_root(candidate, part),
676
+ )
677
+
678
+
679
+ def _evaluate_target_changes_from_graphs(
680
+ scopes: list[ContentScope],
681
+ baseline: InspectionReport,
682
+ candidate: InspectionReport,
683
+ baseline_graph: PackageGraph,
684
+ candidate_graph: PackageGraph,
685
+ ) -> TargetChangeReport:
686
+ return _evaluate_target_changes(
687
+ scopes,
688
+ _part_hashes(baseline),
689
+ _part_hashes(candidate),
690
+ load_baseline_root=lambda part: _load_mutable_xml_root_from_graph(baseline_graph, part),
691
+ load_candidate_root=lambda part: _load_mutable_xml_root_from_graph(candidate_graph, part),
692
+ )
693
+
694
+
695
+ def _flatten_xml(
696
+ root: ET.Element,
697
+ ) -> list[tuple[ET.Element, tuple[str, ...], tuple[str, ...]]]:
698
+ elements: list[tuple[ET.Element, tuple[str, ...], tuple[str, ...]]] = []
699
+
700
+ def visit(
701
+ element: ET.Element,
702
+ qualified_ancestors: tuple[str, ...],
703
+ local_ancestors: tuple[str, ...],
704
+ ) -> None:
705
+ qualified_path = (*qualified_ancestors, element.tag)
706
+ local_path = (*local_ancestors, _local_name(element.tag))
707
+ elements.append((element, qualified_path, local_path))
708
+ for child in element:
709
+ visit(child, qualified_path, local_path)
710
+
711
+ visit(root, (), ())
712
+ return elements
713
+
714
+
715
+ def _proposal_occurrence(
716
+ elements: list[tuple[ET.Element, tuple[str, ...], tuple[str, ...]]],
717
+ position: int,
718
+ element_path: tuple[str, ...],
719
+ ) -> int:
720
+ return sum(
721
+ _matches_element_path(local_path, element_path)
722
+ for _, _, local_path in elements[: position + 1]
723
+ )
724
+
725
+
726
+ def _part_target_proposals(
727
+ baseline_root: ET.Element,
728
+ approved_root: ET.Element,
729
+ *,
730
+ part: str,
731
+ ) -> list[ContentScope] | None:
732
+ baseline_elements = _flatten_xml(baseline_root)
733
+ approved_elements = _flatten_xml(approved_root)
734
+ if len(baseline_elements) != len(approved_elements):
735
+ return None
736
+ proposals: list[ContentScope] = []
737
+ for position, (baseline_item, approved_item) in enumerate(
738
+ zip(baseline_elements, approved_elements, strict=True)
739
+ ):
740
+ baseline_element, baseline_qualified_path, baseline_local_path = baseline_item
741
+ approved_element, approved_qualified_path, _ = approved_item
742
+ if (
743
+ baseline_qualified_path != approved_qualified_path
744
+ or baseline_element.tail != approved_element.tail
745
+ or len(baseline_element) != len(approved_element)
746
+ or set(baseline_element.attrib) != set(approved_element.attrib)
747
+ ):
748
+ return None
749
+ text_changed = baseline_element.text != approved_element.text
750
+ changed_attributes = [
751
+ attribute
752
+ for attribute in sorted(baseline_element.attrib)
753
+ if baseline_element.attrib[attribute] != approved_element.attrib[attribute]
754
+ ]
755
+ if not text_changed and not changed_attributes:
756
+ continue
757
+ element_path = baseline_local_path[-6:]
758
+ occurrence = _proposal_occurrence(baseline_elements, position, element_path)
759
+ if text_changed:
760
+ if (baseline_element.text or "") == (approved_element.text or ""):
761
+ return None
762
+ if (
763
+ len(baseline_element) != 0
764
+ or _local_name(baseline_element.tag) not in PROPOSABLE_TEXT_ELEMENT_NAMES
765
+ ):
766
+ return None
767
+ proposals.append(
768
+ ContentScope(
769
+ kind="xml_text",
770
+ part=part,
771
+ element_path=element_path,
772
+ occurrence=occurrence,
773
+ )
774
+ )
775
+ local_attributes = [_local_name(name) for name in baseline_element.attrib]
776
+ if changed_attributes and len(local_attributes) != len(set(local_attributes)):
777
+ return None
778
+ for attribute in changed_attributes:
779
+ proposals.append(
780
+ ContentScope(
781
+ kind="xml_attribute",
782
+ part=part,
783
+ element_path=element_path,
784
+ attribute=_local_name(attribute),
785
+ occurrence=occurrence,
786
+ )
787
+ )
788
+ return proposals
789
+
790
+
791
+ def propose_target_changes(
792
+ baseline: InspectionReport,
793
+ approved: InspectionReport,
794
+ ) -> TargetChangeProposalReport:
795
+ baseline_parts = {part.name: part.sha256 for part in baseline.parts}
796
+ approved_parts = {part.name: part.sha256 for part in approved.parts}
797
+ changed_word_parts = sorted(
798
+ name
799
+ for name in baseline_parts.keys() | approved_parts.keys()
800
+ if name.startswith("word/") and baseline_parts.get(name) != approved_parts.get(name)
801
+ )
802
+ changed_word_xml_parts = [name for name in changed_word_parts if name.endswith(".xml")]
803
+ unsupported = [
804
+ part for part in changed_word_parts if XML_ATTRIBUTE_PART_PATTERN.fullmatch(part) is None
805
+ ]
806
+ structural: list[str] = []
807
+ scopes: list[ContentScope] = []
808
+ for part in changed_word_xml_parts:
809
+ if part in unsupported:
810
+ continue
811
+ baseline_root = _load_xml_root(baseline, part)
812
+ approved_root = _load_xml_root(approved, part)
813
+ if baseline_root is None or approved_root is None:
814
+ structural.append(part)
815
+ continue
816
+ part_proposals = _part_target_proposals(
817
+ baseline_root,
818
+ approved_root,
819
+ part=part,
820
+ )
821
+ if part_proposals is None or not part_proposals:
822
+ structural.append(part)
823
+ continue
824
+ scopes.extend(part_proposals)
825
+ issues: list[str] = []
826
+ if unsupported:
827
+ issues.append("unsupported_changed_word_parts")
828
+ if structural:
829
+ issues.append("structurally_incompatible_word_xml_parts")
830
+ if len(scopes) > MAX_TARGET_CHANGES:
831
+ issues.append("allowed_target_change_limit")
832
+ scopes = []
833
+ validation = evaluate_target_changes(scopes, baseline, approved) if scopes else None
834
+ complete = bool(scopes) and not issues and bool(validation and validation.passed)
835
+ if validation is not None and not validation.passed:
836
+ issues.append("target_proposal_validation_failed")
837
+ complete = False
838
+ if not changed_word_parts:
839
+ status = "not_applicable"
840
+ elif complete:
841
+ status = "complete_review_required"
842
+ else:
843
+ status = "incomplete"
844
+ selectors = [scope.to_dict() for scope in scopes]
845
+ covered = sorted({scope.part for scope in scopes if scope.part is not None})
846
+ return TargetChangeProposalReport(
847
+ status=status,
848
+ complete=complete,
849
+ selectors=selectors,
850
+ changed_word_parts=changed_word_parts,
851
+ changed_word_xml_parts=changed_word_xml_parts,
852
+ covered_changed_parts=covered,
853
+ unsupported_changed_parts=unsupported,
854
+ structurally_incompatible_parts=sorted(structural),
855
+ issues=issues,
856
+ validation=validation,
857
+ )
858
+
859
+
860
+ def _scope_text(
861
+ report: InspectionReport,
862
+ scope: ContentScope,
863
+ *,
864
+ load_xml_root: Callable[[str], ET.Element | None],
865
+ ) -> str | None:
866
+ fingerprint = report.fingerprint
867
+ if scope.kind == "document":
868
+ return "\n".join(paragraph["text"] for paragraph in fingerprint.paragraphs)
869
+ if scope.kind == "paragraph":
870
+ assert scope.index is not None
871
+ if scope.index > len(fingerprint.paragraphs):
872
+ return None
873
+ return fingerprint.paragraphs[scope.index - 1]["text"]
874
+ if scope.kind == "part_text":
875
+ assert scope.part is not None
876
+ return report.part_texts.get(scope.part)
877
+ if scope.kind in {"xml_attribute", "xml_text"}:
878
+ assert scope.part is not None
879
+ root = load_xml_root(scope.part)
880
+ return _selected_xml_value(root, scope) if root is not None else None
881
+ assert scope.table is not None
882
+ assert scope.row is not None
883
+ assert scope.cell is not None
884
+ if scope.table > len(fingerprint.tables):
885
+ return None
886
+ table = fingerprint.tables[scope.table - 1]
887
+ if scope.row > len(table["rows"]):
888
+ return None
889
+ row = table["rows"][scope.row - 1]
890
+ if scope.cell > len(row["cells"]):
891
+ return None
892
+ return row["cells"][scope.cell - 1]["text"]
893
+
894
+
895
+ def _evaluate_content_assertions(
896
+ assertions: list[ContentAssertion],
897
+ candidate: InspectionReport,
898
+ *,
899
+ load_xml_root: Callable[[str], ET.Element | None],
900
+ ) -> ContentAssertionReport:
901
+ results: list[ContentAssertionResult] = []
902
+ for assertion in assertions:
903
+ text = _scope_text(
904
+ candidate,
905
+ assertion.scope,
906
+ load_xml_root=load_xml_root,
907
+ )
908
+ observed_count: int | None = None
909
+ passed = False
910
+ if text is not None:
911
+ if assertion.operator == "equals":
912
+ observed_count = 1 if text == assertion.value else 0
913
+ passed = text == assertion.value
914
+ else:
915
+ observed_count = text.count(assertion.value)
916
+ if assertion.operator == "contains":
917
+ passed = observed_count > 0
918
+ elif assertion.operator == "not_contains":
919
+ passed = observed_count == 0
920
+ else:
921
+ passed = observed_count == assertion.expected_count
922
+ results.append(
923
+ ContentAssertionResult(
924
+ assertion_id=assertion.assertion_id,
925
+ passed=passed,
926
+ scope=assertion.scope.to_dict(),
927
+ location=assertion.scope.location,
928
+ operator=assertion.operator,
929
+ value_sha256=hashlib.sha256(assertion.value.encode("utf-8")).hexdigest(),
930
+ value_characters=len(assertion.value),
931
+ scope_found=text is not None,
932
+ scope_text_sha256=(
933
+ hashlib.sha256(text.encode("utf-8")).hexdigest() if text is not None else None
934
+ ),
935
+ scope_characters=len(text) if text is not None else None,
936
+ observed_count=observed_count,
937
+ expected_count=assertion.expected_count,
938
+ )
939
+ )
940
+ return ContentAssertionReport(results=results)
941
+
942
+
943
+ def evaluate_content_assertions(
944
+ assertions: list[ContentAssertion],
945
+ candidate: InspectionReport,
946
+ ) -> ContentAssertionReport:
947
+ return _evaluate_content_assertions(
948
+ assertions,
949
+ candidate,
950
+ load_xml_root=lambda part: _load_xml_root(candidate, part),
951
+ )
952
+
953
+
954
+ def _evaluate_content_assertions_from_graph(
955
+ assertions: list[ContentAssertion],
956
+ candidate: InspectionReport,
957
+ graph: PackageGraph,
958
+ ) -> ContentAssertionReport:
959
+ return _evaluate_content_assertions(
960
+ assertions,
961
+ candidate,
962
+ load_xml_root=lambda part: _load_xml_root_from_graph(graph, part),
963
+ )