Coverage for src/countdown/terminal.py: 100%

1 statements  

« prev     ^ index     » next       coverage.py v7.11.1, created at 2026-03-27 20:23 -0700

1"""Platform-specific terminal and keyboard I/O operations.""" 

2# pragma: no cover 

3 

4import sys 

5 

6if sys.platform == "win32": # pragma: no cover 

7 import msvcrt 

8else: # pragma: no cover 

9 import termios 

10 import tty 

11 from select import select 

12 

13 

14def check_for_keypress(): # pragma: no cover 

15 """Check if a key has been pressed (non-blocking).""" 

16 if not sys.stdin.isatty(): 

17 return False 

18 if sys.platform == "win32": 

19 return msvcrt.kbhit() 

20 else: 

21 return select([sys.stdin], [], [], 0)[0] 

22 

23 

24def read_key(): # pragma: no cover 

25 """Read a single keypress.""" 

26 if sys.platform == "win32": 

27 key = msvcrt.getch() 

28 else: 

29 key = sys.stdin.read(1) 

30 

31 # Convert bytes to string if needed (Windows returns bytes) 

32 if isinstance(key, bytes): 

33 key = key.decode("utf-8", errors="ignore") 

34 return key 

35 

36 

37def drain_keypresses(): # pragma: no cover 

38 """Consume all pending keypresses from the input buffer.""" 

39 while check_for_keypress(): 

40 read_key() 

41 

42 

43def setup_terminal(): # pragma: no cover 

44 """Setup terminal for non-blocking input (Unix only).""" 

45 if sys.platform != "win32" and sys.stdin.isatty(): 

46 try: 

47 fd = sys.stdin.fileno() 

48 old_settings = termios.tcgetattr(fd) 

49 tty.setcbreak(fd) 

50 return old_settings 

51 except (termios.error, OSError): 

52 pass 

53 return None 

54 

55 

56def restore_terminal(old_settings): # pragma: no cover 

57 """Restore terminal settings (Unix only).""" 

58 if sys.platform != "win32" and old_settings: 

59 fd = sys.stdin.fileno() 

60 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)