💫 Toolkit to help you get started with SDD or any other process!
refactor(artifact): extract list operation (#4866)
Manfred Riemb9e08bf3e1a9
diff --git a/src/specify_cli/artifacts/_operation_list.py b/src/specify_cli/artifacts/_operation_list.pynew file mode 100644index 000000000..55cf4beb5--- /dev/null+++ b/src/specify_cli/artifacts/_operation_list.py@@ -0,0 +1,177 @@+"""Shared application operation for the ``artifact.list`` inventory."""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Any, Literal, TypedDict, cast++from ..presets import PresetError+from . import (+ ArtifactCatalog,+ ArtifactError,+ ArtifactResolutionError,+ NotASpecKitProjectError,+)+++class ArtifactListStackEntry(TypedDict):+ """Transport-neutral composition entry for a named artifact."""++ id: str+ layer: Literal["project", "preset", "extension"] | None+ sourceId: str | None+ presetId: str | None+ presetName: str | None+ strategy: Literal["replace", "wrap", "prepend", "append"]+ active: bool+ hidden: bool+ manifestPath: str | None+ lookupId: str | None+ sourcePath: str | None+++class ArtifactListHookStackEntry(TypedDict):+ """Transport-neutral composition entry for a hook artifact."""++ id: str+ layer: Literal["preset", "extension"]+ sourceId: str+ presetId: str | None+ presetName: str | None+ strategy: Literal["additive"]+ active: bool+ hidden: bool+ manifestPath: str+ lookupId: str+ sourcePath: None+ priority: int+ optional: bool+++class ArtifactListRow(TypedDict):+ """One artifact inventory row shared by delivery adapters."""++ id: str+ name: str+ kind: Literal["command", "template", "script"]+ description: str+ stack: list[ArtifactListStackEntry]+++class ArtifactListHookRow(TypedDict):+ """One hook inventory row shared by delivery adapters."""++ id: str+ name: str+ kind: Literal["hook"]+ description: str+ eventName: str+ targetCommand: str+ registered: bool+ stack: list[ArtifactListHookStackEntry]+++ArtifactListItem = ArtifactListRow | ArtifactListHookRow+++@dataclass(frozen=True)+class ArtifactListRequest:+ """Explicit project context for the ``artifact.list`` operation."""++ project_directory: Path+++@dataclass(frozen=True)+class ArtifactListResult:+ """Transport-neutral artifact inventory."""++ rows: tuple[ArtifactListItem, ...]+++class ArtifactListError(ArtifactError):+ """Expected transport-neutral failure from ``artifact.list``."""++ code: str+ details: dict[str, Any]+ retryable: bool++ def __init__(+ self,+ *,+ code: str,+ message: str,+ details: dict[str, Any],+ retryable: bool = False,+ ) -> None:+ self.code = code+ self.message = message+ self.details = details+ self.retryable = retryable+ super().__init__(message)+++class ArtifactListProjectError(ArtifactListError):+ """The supplied directory is not a Spec Kit project root."""++ def __init__(self, project_directory: Path) -> None:+ super().__init__(+ code="not_a_spec_kit_project",+ message="not a Spec Kit project: no .specify/ directory found",+ details={"project_directory": str(project_directory)},+ )+++class ArtifactListResolutionError(ArtifactListError):+ """The artifact inventory could not be resolved."""++ def __init__(self, project_directory: Path) -> None:+ super().__init__(+ code="artifact_resolution_failed",+ message="artifact resolution failed",+ details={"project_directory": str(project_directory)},+ )+++@dataclass(frozen=True)+class ArtifactListOperationDescriptor:+ """Stable metadata shared by delivery adapters for ``artifact.list``."""++ operation_id: Literal["artifact.list"]+ contract_version: Literal["1"]+ request_type: type[ArtifactListRequest]+ result_type: type[ArtifactListResult]+ warning_types: tuple[type[object], ...]+ error_types: tuple[type[ArtifactListError], ...]+ capabilities: frozenset[Literal["local-read"]]+ network_access: Literal["none"]+++ARTIFACT_LIST_OPERATION = ArtifactListOperationDescriptor(+ operation_id="artifact.list",+ contract_version="1",+ request_type=ArtifactListRequest,+ result_type=ArtifactListResult,+ warning_types=(),+ error_types=(ArtifactListProjectError, ArtifactListResolutionError),+ capabilities=frozenset({"local-read"}),+ network_access="none",+)+++def list_artifacts(request: ArtifactListRequest) -> ArtifactListResult:+ """Return the complete typed artifact inventory for an explicit project."""+ project_directory = Path(request.project_directory)+ if not project_directory.is_absolute():+ raise ArtifactListProjectError(project_directory)++ try:+ rows = ArtifactCatalog(project_directory).list_artifacts_with_stack()+ except NotASpecKitProjectError as exc:+ raise ArtifactListProjectError(project_directory) from exc+ except (ArtifactResolutionError, OSError, PresetError) as exc:+ raise ArtifactListResolutionError(project_directory) from exc++ return ArtifactListResult(+ rows=tuple(cast(ArtifactListItem, row) for row in rows),+ )diff --git a/src/specify_cli/artifacts/command_list.py b/src/specify_cli/artifacts/command_list.pyindex 163a59756..33fee0a93 100644--- a/src/specify_cli/artifacts/command_list.py+++ b/src/specify_cli/artifacts/command_list.py@@ -3,18 +3,32 @@from __future__ import annotationsimport json+import osimport sys+from pathlib import Pathimport typer-from ..presets import PresetError-from . import ArtifactCatalog, ArtifactError, ArtifactResolutionError+from . import ArtifactErrorfrom ._commands import (_emit_error_and_exit,_require_json_flag,- _resolve_project_root,artifact_app,)+from ._operation_list import (+ ArtifactListRequest,+ ArtifactListResolutionError,+ list_artifacts,+)+++def _project_directory_from_cli_context() -> Path:+ """Return the explicit project directory selected by the CLI invocation."""+ invocation_directory = Path.cwd()+ override = os.environ.get("SPECIFY_INIT_DIR", "")+ if not override:+ return invocation_directory+ return (invocation_directory / override).resolve()@artifact_app.command("list")@@ -28,15 +42,19 @@ def artifact_list("""List every command, template, script, and hook Spec Kit exposes."""_require_json_flag(json_flag)try:- root = _resolve_project_root()- catalog = ArtifactCatalog(root)- rows = catalog.list_artifacts_with_stack()+ result = list_artifacts(+ ArtifactListRequest(+ project_directory=_project_directory_from_cli_context(),+ )+ )except ArtifactError as exc:_emit_error_and_exit(exc)return # pragma: no cover — _emit_error_and_exit raises- except (OSError, PresetError):- _emit_error_and_exit(ArtifactResolutionError())+ except OSError:+ _emit_error_and_exit(ArtifactListResolutionError(Path(".")))return # pragma: no cover — _emit_error_and_exit raises- sys.stdout.write(json.dumps(rows, indent=2, sort_keys=True, ensure_ascii=False))+ sys.stdout.write(+ json.dumps(result.rows, indent=2, sort_keys=True, ensure_ascii=False)+ )sys.stdout.write("\n")diff --git a/tests/specify_cli/artifacts/test_command_list.py b/tests/specify_cli/artifacts/test_command_list.pyindex dc77531c5..bcefd1d76 100644--- a/tests/specify_cli/artifacts/test_command_list.py+++ b/tests/specify_cli/artifacts/test_command_list.py@@ -4,26 +4,33 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from unittest.mock import Mockimport pytestimport yamlfrom typer.testing import CliRunnerfrom specify_cli import app+from specify_cli.artifacts import command_list+from specify_cli.artifacts._operation_list import ArtifactListResultfrom specify_cli.extensions import ExtensionRegistryfrom specify_cli.presets import PresetRegistryfrom tests.conftest import install_presetclass TestCommandList:- def test_list_requires_json_flag(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):+ def test_list_requires_json_flag(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):monkeypatch.chdir(spec_kit_project)runner = CliRunner()result = runner.invoke(app, ["artifact", "list"])assert result.exit_code == 2assert result.stdout == ""- def test_list_json_emits_array(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):+ def test_list_json_emits_array(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):monkeypatch.chdir(spec_kit_project)runner = CliRunner()result = runner.invoke(app, ["artifact", "list", "--json"])@@ -31,8 +38,49 @@ class TestCommandList:payload = json.loads(result.stdout)assert isinstance(payload, list)assert result.stdout.endswith("\n")+ assert result.stderr == ""++ def test_list_dispatches_directly_to_shared_operation(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):+ expected = ArtifactListResult(+ rows=(+ {+ "id": "template:example",+ "name": "example",+ "kind": "template",+ "description": "Example",+ "stack": [],+ },+ )+ )+ operation = Mock(return_value=expected)+ monkeypatch.setattr(command_list, "list_artifacts", operation)+ monkeypatch.chdir(spec_kit_project)++ result = CliRunner().invoke(app, ["artifact", "list", "--json"])++ assert result.exit_code == 0, result.stderr+ assert json.loads(result.stdout) == list(expected.rows)+ request = operation.call_args.args[0]+ assert request.project_directory == spec_kit_project- def test_list_json_rows_include_stack(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):+ def test_list_json_matches_shared_operation_result(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.chdir(spec_kit_project)+ expected = command_list.list_artifacts(+ command_list.ArtifactListRequest(spec_kit_project)+ )++ result = CliRunner().invoke(app, ["artifact", "list", "--json"])++ assert result.exit_code == 0, result.stderr+ assert json.loads(result.stdout) == list(expected.rows)++ def test_list_json_rows_include_stack(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):monkeypatch.chdir(spec_kit_project)runner = CliRunner()result = runner.invoke(app, ["artifact", "list", "--json"])@@ -85,7 +133,9 @@ class TestCommandList:/ "SKILL.md")skill_file.parent.mkdir(parents=True)- skill_file.write_text("---\nname: speckit-compliance-plan\n---\n", encoding="utf-8")+ skill_file.write_text(+ "---\nname: speckit-compliance-plan\n---\n", encoding="utf-8"+ )extension_dir = spec_kit_project / ".specify" / "extensions" / "quality"(extension_dir / "templates").mkdir(parents=True)@@ -140,14 +190,32 @@ class TestCommandList:assert (spec_kit_project / source_path).is_file()non_null_source_paths.add(source_path)- assert ".github/skills/speckit-compliance-plan/SKILL.md" in non_null_source_paths- assert ".specify/extensions/quality/templates/checklist.md" in non_null_source_paths+ assert (+ ".github/skills/speckit-compliance-plan/SKILL.md" in non_null_source_paths+ )+ assert (+ ".specify/extensions/quality/templates/checklist.md"+ in non_null_source_paths+ )- def test_list_json_is_pretty_printed(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):+ def test_list_json_is_pretty_printed(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):monkeypatch.chdir(spec_kit_project)runner = CliRunner()result = runner.invoke(app, ["artifact", "list", "--json"])assert ' "id"' in result.stdout # 2-space indent visible+ assert result.stdout == (+ json.dumps(+ json.loads(result.stdout),+ indent=2,+ sort_keys=True,+ ensure_ascii=False,+ )+ + "\n"+ )+ assert "\x1b[" not in result.stdout+ assert result.stderr == ""def test_list_corrupt_extension_registry_uses_json_error_envelope(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch@@ -159,8 +227,27 @@ class TestCommandList:assert result.exit_code == 1assert result.stdout == ""assert json.loads(result.stderr) == {"error": "artifact resolution failed"}+ assert result.stderr.count("\n") == 1+ assert "\x1b[" not in result.stderr- def test_not_a_project_error_envelope(self, non_project: Path, monkeypatch: pytest.MonkeyPatch):+ def test_cli_context_filesystem_failure_uses_json_error_envelope(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.setattr(+ command_list,+ "_project_directory_from_cli_context",+ Mock(side_effect=OSError("unreadable cwd")),+ )++ result = CliRunner().invoke(app, ["artifact", "list", "--json"])++ assert result.exit_code == 1+ assert result.stdout == ""+ assert json.loads(result.stderr) == {"error": "artifact resolution failed"}++ def test_not_a_project_error_envelope(+ self, non_project: Path, monkeypatch: pytest.MonkeyPatch+ ):monkeypatch.chdir(non_project)runner = CliRunner()result = runner.invoke(app, ["artifact", "list", "--json"])@@ -169,7 +256,9 @@ class TestCommandList:err = json.loads(result.stderr)assert err["error"] == "not a Spec Kit project: no .specify/ directory found"- def test_output_is_utf8_without_bom(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):+ def test_output_is_utf8_without_bom(+ self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+ ):monkeypatch.chdir(spec_kit_project)runner = CliRunner()result = runner.invoke(app, ["artifact", "list", "--json"])diff --git a/tests/specify_cli/artifacts/test_operation_list.py b/tests/specify_cli/artifacts/test_operation_list.pynew file mode 100644index 000000000..c898a53dc--- /dev/null+++ b/tests/specify_cli/artifacts/test_operation_list.py@@ -0,0 +1,219 @@+"""Tests for the shared ``artifact.list`` operation."""++from __future__ import annotations++from pathlib import Path+from unittest.mock import Mock++import pytest+import yaml++from specify_cli import artifacts+from specify_cli.artifacts import ArtifactCatalog, _operation_list+from specify_cli.artifacts._operation_list import (+ ARTIFACT_LIST_OPERATION,+ ArtifactListProjectError,+ ArtifactListRequest,+ ArtifactListResolutionError,+ ArtifactListResult,+ list_artifacts,+)+from specify_cli.extensions import ExtensionRegistry+from specify_cli.presets import PresetError+++def test_artifact_list_operation_descriptor_is_stable():+ assert ARTIFACT_LIST_OPERATION.operation_id == "artifact.list"+ assert ARTIFACT_LIST_OPERATION.contract_version == "1"+ assert ARTIFACT_LIST_OPERATION.request_type is ArtifactListRequest+ assert ARTIFACT_LIST_OPERATION.result_type is ArtifactListResult+ assert ARTIFACT_LIST_OPERATION.warning_types == ()+ assert ARTIFACT_LIST_OPERATION.error_types == (+ ArtifactListProjectError,+ ArtifactListResolutionError,+ )+ assert ARTIFACT_LIST_OPERATION.capabilities == frozenset({"local-read"})+ assert ARTIFACT_LIST_OPERATION.network_access == "none"+++def test_list_artifacts_returns_complete_typed_inventory(spec_kit_project: Path):+ expected = ArtifactCatalog(spec_kit_project).list_artifacts_with_stack()++ result = list_artifacts(ArtifactListRequest(spec_kit_project))++ assert isinstance(result, ArtifactListResult)+ assert list(result.rows) == expected+ assert result.rows+ assert all(+ {"id", "name", "kind", "description", "stack"} <= row.keys()+ for row in result.rows+ )+++def test_list_artifacts_preserves_empty_inventory(+ spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch+):+ list_with_stack = Mock(return_value=[])+ monkeypatch.setattr(+ _operation_list,+ "ArtifactCatalog",+ lambda _project_directory: Mock(list_artifacts_with_stack=list_with_stack),+ )++ result = list_artifacts(ArtifactListRequest(spec_kit_project))++ assert result == ArtifactListResult(rows=())+ list_with_stack.assert_called_once_with()+++def test_list_artifacts_is_stable_across_repeated_calls(spec_kit_project: Path):+ request = ArtifactListRequest(spec_kit_project)++ first = list_artifacts(request)+ second = list_artifacts(request)++ assert first == second+ assert [row["id"] for row in first.rows] == [row["id"] for row in second.rows]+++def test_list_artifacts_preserves_unicode_source_paths_and_stack(+ spec_kit_project: Path,+):+ extension_dir = spec_kit_project / ".specify" / "extensions" / "quality"+ template = extension_dir / "templates" / "réview-checklist.md"+ template.parent.mkdir(parents=True)+ template.write_text(+ "---\ndescription: Réview checklist\n---\n",+ encoding="utf-8",+ )+ (extension_dir / "extension.yml").write_text(+ yaml.safe_dump(+ {+ "schema_version": "1.0",+ "extension": {+ "id": "quality",+ "name": "Quality",+ "version": "1.0.0",+ "description": "test",+ "author": "test",+ "repository": "https://example.com",+ "license": "MIT",+ },+ "requires": {"speckit_version": ">=0.2.0"},+ "provides": {+ "templates": [+ {+ "name": "review-checklist",+ "file": "templates/réview-checklist.md",+ "description": "Réview checklist",+ }+ ]+ },+ }+ ),+ encoding="utf-8",+ )+ ExtensionRegistry(spec_kit_project / ".specify" / "extensions").add(+ "quality",+ {"version": "1.0.0", "enabled": True},+ )++ result = list_artifacts(ArtifactListRequest(spec_kit_project))+ row = next(+ item for item in result.rows if item["id"] == "template:review-checklist"+ )++ assert row["description"] == "Réview checklist"+ assert row["stack"][0]["sourcePath"] == (+ ".specify/extensions/quality/templates/réview-checklist.md"+ )+ assert (+ row["stack"]+ == ArtifactCatalog(spec_kit_project).get_artifact_info(row["id"])["stack"]+ )+++def test_list_artifacts_uses_explicit_project_without_process_cwd(+ spec_kit_project: Path,+ non_project: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.chdir(non_project)++ result = list_artifacts(ArtifactListRequest(spec_kit_project))++ assert result.rows+++def test_list_artifacts_rejects_relative_project_directory():+ with pytest.raises(ArtifactListProjectError) as exc_info:+ list_artifacts(ArtifactListRequest(Path("relative-project")))++ assert exc_info.value.code == "not_a_spec_kit_project"+ assert exc_info.value.message == (+ "not a Spec Kit project: no .specify/ directory found"+ )+ assert exc_info.value.details == {"project_directory": "relative-project"}+ assert exc_info.value.retryable is False+++def test_list_artifacts_rejects_non_project(non_project: Path):+ with pytest.raises(ArtifactListProjectError) as exc_info:+ list_artifacts(ArtifactListRequest(non_project))++ assert exc_info.value.code == "not_a_spec_kit_project"+ assert exc_info.value.details == {"project_directory": str(non_project)}+++def test_list_artifacts_maps_corrupt_registry_to_resolution_error(+ spec_kit_project: Path,+):+ registry = spec_kit_project / ".specify" / "extensions" / ".registry"+ registry.write_text("{invalid", encoding="utf-8")++ with pytest.raises(ArtifactListResolutionError) as exc_info:+ list_artifacts(ArtifactListRequest(spec_kit_project))++ assert exc_info.value.code == "artifact_resolution_failed"+ assert exc_info.value.message == "artifact resolution failed"+ assert exc_info.value.details == {"project_directory": str(spec_kit_project)}+ assert exc_info.value.retryable is False+++def test_list_artifacts_maps_preset_failures_to_resolution_error(+ spec_kit_project: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setattr(+ artifacts.ArtifactCatalog,+ "list_artifacts_with_stack",+ Mock(side_effect=PresetError("broken preset")),+ )++ with pytest.raises(ArtifactListResolutionError) as exc_info:+ list_artifacts(ArtifactListRequest(spec_kit_project))++ assert isinstance(exc_info.value.__cause__, PresetError)+++def test_list_artifacts_maps_filesystem_failures_to_resolution_error(+ spec_kit_project: Path,+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setattr(+ artifacts.ArtifactCatalog,+ "list_artifacts_with_stack",+ Mock(side_effect=OSError("unreadable")),+ )++ with pytest.raises(ArtifactListResolutionError) as exc_info:+ list_artifacts(ArtifactListRequest(spec_kit_project))++ assert isinstance(exc_info.value.__cause__, OSError)+++def test_operation_contract_is_transport_neutral():+ forbidden_names = {"typer", "rich", "mcp", "console"}++ assert forbidden_names.isdisjoint(_operation_list.__dict__)+ assert ArtifactListResult.__module__ == ("specify_cli.artifacts._operation_list")