prompt.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 .variables import Variable, VariableCollection
  9. logger = logging.getLogger(__name__)
  10. # ---------------------------
  11. # SECTION: PromptHandler Class
  12. # ---------------------------
  13. class PromptHandler:
  14. """Simple interactive prompt handler for collecting template variables."""
  15. def __init__(self) -> None:
  16. self.console = Console()
  17. self.display = DisplayManager()
  18. # --------------------------
  19. # SECTION: Public Methods
  20. # --------------------------
  21. def collect_variables(self, variables: VariableCollection) -> dict[str, Any]:
  22. """Collect values for variables by iterating through sections.
  23. Args:
  24. variables: VariableCollection with organized sections and variables
  25. Returns:
  26. Dict of variable names to collected values
  27. """
  28. if not Confirm.ask("Customize any settings?", default=False):
  29. logger.info("User opted to keep all default values")
  30. return {}
  31. collected: Dict[str, Any] = {}
  32. # Process each section
  33. for section_key, section in variables.get_sections().items():
  34. if not section.variables:
  35. continue
  36. # Always show section header first
  37. self.display.display_section_header(section.title, section.description)
  38. # Handle section toggle - skip for required sections
  39. if section.required:
  40. # Required sections are always processed, no toggle prompt needed
  41. logger.debug(f"Processing required section '{section.key}' without toggle prompt")
  42. elif section.toggle:
  43. toggle_var = section.variables.get(section.toggle)
  44. if toggle_var:
  45. prompt_text = section.prompt or f"Enable {section.title}?"
  46. current_value = toggle_var.get_typed_value()
  47. new_value = self._prompt_bool(prompt_text, current_value)
  48. if new_value != current_value:
  49. collected[toggle_var.name] = new_value
  50. toggle_var.value = new_value
  51. # Use section's native is_enabled() method
  52. if not section.is_enabled():
  53. continue
  54. # Collect variables in this section
  55. for var_name, variable in section.variables.items():
  56. # Skip toggle variable (already handled)
  57. if section.toggle and var_name == section.toggle:
  58. continue
  59. current_value = variable.get_typed_value()
  60. # Pass section.required so _prompt_variable can enforce required inputs
  61. new_value = self._prompt_variable(variable, required=section.required)
  62. if new_value != current_value:
  63. collected[var_name] = new_value
  64. variable.value = new_value
  65. logger.info(f"Variable collection completed. Collected {len(collected)} values")
  66. return collected
  67. # !SECTION
  68. # ---------------------------
  69. # SECTION: Private Methods
  70. # ---------------------------
  71. def _prompt_variable(self, variable: Variable, required: bool = False) -> Any:
  72. """Prompt for a single variable value based on its type."""
  73. logger.debug(f"Prompting for variable '{variable.name}' (type: {variable.type})")
  74. # Use variable's native methods for prompt text and default value
  75. prompt_text = variable.get_prompt_text()
  76. default_value = variable.get_normalized_default()
  77. # If variable is required and there's no default, mark it in the prompt
  78. if required and default_value is None:
  79. prompt_text = f"{prompt_text} [bold red]*required[/bold red]"
  80. handler = self._get_prompt_handler(variable)
  81. # Add validation hint (includes both extra text and enum options)
  82. hint = variable.get_validation_hint()
  83. if hint:
  84. prompt_text = f"{prompt_text} [dim]{hint}[/dim]"
  85. while True:
  86. try:
  87. raw = handler(prompt_text, default_value)
  88. # Convert/validate the user's input using the Variable conversion
  89. converted = variable.convert(raw)
  90. # If this variable is required, do not accept None/empty values
  91. if required and (converted is None or (isinstance(converted, str) and converted == "")):
  92. raise ValueError("value cannot be empty for required variable")
  93. # Return the converted value (caller will update variable.value)
  94. return converted
  95. except ValueError as exc:
  96. # Conversion/validation failed — show a consistent error message and retry
  97. self._show_validation_error(str(exc))
  98. except Exception as e:
  99. # Unexpected error — log and retry using the stored (unconverted) value
  100. logger.error(f"Error prompting for variable '{variable.name}': {str(e)}")
  101. default_value = variable.value
  102. handler = self._get_prompt_handler(variable)
  103. def _get_prompt_handler(self, variable: Variable) -> Callable:
  104. """Return the prompt function for a variable type."""
  105. handlers = {
  106. "bool": self._prompt_bool,
  107. "int": self._prompt_int,
  108. # For enum prompts we pass the variable.extra through so options and extra
  109. # can be combined into a single inline hint.
  110. "enum": lambda text, default: self._prompt_enum(text, variable.options or [], default, extra=getattr(variable, 'extra', None)),
  111. }
  112. return handlers.get(variable.type, lambda text, default: self._prompt_string(text, default, is_sensitive=variable.sensitive))
  113. def _show_validation_error(self, message: str) -> None:
  114. """Display validation feedback consistently."""
  115. self.display.display_validation_error(message)
  116. def _prompt_string(self, prompt_text: str, default: Any = None, is_sensitive: bool = False) -> str:
  117. value = Prompt.ask(
  118. prompt_text,
  119. default=str(default) if default is not None else "",
  120. show_default=True,
  121. password=is_sensitive
  122. )
  123. if value is None:
  124. return None
  125. stripped = value.strip()
  126. return stripped if stripped != "" else None
  127. def _prompt_bool(self, prompt_text: str, default: Any = None) -> bool:
  128. default_bool = None
  129. if default is not None:
  130. default_bool = default if isinstance(default, bool) else str(default).lower() in ("true", "1", "yes", "on")
  131. return Confirm.ask(prompt_text, default=default_bool)
  132. def _prompt_int(self, prompt_text: str, default: Any = None) -> int:
  133. default_int = None
  134. if default is not None:
  135. try:
  136. default_int = int(default)
  137. except (ValueError, TypeError):
  138. logger.warning(f"Invalid default integer value: {default}")
  139. return IntPrompt.ask(prompt_text, default=default_int)
  140. def _prompt_enum(self, prompt_text: str, options: list[str], default: Any = None, extra: str | None = None) -> str:
  141. """Prompt for enum selection with validation.
  142. Note: prompt_text should already include hint from variable.get_validation_hint()
  143. but we keep this for backward compatibility and fallback.
  144. """
  145. if not options:
  146. return self._prompt_string(prompt_text, default)
  147. # Validate default is in options
  148. if default and str(default) not in options:
  149. default = options[0]
  150. while True:
  151. value = Prompt.ask(
  152. prompt_text,
  153. default=str(default) if default else options[0],
  154. show_default=True,
  155. )
  156. if value in options:
  157. return value
  158. self.console.print(f"[red]Invalid choice. Select from: {', '.join(options)}[/red]")
  159. # !SECTION