Coverage for enderchest/prompt.py: 95%
19 statements
« prev ^ index » next coverage.py v7.5.0, created at 2024-05-04 01:41 +0000
« prev ^ index » next coverage.py v7.5.0, created at 2024-05-04 01:41 +0000
1"""Utilities for helping build interactive prompts"""
3import getpass
5CURSOR = "\x1b[35;1m==>\x1b[0m"
7# https://stackoverflow.com/a/18472142
8YES = ("y", "yes", "t", "true", "on", "1")
10NO = ("n", "no", "f", "false", "off", "0")
13def prompt(
14 message: str, suggestion: str | None = None, is_password: bool = False
15) -> str:
16 """Prompt the user and return the response
18 Parameters
19 ----------
20 message : str
21 The prompt message
22 suggestion : str, optional
23 A suggested input. If None is provided, no suggestion will be shown.
24 is_password : bool, optional
25 If this is a prompt for a password, pass in `is_password = True` to
26 hide the user's input
28 Returns
29 -------
30 str
31 The user-provided response
33 Notes
34 -----
35 - The output will be stripped of trailing and leading whitespace, but no
36 other validation or processing will be used.
37 - Regardless of whether a suggestion is provided, if the user provides an
38 empty input, this method will return an empty string. To reiterate: the
39 suggestion *does not serve* as a default / fallback value.
40 """
41 lines = message.splitlines() + [""]
42 message = "\n".join(f"{CURSOR}\x1b[1m {line}\x1b[0m" for line in lines)
43 if suggestion is not None:
44 message += f"\x1b[35;1m[{suggestion}]\x1b[0m "
45 if is_password:
46 return getpass.getpass(prompt=message)
47 return input(message)
50def confirm(default: bool) -> bool:
51 """Confirm that the user wishes to continue
53 Parameters
54 ----------
55 default : bool
56 Whether the default selection should be True (yes) or False (no)
58 Returns
59 -------
60 bool
61 Whether the user has opted to continue
62 """
64 response = prompt("Do you wish to continue?", "Y/n" if default else "y/N").lower()
66 if response == "":
67 return default
69 if response in YES:
70 return True
72 return False