Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cli): compare versions in changelog instead of string equality; strip the v prefix with removeprefix (#1933)

Kevin9ddef2e5eb75
diff --git a/semantica/cli.py b/semantica/cli.py
index dfb1e0bc..b05fec52 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -827,6 +827,42 @@ def shell(ctx: click.Context) -> None:
_warn(cli_ctx, f"Error: {exc}")
+def _plain_release(version: str) -> Optional[Tuple[int, ...]]:
+ """Parse a plain X.Y.Z release into a comparable tuple, or None.
+
+ Trailing zero components are dropped so 0.8 and 0.8.0 compare equal.
+ """
+ if not re.fullmatch(r"\d+(\.\d+)*", version):
+ return None
+ parts = [int(p) for p in version.split(".")]
+ while len(parts) > 1 and parts[-1] == 0:
+ parts.pop()
+ return tuple(parts)
+
+
+def _compare_versions(a: str, b: str) -> Optional[int]:
+ """Compare two version strings: 1 if a > b, 0 if equal, -1 if a < b.
+
+ Uses PEP 440 ordering when packaging is installed. It is not a core
+ dependency (#1513), so without it only plain X.Y.Z releases are ordered.
+ Returns None when no ordering can be established (e.g. a missing release
+ tag), so callers never guess an update from string equality.
+ """
+ try:
+ from packaging.version import InvalidVersion, Version
+ except ImportError:
+ ra, rb = _plain_release(a), _plain_release(b)
+ if ra is None or rb is None:
+ return 0 if a == b else None
+ return (ra > rb) - (ra < rb)
+
+ try:
+ va, vb = Version(a), Version(b)
+ except InvalidVersion:
+ return None
+ return (va > vb) - (va < vb)
+
+
@main.command()
@click.option("--json", "local_json", is_flag=True, default=False)
@click.pass_obj
@@ -850,20 +886,36 @@ def changelog(cli_ctx: CLIContext, local_json: bool) -> None:
tag: str = data.get("tag_name", "unknown")
body: str = data.get("body", "").strip()
html_url: str = data.get("html_url", "")
- latest = tag.lstrip("v")
+ latest = tag.removeprefix("v")
current = __version__
+ order = _compare_versions(latest, current)
+ update_available = None if order is None else order > 0
if _is_json(cli_ctx, local_json):
- _jecho({"current": current, "latest": latest, "url": html_url, "notes": body})
+ _jecho({
+ "current": current,
+ "latest": latest,
+ "update_available": update_available,
+ "url": html_url,
+ "notes": body,
+ })
return
- up_to_date = latest == current
- status = (
- f"[{_SUCCESS}]You are on the latest version ({current})[/{_SUCCESS}]"
- if up_to_date
- else f"[{_WARN_STY}]Update available: {current} → {latest}[/{_WARN_STY}]\n"
- f"[{_DIM}]pip install --upgrade semantica[/{_DIM}]"
- )
+ if order is None:
+ status = f"[{_DIM}]Could not compare {current} with release {tag}[/{_DIM}]"
+ elif order > 0:
+ status = (
+ f"[{_WARN_STY}]Update available: {current} → {latest}[/{_WARN_STY}]\n"
+ f"[{_DIM}]pip install --upgrade semantica[/{_DIM}]"
+ )
+ elif order == 0:
+ status = f"[{_SUCCESS}]You are on the latest version ({current})[/{_SUCCESS}]"
+ else:
+ # A dev or unreleased build sorts above the latest published release.
+ status = (
+ f"[{_SUCCESS}]You are ahead of the latest release "
+ f"({current} > {latest})[/{_SUCCESS}]"
+ )
console.print(
Panel(
Text.from_markup(
@@ -876,7 +928,7 @@ def changelog(cli_ctx: CLIContext, local_json: bool) -> None:
padding=(1, 2),
)
)
- if html_url and not up_to_date:
+ if html_url and update_available:
console.print(f" [{_DIM}]Full notes: {html_url}[/{_DIM}]")
_run_with_error_handling(_action)
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index 20cd09f7..3bd5df78 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -5253,3 +5253,137 @@ class TestOntologyAlignOutput:
# pd.read_json(lines=True) must succeed — this is what the F2 bug broke.
df = pd.read_json(out, lines=True)
assert "alignments" in df.columns
+
+
+class _FakeUrlopenResponse:
+ """Minimal context-manager response for a stubbed urllib.request.urlopen."""
+
+ def __init__(self, payload: bytes):
+ self._payload = payload
+
+ def __enter__(self) -> "_FakeUrlopenResponse":
+ return self
+
+ def __exit__(self, *exc: Any) -> bool:
+ return False
+
+ def read(self) -> bytes:
+ return self._payload
+
+
+def _stub_release(monkeypatch, tag_name: str) -> None:
+ """Make the changelog's GitHub release lookup return *tag_name*."""
+ import urllib.request
+
+ payload = json.dumps({"tag_name": tag_name, "body": "", "html_url": ""}).encode()
+ monkeypatch.setattr(
+ urllib.request,
+ "urlopen",
+ lambda *a, **kw: _FakeUrlopenResponse(payload),
+ )
+
+
+class TestChangelogVersionTag:
+ """changelog must strip the "v" prefix, not a run of leading characters.
+
+ Regression for #1845: ``tag.lstrip("v")`` treats "v" as a character set, so
+ a tag like ``vv1.2.3`` lost both leading v's. ``removeprefix("v")`` strips
+ exactly one, which is the documented intent.
+ """
+
+ @pytest.mark.parametrize(
+ "tag_name,expected",
+ [
+ ("v1.2.3", "1.2.3"),
+ ("vv1.2.3", "v1.2.3"),
+ ("1.2.3", "1.2.3"),
+ ],
+ )
+ def test_changelog_json_latest_strips_one_v(
+ self, runner, monkeypatch, tag_name, expected
+ ):
+ _stub_release(monkeypatch, tag_name)
+ result = runner.invoke(cli_module.main, ["changelog", "--json"])
+ _ok(result)
+ assert json.loads(result.output)["latest"] == expected
+
+
+class TestChangelogUpdateCheck:
+ """changelog must order versions, not compare them as strings.
+
+ A build ahead of the latest release (e.g. 0.8.0 against a v0.7.0 tag) used
+ to be told "Update available: 0.8.0 → 0.7.0", recommending a downgrade.
+ """
+
+ @pytest.mark.parametrize(
+ "current,tag_name,expected",
+ [
+ ("0.7.0", "v0.8.0", True),
+ ("0.8.0", "v0.8.0", False),
+ ("0.8", "v0.8.0", False),
+ ("0.8.0", "v0.7.0", False),
+ ("0.8.0.dev1", "v0.7.0", False),
+ ("0.8.0rc1", "v0.8.0", True),
+ ("0.8.0", "unknown", None),
+ ],
+ )
+ def test_changelog_json_update_available(
+ self, runner, monkeypatch, current, tag_name, expected
+ ):
+ _stub_release(monkeypatch, tag_name)
+ monkeypatch.setattr(cli_module, "__version__", current)
+ result = runner.invoke(cli_module.main, ["changelog", "--json"])
+ _ok(result)
+ assert json.loads(result.output)["update_available"] is expected
+
+ @pytest.mark.parametrize(
+ "current,tag_name,shown,hidden",
+ [
+ ("0.7.0", "v0.8.0", "Update available", "ahead of the latest"),
+ ("0.8.0", "v0.8.0", "on the latest version", "Update available"),
+ ("0.8.0", "v0.7.0", "ahead of the latest", "Update available"),
+ ("0.8.0", "unknown", "Could not compare", "Update available"),
+ ],
+ )
+ def test_changelog_status_line(
+ self, runner, monkeypatch, current, tag_name, shown, hidden
+ ):
+ _stub_release(monkeypatch, tag_name)
+ monkeypatch.setattr(cli_module, "__version__", current)
+ result = runner.invoke(cli_module.main, ["changelog"])
+ _ok(result)
+ assert shown in result.output
+ assert hidden not in result.output
+
+
+class TestChangelogWithoutPackaging:
+ """packaging is not a core dependency (#1513), so a slim install may lack it.
+
+ The fallback must still order plain X.Y.Z releases and must never report
+ an update it cannot establish.
+ """
+
+ @pytest.mark.parametrize(
+ "current,tag_name,expected",
+ [
+ ("0.7.0", "v0.8.0", True),
+ ("0.8.0", "v0.7.0", False),
+ ("0.8", "v0.8.0", False),
+ ("0.10.0", "v0.9.0", False),
+ ("0.8.0.dev1", "v0.8.0.dev1", False),
+ ("0.8.0.dev1", "v0.7.0", None),
+ ("0.8.0", "unknown", None),
+ ],
+ )
+ def test_changelog_json_update_available_without_packaging(
+ self, runner, monkeypatch, current, tag_name, expected
+ ):
+ import sys
+
+ # A None entry makes ``from packaging.version import ...`` raise ImportError.
+ monkeypatch.setitem(sys.modules, "packaging.version", None)
+ _stub_release(monkeypatch, tag_name)
+ monkeypatch.setattr(cli_module, "__version__", current)
+ result = runner.invoke(cli_module.main, ["changelog", "--json"])
+ _ok(result)
+ assert json.loads(result.output)["update_available"] is expected