from __future__ import annotations from typing import Any, Callable, Dict, Iterable, Sequence from importlib import import_module as _import_module # A cmdlet is a callable taking (result, args, config) -> int Cmdlet = Callable[[Any, Sequence[str], Dict[str, Any]], int] # Registry of command-name -> cmdlet function REGISTRY: Dict[str, Cmdlet] = {} def _normalize_cmd_name(name: str) -> str: return str(name or "").replace('_', '-').lower().strip() def register_callable(names: Iterable[str], fn: Cmdlet) -> Cmdlet: """Register a callable under one or more command names. This is the single registration mechanism used by both: - legacy function cmdlet (decorator form) - class-based cmdlet (Cmdlet.register()) """ for name in names: key = _normalize_cmd_name(name) if key: REGISTRY[key] = fn return fn def register(names: Iterable[str]): """Decorator to register a function under one or more command names. Usage: @register(["add-tags"]) def _run(result, args, config) -> int: ... """ def _wrap(fn: Cmdlet) -> Cmdlet: return register_callable(names, fn) return _wrap def get(cmd_name: str) -> Cmdlet | None: return REGISTRY.get(_normalize_cmd_name(cmd_name)) # Dynamically import all cmdlet modules in this directory (ignore files starting with _ and __init__.py) # cmdlet self-register when instantiated via their __init__ method import os cmdlet_dir = os.path.dirname(__file__) for filename in os.listdir(cmdlet_dir): if not ( filename.endswith(".py") and not filename.startswith("_") and filename != "__init__.py" ): continue mod_name = filename[:-3] # Enforce Powershell-style two-word cmdlet naming (e.g., add_file, get_file) # Skip native/utility scripts that are not cmdlet (e.g., adjective, worker, matrix, pipe) if "_" not in mod_name: continue try: _import_module(f".{mod_name}", __name__) except Exception as e: import sys print(f"Error importing cmdlet '{mod_name}': {e}", file=sys.stderr) continue # Import and register native commands that are not considered cmdlet try: from cmdnat import register_native_commands as _register_native_commands _register_native_commands(REGISTRY) except Exception: # Native commands are optional; ignore if unavailable pass # Import root-level modules that also register cmdlet for _root_mod in ("select_cmdlet",): try: _import_module(_root_mod) except Exception: # Allow missing optional modules continue # Also import helper modules that register cmdlet try: import API.alldebrid as _alldebrid except Exception: pass