diff --git a/src/flext_cli/_typings/base.py b/src/flext_cli/_typings/base.py index dbf0c8c3..4d30b672 100644 --- a/src/flext_cli/_typings/base.py +++ b/src/flext_cli/_typings/base.py @@ -12,8 +12,8 @@ from flext_core import t from jinja2.sandbox import SandboxedEnvironment -from tomlkit.container import Container -from tomlkit.items import AoT, Array, Item, Table +from tomlkit.container import Container, OutOfOrderTableProxy +from tomlkit.items import AoT, Array, InlineTable, Item, Table from tomlkit.toml_document import TOMLDocument from typing_extensions import TypeForm @@ -44,7 +44,7 @@ class FlextCliTypesBase: type TomlArray = Array type TomlAoT = AoT type TomlContainer = Container - type TomlParent = TOMLDocument | Table + type TomlParent = TOMLDocument | Table | InlineTable | OutOfOrderTableProxy type TomlValue = TOMLDocument | Table | Item | Array | AoT | Container type RuntimeAnnotation = TypeForm type SignalHandler = int | Callable[[int, FrameType | None], None] | None diff --git a/src/flext_cli/_typings/domain.py b/src/flext_cli/_typings/domain.py index dda79252..ceabe7c4 100644 --- a/src/flext_cli/_typings/domain.py +++ b/src/flext_cli/_typings/domain.py @@ -14,7 +14,7 @@ from flext_core import p, t from ruamel.yaml.comments import CommentedMap, CommentedSeq from ruamel.yaml.tokens import CommentToken -from tomlkit.container import Container +from tomlkit.container import Container, OutOfOrderTableProxy from tomlkit.items import AoT, Array, Item, Table from tomlkit.toml_document import TOMLDocument @@ -98,7 +98,12 @@ class FlextCliTypesDomain: ] type ServiceMessageFormatter = Callable[[str, ResultValue], str] type TomlMappingSource = ( - t.JsonPayload | t.JsonMapping | Mapping[str, t.Scalar] | Item | TOMLDocument + t.JsonPayload + | t.JsonMapping + | Mapping[str, t.Scalar] + | Item + | TOMLDocument + | OutOfOrderTableProxy ) type TomlUnwrappedSource = t.JsonPayload | t.JsonMapping | Item type TomlStringListSource = ( @@ -111,6 +116,7 @@ class FlextCliTypesDomain: | Array | AoT | Container + | OutOfOrderTableProxy | t.JsonMapping | t.JsonPayload ) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py index 72b732e0..2ff07517 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py @@ -12,6 +12,7 @@ import tomlkit from flext_core import r, u +from tomlkit.container import OutOfOrderTableProxy from tomlkit.items import AoT, Array, Item, Table from tomlkit.toml_document import TOMLDocument @@ -52,7 +53,9 @@ def toml_unwrap_item( """ return FlextCliUtilitiesConversion.JSON_VALUE_ADAPTER.validate_python( - value.unwrap() if isinstance(value, TOMLDocument | Item) else value, + value.unwrap() + if isinstance(value, TOMLDocument | Item | OutOfOrderTableProxy) + else value, strict=True, ) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py index cbc7867b..dcfc9b35 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py @@ -108,7 +108,7 @@ def toml_table_child(container: TOMLDocument | Table, key: str) -> Table | None: return value if isinstance(value, Table) else None @staticmethod - def toml_item_child(container: TOMLDocument | Table, key: str) -> Item | None: + def toml_item_child(container: t.Cli.TomlParent, key: str) -> Item | None: """Return a raw TOML item from a container. Returns: diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py index 3c17a96d..79d64990 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py @@ -53,7 +53,7 @@ def toml_ensure_tool_table(doc: TOMLDocument) -> Table: return FlextCliUtilitiesTomlPart02.toml_ensure_table(doc, "tool") @staticmethod - def toml_value(container: TOMLDocument | Table, key: str) -> t.JsonValue | None: + def toml_value(container: t.Cli.TomlParent, key: str) -> t.JsonValue | None: """Return a normalized TOML value from a container. Returns: diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py index 7a87937e..8b1dff73 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py @@ -6,30 +6,147 @@ from __future__ import annotations -from collections.abc import Sequence -from typing import TYPE_CHECKING +from collections.abc import Mapping, Sequence +from itertools import starmap from flext_core import u -from tomlkit.items import Array +from tomlkit.container import OutOfOrderTableProxy +from tomlkit.items import Array, InlineTable, Table +from tomlkit.toml_document import TOMLDocument from flext_cli import t +from flext_cli._utilities import FlextCliUtilitiesConversion from flext_cli._utilities._toml import ( FlextCliUtilitiesTomlPart01, FlextCliUtilitiesTomlPart02, FlextCliUtilitiesTomlPart03, ) -if TYPE_CHECKING: - from tomlkit.items import Table - from tomlkit.toml_document import TOMLDocument - class FlextCliUtilitiesTomlPart04: """Implementation part for FlextCliUtilitiesTomlPart04.""" + @staticmethod + def toml_sync_document_values( + document: TOMLDocument | Table | InlineTable, + payload: t.JsonMapping, + *, + prune: bool = False, + ) -> None: + """Synchronize native TOML values while preserving unchanged source items. + + Validate the complete JSON payload and TOML conversion before mutation. + Absent keys remain untouched; prune=True removes them recursively. The + root must be a stable document or table. Fragmented child views are read + again from that root before every mutation; a proxy is not a valid root. + Native conversion and validation errors propagate unchanged. + """ + validated = FlextCliUtilitiesConversion.JSON_MAPPING_ADAPTER.validate_python( + payload, + strict=True, + ) + FlextCliUtilitiesTomlPart01.toml_document_from_mapping(validated) + current = FlextCliUtilitiesConversion.JSON_MAPPING_ADAPTER.validate_python( + document.unwrap(), + strict=True, + ) + FlextCliUtilitiesTomlPart04._sync_document_values( + document, (), validated, current, prune=prune + ) + + @staticmethod + def _toml_parent_at( + document: TOMLDocument | Table | InlineTable, + path: Sequence[str], + ) -> t.Cli.TomlParent: + """Resolve a fresh native view from the stable document root. + + Returns: + The original table or its current out-of-order view. + + Raises: + TypeError: If a path component no longer identifies a native table. + + """ + parent: t.Cli.TomlParent = document + for key in path: + child: object = parent[key] + if not isinstance(child, Table | InlineTable | OutOfOrderTableProxy): + msg = f"TOML sync path is not a table: {key}" + raise TypeError(msg) + parent = child + return parent + + @staticmethod + def _sync_document_values( + document: TOMLDocument | Table | InlineTable, + path: tuple[str, ...], + payload: t.JsonMapping, + current: t.JsonMapping, + *, + prune: bool, + ) -> None: + """Apply validated values without retaining invalidated native views.""" + if prune: + for key in current: + if key not in payload: + del FlextCliUtilitiesTomlPart04._toml_parent_at(document, path)[ + key + ] + for key, value in payload.items(): + current_value = current.get(key) + if isinstance(value, Mapping) and isinstance(current_value, Mapping): + FlextCliUtilitiesTomlPart04._sync_document_values( + document, (*path, key), value, current_value, prune=prune + ) + elif not FlextCliUtilitiesTomlPart04._toml_values_equal( + current_value, value + ): + parent = FlextCliUtilitiesTomlPart04._toml_parent_at(document, path) + child: object = parent.get(key) + if ( + isinstance(child, Array) + and isinstance(value, list) + and all(isinstance(item, str) for item in child) + and all(isinstance(item, str) for item in value) + ): + FlextCliUtilitiesTomlPart04.toml_sync_string_list( + parent, + key, + tuple(item for item in value if isinstance(item, str)), + ) + else: + parent[key] = value + + @staticmethod + def _toml_values_equal(current: t.JsonValue, expected: t.JsonValue) -> bool: + """Compare TOML scalar kinds through nested array and table values. + + Returns: + Whether the values and every nested native kind are identical. + + """ + if not u.same_type(current, expected): + return False + if isinstance(current, dict) and isinstance(expected, dict): + return current.keys() == expected.keys() and all( + FlextCliUtilitiesTomlPart04._toml_values_equal( + current[key], expected[key] + ) + for key in current + ) + if isinstance(current, list) and isinstance(expected, list): + return len(current) == len(expected) and all( + starmap( + FlextCliUtilitiesTomlPart04._toml_values_equal, + zip(current, expected, strict=True), + ) + ) + return current == expected + @staticmethod def toml_sync_value( - container: TOMLDocument | Table, + container: t.Cli.TomlParent, key: str, expected: t.JsonValue, ) -> bool: @@ -47,7 +164,7 @@ def toml_sync_value( @staticmethod def toml_sync_string_list( - container: TOMLDocument | Table, + container: t.Cli.TomlParent, key: str, expected: Sequence[str], *, diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py new file mode 100644 index 00000000..db3db92a --- /dev/null +++ b/tests/unit/test_toml_document_sync.py @@ -0,0 +1,357 @@ +"""Public recursive TOML synchronization without replacing authored source. + +Copyright (c) 2026 FLEXT Team. All rights reserved. +SPDX-License-Identifier: MIT +""" + +from __future__ import annotations + +from copy import deepcopy + +import pytest +from tomlkit.items import Array, Float, InlineTable, Integer, Table + +from tests import m, t, tm, u + + +class TestsFlextCliTomlDocumentSync: + """Preserve native document structure while applying declared values.""" + + @staticmethod + @pytest.mark.parametrize( + "source", + [ + ( + "# document\n" + "[project]\nname = 'demo' # name\n" + 'description = """first\n[tool.uv]\nlast"""\n' + "[build-system]\nrequires = ['hatchling']\n" + "[project.optional-dependencies]\nextra = ['pkg'] # extra\n" + ), + ( + 'settings = { "literal.key" = " keep ", active = true } # inline\n' + "[[indexes]] # first\nname = 'private'\n" + "[[indexes]] # second\nname = 'other'\n" + ), + ], + ) + def test_equal_values_preserve_document_bytes(source: str) -> None: + """Equal scalars, multiline strings, inline tables and AoT keep trivia.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload = tm.not_none(u.Cli.toml_as_mapping(document)) + + u.Cli.toml_sync_document_values(document, payload, prune=True) + + tm.that(u.Cli.toml_dumps(document), eq=source) + + @staticmethod + def test_sync_updates_out_of_order_values_in_original_document() -> None: + """Nested changes reach every real fragment and keep unrelated source.""" + source = ( + "[tool.uv]\n" + 'link-mode = "copy" # linking\n' + "environments = [\n" + ' "old", # environment\n' + "]\n" + "[project]\nname = 'demo' # project\n" + "[tool.uv.sources]\n" + 'vendor = { path = "vendor/client", editable = true } # source\n' + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload: t.JsonMapping = { + "tool": {"uv": {"link-mode": "clone", "environments": ["new"]}}, + } + + u.Cli.toml_sync_document_values(document, payload) + rendered = u.Cli.toml_dumps(document) + + tm.that( + rendered, + eq=source.replace('"copy"', '"clone"').replace('"old"', '"new"'), + ) + u.Cli.toml_sync_document_values(document, payload) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_sync_changes_inline_values_without_replacing_the_table() -> None: + """A changed inline child retains its siblings, quoted keys and comment.""" + source = ( + 'settings = { "literal.key" = "old", keep = \'literal\' } # inline\n' + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values( + document, + {"settings": {"literal.key": "new"}}, + ) + + tm.that(u.Cli.toml_dumps(document), eq=source.replace('"old"', '"new"')) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + def test_sync_prunes_only_when_requested(*, prune: bool) -> None: + """Remove absent root, fragmented and inline keys only for exact sync.""" + source = ( + "obsolete = true\n" + "[tool.uv]\n" + 'link-mode = "copy" # linking\n' + "retired = true\n" + "[project]\nname = 'demo' # project\n" + "[tool.uv.sources]\n" + 'vendor = { path = "vendor/client", editable = true, retired = true }' + " # source\n" + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload: t.JsonDict = { + "project": {"name": "demo"}, + "tool": { + "uv": { + "link-mode": "clone", + "sources": { + "vendor": {"path": "vendor/client", "editable": True}, + }, + }, + }, + } + original_payload = deepcopy(payload) + + u.Cli.toml_sync_document_values(document, payload, prune=prune) + rendered = u.Cli.toml_dumps(document) + tm.that(payload, eq=original_payload) + tm.that(rendered, has="[project]\nname = 'demo' # project\n") + tm.that(rendered, has="# linking") + tm.that(rendered, has="# source") + if prune: + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=payload) + else: + tm.that(rendered, eq=source.replace('"copy"', '"clone"')) + u.Cli.toml_sync_document_values(document, payload, prune=prune) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + @pytest.mark.parametrize( + ("source", "payload"), + [ + ("", {"values": []}), + ("values = [1]\n", {"values": ["1"]}), + ], + ) + def test_sync_installs_arrays_with_the_declared_values( + source: str, + payload: t.JsonMapping, + ) -> None: + """Empty and string arrays cannot disappear through scalar normalization.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values(document, payload, prune=True) + + tm.that(u.Cli.toml_mapping_from_text(u.Cli.toml_dumps(document)), eq=payload) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + def test_invalid_payload_fails_before_mutating_source(*, prune: bool) -> None: + """Native null rejection precedes both updates and removal of absent keys.""" + source = 'name = "old" # name\nretained = true\n' + document = tm.not_none(u.Cli.toml_parse_text(source)) + + with u.Tests.raises(TypeError, match="TOML does not support null values"): + u.Cli.toml_sync_document_values( + document, + {"name": "new", "invalid": None}, + prune=prune, + ) + + tm.that(u.Cli.toml_dumps(document), eq=source) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + def test_non_json_payload_fails_before_mutating_source(*, prune: bool) -> None: + """A native TOML timestamp cannot pass the public JSON payload boundary.""" + source = 'name = "old" # name\nretained = true\n' + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload_source = 'name = "new"\nstamp = 2026-01-01T00:00:00\n' + payload = tm.not_none(u.Cli.toml_parse_text(payload_source)) + + with u.Tests.raises(m.ValidationError) as error: + u.Cli.toml_sync_document_values(document, payload, prune=prune) + + tm.that(error.value.errors()[0]["loc"], eq=("stamp",)) + tm.that(error.value.errors()[0]["type"], eq="invalid-json-value") + tm.that(u.Cli.toml_dumps(document), eq=source) + tm.that(u.Cli.toml_dumps(payload), eq=payload_source) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + @pytest.mark.parametrize( + "source", + [ + ( + 'outside = "keep" # outside\n' + "[settings] # selected\n" + 'value = "old"\nobsolete = true\n' + ), + ( + 'outside = "keep" # outside\n' + 'settings = { value = "old", obsolete = true } # selected\n' + ), + ], + ids=("table", "inline-table"), + ) + def test_sync_table_roots_mutates_the_containing_document( + source: str, *, prune: bool + ) -> None: + """Stable Table and InlineTable roots update the real parent document.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + root = tm.not_none(u.Cli.toml_item_child(document, "settings")) + assert isinstance(root, Table | InlineTable) + expected: t.JsonMapping = { + "outside": "keep", + "settings": ( + {"value": "new"} if prune else {"value": "new", "obsolete": True} + ), + } + + u.Cli.toml_sync_document_values(root, {"value": "new"}, prune=prune) + rendered = u.Cli.toml_dumps(document) + + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=expected) + tm.that(rendered, has="# outside") + tm.that(rendered, has="# selected") + u.Cli.toml_sync_document_values(root, {"value": "new"}, prune=prune) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + @pytest.mark.parametrize( + ("source", "payload"), + [ + ( + ( + "[section.first]\nobsolete = true\n" + "[unrelated]\nkeep = 'value'\n" + '[section]\nvalue = "old" # retained\n' + ), + {"section": {"value": "new"}, "unrelated": {"keep": "value"}}, + ), + ( + ( + "[tool.uv.first]\nobsolete = true\n" + "[project]\nname = 'demo'\n" + "[tool.uv.second]\nobsolete = true\n" + "[unrelated]\nkeep = 'value'\n" + '[tool.uv]\nvalue = "old" # retained\n' + ), + { + "project": {"name": "demo"}, + "unrelated": {"keep": "value"}, + "tool": {"uv": {"value": "new"}}, + }, + ), + ], + ) + def test_prune_refreshes_fragmented_views_before_later_mutations( + source: str, + payload: t.JsonMapping, + ) -> None: + """Deleting earlier fragments cannot invalidate a later write or deletion.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values(document, payload, prune=True) + rendered = u.Cli.toml_dumps(document) + + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=payload) + tm.that(rendered, has="# retained") + u.Cli.toml_sync_document_values(document, payload, prune=True) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_sync_distinguishes_boolean_integer_and_float_values() -> None: + """Numerically equal scalars still require the declared TOML type.""" + document = tm.not_none( + u.Cli.toml_parse_text("enabled = true\namount = 1\n") + ) + + u.Cli.toml_sync_document_values( + document, + {"enabled": 1, "amount": 1.0}, + ) + + tm.that(document.item("enabled"), is_=Integer) + tm.that(document.item("amount"), is_=Float) + tm.that( + u.Cli.toml_dumps(document), + eq="enabled = 1\namount = 1.0\n", + ) + + @staticmethod + def test_sync_distinguishes_nested_mapping_and_array_types() -> None: + """Nested mappings and arrays cannot hide boolean or numeric type changes.""" + document = tm.not_none( + u.Cli.toml_parse_text( + "values = [true, 1]\n" + "nodes = [{enabled = true, amount = 1}]\n" + "[section]\nenabled = true\n" + "[section.nested]\namount = 1\n" + ) + ) + payload: t.JsonMapping = { + "values": [1, 1.0], + "nodes": [{"enabled": 1, "amount": 1.0}], + "section": {"enabled": 1, "nested": {"amount": 1.0}}, + } + + u.Cli.toml_sync_document_values(document, payload) + rendered = u.Cli.toml_dumps(document) + + values = document.item("values") + assert isinstance(values, Array) + tm.that(values.item(0), is_=Integer) + tm.that(values.item(1), is_=Float) + parsed = tm.ok(u.Cli.toml_mapping_from_text_result(rendered)) + nodes = parsed["nodes"] + assert isinstance(nodes, list) + node = nodes[0] + assert isinstance(node, dict) + tm.that(type(node["enabled"]), eq=int) + tm.that(type(node["amount"]), eq=float) + section = tm.not_none(u.Cli.toml_table_child(document, "section")) + nested = tm.not_none(u.Cli.toml_table_child(section, "nested")) + tm.that(section.item("enabled"), is_=Integer) + tm.that(nested.item("amount"), is_=Float) + u.Cli.toml_sync_document_values(document, payload) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_prune_nested_dotted_inline_key_preserves_valid_toml() -> None: + """Deleting one dotted child preserves its real sibling in the document.""" + document = tm.not_none( + u.Cli.toml_parse_text("x = {a.b.c = 1, a.b.d = 2}\n") + ) + payload: t.JsonMapping = {"x": {"a": {"b": {"d": 2}}}} + + u.Cli.toml_sync_document_values(document, payload, prune=True) + rendered = u.Cli.toml_dumps(document) + + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=payload) + u.Cli.toml_sync_document_values(document, payload, prune=True) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_replacing_fragmented_child_preserves_native_siblings() -> None: + """Replacing a repeated child cannot remove siblings in other fragments.""" + source = ( + "[y.y.b]\nc = 1\n" + "[y]\nd = 1\n" + "[y.b]\ne = 2\n" + "[y.y]\n" + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values(document, {"y": {"y": 1}}) + rendered = u.Cli.toml_dumps(document) + + tm.that( + tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), + eq={"y": {"y": 1, "d": 1, "b": {"e": 2}}}, + ) + u.Cli.toml_sync_document_values(document, {"y": {"y": 1}}) + tm.that(u.Cli.toml_dumps(document), eq=rendered)