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/table_delete.py
ADDED
|
@@ -0,0 +1,942 @@
|
|
|
1
|
+
"""Source-bound DOCX body table deletion and target discovery.
|
|
2
|
+
|
|
3
|
+
Safely removes a targeted top-level body table from a WordprocessingML document
|
|
4
|
+
while guaranteeing preservation of surrounding body paragraphs, document section
|
|
5
|
+
properties, and unrelated package parts. Refuses stale, missing, or nested targets,
|
|
6
|
+
section or relationship hazards, and annotation or bookmark ranges crossing or
|
|
7
|
+
intersecting the removed table where safety cannot be established.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import zipfile
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
from xml.etree import ElementTree as ET
|
|
19
|
+
|
|
20
|
+
from .authoring import (
|
|
21
|
+
_PUBLISHED,
|
|
22
|
+
_REFUSED,
|
|
23
|
+
_cell_structure_fingerprint,
|
|
24
|
+
_require_sha256,
|
|
25
|
+
_sha256_file,
|
|
26
|
+
_unsupported_context_by_element,
|
|
27
|
+
_word_namespace,
|
|
28
|
+
)
|
|
29
|
+
from .inspect import (
|
|
30
|
+
Q,
|
|
31
|
+
inspect_docx,
|
|
32
|
+
parse_xml_with_preserved_qnames,
|
|
33
|
+
serialize_xml_with_preserved_qnames,
|
|
34
|
+
)
|
|
35
|
+
from .package import PackageError, PackageGraph
|
|
36
|
+
from .review import _DOCUMENT, ReviewReport, _publish
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"TableDeleteReport",
|
|
40
|
+
"TableDeleteRequest",
|
|
41
|
+
"TableDeleteTarget",
|
|
42
|
+
"author_table_delete",
|
|
43
|
+
"discover_table_delete_targets",
|
|
44
|
+
"load_table_delete_request",
|
|
45
|
+
"parse_table_delete_request",
|
|
46
|
+
"table_delete_structure_fingerprint",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
_REQUIRED_REQUEST_FIELDS = frozenset(
|
|
50
|
+
{"source", "destination", "source_sha256", "target", "structure_fingerprint_sha256"}
|
|
51
|
+
)
|
|
52
|
+
_ALLOWED_REQUEST_FIELDS = frozenset(
|
|
53
|
+
{"source", "destination", "source_sha256", "target", "structure_fingerprint_sha256"}
|
|
54
|
+
)
|
|
55
|
+
_REQUIRED_TARGET_FIELDS = frozenset({"table"})
|
|
56
|
+
_ALLOWED_TARGET_FIELDS = frozenset({"table", "part"})
|
|
57
|
+
|
|
58
|
+
_RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
|
|
59
|
+
_PACKAGE_RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
|
|
60
|
+
_RELS_DOCUMENT = "word/_rels/document.xml.rels"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _unrelated_parts_preserved(source: Path, candidate: Path, changed: frozenset[str]) -> bool:
|
|
64
|
+
"""True when every part the request did not change is byte-identical to source."""
|
|
65
|
+
with (
|
|
66
|
+
zipfile.ZipFile(source) as before,
|
|
67
|
+
zipfile.ZipFile(candidate) as after,
|
|
68
|
+
):
|
|
69
|
+
names = set(after.namelist())
|
|
70
|
+
return all(
|
|
71
|
+
info.filename in names and before.read(info.filename) == after.read(info.filename)
|
|
72
|
+
for info in before.infolist()
|
|
73
|
+
if info.filename not in changed
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _is_supported_table(table: ET.Element, namespace: str) -> bool:
|
|
78
|
+
"""True if table has supported body table structure and at least one row."""
|
|
79
|
+
def word(local):
|
|
80
|
+
return Q(namespace, local)
|
|
81
|
+
if any(child.tag not in {word("tblPr"), word("tblGrid"), word("tr")} for child in table):
|
|
82
|
+
return False
|
|
83
|
+
rows = table.findall(word("tr"))
|
|
84
|
+
return len(rows) > 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _table_structure_fingerprint(table: ET.Element) -> str:
|
|
88
|
+
"""Hash the table's XML structure while deliberately masking cell text."""
|
|
89
|
+
return _cell_structure_fingerprint(table)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _validate_table_delete_target_dict(target: Any) -> dict[str, Any]:
|
|
93
|
+
if not isinstance(target, Mapping):
|
|
94
|
+
raise TypeError("table_delete_target_invalid")
|
|
95
|
+
keys = set(target)
|
|
96
|
+
if not keys.issubset(_ALLOWED_TARGET_FIELDS) or not _REQUIRED_TARGET_FIELDS.issubset(keys):
|
|
97
|
+
raise ValueError("table_delete_target_fields_invalid")
|
|
98
|
+
table = target["table"]
|
|
99
|
+
if isinstance(table, bool) or not isinstance(table, int) or table < 1:
|
|
100
|
+
raise ValueError("table_delete_table_invalid")
|
|
101
|
+
part = target.get("part", _DOCUMENT)
|
|
102
|
+
if not isinstance(part, str) or not part:
|
|
103
|
+
raise ValueError("table_delete_part_invalid")
|
|
104
|
+
return {"table": table, "part": part}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True)
|
|
108
|
+
class TableDeleteTarget:
|
|
109
|
+
"""One discovered candidate table target for deletion."""
|
|
110
|
+
|
|
111
|
+
table: int
|
|
112
|
+
structure_fingerprint_sha256: str
|
|
113
|
+
part: str = _DOCUMENT
|
|
114
|
+
rows_count: int = 0
|
|
115
|
+
columns_count: int = 0
|
|
116
|
+
style: str | None = None
|
|
117
|
+
preview_text: str = ""
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def target(self) -> dict[str, Any]:
|
|
121
|
+
return {"table": self.table, "part": self.part}
|
|
122
|
+
|
|
123
|
+
def to_dict(self) -> dict[str, Any]:
|
|
124
|
+
return {
|
|
125
|
+
"table": self.table,
|
|
126
|
+
"part": self.part,
|
|
127
|
+
"structure_fingerprint_sha256": self.structure_fingerprint_sha256,
|
|
128
|
+
"rows_count": self.rows_count,
|
|
129
|
+
"columns_count": self.columns_count,
|
|
130
|
+
"style": self.style,
|
|
131
|
+
"preview_text": self.preview_text,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class TableDeleteRequest:
|
|
137
|
+
"""One source-bound request to delete an exact body table."""
|
|
138
|
+
|
|
139
|
+
source: Path
|
|
140
|
+
destination: Path
|
|
141
|
+
source_sha256: str
|
|
142
|
+
target: Mapping[str, Any]
|
|
143
|
+
structure_fingerprint_sha256: str
|
|
144
|
+
|
|
145
|
+
def __post_init__(self) -> None:
|
|
146
|
+
if isinstance(self.source, str):
|
|
147
|
+
object.__setattr__(self, "source", Path(self.source))
|
|
148
|
+
elif not isinstance(self.source, Path):
|
|
149
|
+
raise TypeError("table_delete_source_invalid")
|
|
150
|
+
if not str(self.source):
|
|
151
|
+
raise ValueError("table_delete_source_invalid")
|
|
152
|
+
|
|
153
|
+
if isinstance(self.destination, str):
|
|
154
|
+
object.__setattr__(self, "destination", Path(self.destination))
|
|
155
|
+
elif not isinstance(self.destination, Path):
|
|
156
|
+
raise TypeError("table_delete_destination_invalid")
|
|
157
|
+
if not str(self.destination):
|
|
158
|
+
raise ValueError("table_delete_destination_invalid")
|
|
159
|
+
|
|
160
|
+
_require_sha256(self.source_sha256, "table_delete_source_sha256")
|
|
161
|
+
_require_sha256(
|
|
162
|
+
self.structure_fingerprint_sha256,
|
|
163
|
+
"table_delete_structure_fingerprint_sha256",
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
validated_target = _validate_table_delete_target_dict(self.target)
|
|
167
|
+
object.__setattr__(self, "target", validated_target)
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def table(self) -> int:
|
|
171
|
+
return self.target["table"]
|
|
172
|
+
|
|
173
|
+
@property
|
|
174
|
+
def part(self) -> str:
|
|
175
|
+
return self.target.get("part", _DOCUMENT)
|
|
176
|
+
|
|
177
|
+
def target_dict(self) -> dict[str, Any]:
|
|
178
|
+
return {"table": self.table, "part": self.part}
|
|
179
|
+
|
|
180
|
+
def to_dict(self) -> dict[str, Any]:
|
|
181
|
+
return {
|
|
182
|
+
"source": str(self.source),
|
|
183
|
+
"destination": str(self.destination),
|
|
184
|
+
"source_sha256": self.source_sha256,
|
|
185
|
+
"target": self.target_dict(),
|
|
186
|
+
"structure_fingerprint_sha256": self.structure_fingerprint_sha256,
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass(frozen=True)
|
|
191
|
+
class TableDeleteReport:
|
|
192
|
+
"""Content-safe public result for a table delete authoring request."""
|
|
193
|
+
|
|
194
|
+
status: str
|
|
195
|
+
code: str | None
|
|
196
|
+
source_sha256: str
|
|
197
|
+
destination_sha256: str | None = None
|
|
198
|
+
target: dict[str, Any] | None = None
|
|
199
|
+
deleted_table: dict[str, Any] | None = None
|
|
200
|
+
target_change_report: dict[str, Any] | None = None
|
|
201
|
+
non_target_parts_preserved: bool | None = None
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def passed(self) -> bool:
|
|
205
|
+
return self.status == _PUBLISHED
|
|
206
|
+
|
|
207
|
+
def to_dict(self) -> dict[str, Any]:
|
|
208
|
+
return {
|
|
209
|
+
"schema_version": 1,
|
|
210
|
+
"operation": "table-delete",
|
|
211
|
+
"passed": self.passed,
|
|
212
|
+
"status": self.status,
|
|
213
|
+
"code": self.code,
|
|
214
|
+
"source_sha256": self.source_sha256,
|
|
215
|
+
"destination_sha256": self.destination_sha256,
|
|
216
|
+
"target": self.target,
|
|
217
|
+
"deleted_table": self.deleted_table,
|
|
218
|
+
"target_change_report": self.target_change_report,
|
|
219
|
+
"non_target_parts_preserved": self.non_target_parts_preserved,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _table_delete_refusal(
|
|
224
|
+
request: TableDeleteRequest,
|
|
225
|
+
code: str,
|
|
226
|
+
target: dict[str, Any] | None = None,
|
|
227
|
+
) -> TableDeleteReport:
|
|
228
|
+
return TableDeleteReport(
|
|
229
|
+
status=_REFUSED,
|
|
230
|
+
code=code,
|
|
231
|
+
source_sha256=request.source_sha256,
|
|
232
|
+
destination_sha256=None,
|
|
233
|
+
target=target if target is not None else request.target_dict(),
|
|
234
|
+
deleted_table=None,
|
|
235
|
+
target_change_report=None,
|
|
236
|
+
non_target_parts_preserved=None,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def parse_table_delete_request(value: Any) -> TableDeleteRequest:
|
|
241
|
+
"""Parse and strictly validate a table delete authoring request."""
|
|
242
|
+
if not isinstance(value, Mapping):
|
|
243
|
+
raise TypeError("table_delete_request_invalid")
|
|
244
|
+
|
|
245
|
+
keys = set(value)
|
|
246
|
+
if not keys.issubset(_ALLOWED_REQUEST_FIELDS) or not _REQUIRED_REQUEST_FIELDS.issubset(keys):
|
|
247
|
+
raise ValueError("table_delete_request_fields_invalid")
|
|
248
|
+
|
|
249
|
+
source = value["source"]
|
|
250
|
+
if not isinstance(source, str) or not source:
|
|
251
|
+
raise ValueError("table_delete_source_invalid")
|
|
252
|
+
|
|
253
|
+
destination = value["destination"]
|
|
254
|
+
if not isinstance(destination, str) or not destination:
|
|
255
|
+
raise ValueError("table_delete_destination_invalid")
|
|
256
|
+
|
|
257
|
+
source_sha256 = _require_sha256(value["source_sha256"], "table_delete_source_sha256")
|
|
258
|
+
structure_fingerprint = _require_sha256(
|
|
259
|
+
value["structure_fingerprint_sha256"],
|
|
260
|
+
"table_delete_structure_fingerprint_sha256",
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
target = _validate_table_delete_target_dict(value["target"])
|
|
264
|
+
|
|
265
|
+
return TableDeleteRequest(
|
|
266
|
+
source=Path(source),
|
|
267
|
+
destination=Path(destination),
|
|
268
|
+
source_sha256=source_sha256,
|
|
269
|
+
target=target,
|
|
270
|
+
structure_fingerprint_sha256=structure_fingerprint,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def load_table_delete_request(path: str | Path) -> TableDeleteRequest:
|
|
275
|
+
"""Load and strictly validate one JSON table-delete request from disk."""
|
|
276
|
+
with Path(path).open("r", encoding="utf-8") as stream:
|
|
277
|
+
return parse_table_delete_request(json.load(stream))
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def table_delete_structure_fingerprint(
|
|
281
|
+
source: str | Path,
|
|
282
|
+
*,
|
|
283
|
+
table: int,
|
|
284
|
+
part: str = _DOCUMENT,
|
|
285
|
+
) -> str | None:
|
|
286
|
+
"""Return the source-bound structural fingerprint for one target body table."""
|
|
287
|
+
if part != _DOCUMENT:
|
|
288
|
+
return None
|
|
289
|
+
path = Path(source)
|
|
290
|
+
if not path.is_file():
|
|
291
|
+
return None
|
|
292
|
+
try:
|
|
293
|
+
graph = PackageGraph.from_file(path)
|
|
294
|
+
if part not in graph.parts:
|
|
295
|
+
return None
|
|
296
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
297
|
+
ns = _word_namespace(root)
|
|
298
|
+
if ns is None:
|
|
299
|
+
return None
|
|
300
|
+
tables = list(root.iter(Q(ns, "tbl")))
|
|
301
|
+
if table < 1 or table > len(tables):
|
|
302
|
+
return None
|
|
303
|
+
target_table = tables[table - 1]
|
|
304
|
+
body = root.find(Q(ns, "body"))
|
|
305
|
+
if body is None:
|
|
306
|
+
return None
|
|
307
|
+
parent_map = {c: p for p in root.iter() for c in p}
|
|
308
|
+
if parent_map.get(target_table) is not body:
|
|
309
|
+
return None
|
|
310
|
+
if target_table.find(f".//{Q(ns, 'tbl')}") is not None:
|
|
311
|
+
return None
|
|
312
|
+
if not _is_supported_table(target_table, ns):
|
|
313
|
+
return None
|
|
314
|
+
return _table_structure_fingerprint(target_table)
|
|
315
|
+
except (PackageError, OSError, ET.ParseError, KeyError):
|
|
316
|
+
return None
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _check_nested_hazard(
|
|
320
|
+
root: ET.Element,
|
|
321
|
+
target_table: ET.Element,
|
|
322
|
+
body: ET.Element,
|
|
323
|
+
ns: str,
|
|
324
|
+
) -> str | None:
|
|
325
|
+
"""Refuse nested table targets or targets containing nested tables."""
|
|
326
|
+
parent_map = {c: p for p in root.iter() for c in p}
|
|
327
|
+
if parent_map.get(target_table) is not body:
|
|
328
|
+
return "table_delete_target_nested"
|
|
329
|
+
|
|
330
|
+
curr = parent_map.get(target_table)
|
|
331
|
+
while curr is not None:
|
|
332
|
+
if curr.tag == Q(ns, "tbl"):
|
|
333
|
+
return "table_delete_target_nested"
|
|
334
|
+
curr = parent_map.get(curr)
|
|
335
|
+
|
|
336
|
+
if target_table.find(f".//{Q(ns, 'tbl')}") is not None:
|
|
337
|
+
return "table_delete_target_nested"
|
|
338
|
+
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _check_section_hazard(
|
|
343
|
+
target_table: ET.Element,
|
|
344
|
+
body: ET.Element,
|
|
345
|
+
ns: str,
|
|
346
|
+
) -> str | None:
|
|
347
|
+
"""Refuse targets whose deletion introduces section layout or validity hazards."""
|
|
348
|
+
if target_table.find(f".//{Q(ns, 'sectPr')}") is not None:
|
|
349
|
+
return "table_delete_section_hazard"
|
|
350
|
+
if target_table.find(f".//{Q(ns, 'sectPrChange')}") is not None:
|
|
351
|
+
return "table_delete_section_hazard"
|
|
352
|
+
|
|
353
|
+
remaining_paragraphs = [c for c in body if c is not target_table and c.tag == Q(ns, "p")]
|
|
354
|
+
if not remaining_paragraphs:
|
|
355
|
+
return "table_delete_section_hazard"
|
|
356
|
+
|
|
357
|
+
return None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _check_annotation_and_bookmark_hazards(
|
|
361
|
+
root: ET.Element,
|
|
362
|
+
target_table: ET.Element,
|
|
363
|
+
ns: str,
|
|
364
|
+
) -> str | None:
|
|
365
|
+
"""Refuse annotation or bookmark ranges crossing or intersecting the removed table."""
|
|
366
|
+
table_elems = set(target_table.iter())
|
|
367
|
+
doc_elems = list(root.iter())
|
|
368
|
+
elem_indices = {id(el): idx for idx, el in enumerate(doc_elems)}
|
|
369
|
+
|
|
370
|
+
tbl_start_idx = elem_indices[id(target_table)]
|
|
371
|
+
tbl_end_idx = max(elem_indices[id(el)] for el in table_elems)
|
|
372
|
+
|
|
373
|
+
# 1. Bookmarks
|
|
374
|
+
bm_starts: dict[str, ET.Element] = {}
|
|
375
|
+
bm_ends: dict[str, ET.Element] = {}
|
|
376
|
+
for el in doc_elems:
|
|
377
|
+
if el.tag == Q(ns, "bookmarkStart"):
|
|
378
|
+
bm_id = el.get(Q(ns, "id")) or el.get("id")
|
|
379
|
+
if bm_id is not None:
|
|
380
|
+
bm_starts[bm_id] = el
|
|
381
|
+
elif el.tag == Q(ns, "bookmarkEnd"):
|
|
382
|
+
bm_id = el.get(Q(ns, "id")) or el.get("id")
|
|
383
|
+
if bm_id is not None:
|
|
384
|
+
bm_ends[bm_id] = el
|
|
385
|
+
|
|
386
|
+
all_bm_ids = set(bm_starts) | set(bm_ends)
|
|
387
|
+
for bm_id in all_bm_ids:
|
|
388
|
+
start_el = bm_starts.get(bm_id)
|
|
389
|
+
end_el = bm_ends.get(bm_id)
|
|
390
|
+
start_in = (start_el in table_elems) if start_el is not None else False
|
|
391
|
+
end_in = (end_el in table_elems) if end_el is not None else False
|
|
392
|
+
|
|
393
|
+
# One boundary inside table, one outside -> crossing hazard
|
|
394
|
+
if start_in != end_in:
|
|
395
|
+
return "table_delete_bookmark_intersection_unsupported"
|
|
396
|
+
|
|
397
|
+
# Neither inside table -> check if range encloses / crosses the table
|
|
398
|
+
if not start_in and not end_in and start_el is not None and end_el is not None:
|
|
399
|
+
s_idx = elem_indices[id(start_el)]
|
|
400
|
+
e_idx = elem_indices[id(end_el)]
|
|
401
|
+
if s_idx < tbl_start_idx and e_idx > tbl_end_idx:
|
|
402
|
+
return "table_delete_bookmark_intersection_unsupported"
|
|
403
|
+
if (
|
|
404
|
+
s_idx < tbl_end_idx
|
|
405
|
+
and e_idx > tbl_start_idx
|
|
406
|
+
and not (e_idx < tbl_start_idx or s_idx > tbl_end_idx)
|
|
407
|
+
):
|
|
408
|
+
return "table_delete_bookmark_intersection_unsupported"
|
|
409
|
+
|
|
410
|
+
# Both inside table -> check if bookmark is referenced outside the table
|
|
411
|
+
if start_in and end_in and start_el is not None:
|
|
412
|
+
bm_name = start_el.get(Q(ns, "name")) or start_el.get("name")
|
|
413
|
+
if bm_name:
|
|
414
|
+
for el in doc_elems:
|
|
415
|
+
if el not in table_elems:
|
|
416
|
+
if el.tag == Q(ns, "hyperlink"):
|
|
417
|
+
anchor = el.get(Q(ns, "anchor")) or el.get("anchor")
|
|
418
|
+
if anchor == bm_name:
|
|
419
|
+
return "table_delete_bookmark_intersection_unsupported"
|
|
420
|
+
elif el.tag == Q(ns, "instrText") and el.text:
|
|
421
|
+
if bm_name in el.text:
|
|
422
|
+
return "table_delete_bookmark_intersection_unsupported"
|
|
423
|
+
|
|
424
|
+
# 2. Comments
|
|
425
|
+
comment_tags = {
|
|
426
|
+
Q(ns, "commentRangeStart"),
|
|
427
|
+
Q(ns, "commentRangeEnd"),
|
|
428
|
+
Q(ns, "commentReference"),
|
|
429
|
+
}
|
|
430
|
+
for el in table_elems:
|
|
431
|
+
if el.tag in comment_tags:
|
|
432
|
+
return "table_delete_annotation_intersection_unsupported"
|
|
433
|
+
|
|
434
|
+
c_starts: dict[str, ET.Element] = {}
|
|
435
|
+
c_ends: dict[str, ET.Element] = {}
|
|
436
|
+
for el in doc_elems:
|
|
437
|
+
if el.tag == Q(ns, "commentRangeStart"):
|
|
438
|
+
cid = el.get(Q(ns, "id")) or el.get("id")
|
|
439
|
+
if cid is not None:
|
|
440
|
+
c_starts[cid] = el
|
|
441
|
+
elif el.tag == Q(ns, "commentRangeEnd"):
|
|
442
|
+
cid = el.get(Q(ns, "id")) or el.get("id")
|
|
443
|
+
if cid is not None:
|
|
444
|
+
c_ends[cid] = el
|
|
445
|
+
|
|
446
|
+
for cid in set(c_starts) | set(c_ends):
|
|
447
|
+
s_el = c_starts.get(cid)
|
|
448
|
+
e_el = c_ends.get(cid)
|
|
449
|
+
s_in = (s_el in table_elems) if s_el is not None else False
|
|
450
|
+
e_in = (e_el in table_elems) if e_el is not None else False
|
|
451
|
+
if s_in or e_in:
|
|
452
|
+
return "table_delete_annotation_intersection_unsupported"
|
|
453
|
+
if s_el is not None and e_el is not None:
|
|
454
|
+
s_idx = elem_indices[id(s_el)]
|
|
455
|
+
e_idx = elem_indices[id(e_el)]
|
|
456
|
+
if s_idx < tbl_start_idx and e_idx > tbl_end_idx:
|
|
457
|
+
return "table_delete_annotation_intersection_unsupported"
|
|
458
|
+
|
|
459
|
+
# 3. Tracked Revisions (ins, del, move ranges)
|
|
460
|
+
revision_tags = {
|
|
461
|
+
Q(ns, "ins"),
|
|
462
|
+
Q(ns, "del"),
|
|
463
|
+
Q(ns, "moveFromRangeStart"),
|
|
464
|
+
Q(ns, "moveFromRangeEnd"),
|
|
465
|
+
Q(ns, "moveToRangeStart"),
|
|
466
|
+
Q(ns, "moveToRangeEnd"),
|
|
467
|
+
Q(ns, "moveFrom"),
|
|
468
|
+
Q(ns, "moveTo"),
|
|
469
|
+
}
|
|
470
|
+
for el in table_elems:
|
|
471
|
+
if el.tag in revision_tags:
|
|
472
|
+
return "table_delete_annotation_intersection_unsupported"
|
|
473
|
+
|
|
474
|
+
for start_tag, end_tag in [
|
|
475
|
+
("moveFromRangeStart", "moveFromRangeEnd"),
|
|
476
|
+
("moveToRangeStart", "moveToRangeEnd"),
|
|
477
|
+
]:
|
|
478
|
+
m_starts: dict[str, ET.Element] = {}
|
|
479
|
+
m_ends: dict[str, ET.Element] = {}
|
|
480
|
+
for el in doc_elems:
|
|
481
|
+
if el.tag == Q(ns, start_tag):
|
|
482
|
+
mid = el.get(Q(ns, "id")) or el.get("id")
|
|
483
|
+
if mid is not None:
|
|
484
|
+
m_starts[mid] = el
|
|
485
|
+
elif el.tag == Q(ns, end_tag):
|
|
486
|
+
mid = el.get(Q(ns, "id")) or el.get("id")
|
|
487
|
+
if mid is not None:
|
|
488
|
+
m_ends[mid] = el
|
|
489
|
+
|
|
490
|
+
for mid in set(m_starts) | set(m_ends):
|
|
491
|
+
s_el = m_starts.get(mid)
|
|
492
|
+
e_el = m_ends.get(mid)
|
|
493
|
+
s_in = (s_el in table_elems) if s_el is not None else False
|
|
494
|
+
e_in = (e_el in table_elems) if e_el is not None else False
|
|
495
|
+
if s_in or e_in:
|
|
496
|
+
return "table_delete_annotation_intersection_unsupported"
|
|
497
|
+
if s_el is not None and e_el is not None:
|
|
498
|
+
s_idx = elem_indices[id(s_el)]
|
|
499
|
+
e_idx = elem_indices[id(e_el)]
|
|
500
|
+
if s_idx < tbl_start_idx and e_idx > tbl_end_idx:
|
|
501
|
+
return "table_delete_annotation_intersection_unsupported"
|
|
502
|
+
|
|
503
|
+
return None
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _inspect_and_prune_relationships(
|
|
507
|
+
graph: PackageGraph,
|
|
508
|
+
root: ET.Element,
|
|
509
|
+
target_table: ET.Element,
|
|
510
|
+
) -> tuple[str | None, bytes | None]:
|
|
511
|
+
"""Inspect relationship references in table and safely prune solely-owned external rels.
|
|
512
|
+
|
|
513
|
+
Preserves all relationships used outside the target table. Refuses internal part
|
|
514
|
+
hazards, broken/missing relationship records, and complex embedded dependencies.
|
|
515
|
+
"""
|
|
516
|
+
table_rel_ids: set[str] = set()
|
|
517
|
+
for el in target_table.iter():
|
|
518
|
+
for attr_name, attr_val in el.attrib.items():
|
|
519
|
+
if attr_name.startswith((f"{{{_RELATIONSHIPS_NS}}}", "r:")):
|
|
520
|
+
table_rel_ids.add(attr_val)
|
|
521
|
+
|
|
522
|
+
if not table_rel_ids:
|
|
523
|
+
return None, None
|
|
524
|
+
|
|
525
|
+
if _RELS_DOCUMENT not in graph.parts:
|
|
526
|
+
return "table_delete_relationship_hazard", None
|
|
527
|
+
|
|
528
|
+
try:
|
|
529
|
+
rels_bytes = graph.read_part_bytes(_RELS_DOCUMENT)
|
|
530
|
+
rels_root = parse_xml_with_preserved_qnames(rels_bytes)
|
|
531
|
+
except (ET.ParseError, KeyError, PackageError):
|
|
532
|
+
return "table_delete_relationship_hazard", None
|
|
533
|
+
|
|
534
|
+
rels_by_id: dict[str, ET.Element] = {}
|
|
535
|
+
for r in rels_root:
|
|
536
|
+
rid = r.get("Id")
|
|
537
|
+
if rid:
|
|
538
|
+
rels_by_id[rid] = r
|
|
539
|
+
|
|
540
|
+
for rel_id in table_rel_ids:
|
|
541
|
+
if rel_id not in rels_by_id:
|
|
542
|
+
return "table_delete_relationship_hazard", None
|
|
543
|
+
rel_elem = rels_by_id[rel_id]
|
|
544
|
+
rel_type = rel_elem.get("Type", "").lower()
|
|
545
|
+
if any(
|
|
546
|
+
structural in rel_type
|
|
547
|
+
for structural in (
|
|
548
|
+
"header",
|
|
549
|
+
"footer",
|
|
550
|
+
"comments",
|
|
551
|
+
"numbering",
|
|
552
|
+
"styles",
|
|
553
|
+
"settings",
|
|
554
|
+
"footnotes",
|
|
555
|
+
"endnotes",
|
|
556
|
+
"fonttable",
|
|
557
|
+
)
|
|
558
|
+
):
|
|
559
|
+
return "table_delete_relationship_hazard", None
|
|
560
|
+
|
|
561
|
+
# Determine which relationships are used outside target_table
|
|
562
|
+
table_elems = set(target_table.iter())
|
|
563
|
+
outside_rel_ids: set[str] = set()
|
|
564
|
+
for el in root.iter():
|
|
565
|
+
if el not in table_elems:
|
|
566
|
+
for attr_name, attr_val in el.attrib.items():
|
|
567
|
+
if attr_name.startswith((f"{{{_RELATIONSHIPS_NS}}}", "r:")):
|
|
568
|
+
outside_rel_ids.add(attr_val)
|
|
569
|
+
|
|
570
|
+
sole_rel_ids = table_rel_ids - outside_rel_ids
|
|
571
|
+
|
|
572
|
+
for rid in sole_rel_ids:
|
|
573
|
+
rel_elem = rels_by_id[rid]
|
|
574
|
+
target_mode = rel_elem.get("TargetMode", "")
|
|
575
|
+
rel_type = rel_elem.get("Type", "")
|
|
576
|
+
if target_mode != "External" and "hyperlink" not in rel_type:
|
|
577
|
+
return "table_delete_relationship_hazard", None
|
|
578
|
+
|
|
579
|
+
if sole_rel_ids:
|
|
580
|
+
for rel_elem in list(rels_root):
|
|
581
|
+
if rel_elem.get("Id") in sole_rel_ids:
|
|
582
|
+
rels_root.remove(rel_elem)
|
|
583
|
+
updated_rels = serialize_xml_with_preserved_qnames(rels_root)
|
|
584
|
+
return None, updated_rels
|
|
585
|
+
|
|
586
|
+
return None, None
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def discover_table_delete_targets(
|
|
590
|
+
source: str | Path,
|
|
591
|
+
*,
|
|
592
|
+
part: str = _DOCUMENT,
|
|
593
|
+
) -> dict[str, Any]:
|
|
594
|
+
"""Inventory source-bound candidate table targets for safe deletion."""
|
|
595
|
+
path = Path(source)
|
|
596
|
+
if not path.is_file():
|
|
597
|
+
return {
|
|
598
|
+
"schema_version": 1,
|
|
599
|
+
"operation": "table-delete-targets",
|
|
600
|
+
"passed": False,
|
|
601
|
+
"status": _REFUSED,
|
|
602
|
+
"code": "table_delete_source_missing",
|
|
603
|
+
"source_sha256": None,
|
|
604
|
+
"part": part,
|
|
605
|
+
"targets": [],
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
try:
|
|
609
|
+
source_sha256 = _sha256_file(path)
|
|
610
|
+
graph = PackageGraph.from_file(path)
|
|
611
|
+
except (PackageError, OSError, zipfile.BadZipFile):
|
|
612
|
+
return {
|
|
613
|
+
"schema_version": 1,
|
|
614
|
+
"operation": "table-delete-targets",
|
|
615
|
+
"passed": False,
|
|
616
|
+
"status": _REFUSED,
|
|
617
|
+
"code": "table_delete_package_invalid",
|
|
618
|
+
"source_sha256": None,
|
|
619
|
+
"part": part,
|
|
620
|
+
"targets": [],
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if part != _DOCUMENT or part not in graph.parts:
|
|
624
|
+
return {
|
|
625
|
+
"schema_version": 1,
|
|
626
|
+
"operation": "table-delete-targets",
|
|
627
|
+
"passed": False,
|
|
628
|
+
"status": _REFUSED,
|
|
629
|
+
"code": "table_delete_part_unsupported",
|
|
630
|
+
"source_sha256": source_sha256,
|
|
631
|
+
"part": part,
|
|
632
|
+
"targets": [],
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
try:
|
|
636
|
+
root = ET.fromstring(graph.read_part_bytes(part))
|
|
637
|
+
except (ET.ParseError, KeyError, PackageError):
|
|
638
|
+
return {
|
|
639
|
+
"schema_version": 1,
|
|
640
|
+
"operation": "table-delete-targets",
|
|
641
|
+
"passed": False,
|
|
642
|
+
"status": _REFUSED,
|
|
643
|
+
"code": "table_delete_package_invalid",
|
|
644
|
+
"source_sha256": source_sha256,
|
|
645
|
+
"part": part,
|
|
646
|
+
"targets": [],
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
namespace = _word_namespace(root)
|
|
650
|
+
if namespace is None:
|
|
651
|
+
return {
|
|
652
|
+
"schema_version": 1,
|
|
653
|
+
"operation": "table-delete-targets",
|
|
654
|
+
"passed": False,
|
|
655
|
+
"status": _REFUSED,
|
|
656
|
+
"code": "table_delete_namespace_unsupported",
|
|
657
|
+
"source_sha256": source_sha256,
|
|
658
|
+
"part": part,
|
|
659
|
+
"targets": [],
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
body = root.find(Q(namespace, "body"))
|
|
663
|
+
if body is None:
|
|
664
|
+
return {
|
|
665
|
+
"schema_version": 1,
|
|
666
|
+
"operation": "table-delete-targets",
|
|
667
|
+
"passed": True,
|
|
668
|
+
"status": "discovered",
|
|
669
|
+
"code": None,
|
|
670
|
+
"source_sha256": source_sha256,
|
|
671
|
+
"part": part,
|
|
672
|
+
"targets": [],
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
unsupported_context = _unsupported_context_by_element(root, namespace)
|
|
676
|
+
tables = list(root.iter(Q(namespace, "tbl")))
|
|
677
|
+
targets: list[dict[str, Any]] = []
|
|
678
|
+
|
|
679
|
+
for table_idx, table in enumerate(tables, start=1):
|
|
680
|
+
if unsupported_context.get(id(table), False):
|
|
681
|
+
continue
|
|
682
|
+
if not _is_supported_table(table, namespace):
|
|
683
|
+
continue
|
|
684
|
+
if _check_nested_hazard(root, table, body, namespace) is not None:
|
|
685
|
+
continue
|
|
686
|
+
if _check_section_hazard(table, body, namespace) is not None:
|
|
687
|
+
continue
|
|
688
|
+
if _check_annotation_and_bookmark_hazards(root, table, namespace) is not None:
|
|
689
|
+
continue
|
|
690
|
+
rel_hazard, _ = _inspect_and_prune_relationships(graph, root, table)
|
|
691
|
+
if rel_hazard is not None:
|
|
692
|
+
continue
|
|
693
|
+
|
|
694
|
+
fp = _table_structure_fingerprint(table)
|
|
695
|
+
rows = table.findall(Q(namespace, "tr"))
|
|
696
|
+
tbl_grid = table.find(Q(namespace, "tblGrid"))
|
|
697
|
+
grid_cols = tbl_grid.findall(Q(namespace, "gridCol")) if tbl_grid is not None else []
|
|
698
|
+
cols_count = (
|
|
699
|
+
len(grid_cols)
|
|
700
|
+
if grid_cols
|
|
701
|
+
else max((len(r.findall(Q(namespace, "tc"))) for r in rows), default=0)
|
|
702
|
+
)
|
|
703
|
+
|
|
704
|
+
tbl_pr = table.find(Q(namespace, "tblPr"))
|
|
705
|
+
style: str | None = None
|
|
706
|
+
if tbl_pr is not None:
|
|
707
|
+
style_elem = tbl_pr.find(Q(namespace, "tblStyle"))
|
|
708
|
+
if style_elem is not None:
|
|
709
|
+
style = style_elem.get(Q(namespace, "val"))
|
|
710
|
+
|
|
711
|
+
texts: list[str] = []
|
|
712
|
+
for t in table.iter(Q(namespace, "t")):
|
|
713
|
+
if t.text:
|
|
714
|
+
texts.append(t.text)
|
|
715
|
+
if sum(len(x) for x in texts) >= 50:
|
|
716
|
+
break
|
|
717
|
+
preview_text = "".join(texts)[:50]
|
|
718
|
+
|
|
719
|
+
target = TableDeleteTarget(
|
|
720
|
+
table=table_idx,
|
|
721
|
+
structure_fingerprint_sha256=fp,
|
|
722
|
+
part=part,
|
|
723
|
+
rows_count=len(rows),
|
|
724
|
+
columns_count=cols_count,
|
|
725
|
+
style=style,
|
|
726
|
+
preview_text=preview_text,
|
|
727
|
+
)
|
|
728
|
+
targets.append(target.to_dict())
|
|
729
|
+
|
|
730
|
+
return {
|
|
731
|
+
"schema_version": 1,
|
|
732
|
+
"operation": "table-delete-targets",
|
|
733
|
+
"passed": True,
|
|
734
|
+
"status": "discovered",
|
|
735
|
+
"code": None,
|
|
736
|
+
"source_sha256": source_sha256,
|
|
737
|
+
"part": part,
|
|
738
|
+
"targets": targets,
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def author_table_delete(request: TableDeleteRequest) -> TableDeleteReport:
|
|
743
|
+
"""Delete an exact source-bound body table atomically, preserving surrounding structure."""
|
|
744
|
+
if not isinstance(request, TableDeleteRequest):
|
|
745
|
+
raise TypeError("table_delete_request_invalid")
|
|
746
|
+
|
|
747
|
+
source = request.source
|
|
748
|
+
destination = request.destination
|
|
749
|
+
|
|
750
|
+
if destination.exists() or destination.is_symlink():
|
|
751
|
+
return _table_delete_refusal(request, "table_delete_destination_occupied")
|
|
752
|
+
|
|
753
|
+
if not destination.parent.is_dir():
|
|
754
|
+
return _table_delete_refusal(request, "table_delete_destination_invalid")
|
|
755
|
+
|
|
756
|
+
try:
|
|
757
|
+
if source.resolve() == destination.resolve():
|
|
758
|
+
return _table_delete_refusal(request, "table_delete_destination_invalid")
|
|
759
|
+
except OSError:
|
|
760
|
+
if source == destination:
|
|
761
|
+
return _table_delete_refusal(request, "table_delete_destination_invalid")
|
|
762
|
+
|
|
763
|
+
if not source.is_file():
|
|
764
|
+
return _table_delete_refusal(request, "table_delete_source_missing")
|
|
765
|
+
|
|
766
|
+
try:
|
|
767
|
+
source_sha256 = _sha256_file(source)
|
|
768
|
+
except OSError:
|
|
769
|
+
return _table_delete_refusal(request, "table_delete_source_missing")
|
|
770
|
+
|
|
771
|
+
if source_sha256 != request.source_sha256:
|
|
772
|
+
return _table_delete_refusal(request, "table_delete_source_hash_mismatch")
|
|
773
|
+
|
|
774
|
+
try:
|
|
775
|
+
graph = PackageGraph.from_file(source)
|
|
776
|
+
except (PackageError, OSError, zipfile.BadZipFile):
|
|
777
|
+
return _table_delete_refusal(request, "table_delete_package_invalid")
|
|
778
|
+
|
|
779
|
+
if request.part != _DOCUMENT or request.part not in graph.parts:
|
|
780
|
+
return _table_delete_refusal(request, "table_delete_part_unsupported")
|
|
781
|
+
|
|
782
|
+
try:
|
|
783
|
+
doc_bytes = graph.read_part_bytes(_DOCUMENT)
|
|
784
|
+
root = parse_xml_with_preserved_qnames(doc_bytes)
|
|
785
|
+
except (PackageError, ET.ParseError, KeyError, OSError):
|
|
786
|
+
return _table_delete_refusal(request, "table_delete_package_invalid")
|
|
787
|
+
|
|
788
|
+
namespace = _word_namespace(root)
|
|
789
|
+
if namespace is None:
|
|
790
|
+
return _table_delete_refusal(request, "table_delete_namespace_unsupported")
|
|
791
|
+
|
|
792
|
+
body = root.find(Q(namespace, "body"))
|
|
793
|
+
if body is None:
|
|
794
|
+
return _table_delete_refusal(request, "table_delete_target_missing")
|
|
795
|
+
|
|
796
|
+
tables = list(root.iter(Q(namespace, "tbl")))
|
|
797
|
+
if request.table < 1 or request.table > len(tables):
|
|
798
|
+
return _table_delete_refusal(request, "table_delete_target_missing")
|
|
799
|
+
|
|
800
|
+
target_tbl = tables[request.table - 1]
|
|
801
|
+
|
|
802
|
+
nested_err = _check_nested_hazard(root, target_tbl, body, namespace)
|
|
803
|
+
if nested_err is not None:
|
|
804
|
+
return _table_delete_refusal(request, nested_err)
|
|
805
|
+
|
|
806
|
+
if not _is_supported_table(target_tbl, namespace):
|
|
807
|
+
return _table_delete_refusal(request, "table_delete_context_unsupported")
|
|
808
|
+
|
|
809
|
+
actual_fp = _table_structure_fingerprint(target_tbl)
|
|
810
|
+
if actual_fp != request.structure_fingerprint_sha256:
|
|
811
|
+
return _table_delete_refusal(request, "table_delete_target_stale")
|
|
812
|
+
|
|
813
|
+
unsupported_context = _unsupported_context_by_element(root, namespace)
|
|
814
|
+
if unsupported_context.get(id(target_tbl), False):
|
|
815
|
+
return _table_delete_refusal(request, "table_delete_context_unsupported")
|
|
816
|
+
|
|
817
|
+
sect_err = _check_section_hazard(target_tbl, body, namespace)
|
|
818
|
+
if sect_err is not None:
|
|
819
|
+
return _table_delete_refusal(request, sect_err)
|
|
820
|
+
|
|
821
|
+
annot_err = _check_annotation_and_bookmark_hazards(root, target_tbl, namespace)
|
|
822
|
+
if annot_err is not None:
|
|
823
|
+
return _table_delete_refusal(request, annot_err)
|
|
824
|
+
|
|
825
|
+
rel_err, updated_rels = _inspect_and_prune_relationships(graph, root, target_tbl)
|
|
826
|
+
if rel_err is not None:
|
|
827
|
+
return _table_delete_refusal(request, rel_err)
|
|
828
|
+
|
|
829
|
+
# Capture original structure metrics for delta verification
|
|
830
|
+
orig_tables_count = len(tables)
|
|
831
|
+
orig_body_tables = [c for c in body if c.tag == Q(namespace, "tbl")]
|
|
832
|
+
orig_body_tables_count = len(orig_body_tables)
|
|
833
|
+
orig_body_paragraphs = [c for c in body if c.tag == Q(namespace, "p")]
|
|
834
|
+
orig_body_paragraphs_xml = [ET.tostring(p) for p in orig_body_paragraphs]
|
|
835
|
+
|
|
836
|
+
rows = target_tbl.findall(Q(namespace, "tr"))
|
|
837
|
+
tbl_grid = target_tbl.find(Q(namespace, "tblGrid"))
|
|
838
|
+
grid_cols = tbl_grid.findall(Q(namespace, "gridCol")) if tbl_grid is not None else []
|
|
839
|
+
cols_count = (
|
|
840
|
+
len(grid_cols)
|
|
841
|
+
if grid_cols
|
|
842
|
+
else max((len(r.findall(Q(namespace, "tc"))) for r in rows), default=0)
|
|
843
|
+
)
|
|
844
|
+
|
|
845
|
+
tbl_pr = target_tbl.find(Q(namespace, "tblPr"))
|
|
846
|
+
style: str | None = None
|
|
847
|
+
if tbl_pr is not None:
|
|
848
|
+
style_elem = tbl_pr.find(Q(namespace, "tblStyle"))
|
|
849
|
+
if style_elem is not None:
|
|
850
|
+
style = style_elem.get(Q(namespace, "val"))
|
|
851
|
+
|
|
852
|
+
target_change_report = {
|
|
853
|
+
"table_index": request.table,
|
|
854
|
+
"rows_deleted": len(rows),
|
|
855
|
+
"columns_deleted": cols_count,
|
|
856
|
+
"style": style,
|
|
857
|
+
"remaining_tables": orig_tables_count - 1,
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
# Perform table deletion from body
|
|
861
|
+
body.remove(target_tbl)
|
|
862
|
+
|
|
863
|
+
serialized_doc = serialize_xml_with_preserved_qnames(root)
|
|
864
|
+
replacements: dict[str, bytes] = {_DOCUMENT: serialized_doc}
|
|
865
|
+
changed_parts: set[str] = {_DOCUMENT}
|
|
866
|
+
|
|
867
|
+
if updated_rels is not None:
|
|
868
|
+
replacements[_RELS_DOCUMENT] = updated_rels
|
|
869
|
+
changed_parts.add(_RELS_DOCUMENT)
|
|
870
|
+
|
|
871
|
+
frozen_changed = frozenset(changed_parts)
|
|
872
|
+
|
|
873
|
+
def verify_publication(staged: Path) -> str | None:
|
|
874
|
+
if not _unrelated_parts_preserved(source, staged, frozen_changed):
|
|
875
|
+
return "table_delete_staged_verification_failed"
|
|
876
|
+
insp = inspect_docx(staged)
|
|
877
|
+
if not insp.valid:
|
|
878
|
+
return "table_delete_staged_verification_failed"
|
|
879
|
+
try:
|
|
880
|
+
s_graph = PackageGraph.from_file(staged)
|
|
881
|
+
s_root = ET.fromstring(s_graph.read_part_bytes(_DOCUMENT))
|
|
882
|
+
s_ns = _word_namespace(s_root)
|
|
883
|
+
if s_ns != namespace:
|
|
884
|
+
return "table_delete_staged_verification_failed"
|
|
885
|
+
s_body = s_root.find(Q(s_ns, "body"))
|
|
886
|
+
if s_body is None:
|
|
887
|
+
return "table_delete_staged_verification_failed"
|
|
888
|
+
|
|
889
|
+
# 1. Exact table-count delta proof
|
|
890
|
+
s_tables = list(s_root.iter(Q(s_ns, "tbl")))
|
|
891
|
+
if len(s_tables) != orig_tables_count - 1:
|
|
892
|
+
return "table_delete_staged_verification_failed"
|
|
893
|
+
|
|
894
|
+
s_body_tables = [c for c in s_body if c.tag == Q(s_ns, "tbl")]
|
|
895
|
+
if len(s_body_tables) != orig_body_tables_count - 1:
|
|
896
|
+
return "table_delete_staged_verification_failed"
|
|
897
|
+
|
|
898
|
+
# 2. Surrounding body paragraphs byte-identical proof
|
|
899
|
+
s_body_paragraphs = [c for c in s_body if c.tag == Q(s_ns, "p")]
|
|
900
|
+
if len(s_body_paragraphs) != len(orig_body_paragraphs):
|
|
901
|
+
return "table_delete_staged_verification_failed"
|
|
902
|
+
for orig_xml, s_p in zip(orig_body_paragraphs_xml, s_body_paragraphs):
|
|
903
|
+
if ET.tostring(s_p) != orig_xml:
|
|
904
|
+
return "table_delete_staged_verification_failed"
|
|
905
|
+
|
|
906
|
+
# 3. If rels was replaced, verify it parses cleanly
|
|
907
|
+
if _RELS_DOCUMENT in frozen_changed:
|
|
908
|
+
s_rels_bytes = s_graph.read_part_bytes(_RELS_DOCUMENT)
|
|
909
|
+
ET.fromstring(s_rels_bytes)
|
|
910
|
+
|
|
911
|
+
return None
|
|
912
|
+
except (PackageError, ET.ParseError, KeyError, OSError):
|
|
913
|
+
return "table_delete_staged_verification_failed"
|
|
914
|
+
|
|
915
|
+
published: ReviewReport = _publish(
|
|
916
|
+
source=source,
|
|
917
|
+
output=destination,
|
|
918
|
+
source_sha256=request.source_sha256,
|
|
919
|
+
replacements=replacements,
|
|
920
|
+
revisions=[],
|
|
921
|
+
targets=[target_change_report],
|
|
922
|
+
verify=verify_publication,
|
|
923
|
+
failure_code="table_delete_staged_verification_failed",
|
|
924
|
+
exists_code="table_delete_destination_occupied",
|
|
925
|
+
unavailable_code="table_delete_publication_unavailable",
|
|
926
|
+
)
|
|
927
|
+
|
|
928
|
+
if not published.passed:
|
|
929
|
+
return _table_delete_refusal(
|
|
930
|
+
request, published.code or "table_delete_staged_verification_failed"
|
|
931
|
+
)
|
|
932
|
+
|
|
933
|
+
return TableDeleteReport(
|
|
934
|
+
status=_PUBLISHED,
|
|
935
|
+
code=None,
|
|
936
|
+
source_sha256=request.source_sha256,
|
|
937
|
+
destination_sha256=published.output_sha256,
|
|
938
|
+
target=request.target_dict(),
|
|
939
|
+
deleted_table=target_change_report,
|
|
940
|
+
target_change_report=target_change_report,
|
|
941
|
+
non_target_parts_preserved=True,
|
|
942
|
+
)
|