prompt.py 11 KB

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