prompt_manager.py 9.5 KB

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