prompt.py 8.9 KB

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