This commit is contained in:
nose
2025-12-05 03:42:57 -08:00
parent 5e4df11dbf
commit 5482ee5586
20 changed files with 911 additions and 223 deletions

39
cmdnats/__init__.py Normal file
View File

@@ -0,0 +1,39 @@
from __future__ import annotations
import os
from importlib import import_module
from typing import Any, Callable, Dict, Sequence
CmdletFn = Callable[[Any, Sequence[str], Dict[str, Any]], int]
def _register_cmdlet_object(cmdlet_obj, registry: Dict[str, CmdletFn]) -> None:
run_fn = getattr(cmdlet_obj, "exec", None) if hasattr(cmdlet_obj, "exec") else None
if not callable(run_fn):
return
if hasattr(cmdlet_obj, "name") and cmdlet_obj.name:
registry[cmdlet_obj.name.replace("_", "-").lower()] = run_fn
if hasattr(cmdlet_obj, "aliases") and getattr(cmdlet_obj, "aliases"):
for alias in cmdlet_obj.aliases:
registry[alias.replace("_", "-").lower()] = run_fn
def register_native_commands(registry: Dict[str, CmdletFn]) -> None:
"""Import native command modules and register their CMDLET exec functions."""
base_dir = os.path.dirname(__file__)
for filename in os.listdir(base_dir):
if not (filename.endswith(".py") and not filename.startswith("_") and filename != "__init__.py"):
continue
mod_name = filename[:-3]
try:
module = import_module(f".{mod_name}", __name__)
cmdlet_obj = getattr(module, "CMDLET", None)
if cmdlet_obj:
_register_cmdlet_object(cmdlet_obj, registry)
except Exception as exc:
import sys
print(f"Error importing native command '{mod_name}': {exc}", file=sys.stderr)
continue