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/document.py ADDED
@@ -0,0 +1,215 @@
1
+ """Open a DOCX once, edit in memory, and preserve untouched ZIP members."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import mmap
6
+ import tempfile
7
+ import zipfile
8
+ from pathlib import Path
9
+ from types import TracebackType
10
+ from typing import TYPE_CHECKING, Any, BinaryIO, Self
11
+
12
+ from .admission import _CFB_SIGNATURE, _admit, _Damage
13
+ from .package import PackageError, PackageLimits
14
+
15
+ if TYPE_CHECKING:
16
+ from xml.etree import ElementTree as ET
17
+
18
+ from .render_warnings import WarningCollection
19
+
20
+ __all__ = ["Document"]
21
+
22
+
23
+ class _EditMethod:
24
+ """Resolve an editing operation on first use and retain its descriptor."""
25
+
26
+ def __init__(self, name: str) -> None:
27
+ self.name = name
28
+
29
+ def _resolve(self) -> Any:
30
+ from .session_ops.rich_objects import DocumentOperations
31
+
32
+ value = getattr(DocumentOperations, self.name)
33
+ setattr(Document, self.name, value)
34
+ return value
35
+
36
+ def __get__(self, instance: Any, owner: type) -> Any:
37
+ return self._resolve().__get__(instance, owner)
38
+
39
+
40
+ class _EditProperty(_EditMethod):
41
+ def __set__(self, instance: Any, value: Any) -> None:
42
+ self._resolve().__set__(instance, value)
43
+
44
+
45
+ class Document:
46
+ """A validated DOCX package with in-memory editing and no-clobber saves.
47
+
48
+ Accept a path or an open, seekable binary stream. Streams remain caller-owned
49
+ and are copied to a private snapshot. Changes are written only by ``save``.
50
+ Untouched members retain their compressed bytes and ZIP entry metadata.
51
+ Use the context manager or ``close`` to release the source snapshot.
52
+ """
53
+
54
+ def __init__(
55
+ self, path: str | Path | BinaryIO, *, limits: PackageLimits | None = None
56
+ ) -> None:
57
+ self._source_snapshot: tempfile.TemporaryDirectory | None = None
58
+ if hasattr(path, "read"):
59
+ self._open_stream(path, Path("document.docx").resolve(), limits)
60
+ else:
61
+ resolved = Path(path).resolve()
62
+ with resolved.open("rb") as stream:
63
+ self._open_stream(stream, resolved, limits)
64
+
65
+ @classmethod
66
+ def from_bytes(
67
+ cls, data: bytes | BinaryIO, *, path: str | Path,
68
+ limits: PackageLimits | None = None,
69
+ ) -> Self:
70
+ """Open package bytes or a stream; ``path`` identifies it in reports."""
71
+ document = cls.__new__(cls)
72
+ document._source_snapshot = None
73
+ if hasattr(data, "read"):
74
+ document._open_stream(data, Path(path).resolve(), limits)
75
+ else:
76
+ document._open(bytes(data), Path(path).resolve(), limits)
77
+ return document
78
+
79
+ def _open_stream(
80
+ self, stream: BinaryIO, path: Path, limits: PackageLimits | None
81
+ ) -> None:
82
+ if stream.closed:
83
+ raise PackageError("stream_closed", "Load refused: stream_closed.")
84
+ if not stream.seekable():
85
+ raise PackageError("stream_not_seekable", "Load refused: stream_not_seekable.")
86
+ try:
87
+ stream.seek(0)
88
+ except (OSError, ValueError):
89
+ raise PackageError("stream_read_failed", "Load refused: stream_read_failed.") from None
90
+ self._source_snapshot = tempfile.TemporaryDirectory(prefix="wolfdocx-session-")
91
+ snapshot = Path(self._source_snapshot.name) / "source.docx"
92
+ bound = (limits or PackageLimits()).max_archive_size
93
+ size = 0
94
+ try:
95
+ try:
96
+ with snapshot.open("wb") as output:
97
+ while chunk := stream.read(64 * 1024):
98
+ size += len(chunk)
99
+ if size > bound:
100
+ raise PackageError("archive_size_limit", "Load refused: archive_size_limit.")
101
+ output.write(chunk)
102
+ except (OSError, ValueError):
103
+ raise PackageError("stream_read_failed", "Load refused: stream_read_failed.") from None
104
+ self._open(snapshot, path, limits)
105
+ except BaseException:
106
+ self._source_snapshot.cleanup()
107
+ self._source_snapshot = None
108
+ raise
109
+
110
+ def _open(self, data: bytes | Path, path: Path, limits: PackageLimits | None) -> None:
111
+ self.path = path
112
+ self._warnings: WarningCollection | None = None
113
+ if isinstance(data, Path):
114
+ with data.open("rb") as stream:
115
+ signature = stream.read(len(_CFB_SIGNATURE))
116
+ else:
117
+ signature = data[:len(_CFB_SIGNATURE)]
118
+ if signature == _CFB_SIGNATURE:
119
+ raise PackageError("document_format_unsupported", "A DOCX ZIP package is required.")
120
+ try:
121
+ self._graph = _admit(data, limits or PackageLimits(), self.path, whole=False)
122
+ except _Damage as damage:
123
+ raise PackageError(damage.code, f"Load refused: {damage.code}.", damage.target) from None
124
+ self.source_sha256 = self._graph.file_sha256
125
+ if isinstance(data, Path):
126
+ with data.open("rb") as stream:
127
+ self._data = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)
128
+ else:
129
+ self._data = data
130
+ self._source_graph = self._graph
131
+ with self._graph._open_archive() as archive:
132
+ self._infos = {info.filename: info for info in archive.infolist()}
133
+ self._comment = archive.comment
134
+ self._entries: dict[str, zipfile.ZipInfo] = dict(self._infos)
135
+ self._changed: dict[str, bytes] = {}
136
+ self._trees: dict[str, ET.Element] = {}
137
+ self._checked: dict[str, tuple[bytes, ET.Element, int]] = {}
138
+ self._edits: list[dict[str, Any]] = []
139
+
140
+ def __enter__(self) -> Self:
141
+ return self
142
+
143
+ def __exit__(
144
+ self, exc_type: type[BaseException] | None,
145
+ exc: BaseException | None, traceback: TracebackType | None,
146
+ ) -> None:
147
+ self.close()
148
+
149
+ def close(self) -> None:
150
+ """Release package bytes, disk snapshot, and parsed trees."""
151
+ if isinstance(self._data, mmap.mmap):
152
+ self._data.close()
153
+ self._data = None
154
+ if self._source_snapshot is not None:
155
+ self._source_snapshot.cleanup()
156
+ self._source_snapshot = None
157
+ self._changed.clear()
158
+ self._trees.clear()
159
+ self._checked.clear()
160
+
161
+ @property
162
+ def changed_parts(self) -> tuple[str, ...]:
163
+ """Source parts changed and parts added by this session."""
164
+ return tuple(sorted(self._changed))
165
+
166
+ def part_bytes(self, name: str) -> bytes:
167
+ """Current part bytes, including pending edits."""
168
+ self._source()
169
+ if name in self._changed:
170
+ return self._changed[name]
171
+ if name not in self._entries:
172
+ raise PackageError("missing_part", f"Part {name!r} not in package", name)
173
+ return self._source_graph.read_part_bytes(name)
174
+
175
+ def _source(self) -> bytes | mmap.mmap:
176
+ if self._data is None:
177
+ raise ValueError("document_closed")
178
+ return self._data
179
+
180
+
181
+ for _name in (
182
+ "_adopt", "_apply_operation", "_apply_paragraph_request", "_apply_steps",
183
+ "_bind_imported_node", "_checked_tree", "_column", "_current_tree",
184
+ "_definition_part", "_edit_paragraph", "_edit_part", "_editable", "_materialize",
185
+ "_merge", "_note_parts", "_numbering", "_paragraph", "_paragraph_request",
186
+ "_parse", "_parse_checked", "_record", "_record_save_report", "_replace_definitions",
187
+ "_restore", "_row", "_run_edit", "_section_break", "_set_part", "_snapshot",
188
+ "_take_editable", "_unchanged_raw", "_unchanged_raw_bytes", "_write", "_write_to",
189
+ "accept", "append_paragraph", "apply_list", "delete_paragraph", "delete_run",
190
+ "delete_section_break", "delete_table", "delete_table_column", "delete_table_row",
191
+ "edit_header_footer", "find_replace", "format_paragraph", "format_text", "get_story",
192
+ "insert_list_item", "insert_paragraph", "insert_run", "insert_section_break",
193
+ "insert_story", "insert_table", "insert_table_column", "insert_table_row",
194
+ "merge_table_cells", "remove_list", "restart_list", "save", "set_cell_text",
195
+ "set_page_setup", "set_run_text", "split_paragraph", "split_table_cells",
196
+ ):
197
+ setattr(Document, _name, _EditMethod(_name))
198
+
199
+ for _name in ("background", "background_xml", "lists", "node", "part_names", "stories", "styles", "warnings"):
200
+ setattr(Document, _name, _EditProperty(_name))
201
+ del _name
202
+
203
+
204
+ def __getattr__(name: str) -> Any:
205
+ if name == "SessionEditReport":
206
+ from .session_ops import SessionEditReport
207
+ return SessionEditReport
208
+ if name in {
209
+ "_raw_member", "_without_zip64_extra", "_structural", "_parse_part",
210
+ "_copy_member_raw", "_main_part", "_validate_node_structure", "_patch_node_texts",
211
+ "_added_entry", "_PART_ERRORS", "SessionSaveReport", "_plan_paragraph_edit",
212
+ }:
213
+ from .session_ops import rich_objects
214
+ return getattr(rich_objects, name)
215
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
wolfdocx/errors.py ADDED
@@ -0,0 +1,169 @@
1
+ """Typed public error taxonomy and the deterministic CLI exit contract.
2
+
3
+ Every WolfDocx failure is classified into one stable category with a safe
4
+ machine code, and every CLI command selects its exit status through
5
+ :func:`select_exit` so equivalent API and CLI failures expose the same
6
+ classification. Failure data never carries paths, document content, raw tool
7
+ output, or exception strings.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import subprocess
13
+ from dataclasses import dataclass
14
+ from enum import IntEnum, StrEnum, unique
15
+
16
+ from .canonical import safe_diagnostic_code
17
+
18
+
19
+ @unique
20
+ class ExitStatus(IntEnum):
21
+ """Deterministic CLI exit codes.
22
+
23
+ - ``SUCCESS``: the command completed with a positive outcome.
24
+ - ``NEGATIVE_DECISION``: the command completed a decision or validation
25
+ and the answer was negative, with no execution failure.
26
+ - ``EXECUTION_FAILURE``: invalid input or precondition, missing or
27
+ unreadable required artifacts, unavailable or failed tools, timeouts,
28
+ or internal execution failures.
29
+ """
30
+
31
+ SUCCESS = 0
32
+ NEGATIVE_DECISION = 1
33
+ EXECUTION_FAILURE = 2
34
+
35
+
36
+ @unique
37
+ class ErrorCategory(StrEnum):
38
+ """Public failure categories; all map to :attr:`ExitStatus.EXECUTION_FAILURE`."""
39
+
40
+ INVALID_INPUT = "invalid_input"
41
+ MISSING_ARTIFACT = "missing_artifact"
42
+ UNREADABLE_ARTIFACT = "unreadable_artifact"
43
+ PRECONDITION_FAILED = "precondition_failed"
44
+ TOOL_UNAVAILABLE = "tool_unavailable"
45
+ TOOL_FAILURE = "tool_failure"
46
+ TIMEOUT = "timeout"
47
+ INTERNAL_ERROR = "internal_error"
48
+
49
+ @property
50
+ def exit_status(self) -> ExitStatus:
51
+ return ExitStatus.EXECUTION_FAILURE
52
+
53
+
54
+ def safe_code(value: object, category: ErrorCategory) -> str:
55
+ """Return ``value`` only when it is a stable snake-case machine code.
56
+
57
+ Anything else — including exception text, paths, and document content —
58
+ collapses to the category's own stable code, so unsafe detail can never
59
+ enter a public error envelope.
60
+ """
61
+
62
+ return safe_diagnostic_code(value, fallback=str(category))
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Failure:
67
+ """Immutable machine-readable failure with a stable safe code."""
68
+
69
+ code: str
70
+ category: ErrorCategory
71
+
72
+ @property
73
+ def exit_status(self) -> ExitStatus:
74
+ return self.category.exit_status
75
+
76
+ def to_dict(self) -> dict[str, object]:
77
+ """Content-safe serialization: code, category, and exit status only."""
78
+
79
+ return {
80
+ "code": self.code,
81
+ "category": str(self.category),
82
+ "exit_code": int(self.exit_status),
83
+ }
84
+
85
+
86
+ class WolfDocxError(Exception):
87
+ """Typed WolfDocx execution failure carrying a :class:`Failure`.
88
+
89
+ The exception never carries message content; its public surface is the
90
+ immutable :attr:`failure` value and its stable code.
91
+ """
92
+
93
+ category: ErrorCategory = ErrorCategory.INTERNAL_ERROR
94
+
95
+ def __init__(self, code: str | None = None) -> None:
96
+ resolved = safe_code(code, self.category)
97
+ super().__init__(resolved)
98
+ self._code = resolved
99
+
100
+ @property
101
+ def code(self) -> str:
102
+ return self._code
103
+
104
+ @property
105
+ def failure(self) -> Failure:
106
+ return Failure(self._code, self.category)
107
+
108
+ def to_dict(self) -> dict[str, object]:
109
+ return self.failure.to_dict()
110
+
111
+
112
+ def _trusted_code_errors() -> tuple[type[Exception], ...]:
113
+ """Domain exceptions whose stable machine codes can be exposed safely."""
114
+ from .content import ContentPolicyError
115
+
116
+ return WolfDocxError, ContentPolicyError
117
+
118
+
119
+ def classify_failure(error: Exception) -> Failure:
120
+ """Classify any exception into the public taxonomy without leaking content.
121
+
122
+ Custom machine codes are honored only on the explicit trusted hierarchy
123
+ (:class:`WolfDocxError` and WolfDocx domain errors that carry a ``code``
124
+ attribute). A foreign exception's ``code`` attribute or message text is
125
+ never trusted and never becomes a public code: untrusted failures always
126
+ reduce to their category's stable default code.
127
+ """
128
+
129
+ if isinstance(error, WolfDocxError):
130
+ return error.failure
131
+ if isinstance(error, (subprocess.TimeoutExpired, TimeoutError)):
132
+ category = ErrorCategory.TIMEOUT
133
+ elif isinstance(error, FileNotFoundError):
134
+ category = ErrorCategory.MISSING_ARTIFACT
135
+ elif isinstance(error, OSError):
136
+ category = ErrorCategory.UNREADABLE_ARTIFACT
137
+ elif isinstance(error, (TypeError, ValueError)):
138
+ category = ErrorCategory.INVALID_INPUT
139
+ else:
140
+ category = ErrorCategory.INTERNAL_ERROR
141
+ code: object = category
142
+ if isinstance(error, _trusted_code_errors()):
143
+ code = getattr(error, "code", category)
144
+ return Failure(safe_code(code, category), category)
145
+
146
+
147
+ def failure_envelope(failure: Failure) -> dict[str, object]:
148
+ """Build the public pathless, contentless JSON envelope for a failure."""
149
+
150
+ return {
151
+ "schema_version": 1,
152
+ "passed": False,
153
+ "execution_error": True,
154
+ "error": failure.to_dict(),
155
+ }
156
+
157
+
158
+ def select_exit(*, decision_passed: bool, execution_failure: bool = False) -> ExitStatus:
159
+ """The one centralized exit selection used by every CLI command.
160
+
161
+ A negative decision is never hidden as an execution failure: only an
162
+ explicit execution failure yields :attr:`ExitStatus.EXECUTION_FAILURE`.
163
+ """
164
+
165
+ if execution_failure:
166
+ return ExitStatus.EXECUTION_FAILURE
167
+ if decision_passed:
168
+ return ExitStatus.SUCCESS
169
+ return ExitStatus.NEGATIVE_DECISION