ai-editor-tree-engine-dev 1.0.176__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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Explicit ``apply_subtree`` return path for concept C-019 (SubtreeCopyAndApply).
|
|
2
|
+
|
|
3
|
+
Scope: the counterpart to ``subtree_copy.py``'s read-only ``copy_subtree``,
|
|
4
|
+
per A-002. :func:`apply_subtree` returns a (possibly edited)
|
|
5
|
+
:class:`~tree_engine.core.subtree_copy.CopiedDocument` back into a target
|
|
6
|
+
document, replacing the original subtree it was copied from, per {p076}.
|
|
7
|
+
Out of scope: merge semantics (only the explicit replace), and a parallel
|
|
8
|
+
error taxonomy -- every rejection carries a stable
|
|
9
|
+
:class:`~tree_engine.errors.ErrorCode`, reusing ``NODE_ID_CONFLICT`` for
|
|
10
|
+
every identity collision this module rejects.
|
|
11
|
+
|
|
12
|
+
Locating the replaced subtree: the copy's own ``old_uuid_to_new_uuid`` map
|
|
13
|
+
(populated by ``copy_subtree`` in both identity modes, per {p073}/{p074})
|
|
14
|
+
carries the *origin* node_id of every copied node under its *new* one, so
|
|
15
|
+
the target node being replaced is found by inverting that map at the copy's
|
|
16
|
+
root -- uniform for both ``preserve_ids`` modes, no location parameter
|
|
17
|
+
needed from the caller.
|
|
18
|
+
|
|
19
|
+
NODE_ID_CONFLICT, per {p076}: the shared ``validate_mutation`` preflight
|
|
20
|
+
({p009}/C-006) rejects an incoming node_id colliding with an existing
|
|
21
|
+
``nodes_by_id`` key (its stage 2). Run unmodified, that would misfire on
|
|
22
|
+
every ``preserve_ids=True`` replace applied back to its own true origin --
|
|
23
|
+
the very identity it preserves always "collides" with the node it replaces.
|
|
24
|
+
This module runs ``validate_mutation`` against a *view* of the target with
|
|
25
|
+
the origin subtree's node_ids excluded -- but only once that origin is
|
|
26
|
+
confirmed the *same logical* subtree the copy came from: cross-referencing
|
|
27
|
+
``origin_document_id`` (must equal the target's ``document_id``) and, when
|
|
28
|
+
{p074}'s ``origin_parent_id`` was recorded (``preserve_ids=True``), the
|
|
29
|
+
origin's current parent in the target. Fresh-UUID4 mode ({p073}) has no
|
|
30
|
+
``origin_document_id`` recorded, so identity rests on
|
|
31
|
+
``old_uuid_to_new_uuid`` membership alone -- safe, a fresh UUID4 essentially
|
|
32
|
+
never collides with an unrelated node. Any collision left unexcluded -- an
|
|
33
|
+
unrelated node sharing the UUID4, or any collision against a document that
|
|
34
|
+
never held the recorded origin -- is a genuine ``NODE_ID_CONFLICT``, raised
|
|
35
|
+
as :class:`NodeIDConflictError` before anything is written.
|
|
36
|
+
|
|
37
|
+
short_id handling: a node already present in the target under its own
|
|
38
|
+
(copy) node_id -- identity-preserved by a legitimate ``preserve_ids=True``
|
|
39
|
+
replace -- keeps its existing target short_id untouched, and is not part of
|
|
40
|
+
the remap. Every other copied node is genuinely new, so its candidate
|
|
41
|
+
short_id (from the copy's own independent ``ShortIdMap``) is merged into
|
|
42
|
+
the target's ``short_id_map`` via
|
|
43
|
+
:meth:`~tree_engine.core.short_id.ShortIdMap.merge_insert`: free per {p097}
|
|
44
|
+
it survives, conflicting it gets a fresh value. :func:`build_short_id_remap`
|
|
45
|
+
turns that into the returned ``old -> new`` short_id map; a candidate that
|
|
46
|
+
stayed free is left out of it.
|
|
47
|
+
|
|
48
|
+
Duck-typed target ``document``: mutable ``nodes_by_id``, optional
|
|
49
|
+
``document_id``, optional ``document_version``/``version`` (for
|
|
50
|
+
``expected_version``), optional ``parent_index``, optional ``root`` (a
|
|
51
|
+
whole-document replace, no parent), optional ``short_id_index``, optional
|
|
52
|
+
``short_id_map`` (a :class:`~tree_engine.core.short_id.ShortIdMap``). A node
|
|
53
|
+
exposes ``node_id``, settable ``short_id``, settable ``children``, and
|
|
54
|
+
optionally settable ``parent_id``.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
from __future__ import annotations
|
|
58
|
+
|
|
59
|
+
from dataclasses import dataclass
|
|
60
|
+
from typing import (
|
|
61
|
+
Any,
|
|
62
|
+
Callable,
|
|
63
|
+
Dict,
|
|
64
|
+
FrozenSet,
|
|
65
|
+
Iterable,
|
|
66
|
+
List,
|
|
67
|
+
Mapping,
|
|
68
|
+
Optional,
|
|
69
|
+
Sequence,
|
|
70
|
+
Tuple,
|
|
71
|
+
)
|
|
72
|
+
from uuid import UUID
|
|
73
|
+
|
|
74
|
+
from tree_engine.core.identity import NodeAddress
|
|
75
|
+
from tree_engine.core.short_id import ShortIdMap
|
|
76
|
+
from tree_engine.core.subtree_copy import CopiedDocument
|
|
77
|
+
from tree_engine.core.validation import ValidationError, validate_mutation
|
|
78
|
+
from tree_engine.errors import ErrorCode
|
|
79
|
+
|
|
80
|
+
__all__ = [
|
|
81
|
+
"SubtreeApplyError",
|
|
82
|
+
"NodeIDConflictError",
|
|
83
|
+
"ApplySubtreeResult",
|
|
84
|
+
"build_short_id_remap",
|
|
85
|
+
"apply_subtree",
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class SubtreeApplyError(Exception):
|
|
90
|
+
"""Raised when ``apply_subtree`` cannot be performed as requested.
|
|
91
|
+
|
|
92
|
+
Carries the originating :class:`~tree_engine.errors.ErrorCode` as
|
|
93
|
+
``self.code`` (convention shared with ``subtree_copy.py``'s
|
|
94
|
+
``SubtreeCopyError``). Raising it guarantees the target document was
|
|
95
|
+
not touched.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, code: ErrorCode, message: str) -> None:
|
|
99
|
+
super().__init__(f"[{code.value}] {message}")
|
|
100
|
+
self.code = code
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class NodeIDConflictError(SubtreeApplyError):
|
|
104
|
+
"""A node_id from the incoming copy collides with the target and is not
|
|
105
|
+
the same logical node the copy was taken from ({p076}). Always carries
|
|
106
|
+
``ErrorCode.NODE_ID_CONFLICT`` as ``self.code``. ``self.errors`` holds
|
|
107
|
+
the underlying ``ValidationError`` entries from the shared preflight."""
|
|
108
|
+
|
|
109
|
+
def __init__(self, errors: Sequence[ValidationError]) -> None:
|
|
110
|
+
self.errors: List[ValidationError] = list(errors)
|
|
111
|
+
detail = "; ".join(e.message for e in self.errors) or "node_id conflict"
|
|
112
|
+
super().__init__(ErrorCode.NODE_ID_CONFLICT, detail)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class ApplySubtreeResult:
|
|
117
|
+
"""Outcome of ``apply_subtree``: ``node_id`` is the copy's root, now
|
|
118
|
+
live in the target. ``short_id_remap`` maps every reassigned ``old ->
|
|
119
|
+
new`` short_id ({p076}); a short_id that stayed free, or an
|
|
120
|
+
identity-preserved node, is not an entry. ``removed``/``inserted`` are
|
|
121
|
+
the touched :class:`~tree_engine.core.identity.NodeAddress` values."""
|
|
122
|
+
|
|
123
|
+
node_id: UUID
|
|
124
|
+
short_id_remap: Mapping[Any, Any]
|
|
125
|
+
removed: NodeAddress
|
|
126
|
+
inserted: NodeAddress
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# --------------------------------------------------------------------------
|
|
130
|
+
# Internal helpers
|
|
131
|
+
# --------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _get_children(node: Any) -> Tuple[Any, ...]:
|
|
135
|
+
return tuple(getattr(node, "children", None) or ())
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _walk(node: Any):
|
|
139
|
+
yield node
|
|
140
|
+
for child in _get_children(node):
|
|
141
|
+
yield from _walk(child)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _check_version(document: Any, expected_version: Optional[Any]) -> None:
|
|
145
|
+
if expected_version is None:
|
|
146
|
+
return
|
|
147
|
+
_absent = object()
|
|
148
|
+
current = getattr(document, "document_version", _absent)
|
|
149
|
+
current = getattr(document, "version", None) if current is _absent else current
|
|
150
|
+
if current != expected_version:
|
|
151
|
+
raise SubtreeApplyError(
|
|
152
|
+
ErrorCode.DOCUMENT_VERSION_CONFLICT,
|
|
153
|
+
f"expected_version {expected_version!r} does not match target "
|
|
154
|
+
f"document_version {current!r}",
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _origin_root_id(copy: CopiedDocument) -> UUID:
|
|
159
|
+
root_id = getattr(copy.root, "node_id")
|
|
160
|
+
for old_id, new_id in copy.old_uuid_to_new_uuid.items():
|
|
161
|
+
if new_id == root_id:
|
|
162
|
+
return old_id
|
|
163
|
+
raise SubtreeApplyError(
|
|
164
|
+
ErrorCode.NODE_NOT_FOUND,
|
|
165
|
+
"copy.root.node_id is not recorded in old_uuid_to_new_uuid; cannot "
|
|
166
|
+
"establish which target node this copy replaces",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _resolved_parent_id(document: Any, node_id: UUID, node: Any) -> Optional[UUID]:
|
|
171
|
+
parent_index = getattr(document, "parent_index", None)
|
|
172
|
+
if isinstance(parent_index, dict):
|
|
173
|
+
return parent_index.get(node_id)
|
|
174
|
+
return getattr(node, "parent_id", None)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _legitimate_old_ids(
|
|
178
|
+
document: Any,
|
|
179
|
+
copy: CopiedDocument,
|
|
180
|
+
target_parent_id: Optional[UUID],
|
|
181
|
+
) -> FrozenSet[UUID]:
|
|
182
|
+
"""Origin subtree node_ids {p076} treats as the *same logical* node in
|
|
183
|
+
the target's ``nodes_by_id``, not a conflict (module docstring has the
|
|
184
|
+
cross-reference rules)."""
|
|
185
|
+
|
|
186
|
+
if copy.origin_document_id is not None:
|
|
187
|
+
if copy.origin_document_id != getattr(document, "document_id", None):
|
|
188
|
+
return frozenset()
|
|
189
|
+
if copy.origin_parent_id is not None and target_parent_id != copy.origin_parent_id:
|
|
190
|
+
return frozenset()
|
|
191
|
+
return frozenset(copy.old_uuid_to_new_uuid.keys())
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class _FilteredView:
|
|
195
|
+
"""Minimal read-only ``validate_mutation`` target: real ``nodes_by_id``
|
|
196
|
+
minus the confirmed-legitimate origin subtree's node_ids, so stage 2
|
|
197
|
+
does not misfire on the identity {p076} means to preserve."""
|
|
198
|
+
|
|
199
|
+
__slots__ = ("nodes_by_id", "document_id")
|
|
200
|
+
|
|
201
|
+
def __init__(self, nodes_by_id: Dict[UUID, Any], document_id: Optional[UUID]) -> None:
|
|
202
|
+
self.nodes_by_id = nodes_by_id
|
|
203
|
+
self.document_id = document_id
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _children_list(node: Any) -> List[Any]:
|
|
207
|
+
return list(getattr(node, "children", None) or ())
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _set_children(node: Any, children: Sequence[Any]) -> None:
|
|
211
|
+
if isinstance(getattr(node, "children", None), tuple):
|
|
212
|
+
node.children = tuple(children)
|
|
213
|
+
else:
|
|
214
|
+
node.children = list(children)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _partition_fragment(
|
|
218
|
+
copy_root: Any, nodes_by_id: Mapping[UUID, Any]
|
|
219
|
+
) -> Tuple[List[Any], List[Any]]:
|
|
220
|
+
"""Split the copy's fragment into ``kept`` (node_id already live in the
|
|
221
|
+
target -- identity-preserved) and ``new``, against the target's
|
|
222
|
+
*unmodified* ``nodes_by_id``."""
|
|
223
|
+
|
|
224
|
+
kept: List[Any] = []
|
|
225
|
+
new: List[Any] = []
|
|
226
|
+
for node in _walk(copy_root):
|
|
227
|
+
(kept if node.node_id in nodes_by_id else new).append(node)
|
|
228
|
+
return kept, new
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def build_short_id_remap(
|
|
232
|
+
candidates: Mapping[UUID, Any], assigned: Mapping[UUID, Any]
|
|
233
|
+
) -> Dict[Any, Any]:
|
|
234
|
+
"""Build the ``old -> new`` short_id remap ({p076}) from each *new*
|
|
235
|
+
node's candidate (its value in the copy's own ``ShortIdMap``) and the
|
|
236
|
+
final value ``merge_insert``/``allocate`` assigned in the target. A
|
|
237
|
+
candidate that stayed free is left out, per {p097}."""
|
|
238
|
+
|
|
239
|
+
remap: Dict[Any, Any] = {}
|
|
240
|
+
for node_id, candidate in candidates.items():
|
|
241
|
+
final = assigned.get(node_id)
|
|
242
|
+
if candidate is not None and final is not None and final != candidate:
|
|
243
|
+
remap[candidate] = final
|
|
244
|
+
return remap
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _apply_short_ids(
|
|
248
|
+
document: Any, kept: Sequence[Any], new: Sequence[Any], nodes_by_id: Mapping[UUID, Any]
|
|
249
|
+
) -> Dict[Any, Any]:
|
|
250
|
+
"""Assign every copied node its final target short_id in place and
|
|
251
|
+
return the remap. ``kept`` nodes reuse the target's existing short_id;
|
|
252
|
+
``new`` nodes go through the target's ``short_id_map``."""
|
|
253
|
+
|
|
254
|
+
for node in kept:
|
|
255
|
+
node.short_id = getattr(nodes_by_id[node.node_id], "short_id", None)
|
|
256
|
+
short_id_map: Optional[ShortIdMap] = getattr(document, "short_id_map", None)
|
|
257
|
+
if short_id_map is None or not new:
|
|
258
|
+
return {}
|
|
259
|
+
candidates = {node.node_id: node.short_id for node in new}
|
|
260
|
+
with_value = {nid: sid for nid, sid in candidates.items() if sid is not None}
|
|
261
|
+
without_value = [nid for nid, sid in candidates.items() if sid is None]
|
|
262
|
+
assigned: Dict[UUID, int] = dict(short_id_map.merge_insert(with_value)) if with_value else {}
|
|
263
|
+
for node_id in without_value:
|
|
264
|
+
assigned[node_id] = short_id_map.allocate(node_id)
|
|
265
|
+
by_id = {node.node_id: node for node in new}
|
|
266
|
+
for node_id, final_short_id in assigned.items():
|
|
267
|
+
by_id[node_id].short_id = final_short_id
|
|
268
|
+
return build_short_id_remap(candidates, assigned)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _splice(document: Any, parent_node: Optional[Any], target_root: Any, new_root: Any) -> None:
|
|
272
|
+
nodes_by_id = document.nodes_by_id
|
|
273
|
+
short_index = getattr(document, "short_id_index", None)
|
|
274
|
+
for old_node in _walk(target_root):
|
|
275
|
+
nodes_by_id.pop(getattr(old_node, "node_id", None), None)
|
|
276
|
+
if isinstance(short_index, dict):
|
|
277
|
+
short_index.pop(getattr(old_node, "short_id", None), None)
|
|
278
|
+
if parent_node is not None:
|
|
279
|
+
siblings = _children_list(parent_node)
|
|
280
|
+
index = next(
|
|
281
|
+
(i for i, c in enumerate(siblings) if getattr(c, "node_id", None) == target_root.node_id),
|
|
282
|
+
None,
|
|
283
|
+
)
|
|
284
|
+
if index is None:
|
|
285
|
+
raise SubtreeApplyError(
|
|
286
|
+
ErrorCode.NODE_NOT_FOUND, "target root is not among its parent's children"
|
|
287
|
+
)
|
|
288
|
+
siblings[index] = new_root
|
|
289
|
+
_set_children(parent_node, siblings)
|
|
290
|
+
if hasattr(new_root, "parent_id"):
|
|
291
|
+
new_root.parent_id = getattr(parent_node, "node_id", None)
|
|
292
|
+
elif hasattr(document, "root"):
|
|
293
|
+
document.root = new_root
|
|
294
|
+
for new_node in _walk(new_root):
|
|
295
|
+
node_id = getattr(new_node, "node_id", None)
|
|
296
|
+
if node_id is not None:
|
|
297
|
+
nodes_by_id[node_id] = new_node
|
|
298
|
+
if isinstance(short_index, dict):
|
|
299
|
+
sid = getattr(new_node, "short_id", None)
|
|
300
|
+
if sid is not None:
|
|
301
|
+
short_index[sid] = node_id
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# --------------------------------------------------------------------------
|
|
305
|
+
# Public entry point
|
|
306
|
+
# --------------------------------------------------------------------------
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def apply_subtree(
|
|
310
|
+
document: Any,
|
|
311
|
+
copy: CopiedDocument,
|
|
312
|
+
*,
|
|
313
|
+
expected_version: Optional[Any] = None,
|
|
314
|
+
is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
|
|
315
|
+
references: Optional[Iterable[Any]] = None,
|
|
316
|
+
loaded_documents: Optional[Dict[Any, Any]] = None,
|
|
317
|
+
) -> ApplySubtreeResult:
|
|
318
|
+
"""Return ``copy`` into ``document``, replacing the original subtree it
|
|
319
|
+
was copied from, per {p076}. ``expected_version`` is checked first
|
|
320
|
+
(:class:`SubtreeApplyError`, ``DOCUMENT_VERSION_CONFLICT`` on
|
|
321
|
+
mismatch). The origin node is located via ``copy.old_uuid_to_new_uuid``
|
|
322
|
+
(uniform for both ``preserve_ids`` modes); its absence raises
|
|
323
|
+
``NODE_NOT_FOUND``. The shared {p009}/C-006 ``validate_mutation``
|
|
324
|
+
preflight runs before any write; a ``NODE_ID_CONFLICT`` not recognized
|
|
325
|
+
as the same logical node raises :class:`NodeIDConflictError`, any other
|
|
326
|
+
failure raises :class:`SubtreeApplyError` -- the target is left
|
|
327
|
+
untouched either way. On success the fragment is spliced in, short_ids
|
|
328
|
+
are merged per {p097}, and the ``old -> new`` short_id remap is
|
|
329
|
+
returned."""
|
|
330
|
+
|
|
331
|
+
_check_version(document, expected_version)
|
|
332
|
+
nodes_by_id = getattr(document, "nodes_by_id", None)
|
|
333
|
+
if nodes_by_id is None:
|
|
334
|
+
raise SubtreeApplyError(
|
|
335
|
+
ErrorCode.NODE_NOT_FOUND, "target document exposes no 'nodes_by_id' map"
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
origin_root_id = _origin_root_id(copy)
|
|
339
|
+
target_root = nodes_by_id.get(origin_root_id)
|
|
340
|
+
if target_root is None:
|
|
341
|
+
raise SubtreeApplyError(
|
|
342
|
+
ErrorCode.NODE_NOT_FOUND,
|
|
343
|
+
f"original subtree root not found in target document: {origin_root_id!r}",
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
target_parent_id = _resolved_parent_id(document, origin_root_id, target_root)
|
|
347
|
+
parent_node = nodes_by_id.get(target_parent_id) if target_parent_id is not None else None
|
|
348
|
+
|
|
349
|
+
legitimate = _legitimate_old_ids(document, copy, target_parent_id)
|
|
350
|
+
filtered_nodes_by_id = {nid: n for nid, n in nodes_by_id.items() if nid not in legitimate}
|
|
351
|
+
view = _FilteredView(filtered_nodes_by_id, getattr(document, "document_id", None))
|
|
352
|
+
|
|
353
|
+
position: Optional[str] = None
|
|
354
|
+
index: Optional[int] = None
|
|
355
|
+
if parent_node is not None:
|
|
356
|
+
siblings = _children_list(parent_node)
|
|
357
|
+
found = next(
|
|
358
|
+
(i for i, c in enumerate(siblings) if getattr(c, "node_id", None) == origin_root_id),
|
|
359
|
+
None,
|
|
360
|
+
)
|
|
361
|
+
if found is not None:
|
|
362
|
+
position, index = "child_index", found
|
|
363
|
+
|
|
364
|
+
result = validate_mutation(
|
|
365
|
+
view,
|
|
366
|
+
copy.root,
|
|
367
|
+
parent=parent_node,
|
|
368
|
+
position=position,
|
|
369
|
+
index=index,
|
|
370
|
+
is_type_compatible=is_type_compatible,
|
|
371
|
+
references=references,
|
|
372
|
+
loaded_documents=loaded_documents,
|
|
373
|
+
)
|
|
374
|
+
if not result.success:
|
|
375
|
+
conflicts = [e for e in result.errors if e.code == ErrorCode.NODE_ID_CONFLICT]
|
|
376
|
+
if conflicts:
|
|
377
|
+
raise NodeIDConflictError(conflicts)
|
|
378
|
+
first = result.errors[0]
|
|
379
|
+
raise SubtreeApplyError(first.code, first.message)
|
|
380
|
+
|
|
381
|
+
kept, new = _partition_fragment(copy.root, nodes_by_id)
|
|
382
|
+
remap = _apply_short_ids(document, kept, new, nodes_by_id)
|
|
383
|
+
|
|
384
|
+
removed_address = NodeAddress(
|
|
385
|
+
document_id=getattr(document, "document_id", None), node_id=origin_root_id
|
|
386
|
+
)
|
|
387
|
+
_splice(document, parent_node, target_root, copy.root)
|
|
388
|
+
inserted_address = NodeAddress(
|
|
389
|
+
document_id=getattr(document, "document_id", None), node_id=getattr(copy.root, "node_id")
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
return ApplySubtreeResult(
|
|
393
|
+
node_id=getattr(copy.root, "node_id"),
|
|
394
|
+
short_id_remap=remap,
|
|
395
|
+
removed=removed_address,
|
|
396
|
+
inserted=inserted_address,
|
|
397
|
+
)
|