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,399 @@
|
|
|
1
|
+
"""Read-only independent subtree copying for concept C-019 (SubtreeCopyAndApply).
|
|
2
|
+
|
|
3
|
+
Scope (concept C-019, narrowed to the copy half only, per A-001): one
|
|
4
|
+
read-only entry point, :func:`copy_subtree`, plus its result type
|
|
5
|
+
:class:`CopiedDocument`. Never mutates the source document, its nodes, or
|
|
6
|
+
its index maps. The explicit ``replace_subtree``/``apply_subtree`` return
|
|
7
|
+
path ({p076}) is a sibling artifact's job -- out of scope here.
|
|
8
|
+
|
|
9
|
+
Per {p072}-{p074}, two identity modes:
|
|
10
|
+
|
|
11
|
+
* ``preserve_ids=False`` (default): every copied node gets a fresh UUID4
|
|
12
|
+
node_id; ``CopiedDocument.old_uuid_to_new_uuid`` records the resulting
|
|
13
|
+
old->new map for the whole copied subtree.
|
|
14
|
+
* ``preserve_ids=True``: every copied node keeps its original UUID4 under a
|
|
15
|
+
brand-new ``document_id``. ``old_uuid_to_new_uuid`` is still populated, as
|
|
16
|
+
the identity map (``old == new``); ``origin_document_id``/
|
|
17
|
+
``origin_parent_id`` record where the copy came from, per {p074}.
|
|
18
|
+
|
|
19
|
+
In both modes, per {p073}/{p074}: references whose source and target both
|
|
20
|
+
lie inside the copied subtree become new intra-document references of the
|
|
21
|
+
copy (implicit-local form, ``document_id=None``); references that leave the
|
|
22
|
+
subtree are preserved unchanged as explicit external ``NodeAddress`` values
|
|
23
|
+
naming the *source* document and the *original* target node_id. References
|
|
24
|
+
incoming from outside the subtree are never copied -- traversal never
|
|
25
|
+
visits any node outside the chosen subtree ({p077}, bounded cost).
|
|
26
|
+
|
|
27
|
+
Per {p075}, the returned :class:`CopiedDocument` is fully independent of the
|
|
28
|
+
source: its own ``document_id``, its own fresh :class:`ShortIdMap`, its own
|
|
29
|
+
``nodes_by_id`` of freshly built node objects (immutable dataclass nodes
|
|
30
|
+
rebuilt bottom-up via ``dataclasses.replace``; any other duck-typed mutable
|
|
31
|
+
node is shallow-copied via ``copy.copy`` then has its identity-bearing
|
|
32
|
+
attributes overwritten). Mutating either side afterwards updates only that
|
|
33
|
+
side's own state. ``document_version`` on the copy always starts at ``1``:
|
|
34
|
+
{p075} requires an independent version counter, not inheritance of the
|
|
35
|
+
source's current value.
|
|
36
|
+
|
|
37
|
+
Duck-typed contracts, matching the convention already established by
|
|
38
|
+
``identity.py``, ``validation.py`` and ``operations.py`` -- no concrete
|
|
39
|
+
``Document``/``Node`` type is imported or required:
|
|
40
|
+
|
|
41
|
+
* ``document``: ``nodes_by_id`` (``node_id -> node``, read-only, consulted
|
|
42
|
+
only to look up the requested subtree root), optionally ``root`` (used
|
|
43
|
+
when ``node_id`` is ``None``, i.e. "copy the whole tree"), optionally
|
|
44
|
+
``document_id``, optionally ``document_version``/``version`` for the
|
|
45
|
+
``expected_version`` check, and optionally ``parent_index`` (a
|
|
46
|
+
``node_id -> parent_id`` mapping, consulted only for ``origin_parent_id``
|
|
47
|
+
under ``preserve_ids=True``).
|
|
48
|
+
* a node: ``node_id`` (required), an ordered ``children`` sequence
|
|
49
|
+
(optional, absent/``None`` means a leaf), and optionally ``short_id``,
|
|
50
|
+
``references`` (an iterable of :class:`~tree_engine.core.identity.NodeAddress`),
|
|
51
|
+
and ``parent_id``. A node built through ``nodes.py``'s immutable
|
|
52
|
+
``Node``/``make_node`` is rebuilt via ``dataclasses.replace``, including
|
|
53
|
+
``fields`` (any value that *is* one of ``node.children``, by object
|
|
54
|
+
identity, tracks that child's copy, so ``fields``/``children`` never
|
|
55
|
+
drift apart); a fields-embedded ``Node`` not also reachable through
|
|
56
|
+
``children`` is not deep-copied, matching ``nodes.py``'s own "not
|
|
57
|
+
required to be kept in lockstep" note.
|
|
58
|
+
|
|
59
|
+
Non-goals: no ``replace_subtree``/``apply_subtree``, no shared insertion
|
|
60
|
+
validation, no ``NODE_ID_CONFLICT`` detection on return -- a sibling step.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
from __future__ import annotations
|
|
64
|
+
|
|
65
|
+
import copy as _copy
|
|
66
|
+
import dataclasses
|
|
67
|
+
from dataclasses import dataclass
|
|
68
|
+
from types import MappingProxyType
|
|
69
|
+
from typing import Any, Dict, List, Mapping, Optional, Set, Tuple
|
|
70
|
+
from uuid import UUID
|
|
71
|
+
|
|
72
|
+
from tree_engine.core.identity import NodeAddress, generate_node_id
|
|
73
|
+
from tree_engine.core.references import is_local
|
|
74
|
+
from tree_engine.core.short_id import ShortIdMap
|
|
75
|
+
from tree_engine.errors import ErrorCode
|
|
76
|
+
|
|
77
|
+
__all__ = ["SubtreeCopyError", "CopiedDocument", "copy_subtree"]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class SubtreeCopyError(Exception):
|
|
81
|
+
"""Raised when ``copy_subtree`` cannot be performed as requested.
|
|
82
|
+
|
|
83
|
+
Carries the originating :class:`~tree_engine.errors.ErrorCode` as
|
|
84
|
+
``self.code`` (convention shared with ``nodes.py``'s
|
|
85
|
+
``NodeSchemaError``): an ``expected_version`` mismatch
|
|
86
|
+
(``DOCUMENT_VERSION_CONFLICT``) or an unresolvable ``node_id``/missing
|
|
87
|
+
document root (``NODE_NOT_FOUND``). Raising it guarantees the source
|
|
88
|
+
document was not touched.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(self, code: ErrorCode, message: str) -> None:
|
|
92
|
+
super().__init__(f"[{code.value}] {message}")
|
|
93
|
+
self.code = code
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass
|
|
97
|
+
class CopiedDocument:
|
|
98
|
+
"""The independent tree copy returned by :func:`copy_subtree` ({p072}).
|
|
99
|
+
|
|
100
|
+
``root`` is the copied subtree's root, always with ``parent_id`` (when
|
|
101
|
+
the node type carries one) set to ``None``. ``nodes_by_id`` and
|
|
102
|
+
``short_id_map`` are freshly built, touching nothing of the source's own
|
|
103
|
+
maps. ``old_uuid_to_new_uuid`` maps every copied node's original
|
|
104
|
+
node_id to its node_id here (identity mapping under
|
|
105
|
+
``preserve_ids=True``). ``origin_document_id``/``origin_parent_id`` are
|
|
106
|
+
populated only under ``preserve_ids=True`` ({p074}), else ``None``.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
document_id: UUID
|
|
110
|
+
document_version: int
|
|
111
|
+
root: Any
|
|
112
|
+
nodes_by_id: Dict[UUID, Any]
|
|
113
|
+
short_id_map: ShortIdMap
|
|
114
|
+
old_uuid_to_new_uuid: Dict[UUID, UUID]
|
|
115
|
+
origin_document_id: Optional[UUID] = None
|
|
116
|
+
origin_parent_id: Optional[UUID] = None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# --------------------------------------------------------------------------
|
|
120
|
+
# Internal helpers
|
|
121
|
+
# --------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _get_children(node: Any) -> Tuple[Any, ...]:
|
|
125
|
+
return tuple(getattr(node, "children", None) or ())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _walk(node: Any):
|
|
129
|
+
yield node
|
|
130
|
+
for child in _get_children(node):
|
|
131
|
+
yield from _walk(child)
|
|
132
|
+
|
|
133
|
+
def _check_version(document: Any, expected_version: Optional[Any]) -> None:
|
|
134
|
+
if expected_version is None:
|
|
135
|
+
return
|
|
136
|
+
_absent = object()
|
|
137
|
+
current = getattr(document, "document_version", _absent)
|
|
138
|
+
current = getattr(document, "version", None) if current is _absent else current
|
|
139
|
+
if current != expected_version:
|
|
140
|
+
raise SubtreeCopyError(
|
|
141
|
+
ErrorCode.DOCUMENT_VERSION_CONFLICT,
|
|
142
|
+
f"expected_version {expected_version!r} does not match source "
|
|
143
|
+
f"document_version {current!r}",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _find_root(document: Any, node_id: Optional[UUID]) -> Any:
|
|
148
|
+
if node_id is None:
|
|
149
|
+
root = getattr(document, "root", None)
|
|
150
|
+
if root is None:
|
|
151
|
+
raise SubtreeCopyError(
|
|
152
|
+
ErrorCode.NODE_NOT_FOUND,
|
|
153
|
+
"document exposes no 'root' node and no node_id was given",
|
|
154
|
+
)
|
|
155
|
+
return root
|
|
156
|
+
nodes_by_id = getattr(document, "nodes_by_id", None) or {}
|
|
157
|
+
node = nodes_by_id.get(node_id)
|
|
158
|
+
if node is None:
|
|
159
|
+
raise SubtreeCopyError(
|
|
160
|
+
ErrorCode.NODE_NOT_FOUND,
|
|
161
|
+
f"node_id not found in source document: {node_id!r}",
|
|
162
|
+
)
|
|
163
|
+
return node
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _collect_ids(
|
|
167
|
+
node: Any,
|
|
168
|
+
preserve_ids: bool,
|
|
169
|
+
id_map: Dict[UUID, UUID],
|
|
170
|
+
old_id_set: Set[UUID],
|
|
171
|
+
ordered_new_ids: List[UUID],
|
|
172
|
+
) -> None:
|
|
173
|
+
"""Pre-order, subtree-only walk ({p077}): assigns each node's new
|
|
174
|
+
node_id (fresh UUID4, or same UUID4 under ``preserve_ids``) without
|
|
175
|
+
building any node object yet."""
|
|
176
|
+
|
|
177
|
+
old_id = node.node_id
|
|
178
|
+
old_id_set.add(old_id)
|
|
179
|
+
new_id = old_id if preserve_ids else generate_node_id()
|
|
180
|
+
id_map[old_id] = new_id
|
|
181
|
+
ordered_new_ids.append(new_id)
|
|
182
|
+
for child in _get_children(node):
|
|
183
|
+
_collect_ids(child, preserve_ids, id_map, old_id_set, ordered_new_ids)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _rewrite_references(
|
|
187
|
+
node: Any,
|
|
188
|
+
old_id_set: Set[UUID],
|
|
189
|
+
id_map: Dict[UUID, UUID],
|
|
190
|
+
source_document_id: Optional[UUID],
|
|
191
|
+
) -> Tuple[NodeAddress, ...]:
|
|
192
|
+
"""Rewrite outgoing references per {p073}/{p074}: internal (target
|
|
193
|
+
inside the subtree) -> new implicit-local reference of the copy;
|
|
194
|
+
external (target outside) -> preserved, unchanged, as an explicit
|
|
195
|
+
``NodeAddress`` of the source document."""
|
|
196
|
+
|
|
197
|
+
raw_refs = getattr(node, "references", None) or ()
|
|
198
|
+
new_refs = []
|
|
199
|
+
for ref in raw_refs:
|
|
200
|
+
target_id = ref.node_id
|
|
201
|
+
if target_id in old_id_set:
|
|
202
|
+
new_refs.append(NodeAddress(document_id=None, node_id=id_map[target_id]))
|
|
203
|
+
else:
|
|
204
|
+
doc_id = source_document_id if is_local(ref) else ref.document_id
|
|
205
|
+
new_refs.append(NodeAddress(document_id=doc_id, node_id=target_id))
|
|
206
|
+
return tuple(new_refs)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _rewrite_fields(
|
|
210
|
+
fields: Any, original_children: Tuple[Any, ...], new_children: List[Any]
|
|
211
|
+
) -> Any:
|
|
212
|
+
"""Sync a dataclass node's ``fields`` with its rebuilt ``children``: a
|
|
213
|
+
field value that *is* one of ``original_children`` (by identity) is
|
|
214
|
+
replaced by that child's already-built copy; anything else is left
|
|
215
|
+
untouched (``nodes.py``'s "not required to be kept in lockstep")."""
|
|
216
|
+
|
|
217
|
+
if not isinstance(fields, Mapping):
|
|
218
|
+
return fields
|
|
219
|
+
child_copy_of = {id(oc): nc for oc, nc in zip(original_children, new_children)}
|
|
220
|
+
|
|
221
|
+
def _map_value(value: Any) -> Any:
|
|
222
|
+
if isinstance(value, tuple):
|
|
223
|
+
return tuple(child_copy_of.get(id(v), v) for v in value)
|
|
224
|
+
return child_copy_of.get(id(value), value)
|
|
225
|
+
|
|
226
|
+
return MappingProxyType({key: _map_value(value) for key, value in fields.items()})
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _clone_leaf(
|
|
230
|
+
node: Any,
|
|
231
|
+
*,
|
|
232
|
+
new_node_id: UUID,
|
|
233
|
+
new_short_id: Any,
|
|
234
|
+
new_children: List[Any],
|
|
235
|
+
new_references: Tuple[NodeAddress, ...],
|
|
236
|
+
new_parent_id: Optional[UUID],
|
|
237
|
+
) -> Any:
|
|
238
|
+
"""Build one copied node, independent of ``node``: an immutable
|
|
239
|
+
dataclass node (e.g. ``nodes.py``'s ``Node``) is rebuilt via
|
|
240
|
+
``dataclasses.replace``; any other duck-typed node is shallow-copied via
|
|
241
|
+
``copy.copy`` then has every identity-bearing attribute overwritten."""
|
|
242
|
+
|
|
243
|
+
if dataclasses.is_dataclass(node) and not isinstance(node, type):
|
|
244
|
+
changes: Dict[str, Any] = {}
|
|
245
|
+
if hasattr(node, "node_id"):
|
|
246
|
+
changes["node_id"] = new_node_id
|
|
247
|
+
if hasattr(node, "short_id"):
|
|
248
|
+
changes["short_id"] = new_short_id
|
|
249
|
+
if hasattr(node, "children"):
|
|
250
|
+
original = getattr(node, "children")
|
|
251
|
+
changes["children"] = (
|
|
252
|
+
tuple(new_children) if isinstance(original, tuple) else list(new_children)
|
|
253
|
+
)
|
|
254
|
+
if hasattr(node, "references"):
|
|
255
|
+
changes["references"] = new_references
|
|
256
|
+
if hasattr(node, "fields"):
|
|
257
|
+
changes["fields"] = _rewrite_fields(node.fields, _get_children(node), new_children)
|
|
258
|
+
if hasattr(node, "parent_id"):
|
|
259
|
+
changes["parent_id"] = new_parent_id
|
|
260
|
+
return dataclasses.replace(node, **changes)
|
|
261
|
+
|
|
262
|
+
cloned = _copy.copy(node)
|
|
263
|
+
if hasattr(cloned, "node_id"):
|
|
264
|
+
cloned.node_id = new_node_id
|
|
265
|
+
if hasattr(cloned, "short_id"):
|
|
266
|
+
cloned.short_id = new_short_id
|
|
267
|
+
if hasattr(cloned, "children"):
|
|
268
|
+
original = getattr(node, "children")
|
|
269
|
+
cloned.children = (
|
|
270
|
+
type(original)(new_children) if isinstance(original, (tuple, list)) else list(new_children)
|
|
271
|
+
)
|
|
272
|
+
if hasattr(cloned, "references"):
|
|
273
|
+
original_refs = getattr(node, "references", None)
|
|
274
|
+
cloned.references = (
|
|
275
|
+
tuple(new_references) if not isinstance(original_refs, list) else list(new_references)
|
|
276
|
+
)
|
|
277
|
+
if hasattr(cloned, "parent_id"):
|
|
278
|
+
cloned.parent_id = new_parent_id
|
|
279
|
+
return cloned
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _build_copy(
|
|
283
|
+
node: Any,
|
|
284
|
+
*,
|
|
285
|
+
is_root: bool,
|
|
286
|
+
old_id_set: Set[UUID],
|
|
287
|
+
id_map: Dict[UUID, UUID],
|
|
288
|
+
short_ids: Dict[UUID, Any],
|
|
289
|
+
source_document_id: Optional[UUID],
|
|
290
|
+
) -> Any:
|
|
291
|
+
"""Bottom-up rebuild ({p077}, subtree-only): children first (an
|
|
292
|
+
immutable node is built from already-existing children), then this
|
|
293
|
+
node is cloned with its new identity, ``children``, ``references``,
|
|
294
|
+
and a ``parent_id`` remapped through ``id_map`` (a no-op under
|
|
295
|
+
``preserve_ids=True``, where ``id_map`` is the identity map)."""
|
|
296
|
+
|
|
297
|
+
new_children = [
|
|
298
|
+
_build_copy(
|
|
299
|
+
child,
|
|
300
|
+
is_root=False,
|
|
301
|
+
old_id_set=old_id_set,
|
|
302
|
+
id_map=id_map,
|
|
303
|
+
short_ids=short_ids,
|
|
304
|
+
source_document_id=source_document_id,
|
|
305
|
+
)
|
|
306
|
+
for child in _get_children(node)
|
|
307
|
+
]
|
|
308
|
+
new_node_id = id_map[node.node_id]
|
|
309
|
+
new_short_id = short_ids[new_node_id]
|
|
310
|
+
new_references = _rewrite_references(node, old_id_set, id_map, source_document_id)
|
|
311
|
+
old_parent_id = getattr(node, "parent_id", None)
|
|
312
|
+
new_parent_id = None if is_root else id_map.get(old_parent_id, old_parent_id)
|
|
313
|
+
return _clone_leaf(
|
|
314
|
+
node,
|
|
315
|
+
new_node_id=new_node_id,
|
|
316
|
+
new_short_id=new_short_id,
|
|
317
|
+
new_children=new_children,
|
|
318
|
+
new_references=new_references,
|
|
319
|
+
new_parent_id=new_parent_id,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _find_origin_parent_id(document: Any, node_id: Optional[UUID], root: Any) -> Optional[UUID]:
|
|
324
|
+
if node_id is None:
|
|
325
|
+
return None
|
|
326
|
+
parent_index = getattr(document, "parent_index", None)
|
|
327
|
+
return parent_index.get(node_id) if isinstance(parent_index, dict) else getattr(root, "parent_id", None)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# --------------------------------------------------------------------------
|
|
331
|
+
# Public entry point
|
|
332
|
+
# --------------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def copy_subtree(
|
|
336
|
+
document: Any,
|
|
337
|
+
node_id: Optional[UUID] = None,
|
|
338
|
+
expected_version: Optional[Any] = None,
|
|
339
|
+
preserve_ids: bool = False,
|
|
340
|
+
) -> CopiedDocument:
|
|
341
|
+
"""Return an independent copy of ``document``'s subtree rooted at
|
|
342
|
+
``node_id`` (whole document when ``None``), per {p072}. Read-only: the
|
|
343
|
+
source document, its nodes, and its index maps are never mutated.
|
|
344
|
+
|
|
345
|
+
``expected_version`` -- checked first -- must equal
|
|
346
|
+
``document.document_version``/``version`` when given, or
|
|
347
|
+
:class:`SubtreeCopyError` (``DOCUMENT_VERSION_CONFLICT``) is raised. An
|
|
348
|
+
unresolvable ``node_id`` (or missing ``document.root`` when ``node_id``
|
|
349
|
+
is ``None``) raises :class:`SubtreeCopyError` (``NODE_NOT_FOUND``).
|
|
350
|
+
|
|
351
|
+
``preserve_ids`` selects the identity mode: ``False`` (default) mints a
|
|
352
|
+
fresh UUID4 per copied node ({p073}); ``True`` keeps every UUID4
|
|
353
|
+
unchanged under the copy's new ``document_id``, recording
|
|
354
|
+
``origin_document_id``/``origin_parent_id`` ({p074}). Either way the
|
|
355
|
+
copy gets its own fresh :class:`~tree_engine.core.short_id.ShortIdMap`,
|
|
356
|
+
``nodes_by_id``, and ``document_version`` starting at ``1``; references
|
|
357
|
+
are rewritten/preserved as documented at module level. Traversal and
|
|
358
|
+
copying touch only the chosen subtree's nodes ({p077}).
|
|
359
|
+
"""
|
|
360
|
+
|
|
361
|
+
_check_version(document, expected_version)
|
|
362
|
+
root = _find_root(document, node_id)
|
|
363
|
+
source_document_id = getattr(document, "document_id", None)
|
|
364
|
+
|
|
365
|
+
id_map: Dict[UUID, UUID] = {}
|
|
366
|
+
old_id_set: Set[UUID] = set()
|
|
367
|
+
ordered_new_ids: List[UUID] = []
|
|
368
|
+
_collect_ids(root, preserve_ids, id_map, old_id_set, ordered_new_ids)
|
|
369
|
+
|
|
370
|
+
short_id_map = ShortIdMap()
|
|
371
|
+
short_ids = short_id_map.assign_bulk(ordered_new_ids)
|
|
372
|
+
|
|
373
|
+
new_root = _build_copy(
|
|
374
|
+
root,
|
|
375
|
+
is_root=True,
|
|
376
|
+
old_id_set=old_id_set,
|
|
377
|
+
id_map=id_map,
|
|
378
|
+
short_ids=short_ids,
|
|
379
|
+
source_document_id=source_document_id,
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
nodes_by_id = {n.node_id: n for n in _walk(new_root)}
|
|
383
|
+
|
|
384
|
+
origin_document_id: Optional[UUID] = None
|
|
385
|
+
origin_parent_id: Optional[UUID] = None
|
|
386
|
+
if preserve_ids:
|
|
387
|
+
origin_document_id = source_document_id
|
|
388
|
+
origin_parent_id = _find_origin_parent_id(document, node_id, root)
|
|
389
|
+
|
|
390
|
+
return CopiedDocument(
|
|
391
|
+
document_id=generate_node_id(),
|
|
392
|
+
document_version=1,
|
|
393
|
+
root=new_root,
|
|
394
|
+
nodes_by_id=nodes_by_id,
|
|
395
|
+
short_id_map=short_id_map,
|
|
396
|
+
old_uuid_to_new_uuid=id_map,
|
|
397
|
+
origin_document_id=origin_document_id,
|
|
398
|
+
origin_parent_id=origin_parent_id,
|
|
399
|
+
)
|