prompt.py 10 KB

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