prompt.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload
  2. from . import get_console
  3. from .console import Console
  4. from .text import Text, TextType
  5. PromptType = TypeVar("PromptType")
  6. DefaultType = TypeVar("DefaultType")
  7. class PromptError(Exception):
  8. """Exception base class for prompt related errors."""
  9. class InvalidResponse(PromptError):
  10. """Exception to indicate a response was invalid. Raise this within process_response() to indicate an error
  11. and provide an error message.
  12. Args:
  13. message (Union[str, Text]): Error message.
  14. """
  15. def __init__(self, message: TextType) -> None:
  16. self.message = message
  17. def __rich__(self) -> TextType:
  18. return self.message
  19. class PromptBase(Generic[PromptType]):
  20. """Ask the user for input until a valid response is received. This is the base class, see one of
  21. the concrete classes for examples.
  22. Args:
  23. prompt (TextType, optional): Prompt text. Defaults to "".
  24. console (Console, optional): A Console instance or None to use global console. Defaults to None.
  25. password (bool, optional): Enable password input. Defaults to False.
  26. choices (List[str], optional): A list of valid choices. Defaults to None.
  27. show_default (bool, optional): Show default in prompt. Defaults to True.
  28. show_choices (bool, optional): Show choices in prompt. Defaults to True.
  29. """
  30. response_type: type = str
  31. validate_error_message = "[prompt.invalid]Please enter a valid value"
  32. illegal_choice_message = (
  33. "[prompt.invalid.choice]Please select one of the available options"
  34. )
  35. prompt_suffix = ": "
  36. choices: Optional[List[str]] = None
  37. def __init__(
  38. self,
  39. prompt: TextType = "",
  40. *,
  41. console: Optional[Console] = None,
  42. password: bool = False,
  43. choices: Optional[List[str]] = None,
  44. show_default: bool = True,
  45. show_choices: bool = True,
  46. ) -> None:
  47. self.console = console or get_console()
  48. self.prompt = (
  49. Text.from_markup(prompt, style="prompt")
  50. if isinstance(prompt, str)
  51. else prompt
  52. )
  53. self.password = password
  54. if choices is not None:
  55. self.choices = choices
  56. self.show_default = show_default
  57. self.show_choices = show_choices
  58. @classmethod
  59. @overload
  60. def ask(
  61. cls,
  62. prompt: TextType = "",
  63. *,
  64. console: Optional[Console] = None,
  65. password: bool = False,
  66. choices: Optional[List[str]] = None,
  67. show_default: bool = True,
  68. show_choices: bool = True,
  69. default: DefaultType,
  70. stream: Optional[TextIO] = None,
  71. ) -> Union[DefaultType, PromptType]:
  72. ...
  73. @classmethod
  74. @overload
  75. def ask(
  76. cls,
  77. prompt: TextType = "",
  78. *,
  79. console: Optional[Console] = None,
  80. password: bool = False,
  81. choices: Optional[List[str]] = None,
  82. show_default: bool = True,
  83. show_choices: bool = True,
  84. stream: Optional[TextIO] = None,
  85. ) -> PromptType:
  86. ...
  87. @classmethod
  88. def ask(
  89. cls,
  90. prompt: TextType = "",
  91. *,
  92. console: Optional[Console] = None,
  93. password: bool = False,
  94. choices: Optional[List[str]] = None,
  95. show_default: bool = True,
  96. show_choices: bool = True,
  97. default: Any = ...,
  98. stream: Optional[TextIO] = None,
  99. ) -> Any:
  100. """Shortcut to construct and run a prompt loop and return the result.
  101. Example:
  102. >>> filename = Prompt.ask("Enter a filename")
  103. Args:
  104. prompt (TextType, optional): Prompt text. Defaults to "".
  105. console (Console, optional): A Console instance or None to use global console. Defaults to None.
  106. password (bool, optional): Enable password input. Defaults to False.
  107. choices (List[str], optional): A list of valid choices. Defaults to None.
  108. show_default (bool, optional): Show default in prompt. Defaults to True.
  109. show_choices (bool, optional): Show choices in prompt. Defaults to True.
  110. stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.
  111. """
  112. _prompt = cls(
  113. prompt,
  114. console=console,
  115. password=password,
  116. choices=choices,
  117. show_default=show_default,
  118. show_choices=show_choices,
  119. )
  120. return _prompt(default=default, stream=stream)
  121. def render_default(self, default: DefaultType) -> Text:
  122. """Turn the supplied default in to a Text instance.
  123. Args:
  124. default (DefaultType): Default value.
  125. Returns:
  126. Text: Text containing rendering of default value.
  127. """
  128. return Text(f"({default})", "prompt.default")
  129. def make_prompt(self, default: DefaultType) -> Text:
  130. """Make prompt text.
  131. Args:
  132. default (DefaultType): Default value.
  133. Returns:
  134. Text: Text to display in prompt.
  135. """
  136. prompt = self.prompt.copy()
  137. prompt.end = ""
  138. if self.show_choices and self.choices:
  139. _choices = "/".join(self.choices)
  140. choices = f"[{_choices}]"
  141. prompt.append(" ")
  142. prompt.append(choices, "prompt.choices")
  143. if (
  144. default != ...
  145. and self.show_default
  146. and isinstance(default, (str, self.response_type))
  147. ):
  148. prompt.append(" ")
  149. _default = self.render_default(default)
  150. prompt.append(_default)
  151. prompt.append(self.prompt_suffix)
  152. return prompt
  153. @classmethod
  154. def get_input(
  155. cls,
  156. console: Console,
  157. prompt: TextType,
  158. password: bool,
  159. stream: Optional[TextIO] = None,
  160. ) -> str:
  161. """Get input from user.
  162. Args:
  163. console (Console): Console instance.
  164. prompt (TextType): Prompt text.
  165. password (bool): Enable password entry.
  166. Returns:
  167. str: String from user.
  168. """
  169. return console.input(prompt, password=password, stream=stream)
  170. def check_choice(self, value: str) -> bool:
  171. """Check value is in the list of valid choices.
  172. Args:
  173. value (str): Value entered by user.
  174. Returns:
  175. bool: True if choice was valid, otherwise False.
  176. """
  177. assert self.choices is not None
  178. return value.strip() in self.choices
  179. def process_response(self, value: str) -> PromptType:
  180. """Process response from user, convert to prompt type.
  181. Args:
  182. value (str): String typed by user.
  183. Raises:
  184. InvalidResponse: If ``value`` is invalid.
  185. Returns:
  186. PromptType: The value to be returned from ask method.
  187. """
  188. value = value.strip()
  189. try:
  190. return_value: PromptType = self.response_type(value)
  191. except ValueError:
  192. raise InvalidResponse(self.validate_error_message)
  193. if self.choices is not None and not self.check_choice(value):
  194. raise InvalidResponse(self.illegal_choice_message)
  195. return return_value
  196. def on_validate_error(self, value: str, error: InvalidResponse) -> None:
  197. """Called to handle validation error.
  198. Args:
  199. value (str): String entered by user.
  200. error (InvalidResponse): Exception instance the initiated the error.
  201. """
  202. self.console.print(error)
  203. def pre_prompt(self) -> None:
  204. """Hook to display something before the prompt."""
  205. @overload
  206. def __call__(self, *, stream: Optional[TextIO] = None) -> PromptType:
  207. ...
  208. @overload
  209. def __call__(
  210. self, *, default: DefaultType, stream: Optional[TextIO] = None
  211. ) -> Union[PromptType, DefaultType]:
  212. ...
  213. def __call__(self, *, default: Any = ..., stream: Optional[TextIO] = None) -> Any:
  214. """Run the prompt loop.
  215. Args:
  216. default (Any, optional): Optional default value.
  217. Returns:
  218. PromptType: Processed value.
  219. """
  220. while True:
  221. self.pre_prompt()
  222. prompt = self.make_prompt(default)
  223. value = self.get_input(self.console, prompt, self.password, stream=stream)
  224. if value == "" and default != ...:
  225. return default
  226. try:
  227. return_value = self.process_response(value)
  228. except InvalidResponse as error:
  229. self.on_validate_error(value, error)
  230. continue
  231. else:
  232. return return_value
  233. class Prompt(PromptBase[str]):
  234. """A prompt that returns a str.
  235. Example:
  236. >>> name = Prompt.ask("Enter your name")
  237. """
  238. response_type = str
  239. class IntPrompt(PromptBase[int]):
  240. """A prompt that returns an integer.
  241. Example:
  242. >>> burrito_count = IntPrompt.ask("How many burritos do you want to order")
  243. """
  244. response_type = int
  245. validate_error_message = "[prompt.invalid]Please enter a valid integer number"
  246. class FloatPrompt(PromptBase[int]):
  247. """A prompt that returns a float.
  248. Example:
  249. >>> temperature = FloatPrompt.ask("Enter desired temperature")
  250. """
  251. response_type = float
  252. validate_error_message = "[prompt.invalid]Please enter a number"
  253. class Confirm(PromptBase[bool]):
  254. """A yes / no confirmation prompt.
  255. Example:
  256. >>> if Confirm.ask("Continue"):
  257. run_job()
  258. """
  259. response_type = bool
  260. validate_error_message = "[prompt.invalid]Please enter Y or N"
  261. choices: List[str] = ["y", "n"]
  262. def render_default(self, default: DefaultType) -> Text:
  263. """Render the default as (y) or (n) rather than True/False."""
  264. yes, no = self.choices
  265. return Text(f"({yes})" if default else f"({no})", style="prompt.default")
  266. def process_response(self, value: str) -> bool:
  267. """Convert choices to a bool."""
  268. value = value.strip().lower()
  269. if value not in self.choices:
  270. raise InvalidResponse(self.validate_error_message)
  271. return value == self.choices[0]
  272. if __name__ == "__main__": # pragma: no cover
  273. from pip._vendor.rich import print
  274. if Confirm.ask("Run [i]prompt[/i] tests?", default=True):
  275. while True:
  276. result = IntPrompt.ask(
  277. ":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5
  278. )
  279. if result >= 1 and result <= 10:
  280. break
  281. print(":pile_of_poo: [prompt.invalid]Number must be between 1 and 10")
  282. print(f"number={result}")
  283. while True:
  284. password = Prompt.ask(
  285. "Please enter a password [cyan](must be at least 5 characters)",
  286. password=True,
  287. )
  288. if len(password) >= 5:
  289. break
  290. print("[prompt.invalid]password too short")
  291. print(f"password={password!r}")
  292. fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"])
  293. print(f"fruit={fruit!r}")
  294. else:
  295. print("[b]OK :loudly_crying_face:")