config_section_guard.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """Guard ``hermes config set`` against a single-segment key overwriting a whole config section.
  2. Split out of :mod:`hermes_cli.config` (code-health size ratchet); ``set_config_value`` late-imports it.
  3. """
  4. from __future__ import annotations
  5. import sys
  6. from typing import Any, Dict
  7. def _guard_section_overwrite(key: str, value: Any, user_config: dict[str, Any], force: bool) -> str:
  8. """Refuse (or with ``force`` allow) a single-segment key overwriting a mapping with a scalar.
  9. Bare ``model`` is a documented shorthand — redirected to ``model.default`` so siblings survive;
  10. a list (or a mapping over an existing section) under it is refused without ``force``.
  11. Returns the (possibly redirected) key."""
  12. from hermes_cli.config import _exit_invalid
  13. existing = user_config.get(key)
  14. kind = "mapping" if isinstance(value, dict) else "list"
  15. # Containers under the model-id shorthand have no reader slot (#131435).
  16. if key == "model" and not force and (
  17. isinstance(value, list) or (isinstance(value, dict) and isinstance(existing, dict))):
  18. _exit_invalid(
  19. f"✗ Cannot set 'model' to a {kind} — "
  20. "the bare 'model' shorthand takes a model id, and a container value has no "
  21. "slot there.\n"
  22. " Set the section's keys individually instead:\n"
  23. " hermes config set model.provider <provider>\n"
  24. " hermes config set model.default <model-id>\n"
  25. " Or replace the whole section deliberately:\n"
  26. " hermes config set --force model '{provider: <provider>, default: <model-id>}'")
  27. if "." in key or not isinstance(existing, dict):
  28. return key
  29. if key == "model":
  30. if force:
  31. what = f"the given {kind}" if isinstance(value, (dict, list)) else "a scalar"
  32. print(
  33. f"⚠ Replacing entire 'model' section with {what} "
  34. f"(discarding {len(existing)} existing sub-key(s))")
  35. return key
  36. print(
  37. f"✓ Redirecting bare 'model' to 'model.default' "
  38. f"(preserving {len(existing)} existing model sub-key(s))")
  39. return "model.default"
  40. if force:
  41. return key
  42. sub = [k for k in existing if isinstance(k, str)]
  43. err = [
  44. f"✗ Cannot set '{key}' to a scalar — '{key}' is a "
  45. f"configuration section with {len(sub)} sub-key(s)."]
  46. if sub:
  47. err.append(f" Sub-keys: {', '.join(sub[:8])}")
  48. if len(sub) > 8:
  49. err.append(f" ... and {len(sub) - 8} more")
  50. err += [
  51. " Use a dotted path to set a specific leaf key:",
  52. f" hermes config set {key}.<sub-key> <value>",
  53. " Or use --force to replace the entire section:",
  54. f" hermes config set --force {key} {value!r}"]
  55. print("\n".join(err), file=sys.stderr)
  56. sys.exit(1)