prompt.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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, IconManager
  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.console.print(
  45. f"\n[dim]{IconManager.get_status_icon('skipped')} {section.title} (skipped - requires {dep_names} to be enabled)[/dim]"
  46. )
  47. logger.debug(f"Skipping section '{section_key}' - dependencies not satisfied: {dep_names}")
  48. continue
  49. # Always show section header first
  50. self.display.display_section_header(section.title, section.description)
  51. # Handle section toggle - skip for required sections
  52. if section.required:
  53. # Required sections are always processed, no toggle prompt needed
  54. logger.debug(f"Processing required section '{section.key}' without toggle prompt")
  55. elif section.toggle:
  56. toggle_var = section.variables.get(section.toggle)
  57. if toggle_var:
  58. # Use description for prompt if available, otherwise use title
  59. prompt_text = section.description if section.description else f"Enable {section.title}?"
  60. current_value = toggle_var.convert(toggle_var.value)
  61. new_value = self._prompt_bool(prompt_text, current_value)
  62. if new_value != current_value:
  63. collected[toggle_var.name] = new_value
  64. toggle_var.value = new_value
  65. # Use section's native is_enabled() method
  66. if not section.is_enabled():
  67. continue
  68. # Collect variables in this section
  69. for var_name, variable in section.variables.items():
  70. # Skip toggle variable (already handled)
  71. if section.toggle and var_name == section.toggle:
  72. continue
  73. current_value = variable.convert(variable.value)
  74. # Pass section.required so _prompt_variable can enforce required inputs
  75. new_value = self._prompt_variable(variable, required=section.required)
  76. # For autogenerated variables, always update even if None (signals autogeneration)
  77. if variable.autogenerated and new_value is None:
  78. collected[var_name] = None
  79. variable.value = None
  80. elif new_value != current_value:
  81. collected[var_name] = new_value
  82. variable.value = new_value
  83. logger.info(f"Variable collection completed. Collected {len(collected)} values")
  84. return collected
  85. def _prompt_variable(self, variable: Variable, required: bool = False) -> Any:
  86. """Prompt for a single variable value based on its type.
  87. Args:
  88. variable: The variable to prompt for
  89. required: Whether the containing section is required (for context/display)
  90. Returns:
  91. The validated value entered by the user
  92. """
  93. logger.debug(f"Prompting for variable '{variable.name}' (type: {variable.type})")
  94. # Use variable's native methods for prompt text and default value
  95. prompt_text = variable.get_prompt_text()
  96. default_value = variable.get_normalized_default()
  97. # Add lock icon before default value for sensitive or autogenerated variables
  98. if variable.sensitive or variable.autogenerated:
  99. # Format: "Prompt text 🔒 (default)"
  100. # The lock icon goes between the text and the default value in parentheses
  101. prompt_text = f"{prompt_text} {IconManager.lock()}"
  102. # Check if this specific variable is required (has no default and not autogenerated)
  103. var_is_required = variable.is_required()
  104. # If variable is required, mark it in the prompt
  105. if var_is_required:
  106. prompt_text = f"{prompt_text} [bold red]*required[/bold red]"
  107. handler = self._get_prompt_handler(variable)
  108. # Add validation hint (includes both extra text and enum options)
  109. hint = variable.get_validation_hint()
  110. if hint:
  111. # Show options/extra inline inside parentheses, before the default
  112. prompt_text = f"{prompt_text} [dim]({hint})[/dim]"
  113. while True:
  114. try:
  115. raw = handler(prompt_text, default_value)
  116. # Use Variable's centralized validation method that handles:
  117. # - Type conversion
  118. # - Autogenerated variable detection
  119. # - Required field validation
  120. converted = variable.validate_and_convert(raw, check_required=True)
  121. # Return the converted value (caller will update variable.value)
  122. return converted
  123. except ValueError as exc:
  124. # Conversion/validation failed — show a consistent error message and retry
  125. self._show_validation_error(str(exc))
  126. except Exception as e:
  127. # Unexpected error — log and retry using the stored (unconverted) value
  128. logger.error(f"Error prompting for variable '{variable.name}': {str(e)}")
  129. default_value = variable.value
  130. handler = self._get_prompt_handler(variable)
  131. def _get_prompt_handler(self, variable: Variable) -> Callable:
  132. """Return the prompt function for a variable type."""
  133. handlers = {
  134. "bool": self._prompt_bool,
  135. "int": self._prompt_int,
  136. # For enum prompts we pass the variable.extra through so options and extra
  137. # can be combined into a single inline hint.
  138. "enum": lambda text, default: self._prompt_enum(text, variable.options or [], default, extra=getattr(variable, 'extra', None)),
  139. }
  140. return handlers.get(variable.type, lambda text, default: self._prompt_string(text, default, is_sensitive=variable.sensitive))
  141. def _show_validation_error(self, message: str) -> None:
  142. """Display validation feedback consistently."""
  143. self.display.display_validation_error(message)
  144. def _prompt_string(self, prompt_text: str, default: Any = None, is_sensitive: bool = False) -> str | None:
  145. value = Prompt.ask(
  146. prompt_text,
  147. default=str(default) if default is not None else "",
  148. show_default=True,
  149. password=is_sensitive
  150. )
  151. stripped = value.strip() if value else None
  152. return stripped if stripped else None
  153. def _prompt_bool(self, prompt_text: str, default: Any = None) -> bool | None:
  154. if default is None:
  155. return Confirm.ask(prompt_text, default=None)
  156. converted = default if isinstance(default, bool) else str(default).lower() in ("true", "1", "yes", "on")
  157. return Confirm.ask(prompt_text, default=converted)
  158. def _prompt_int(self, prompt_text: str, default: Any = None) -> int | None:
  159. converted = None
  160. if default is not None:
  161. try:
  162. converted = int(default)
  163. except (ValueError, TypeError):
  164. logger.warning(f"Invalid default integer value: {default}")
  165. return IntPrompt.ask(prompt_text, default=converted)
  166. def _prompt_enum(self, prompt_text: str, options: list[str], default: Any = None, extra: str | None = None) -> str:
  167. """Prompt for enum selection with validation.
  168. Note: prompt_text should already include hint from variable.get_validation_hint()
  169. but we keep this for backward compatibility and fallback.
  170. """
  171. if not options:
  172. return self._prompt_string(prompt_text, default)
  173. # Validate default is in options
  174. if default and str(default) not in options:
  175. default = options[0]
  176. while True:
  177. value = Prompt.ask(
  178. prompt_text,
  179. default=str(default) if default else options[0],
  180. show_default=True,
  181. )
  182. if value in options:
  183. return value
  184. self.console.print(f"[red]Invalid choice. Select from: {', '.join(options)}[/red]")