prompt.py 11 KB

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