prompt_manager.py 9.3 KB

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