Skip to content
Open
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
23 changes: 18 additions & 5 deletions src/specify_cli/_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,32 @@ def _locate_bundled_preset(preset_id: str) -> Path | None:

def get_speckit_version() -> str:
"""Get current spec-kit version."""
# Mirror _version._get_installed_version(): a malformed installed
# distribution raises InvalidMetadataError, which is not a
# PackageNotFoundError and must not escape the fallback path.
metadata_errors = [importlib.metadata.PackageNotFoundError]
invalid_metadata_error = getattr(importlib.metadata, "InvalidMetadataError", None)
if invalid_metadata_error is not None:
metadata_errors.append(invalid_metadata_error)

try:
return importlib.metadata.version("specify-cli")
except Exception:
except tuple(metadata_errors):
# Fallback: try reading from pyproject.toml
try:
import tomllib
pyproject_path = _repo_root() / "pyproject.toml"
if pyproject_path.exists():
with open(pyproject_path, "rb") as f:
data = tomllib.load(f)
return data.get("project", {}).get("version", "unknown")
except Exception:
# Intentionally ignore any errors while reading/parsing pyproject.toml.
# If this lookup fails for any reason, we fall back to returning "unknown" below.
project = data.get("project") if isinstance(data, dict) else None
# A present but non-mapping ``project`` table must not turn
# into an AttributeError from the narrowing of this branch.
if isinstance(project, dict):
version = project.get("version")
if isinstance(version, str) and version:
return version
return "unknown"
except (OSError, KeyError, ValueError):
pass
return "unknown"
61 changes: 61 additions & 0 deletions tests/test_utils_assets_imports.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""Regression guard: utility and asset symbols importable from specify_cli."""
import importlib.metadata

from specify_cli import (
check_tool, merge_json_files,
get_speckit_version,
CLAUDE_LOCAL_PATH, CLAUDE_NPM_LOCAL_PATH,
)
from specify_cli import _assets
from pathlib import Path

def test_utils_symbols_importable():
Expand All @@ -17,3 +20,61 @@ def test_get_speckit_version_returns_string():
def test_claude_paths_are_paths():
assert isinstance(CLAUDE_LOCAL_PATH, Path)
assert isinstance(CLAUDE_NPM_LOCAL_PATH, Path)


def test_get_speckit_version_survives_invalid_metadata(monkeypatch):
"""A corrupt installed distribution must fall back, not raise.

``InvalidMetadataError`` is not a ``PackageNotFoundError``, so catching
only the latter lets it escape the version fallback (the same guard
Comment on lines +25 to +29
_version._get_installed_version() already applies). The class is looked up
dynamically and was removed from the stdlib in 3.14, so install a stand-in
to exercise the guard on every supported interpreter.
"""

class _InvalidMetadataError(Exception):
pass

monkeypatch.setattr(
importlib.metadata, "InvalidMetadataError", _InvalidMetadataError, raising=False
)

def _corrupt(name):
raise _InvalidMetadataError("corrupt metadata")

monkeypatch.setattr(importlib.metadata, "version", _corrupt)

assert isinstance(get_speckit_version(), str)


def test_get_speckit_version_survives_non_mapping_project(monkeypatch, tmp_path):
"""A present but non-mapping ``project`` value must not raise.

The narrowed pyproject branch previously called ``.get`` on whatever the
``project`` key held, so ``project = 5`` turned the fallback into an
AttributeError.
"""
(tmp_path / "pyproject.toml").write_text("project = 5\n", encoding="utf-8")
monkeypatch.setattr(_assets, "_repo_root", lambda: tmp_path)

def _not_found(name):
raise importlib.metadata.PackageNotFoundError(name)

monkeypatch.setattr(importlib.metadata, "version", _not_found)

assert get_speckit_version() == "unknown"


def test_get_speckit_version_reads_pyproject_fallback(monkeypatch, tmp_path):
"""When the distribution is missing, a valid pyproject.toml is the source."""
(tmp_path / "pyproject.toml").write_text(
'[project]\nname = "demo"\nversion = "9.9.9"\n', encoding="utf-8"
)
monkeypatch.setattr(_assets, "_repo_root", lambda: tmp_path)

def _not_found(name):
raise importlib.metadata.PackageNotFoundError(name)

monkeypatch.setattr(importlib.metadata, "version", _not_found)

assert get_speckit_version() == "9.9.9"
Loading