Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- `apm install` and `apm uninstall` no longer strip comments from `apm.yml`
while updating dependency entries, so inline annotations and section notes
survive dependency updates. (#2012)
- `apm pack` now produces a `marketplace.json` the Copilot App accepts even
when your manifest `name` contains dots, underscores, or other non-kebab-case
characters (e.g. `my.marketplace`): the emitted `name` field is normalized to
Expand Down
8 changes: 4 additions & 4 deletions src/apm_cli/commands/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,9 +609,9 @@ def _merge_packages_into_yml(

# Write back to apm.yml
try:
from ..utils.yaml_io import dump_yaml
from ..utils.yaml_io import dump_yaml_roundtrip

dump_yaml(data, apm_yml_path)
dump_yaml_roundtrip(data, apm_yml_path)
if logger:
logger.success(
f"Updated {APM_YML_FILENAME} with {len(validated_packages)} new package(s)"
Expand Down Expand Up @@ -660,9 +660,9 @@ def _validate_and_add_packages_to_apm_yml(

# Read current apm.yml
try:
from ..utils.yaml_io import load_yaml
from ..utils.yaml_io import load_yaml_roundtrip

data = load_yaml(apm_yml_path) or {}
data = load_yaml_roundtrip(apm_yml_path) or {}
except Exception as e:
if logger:
logger.error(f"Failed to read {APM_YML_FILENAME}: {e}")
Expand Down
6 changes: 3 additions & 3 deletions src/apm_cli/commands/uninstall/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ def uninstall(ctx, packages, dry_run, verbose, global_):
)

# Read current apm.yml
from ...utils.yaml_io import dump_yaml, load_yaml
from ...utils.yaml_io import dump_yaml_roundtrip, load_yaml_roundtrip

apm_yml_path = manifest_path
try:
data = load_yaml(apm_yml_path) or {}
data = load_yaml_roundtrip(apm_yml_path) or {}
except Exception as e:
logger.error(f"Failed to read {apm_yml_path}: {e}")
sys.exit(1)
Expand Down Expand Up @@ -166,7 +166,7 @@ def uninstall(ctx, packages, dry_run, verbose, global_):
if not data["devDependencies"] and not had_dev_section:
del data["devDependencies"]
try:
dump_yaml(data, apm_yml_path)
dump_yaml_roundtrip(data, apm_yml_path)
logger.success(f"Updated {apm_yml_path} (removed {len(packages_to_remove)} package(s))")
except Exception as e:
logger.error(f"Failed to write {apm_yml_path}: {e}")
Expand Down
4 changes: 2 additions & 2 deletions src/apm_cli/install/package_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,9 @@ def persist_dependency_list_if_changed(
return
data[dep_section]["apm"] = current_deps
try:
from apm_cli.utils.yaml_io import dump_yaml
from apm_cli.utils.yaml_io import dump_yaml_roundtrip

dump_yaml(data, apm_yml_path)
dump_yaml_roundtrip(data, apm_yml_path)
if logger:
logger.success(f"Updated {apm_yml_filename} dependency entries")
except Exception as e:
Expand Down
71 changes: 67 additions & 4 deletions src/apm_cli/utils/yaml_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,19 @@

Public API::

load_yaml(path) -- read a .yml/.yaml file -> dict | None
dump_yaml(data, path) -- write dict -> .yml/.yaml file
yaml_to_str(data) -- serialize dict -> YAML string
load_yaml(path) -- read a .yml/.yaml file -> dict | None
dump_yaml(data, path) -- write dict -> .yml/.yaml file
load_yaml_roundtrip(path) -- read YAML while preserving comments
dump_yaml_roundtrip(data, path) -- write round-trip YAML data
yaml_to_str(data) -- serialize dict -> YAML string
"""

import os
import secrets
from contextlib import suppress
from io import StringIO
from pathlib import Path
from typing import Any
from typing import Any, NoReturn

import yaml
from frontmatter.default_handlers import YAMLHandler as _FrontmatterYAMLHandler
Expand Down Expand Up @@ -285,6 +288,66 @@ def load_yaml_str(text: str) -> dict[str, Any] | None:
return _bounded_load(text)


def _roundtrip_yaml() -> Any:
"""Return a configured ruamel.yaml round-trip parser."""
from ruamel.yaml import YAML
from ruamel.yaml.constructor import ConstructorError

def reject_python_tag(_constructor: Any, tag_suffix: str, node: Any) -> NoReturn:
raise ConstructorError(
None,
None,
f"forbidden Python YAML tag: {tag_suffix}",
node.start_mark,
)

rt = YAML(typ="rt")
# Class-level constructor registration is intentional: every round-trip
# YAML instance in this process should reject unsafe Python tags.
rt.Constructor.add_multi_constructor("tag:yaml.org,2002:python/", reject_python_tag)
rt.preserve_quotes = True
rt.indent(mapping=2, sequence=4, offset=2)
return rt


def _raise_as_pyyaml_error(exc: Exception) -> NoReturn:
"""Normalize ruamel parser failures to the yaml.YAMLError family."""
from ruamel.yaml import YAMLError as RuamelYAMLError

if isinstance(exc, RuamelYAMLError):
raise yaml.YAMLError(f"YAML parse failed: {exc}") from exc
raise exc


def load_yaml_roundtrip(path: str | Path) -> Any:
"""Load YAML while preserving comments and formatting metadata.

The document is first parsed by the bounded PyYAML loader so the manifest
update paths keep the same alias and merge-key safety budget as
:func:`load_yaml`. The original text is then parsed with ruamel.yaml
round-trip mode so callers can mutate the returned object and write it back
without stripping comments.
"""
text = Path(path).read_text(encoding="utf-8")
_bounded_load(text)
try:
return _roundtrip_yaml().load(text)
except Exception as exc:
_raise_as_pyyaml_error(exc)


def dump_yaml_roundtrip(data: Any, path: str | Path) -> None:
"""Write ruamel round-trip YAML data with explicit UTF-8 encoding."""
stream = StringIO()
try:
_roundtrip_yaml().dump(data, stream)
except Exception as exc:
_raise_as_pyyaml_error(exc)
text = stream.getvalue()
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
Comment on lines +341 to +348


class _BoundedYAMLHandler(_FrontmatterYAMLHandler):
"""python-frontmatter YAML handler bound to ``_BoundedSafeLoader``.

Expand Down
81 changes: 81 additions & 0 deletions tests/integration/test_manifest_comments_e2e.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""E2E regression test for comment-preserving apm.yml rewrites."""

from __future__ import annotations

from types import SimpleNamespace
from unittest.mock import patch

import pytest
import yaml
from click.testing import CliRunner

from apm_cli.cli import cli
from apm_cli.models.apm_package import clear_apm_yml_cache

pytestmark = [
pytest.mark.integration,
pytest.mark.requires_e2e_mode,
]

_PATCH_UPDATES = "apm_cli.commands._helpers.check_for_updates"


@pytest.fixture(autouse=True)
def _clear_manifest_cache() -> None:
"""Keep manifest parsing isolated across CLI invocations."""
clear_apm_yml_cache()
yield
clear_apm_yml_cache()


def test_install_preserves_manifest_comments_and_formatting(tmp_path, monkeypatch) -> None:
"""Running real ``apm install`` keeps comments and formatting in apm.yml."""
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("APM_PROGRESS", "never")
manifest = tmp_path / "apm.yml"
manifest.write_text(
"""\
# project intent: keep this manifest annotated
name: comment-roundtrip
version: "1.0.0"

dependencies:
# APM dependency notes must survive installs
apm:
- "owner/existing-skill" # inline package note
mcp: [] # compact MCP list stays compact
targets:
# target comment remains attached
- copilot
""",
encoding="utf-8",
)

install_result = SimpleNamespace(installed_count=1, diagnostics=None)
runner = CliRunner()

with (
patch(_PATCH_UPDATES, return_value=None),
patch("apm_cli.commands.install._validate_package_exists", return_value=True),
patch("apm_cli.commands.install._install_apm_dependencies", return_value=install_result),
):
result = runner.invoke(
cli,
["install", "owner/new-skill", "--only=apm", "--no-policy"],
catch_exceptions=False,
)

assert result.exit_code == 0, result.output
rendered = manifest.read_text(encoding="utf-8")
parsed = yaml.safe_load(rendered)

assert parsed["dependencies"]["apm"] == [
"owner/existing-skill",
"owner/new-skill",
]
assert "# project intent: keep this manifest annotated" in rendered
assert 'version: "1.0.0"' in rendered
assert " # APM dependency notes must survive installs" in rendered
assert ' - "owner/existing-skill" # inline package note' in rendered
assert " mcp: [] # compact MCP list stays compact" in rendered
assert " # target comment remains attached" in rendered
1 change: 1 addition & 0 deletions tests/integration/test_runtime_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

pytestmark = [
pytest.mark.requires_e2e_mode,
pytest.mark.requires_network_integration,
# Mutates os.environ["HOME"]; must be serialized on a single xdist worker.
# Requires --dist loadgroup in the xdist invocation (the only
# scheduler that honors xdist_group); without it the marker is
Expand Down
5 changes: 4 additions & 1 deletion tests/integration/test_skill_bundle_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@
# Markers and skip gates
# ---------------------------------------------------------------------------

pytestmark = pytest.mark.live
pytestmark = [
pytest.mark.live,
pytest.mark.requires_network_integration,
]


# ---------------------------------------------------------------------------
Expand Down
50 changes: 46 additions & 4 deletions tests/unit/commands/test_install_context_and_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def test_appends_packages_to_current_deps(self, tmp_path: Path) -> None:
data = {"dependencies": {"apm": ["existing/pkg"]}}
current_deps = data["dependencies"]["apm"]

with patch("apm_cli.utils.yaml_io.dump_yaml") as mock_dump:
with patch("apm_cli.utils.yaml_io.dump_yaml_roundtrip") as mock_dump:
_merge_packages_into_yml(
["new/pkg"],
{},
Expand All @@ -273,7 +273,7 @@ def test_uses_apm_yml_entry_when_present(self, tmp_path: Path) -> None:
current_deps = data["dependencies"]["apm"]
apm_yml_entries = {"owner/repo": {"repo": "owner/repo", "ref": "main"}}

with patch("apm_cli.utils.yaml_io.dump_yaml"):
with patch("apm_cli.utils.yaml_io.dump_yaml_roundtrip"):
_merge_packages_into_yml(
["owner/repo"],
apm_yml_entries,
Expand All @@ -292,7 +292,7 @@ def test_write_failure_exits(self, tmp_path: Path) -> None:
data = {"dependencies": {"apm": []}}
current_deps = data["dependencies"]["apm"]

with patch("apm_cli.utils.yaml_io.dump_yaml", side_effect=Exception("disk full")):
with patch("apm_cli.utils.yaml_io.dump_yaml_roundtrip", side_effect=Exception("disk full")):
with pytest.raises(SystemExit) as exc_info:
_merge_packages_into_yml(
["owner/repo"],
Expand All @@ -312,7 +312,7 @@ def test_dev_flag_logs_devDependencies_label(self, tmp_path: Path) -> None:
data = {"devDependencies": {"apm": []}}
current_deps = data["devDependencies"]["apm"]

with patch("apm_cli.utils.yaml_io.dump_yaml"):
with patch("apm_cli.utils.yaml_io.dump_yaml_roundtrip"):
_merge_packages_into_yml(
["owner/repo"],
{},
Expand Down Expand Up @@ -421,6 +421,48 @@ def test_validation_summary_false_returns_early(self, tmp_path: Path) -> None:
)
assert validated == []

def test_manifest_update_preserves_comments(self, tmp_path: Path) -> None:
from apm_cli.commands.install import _validate_and_add_packages_to_apm_yml

apm_yml = tmp_path / "apm.yml"
apm_yml.write_text(
"# project comment\n"
"name: project\n"
"# dependency section comment\n"
"dependencies: # dependencies inline comment\n"
" # apm list comment\n"
" apm:\n"
" - existing/pkg # existing dependency comment\n",
encoding="utf-8",
)
logger = _make_install_logger()
logger.validation_summary.return_value = True

with patch("apm_cli.commands.install._check_package_conflicts", return_value=set()):
with patch("apm_cli.commands.install._resolve_package_references") as mock_resolve:
mock_resolve.return_value = (
[("new/pkg", False)],
[],
["new/pkg"],
{},
{},
False,
)
validated, _outcome = _validate_and_add_packages_to_apm_yml(
["new/pkg"],
logger=logger,
manifest_path=apm_yml,
)

text = apm_yml.read_text(encoding="utf-8")
assert validated == ["new/pkg"]
assert "# project comment" in text
assert "# dependency section comment" in text
assert "# dependencies inline comment" in text
assert "# apm list comment" in text
assert "# existing dependency comment" in text
assert "new/pkg" in text


# ---------------------------------------------------------------------------
# install CLI command -- validation / early-exit branches
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/commands/test_install_error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def test_write_error_no_logger_calls_rich_error(self, tmp_path: Path) -> None:
),
),
patch(
"apm_cli.utils.yaml_io.dump_yaml",
"apm_cli.utils.yaml_io.dump_yaml_roundtrip",
side_effect=OSError("write fail"),
),
):
Expand Down Expand Up @@ -213,7 +213,7 @@ def test_write_error_with_logger_calls_logger_error(self, tmp_path: Path) -> Non
False,
),
),
patch("apm_cli.utils.yaml_io.dump_yaml", side_effect=OSError("write fail")),
patch("apm_cli.utils.yaml_io.dump_yaml_roundtrip", side_effect=OSError("write fail")),
):
with pytest.raises(SystemExit) as exc_info:
_validate_and_add_packages_to_apm_yml(
Expand Down
Loading
Loading