Skip to content

Commit fe484b2

Browse files
mbachorikclaude
andcommitted
feat(presets): add enable/disable toggle and update semantics
Add preset enable/disable CLI commands and update semantics to match the extension system capabilities. Changes: - Add `preset enable` and `preset disable` CLI commands - Add `restore()` method to PresetRegistry for rollback scenarios - Update `get()` and `list()` to return deep copies (prevents mutation) - Update `list_by_priority()` to filter disabled presets by default - Add input validation to `restore()` for defensive programming - Add 16 new tests covering all functionality and edge cases Closes github#1851 Closes github#1852 Co-Authored-By: Claude Opus 4.5 <[email protected]>
1 parent 6644f69 commit fe484b2

3 files changed

Lines changed: 416 additions & 5 deletions

File tree

‎src/specify_cli/__init__.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2405,6 +2405,87 @@ def preset_set_priority(
24052405
console.print("\n[dim]Lower priority = higher precedence in template resolution[/dim]")
24062406

24072407

2408+
@preset_app.command("enable")
2409+
def preset_enable(
2410+
pack_id: str = typer.Argument(help="Preset ID to enable"),
2411+
):
2412+
"""Enable a disabled preset."""
2413+
from .presets import PresetManager
2414+
2415+
project_root = Path.cwd()
2416+
2417+
# Check if we're in a spec-kit project
2418+
specify_dir = project_root / ".specify"
2419+
if not specify_dir.exists():
2420+
console.print("[red]Error:[/red] Not a spec-kit project (no .specify/ directory)")
2421+
console.print("Run this command from a spec-kit project root")
2422+
raise typer.Exit(1)
2423+
2424+
manager = PresetManager(project_root)
2425+
2426+
# Check if preset is installed
2427+
if not manager.registry.is_installed(pack_id):
2428+
console.print(f"[red]Error:[/red] Preset '{pack_id}' is not installed")
2429+
raise typer.Exit(1)
2430+
2431+
# Get current metadata
2432+
metadata = manager.registry.get(pack_id)
2433+
if metadata is None or not isinstance(metadata, dict):
2434+
console.print(f"[red]Error:[/red] Preset '{pack_id}' not found in registry (corrupted state)")
2435+
raise typer.Exit(1)
2436+
2437+
if metadata.get("enabled", True):
2438+
console.print(f"[yellow]Preset '{pack_id}' is already enabled[/yellow]")
2439+
raise typer.Exit(0)
2440+
2441+
# Enable the preset
2442+
manager.registry.update(pack_id, {"enabled": True})
2443+
2444+
console.print(f"[green]✓[/green] Preset '{pack_id}' enabled")
2445+
console.print("\nTemplates from this preset will now be included in resolution.")
2446+
2447+
2448+
@preset_app.command("disable")
2449+
def preset_disable(
2450+
pack_id: str = typer.Argument(help="Preset ID to disable"),
2451+
):
2452+
"""Disable a preset without removing it."""
2453+
from .presets import PresetManager
2454+
2455+
project_root = Path.cwd()
2456+
2457+
# Check if we're in a spec-kit project
2458+
specify_dir = project_root / ".specify"
2459+
if not specify_dir.exists():
2460+
console.print("[red]Error:[/red] Not a spec-kit project (no .specify/ directory)")
2461+
console.print("Run this command from a spec-kit project root")
2462+
raise typer.Exit(1)
2463+
2464+
manager = PresetManager(project_root)
2465+
2466+
# Check if preset is installed
2467+
if not manager.registry.is_installed(pack_id):
2468+
console.print(f"[red]Error:[/red] Preset '{pack_id}' is not installed")
2469+
raise typer.Exit(1)
2470+
2471+
# Get current metadata
2472+
metadata = manager.registry.get(pack_id)
2473+
if metadata is None or not isinstance(metadata, dict):
2474+
console.print(f"[red]Error:[/red] Preset '{pack_id}' not found in registry (corrupted state)")
2475+
raise typer.Exit(1)
2476+
2477+
if not metadata.get("enabled", True):
2478+
console.print(f"[yellow]Preset '{pack_id}' is already disabled[/yellow]")
2479+
raise typer.Exit(0)
2480+
2481+
# Disable the preset
2482+
manager.registry.update(pack_id, {"enabled": False})
2483+
2484+
console.print(f"[green]✓[/green] Preset '{pack_id}' disabled")
2485+
console.print("\nTemplates from this preset will be skipped during resolution.")
2486+
console.print(f"To re-enable: specify preset enable {pack_id}")
2487+
2488+
24082489
# ===== Preset Catalog Commands =====
24092490

24102491

‎src/specify_cli/presets.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -306,32 +306,61 @@ def update(self, pack_id: str, updates: dict):
306306
self.data["presets"][pack_id] = merged
307307
self._save()
308308

309+
def restore(self, pack_id: str, metadata: dict):
310+
"""Restore preset metadata to registry without modifying timestamps.
311+
312+
Use this method for rollback scenarios where you have a complete backup
313+
of the registry entry (including installed_at) and want to restore it
314+
exactly as it was.
315+
316+
Args:
317+
pack_id: Preset ID
318+
metadata: Complete preset metadata including installed_at
319+
320+
Raises:
321+
ValueError: If metadata is None or not a dict
322+
"""
323+
if metadata is None or not isinstance(metadata, dict):
324+
raise ValueError(f"Cannot restore '{pack_id}': metadata must be a non-empty dict")
325+
self.data["presets"][pack_id] = dict(metadata)
326+
self._save()
327+
309328
def get(self, pack_id: str) -> Optional[dict]:
310329
"""Get preset metadata from registry.
311330
331+
Returns a deep copy to prevent callers from accidentally mutating
332+
nested internal registry state without going through the write path.
333+
312334
Args:
313335
pack_id: Preset ID
314336
315337
Returns:
316-
Pack metadata or None if not found
338+
Deep copy of preset metadata, or None if not found
317339
"""
318-
return self.data["presets"].get(pack_id)
340+
entry = self.data["presets"].get(pack_id)
341+
return copy.deepcopy(entry) if entry is not None else None
319342

320343
def list(self) -> Dict[str, dict]:
321344
"""Get all installed presets.
322345
346+
Returns a deep copy of the presets mapping to prevent callers
347+
from accidentally mutating nested internal registry state.
348+
323349
Returns:
324-
Dictionary of pack_id -> metadata
350+
Dictionary of pack_id -> metadata (deep copies)
325351
"""
326-
return self.data["presets"]
352+
return copy.deepcopy(self.data["presets"])
327353

328-
def list_by_priority(self) -> List[tuple]:
354+
def list_by_priority(self, include_disabled: bool = False) -> List[tuple]:
329355
"""Get all installed presets sorted by priority.
330356
331357
Lower priority number = higher precedence (checked first).
332358
Presets with equal priority are sorted alphabetically by ID
333359
for deterministic ordering.
334360
361+
Args:
362+
include_disabled: If True, include disabled presets. Default False.
363+
335364
Returns:
336365
List of (pack_id, metadata_copy) tuples sorted by priority.
337366
Metadata is deep-copied to prevent accidental mutation.
@@ -343,6 +372,9 @@ def list_by_priority(self) -> List[tuple]:
343372
for pack_id, meta in packs.items():
344373
if not isinstance(meta, dict):
345374
continue
375+
# Skip disabled presets unless explicitly requested
376+
if not include_disabled and not meta.get("enabled", True):
377+
continue
346378
metadata_copy = copy.deepcopy(meta)
347379
metadata_copy["priority"] = normalize_priority(metadata_copy.get("priority", 10))
348380
sortable_packs.append((pack_id, metadata_copy))

0 commit comments

Comments
 (0)