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
29 changes: 29 additions & 0 deletions src/specify_cli/extensions/catalog/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,32 @@ def load_catalog_command_config(project_root: Path, config_path: Path) -> dict:
)
raise typer.Exit(1)
return config


def displayed_catalog_names(catalogs: list, *, usable_only: bool = False) -> list[str]:
"""Return the effective display name for each catalog entry.

Mirrors ``CatalogStackBase._load_catalog_config`` so ``catalog add`` and
``catalog remove`` match legacy whitespace-padded or blank entries by the
same name ``catalog list`` displays (including ``catalog-{n}`` fallbacks).

Entries without a usable URL are skipped by the loader and never listed. By
default they keep their stripped name so ``catalog remove`` can still clean
them up; with ``usable_only=True`` they yield ``""`` so ``catalog add`` does
not treat an unlisted entry as an existing duplicate.
"""
valid_count = 0
names: list[str] = []
for entry in catalogs:
if not isinstance(entry, dict):
names.append("")
continue
url = str(entry.get("url", "")).strip()
raw_name = entry.get("name")
stripped = str(raw_name).strip() if raw_name is not None else ""
if url:
valid_count += 1
names.append(stripped or f"catalog-{valid_count}")
else:
names.append("" if usable_only else stripped)
return names
13 changes: 10 additions & 3 deletions src/specify_cli/extensions/catalog/command_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from .. import _commands
from . import catalog_app
from ._helpers import load_catalog_command_config
from ._helpers import displayed_catalog_names, load_catalog_command_config


@catalog_app.command("add")
Expand All @@ -34,6 +34,11 @@ def catalog_add(
project_root = _commands._require_specify_project()
specify_dir = project_root / ".specify"

name = name.strip()
if not name:
_commands.console.print("[red]Error:[/red] Catalog name must not be blank.")
raise typer.Exit(1)

# Validate URL
tmp_catalog = ExtensionCatalog(project_root)
try:
Expand Down Expand Up @@ -69,8 +74,10 @@ def catalog_add(
}

# Check for duplicate name
for existing in catalogs:
if isinstance(existing, dict) and existing.get("name") == name:
for existing, existing_display_name in zip(
catalogs, displayed_catalog_names(catalogs, usable_only=True)
):
if isinstance(existing, dict) and existing_display_name == name:
if all(
existing.get(field) == entry[field]
for field in (
Expand Down
18 changes: 10 additions & 8 deletions src/specify_cli/extensions/catalog/command_remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from .. import _commands
from . import catalog_app
from ._helpers import load_catalog_command_config
from ._helpers import displayed_catalog_names, load_catalog_command_config


@catalog_app.command("remove")
Expand Down Expand Up @@ -45,19 +45,21 @@ def catalog_remove(
f"expected a mapping, got {type(entry).__name__}"
)
raise typer.Exit(1)
safe_name = _escape_markup(name)
target = name.strip()
safe_name = _escape_markup(target or name)
original_count = len(catalogs)
catalogs = [
catalog
for catalog in catalogs
if catalog.get("name") != name
for catalog, display_name in zip(catalogs, displayed_catalog_names(catalogs))
if catalog.get("name") != name and (not target or display_name != target)
]
Comment thread
dlwlgnsrhy marked this conversation as resolved.
Resolved

if len(catalogs) == original_count:
_commands.console.print(f"[red]Error:[/red] Catalog '{safe_name}' not found.")
raise typer.Exit(1)

if catalogs:
has_usable = any(displayed_catalog_names(catalogs, usable_only=True))
if has_usable:
config["catalogs"] = catalogs
config_path.write_text(
_commands.yaml.safe_dump(
Expand All @@ -69,8 +71,8 @@ def catalog_remove(
encoding="utf-8",
)
else:
# The catalog loader rejects an existing config with no entries, so
# delete the file instead of writing ``catalogs: []``.
# The catalog loader rejects an existing config with no usable entries,
# so delete the file instead of writing an unusable config.
try:
config_path.unlink(missing_ok=True)
except OSError as error:
Expand All @@ -84,7 +86,7 @@ def catalog_remove(
raise typer.Exit(1)

_commands.console.print(f"[green]✓[/green] Removed catalog '{safe_name}'")
if not catalogs:
if not has_usable:
if os.environ.get("SPECKIT_CATALOG_URL"):
fallback = "the SPECKIT_CATALOG_URL environment variable still takes precedence"
else:
Expand Down
88 changes: 88 additions & 0 deletions tests/specify_cli/extensions/catalog/test_command_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,73 @@ def test_catalog_add_is_idempotent_for_identical_entry(self, tmp_path):
assert config_path.read_bytes() == original
assert runner.invoke(app, [*args, "--priority", "11"]).exit_code == 1

def test_catalog_add_rejects_blank_name_without_creating_config(self, tmp_path):
(tmp_path / ".specify").mkdir()
with patch.object(Path, "cwd", return_value=tmp_path):
result = CliRunner().invoke(
app, ["extension", "catalog", "add", "https://example.com/catalog.json", "--name", " "],
)

assert result.exit_code == 1
assert "Catalog name must not be blank" in result.output
assert not (tmp_path / ".specify" / "extension-catalogs.yml").exists()

def test_catalog_add_compares_names_as_the_catalog_loader_displays_them(self, tmp_path):
(tmp_path / ".specify").mkdir()
config_path = tmp_path / ".specify" / "extension-catalogs.yml"
runner = CliRunner()
command = ["extension", "catalog", "add"]
with patch.object(Path, "cwd", return_value=tmp_path):
result = runner.invoke(app, [*command, "https://example.com/a.json", "--name", " team "])
assert result.exit_code == 0, result.output
config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert config["catalogs"][0]["name"] == "team"

# Older versions could write the padded spelling to the config.
config["catalogs"][0]["name"] = " team "
config_path.write_text(yaml.safe_dump(config), encoding="utf-8")
original = config_path.read_bytes()
identical = runner.invoke(app, [*command, "https://example.com/a.json", "--name", "team"])
duplicate = runner.invoke(app, [*command, "https://example.com/b.json", "--name", "team"])

assert identical.exit_code == 0, identical.output
assert duplicate.exit_code == 1, duplicate.output
assert config_path.read_bytes() == original

def test_catalog_add_detects_legacy_blank_name_by_display_fallback(self, tmp_path):
(tmp_path / ".specify").mkdir()
config_path = tmp_path / ".specify" / "extension-catalogs.yml"
config_path.write_text(
yaml.safe_dump(
{
"catalogs": [
{
"name": " ",
"url": "https://example.com/a.json",
"priority": 10,
"install_allowed": False,
"description": "",
}
]
}
),
encoding="utf-8",
)
original = config_path.read_bytes()
runner = CliRunner()
command = ["extension", "catalog", "add"]
with patch.object(Path, "cwd", return_value=tmp_path):
identical = runner.invoke(
app, [*command, "https://example.com/a.json", "--name", "catalog-1"]
)
conflict = runner.invoke(
app, [*command, "https://example.com/b.json", "--name", "catalog-1"]
)

assert identical.exit_code == 0, identical.output
assert conflict.exit_code == 1, conflict.output
assert config_path.read_bytes() == original

def test_catalog_add_escapes_url_markup(self, tmp_path):
"""Catalog add should render user-supplied URLs literally."""
from specify_cli import app
Expand Down Expand Up @@ -219,3 +286,24 @@ def test_extension_catalog_add_escapes_catalog_name_markup(self, tmp_path):
assert result.exit_code == 0, result.output
output = _normalize_cli_output(result.output)
assert f"Added catalog '{catalog_name}'" in output

def test_catalog_add_ignores_legacy_entry_without_url(self, tmp_path):
project = self._make_project(tmp_path)
config_path = project / ".specify" / "extension-catalogs.yml"
config_path.write_text(
yaml.safe_dump({"catalogs": [{"name": " team ", "url": " "}]}),
encoding="utf-8",
)

result = self._invoke([
"extension", "catalog", "add",
"https://example.com/extension-catalog.yml",
"--name", "team",
], project)

assert result.exit_code == 0, result.output
saved = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert [c["url"] for c in saved["catalogs"]] == [
" ",
"https://example.com/extension-catalog.yml",
]
65 changes: 65 additions & 0 deletions tests/specify_cli/extensions/catalog/test_command_remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,3 +349,68 @@ def test_extension_catalog_remove_keeps_config_with_remaining_entries(
assert yaml.safe_load(cfg_path.read_text(encoding="utf-8")) == {
"catalogs": [keep]
}


def test_remove_legacy_padded_and_blank_names_by_displayed_name(self, tmp_path):
"""Legacy padded or blank entries can be removed using the name shown by catalog list."""
project = self._make_project(tmp_path)
config_path = project / ".specify" / "extension-catalogs.yml"
config_path.write_text(
yaml.safe_dump(
{
"catalogs": [
{"name": " ", "url": "https://example.com/first.json"},
{"name": " team ", "url": "https://example.com/team.json"},
{"name": "keep", "url": "https://example.com/keep.json"},
]
}
),
encoding="utf-8",
)

remove_blank = self._invoke(["extension", "catalog", "remove", "catalog-1"], project)
assert remove_blank.exit_code == 0, remove_blank.output
remaining = yaml.safe_load(config_path.read_text(encoding="utf-8"))["catalogs"]
assert [entry["url"] for entry in remaining] == [
"https://example.com/team.json",
"https://example.com/keep.json",
]

remove_padded = self._invoke(["extension", "catalog", "remove", "team"], project)
assert remove_padded.exit_code == 0, remove_padded.output
remaining = yaml.safe_load(config_path.read_text(encoding="utf-8"))["catalogs"]
assert [entry["url"] for entry in remaining] == ["https://example.com/keep.json"]

def test_remove_last_usable_entry_prunes_config_with_blank_url_legacy_entry(
self, tmp_path, monkeypatch
):
"""Removing the last usable catalog prunes the file even if a blank-URL entry remains."""
project = self._make_project(tmp_path)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
monkeypatch.delenv("SPECKIT_CATALOG_URL", raising=False)

config_path = project / ".specify" / "extension-catalogs.yml"
config_path.write_text(
yaml.safe_dump(
{
"catalogs": [
{"name": "legacy", "url": " "},
{"name": "team", "url": "https://example.com/team.json"},
]
}
),
encoding="utf-8",
)

remove = self._invoke(["extension", "catalog", "remove", "team"], project)
assert remove.exit_code == 0, remove.output
assert not config_path.exists()
assert (
"Project catalog override removed; user configuration or built-in "
"defaults will be used." in _normalize_cli_output(remove.output)
)

listing = self._invoke(["extension", "catalog", "list"], project)
assert listing.exit_code == 0, listing.output
assert "Using built-in default catalog stack" in _normalize_cli_output(listing.output)