prompt.py 11 KB

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