Coverage for enderchest/prompt.py: 95%

19 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-06 16:00 +0000

1"""Utilities for helping build interactive prompts""" 

2import getpass 

3 

4CURSOR = "\x1b[35;1m==>\x1b[0m" 

5 

6# https://stackoverflow.com/a/18472142 

7YES = ("y", "yes", "t", "true", "on", "1") 

8 

9NO = ("n", "no", "f", "false", "off", "0") 

10 

11 

12def prompt( 

13 message: str, suggestion: str | None = None, is_password: bool = False 

14) -> str: 

15 """Prompt the user and return the response 

16 

17 Parameters 

18 ---------- 

19 message : str 

20 The prompt message 

21 suggestion : str, optional 

22 A suggested input. If None is provided, no suggestion will be shown. 

23 is_password : bool, optional 

24 If this is a prompt for a password, pass in `is_password = True` to 

25 hide the user's input 

26 

27 Returns 

28 ------- 

29 str 

30 The user-provided response 

31 

32 Notes 

33 ----- 

34 - The output will be stripped of trailing and leading whitespace, but no 

35 other validation or processing will be used. 

36 - Regardless of whether a suggestion is provided, if the user provides an 

37 empty input, this method will return an empty string. To reiterate: the 

38 suggestion *does not serve* as a default / fallback value. 

39 """ 

40 lines = message.splitlines() + [""] 

41 message = "\n".join(f"{CURSOR}\x1b[1m {line}\x1b[0m" for line in lines) 

42 if suggestion is not None: 

43 message += f"\x1b[35;1m[{suggestion}]\x1b[0m " 

44 if is_password: 

45 return getpass.getpass(prompt=message) 

46 return input(message) 

47 

48 

49def confirm(default: bool) -> bool: 

50 """Confirm that the user wishes to continue 

51 

52 Parameters 

53 ---------- 

54 default : bool 

55 Whether the default selection should be True (yes) or False (no) 

56 

57 Returns 

58 ------- 

59 bool 

60 Whether the user has opted to continue 

61 """ 

62 

63 response = prompt("Do you wish to continue?", "Y/n" if default else "y/N") 

64 

65 if response == "": 

66 return default 

67 

68 if response in YES: 

69 return True 

70 

71 return False