prompt_manager.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 IntPrompt, 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. # Add lock icon before default value for sensitive or autogenerated variables
  92. if variable.sensitive or variable.autogenerated:
  93. # Format: "Prompt text 🔒 (default)"
  94. # The lock icon goes between the text and the default value in parentheses
  95. prompt_text = f"{prompt_text} {self.display.get_lock_icon()}"
  96. # Check if this specific variable is required (has no default and not autogenerated)
  97. var_is_required = variable.is_required()
  98. # If variable is required, mark it in the prompt
  99. if var_is_required:
  100. prompt_text = f"{prompt_text} [bold red]*required[/bold red]"
  101. handler = self._get_prompt_handler(variable)
  102. # Add validation hint (includes both extra text and enum options)
  103. hint = variable.get_validation_hint()
  104. if hint:
  105. # Show options/extra inline inside parentheses, before the default
  106. prompt_text = f"{prompt_text} [dim]({hint})[/dim]"
  107. while True:
  108. try:
  109. raw = handler(prompt_text, default_value)
  110. # Use Variable's centralized validation method that handles:
  111. # - Type conversion
  112. # - Autogenerated variable detection
  113. # - Required field validation
  114. return variable.validate_and_convert(raw, check_required=True)
  115. # Return the converted value (caller will update variable.value)
  116. except ValueError as exc:
  117. # Conversion/validation failed — show a consistent error message and retry
  118. self._show_validation_error(str(exc))
  119. except Exception as e:
  120. # Unexpected error — log and retry using the stored (unconverted) value
  121. logger.error(f"Error prompting for variable '{variable.name}': {e!s}")
  122. default_value = variable.value
  123. handler = self._get_prompt_handler(variable)
  124. def _get_prompt_handler(self, variable: Variable) -> Callable:
  125. """Return the prompt function for a variable type."""
  126. handlers = {
  127. "bool": self._prompt_bool,
  128. "int": self._prompt_int,
  129. # For enum prompts we pass the variable.extra through so options and extra
  130. # can be combined into a single inline hint.
  131. "enum": lambda text, default: self._prompt_enum(
  132. text,
  133. variable.options or [],
  134. default,
  135. _extra=getattr(variable, "extra", None),
  136. ),
  137. }
  138. return handlers.get(
  139. variable.type,
  140. lambda text, default: self._prompt_string(text, default, is_sensitive=variable.sensitive),
  141. )
  142. def _show_validation_error(self, message: str) -> None:
  143. """Display validation feedback consistently."""
  144. self.display.error(message)
  145. def _prompt_string(self, prompt_text: str, default: Any = None, is_sensitive: bool = False) -> str | None:
  146. value = Prompt.ask(
  147. prompt_text,
  148. default=str(default) if default is not None else "",
  149. show_default=True,
  150. password=is_sensitive,
  151. )
  152. stripped = value.strip() if value else None
  153. return stripped if stripped else None
  154. def _prompt_bool(self, prompt_text: str, default: Any = None) -> bool | None:
  155. input_mgr = InputManager()
  156. if default is None:
  157. return input_mgr.confirm(prompt_text, default=None)
  158. converted = default if isinstance(default, bool) else str(default).lower() in ("true", "1", "yes", "on")
  159. return input_mgr.confirm(prompt_text, default=converted)
  160. def _prompt_int(self, prompt_text: str, default: Any = None) -> int | None:
  161. converted = None
  162. if default is not None:
  163. try:
  164. converted = int(default)
  165. except (ValueError, TypeError):
  166. logger.warning(f"Invalid default integer value: {default}")
  167. return IntPrompt.ask(prompt_text, default=converted)
  168. def _prompt_enum(
  169. self,
  170. prompt_text: str,
  171. options: list[str],
  172. default: Any = None,
  173. _extra: str | None = None,
  174. ) -> str:
  175. """Prompt for enum selection with validation.
  176. Note: prompt_text should already include hint from variable.get_validation_hint()
  177. but we keep this for backward compatibility and fallback.
  178. """
  179. if not options:
  180. return self._prompt_string(prompt_text, default)
  181. # Validate default is in options
  182. if default and str(default) not in options:
  183. default = options[0]
  184. while True:
  185. value = Prompt.ask(
  186. prompt_text,
  187. default=str(default) if default else options[0],
  188. show_default=True,
  189. )
  190. if value in options:
  191. return value
  192. self.console.print(f"[red]Invalid choice. Select from: {', '.join(options)}[/red]")