prompt_manager.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. from __future__ import annotations
  2. import logging
  3. from typing import Any, Callable
  4. from rich.console import Console
  5. from rich.prompt import Prompt
  6. from ..display import DisplayManager
  7. from ..input import InputManager
  8. from ..template import Variable, VariableCollection
  9. logger = logging.getLogger(__name__)
  10. class PromptHandler:
  11. """Simple interactive prompt handler for collecting template variables."""
  12. def __init__(self) -> None:
  13. self.console = Console()
  14. self.display = DisplayManager()
  15. def _handle_section_toggle(self, section, collected: dict[str, Any]) -> bool:
  16. """Handle section toggle variable and return whether section should be enabled."""
  17. if not section.toggle:
  18. return True
  19. toggle_var = section.variables.get(section.toggle)
  20. if not toggle_var:
  21. return True
  22. current_value = toggle_var.convert(toggle_var.value)
  23. new_value = self._prompt_variable(toggle_var, _required=False)
  24. if new_value != current_value:
  25. collected[toggle_var.name] = new_value
  26. toggle_var.value = new_value
  27. return section.is_enabled()
  28. def _should_skip_variable(
  29. self,
  30. var_name: str,
  31. section,
  32. variables: VariableCollection,
  33. section_enabled: bool,
  34. ) -> bool:
  35. """Determine if a variable should be skipped during collection."""
  36. if section.toggle and var_name == section.toggle:
  37. return True
  38. if not variables.is_variable_satisfied(var_name):
  39. logger.debug(f"Skipping variable '{var_name}' - needs not satisfied")
  40. return True
  41. if not section_enabled:
  42. logger.debug(f"Skipping variable '{var_name}' from disabled section '{section.key}'")
  43. return True
  44. return False
  45. def _collect_variable_value(self, variable: Variable, collected: dict[str, Any]) -> None:
  46. """Collect a single variable value and update if changed."""
  47. current_value = variable.convert(variable.value)
  48. new_value = self._prompt_variable(variable, _required=False)
  49. if variable.autogenerated and new_value is None:
  50. collected[variable.name] = None
  51. variable.value = None
  52. elif new_value != current_value:
  53. collected[variable.name] = new_value
  54. variable.value = new_value
  55. def collect_variables(self, variables: VariableCollection) -> dict[str, Any]:
  56. """Collect values for variables by iterating through sections.
  57. Args:
  58. variables: VariableCollection with organized sections and variables
  59. Returns:
  60. Dict of variable names to collected values
  61. """
  62. input_mgr = InputManager()
  63. if not input_mgr.confirm("Customize any settings?", default=False):
  64. logger.info("User opted to keep all default values")
  65. return {}
  66. collected: dict[str, Any] = {}
  67. for _section_key, section in variables.get_sections().items():
  68. if not section.variables:
  69. continue
  70. self.display.section(section.title, section.description)
  71. section_enabled = self._handle_section_toggle(section, collected)
  72. for var_name, variable in section.variables.items():
  73. if self._should_skip_variable(var_name, section, variables, section_enabled):
  74. continue
  75. self._collect_variable_value(variable, collected)
  76. logger.info(f"Variable collection completed. Collected {len(collected)} values")
  77. return collected
  78. def _prompt_variable(self, variable: Variable, _required: bool = False) -> Any:
  79. """Prompt for a single variable value based on its type.
  80. Args:
  81. variable: The variable to prompt for
  82. _required: Whether the containing section is required
  83. (unused, kept for API compatibility)
  84. Returns:
  85. The validated value entered by the user
  86. """
  87. logger.debug(f"Prompting for variable '{variable.name}' (type: {variable.type})")
  88. # Use variable's native methods for prompt text and default value
  89. prompt_text = variable.get_prompt_text()
  90. default_value = variable.get_normalized_default()
  91. has_explicit_default = "default" in variable._explicit_fields or "value" in variable._explicit_fields
  92. if not has_explicit_default and not variable.autogenerated and not variable.is_required():
  93. default_value = None
  94. # Add lock icon before default value for secret or autogenerated variables
  95. if variable.is_secret() or variable.autogenerated:
  96. # Format: "Prompt text 🔒 (default)"
  97. # The lock icon goes between the text and the default value in parentheses
  98. prompt_text = f"{prompt_text} {self.display.get_lock_icon()}"
  99. if variable.config.placeholder:
  100. prompt_text = f"{prompt_text} [dim]({variable.config.placeholder})[/dim]"
  101. # Check if this specific variable is required (has no default and not autogenerated)
  102. var_is_required = variable.is_required()
  103. # If variable is required, mark it in the prompt
  104. if var_is_required:
  105. prompt_text = f"{prompt_text} [bold red]*required[/bold red]"
  106. allow_empty = not var_is_required and default_value is None
  107. handler = self._get_prompt_handler(variable, allow_empty=allow_empty)
  108. # Add validation hint (includes both extra text and enum options)
  109. hint = variable.get_validation_hint()
  110. if hint:
  111. prompt_text = f"{prompt_text} [dim]({hint})[/dim]"
  112. while True:
  113. try:
  114. raw = handler(prompt_text, default_value)
  115. # Use Variable's centralized validation method that handles:
  116. # - Type conversion
  117. # - Autogenerated variable detection
  118. # - Required field validation
  119. return variable.validate_and_convert(raw, check_required=True)
  120. # Return the converted value (caller will update variable.value)
  121. except ValueError as exc:
  122. # Conversion/validation failed — show a consistent error message and retry
  123. self._show_validation_error(str(exc))
  124. except Exception as e:
  125. # Unexpected error — log and retry using the stored (unconverted) value
  126. logger.error(f"Error prompting for variable '{variable.name}': {e!s}")
  127. default_value = variable.value
  128. handler = self._get_prompt_handler(variable, allow_empty=allow_empty)
  129. def _get_prompt_handler(self, variable: Variable, allow_empty: bool = False) -> Callable:
  130. """Return the prompt function for a variable type."""
  131. handlers = {
  132. "bool": lambda text, default: self._prompt_bool(text, default, allow_empty=allow_empty),
  133. "int": lambda text, default: self._prompt_int(
  134. text,
  135. default,
  136. allow_empty=allow_empty,
  137. min_value=variable.config.min if variable.config else None,
  138. max_value=variable.config.max if variable.config else None,
  139. ),
  140. # For enum prompts we pass the variable.extra through so options and extra
  141. # can be combined into a single inline hint.
  142. "enum": lambda text, default: self._prompt_enum(
  143. text,
  144. variable.options or [],
  145. default,
  146. allow_empty=allow_empty,
  147. _extra=getattr(variable, "extra", None),
  148. ),
  149. }
  150. return handlers.get(
  151. variable.type,
  152. lambda text, default: self._prompt_string(text, default, is_secret=variable.is_secret()),
  153. )
  154. def _show_validation_error(self, message: str) -> None:
  155. """Display validation feedback consistently."""
  156. self.display.error(message)
  157. def _prompt_string(self, prompt_text: str, default: Any = None, is_secret: bool = False) -> str | None:
  158. if is_secret:
  159. value = Prompt.ask(
  160. prompt_text,
  161. default="",
  162. show_default=False,
  163. password=True,
  164. )
  165. stripped = value.strip() if value else None
  166. if stripped:
  167. return stripped
  168. return default
  169. value = Prompt.ask(
  170. prompt_text,
  171. default=str(default) if default is not None else "",
  172. show_default=True,
  173. password=False,
  174. )
  175. stripped = value.strip() if value else None
  176. return stripped if stripped else None
  177. def _prompt_bool(self, prompt_text: str, default: Any = None, allow_empty: bool = False) -> bool | str | None:
  178. input_mgr = InputManager()
  179. if allow_empty and default is None:
  180. value = Prompt.ask(prompt_text, default="", show_default=False)
  181. stripped = value.strip() if value else ""
  182. return stripped if stripped else None
  183. if default is None:
  184. return input_mgr.confirm(prompt_text, default=None)
  185. converted = default if isinstance(default, bool) else str(default).lower() in ("true", "1", "yes", "on")
  186. return input_mgr.confirm(prompt_text, default=converted)
  187. def _prompt_int(
  188. self,
  189. prompt_text: str,
  190. default: Any = None,
  191. allow_empty: bool = False,
  192. min_value: int | None = None,
  193. max_value: int | None = None,
  194. ) -> int | str | None:
  195. converted = None
  196. if default is not None:
  197. try:
  198. converted = int(default)
  199. except (ValueError, TypeError):
  200. logger.warning(f"Invalid default integer value: {default}")
  201. if allow_empty and converted is None:
  202. value = Prompt.ask(prompt_text, default="", show_default=False)
  203. stripped = value.strip() if value else ""
  204. return stripped if stripped else None
  205. input_mgr = InputManager()
  206. return input_mgr.integer(
  207. prompt_text,
  208. default=converted,
  209. min_value=min_value,
  210. max_value=max_value,
  211. )
  212. def _prompt_enum(
  213. self,
  214. prompt_text: str,
  215. options: list[str],
  216. default: Any = None,
  217. allow_empty: bool = False,
  218. _extra: str | None = None,
  219. ) -> str | None:
  220. """Prompt for enum selection with validation.
  221. Note: prompt_text should already include hint from variable.get_validation_hint()
  222. but we keep this for backward compatibility and fallback.
  223. """
  224. if not options:
  225. return self._prompt_string(prompt_text, default)
  226. # Validate default is in options
  227. if default and str(default) not in options:
  228. default = options[0]
  229. if allow_empty and default is None:
  230. value = Prompt.ask(prompt_text, default="", show_default=False)
  231. stripped = value.strip() if value else ""
  232. return stripped if stripped else None
  233. while True:
  234. value = Prompt.ask(
  235. prompt_text,
  236. default=str(default) if default else options[0],
  237. show_default=True,
  238. )
  239. if value in options:
  240. return value
  241. self.console.print(f"[red]Invalid choice. Select from: {', '.join(options)}[/red]")