|
| 1 | +# needed < 3.14 so that annotations aren't evaluated |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import datetime |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from collections.abc import Callable |
| 10 | +from contextlib import asynccontextmanager |
| 11 | +from dataclasses import dataclass |
| 12 | +from functools import partial |
| 13 | + |
| 14 | +from click_async_plugins.util import CliContext |
| 15 | + |
| 16 | +from . import ITC, PluginLifespan, pass_clictx, plugin |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def puts(s: str) -> None: |
| 22 | + print(s, file=sys.stderr) |
| 23 | + |
| 24 | + |
| 25 | +def simulate_reload_tpdata(itc: ITC) -> None: |
| 26 | + """Simulate event that TPData was reloaded""" |
| 27 | + itc.fire("tpdata") |
| 28 | + |
| 29 | + |
| 30 | +def echo_newline(_: ITC) -> None: |
| 31 | + """Outputs a new line""" |
| 32 | + puts("") |
| 33 | + |
| 34 | + |
| 35 | +def terminal_block(_: ITC) -> None: |
| 36 | + """Outputs a couple of newlines and the current time""" |
| 37 | + puts(f"{'\n' * 8}The time is now: {datetime.datetime.now().isoformat(sep=' ')}\n") |
| 38 | + |
| 39 | + |
| 40 | +def debug_info(itc: ITC) -> None: |
| 41 | + """Prints debugging information on tasks and ITC""" |
| 42 | + puts("*** BEGIN DEBUG INFO: ***") |
| 43 | + puts("Tasks:") |
| 44 | + for i, task in enumerate(asyncio.all_tasks(asyncio.get_event_loop()), 1): |
| 45 | + coro = task.get_coro() |
| 46 | + puts( |
| 47 | + f" {i:02n} {task.get_name():24s} " |
| 48 | + f"state={task._state.lower():8s} " |
| 49 | + f"coro={None if coro is None else coro.__qualname__}" |
| 50 | + ) |
| 51 | + puts("ITC:") |
| 52 | + puts(f" {itc}") |
| 53 | + puts("*** END DEBUG INFO: ***") |
| 54 | + |
| 55 | + |
| 56 | +_LOGLEVELS = { |
| 57 | + logging.DEBUG: "DEBUG", |
| 58 | + logging.INFO: "INFO", |
| 59 | + logging.WARN: "WARN", |
| 60 | + logging.ERROR: "ERROR", |
| 61 | + logging.CRITICAL: "CRITICAL", |
| 62 | +} |
| 63 | + |
| 64 | + |
| 65 | +def adjust_loglevel(_: ITC, change: int) -> None: |
| 66 | + """Adjusts the log level""" |
| 67 | + rootlogger = logging.getLogger() |
| 68 | + newlevel = rootlogger.getEffectiveLevel() + change |
| 69 | + if newlevel < logging.DEBUG or newlevel > logging.CRITICAL: |
| 70 | + return |
| 71 | + |
| 72 | + rootlogger.setLevel(newlevel) |
| 73 | + puts(f"Log level now at {_LOGLEVELS[logger.getEffectiveLevel()]}") |
| 74 | + |
| 75 | + |
| 76 | +@dataclass |
| 77 | +class KeyAndFunc: |
| 78 | + key: str |
| 79 | + func: Callable[[ITC], None] |
| 80 | + |
| 81 | + |
| 82 | +type KeyCmdMapType = dict[int, KeyAndFunc] |
| 83 | + |
| 84 | + |
| 85 | +def print_help(_: ITC, key_to_cmd: KeyCmdMapType) -> None: |
| 86 | + puts("Keys I know about for debugging:") |
| 87 | + for keyfunc in key_to_cmd.values(): |
| 88 | + puts(f" {keyfunc.key:5s} {keyfunc.func.__doc__}") |
| 89 | + puts(" ? Print this message") |
| 90 | + |
| 91 | + |
| 92 | +try: |
| 93 | + import fcntl |
| 94 | + import termios |
| 95 | + import tty |
| 96 | + |
| 97 | + async def _monitor_stdin(itc: ITC, key_to_cmd: KeyCmdMapType) -> None: |
| 98 | + fd = sys.stdin.fileno() |
| 99 | + termios_saved = termios.tcgetattr(fd) |
| 100 | + fnctl_flags = fcntl.fcntl(sys.stdin, fcntl.F_GETFL) |
| 101 | + |
| 102 | + try: |
| 103 | + logger.debug("Configuring stdin for raw input") |
| 104 | + tty.setcbreak(fd) |
| 105 | + fcntl.fcntl(sys.stdin, fcntl.F_SETFL, fnctl_flags | os.O_NONBLOCK) |
| 106 | + |
| 107 | + while True: |
| 108 | + ch = sys.stdin.read(1) |
| 109 | + |
| 110 | + if len(ch) == 0: |
| 111 | + await asyncio.sleep(0.1) |
| 112 | + continue |
| 113 | + |
| 114 | + if (key := ord(ch)) == 0x3F: |
| 115 | + print_help(itc, key_to_cmd) |
| 116 | + |
| 117 | + elif (keyfunc := key_to_cmd.get(key)) is not None and callable( |
| 118 | + keyfunc.func |
| 119 | + ): |
| 120 | + keyfunc.func(itc) |
| 121 | + |
| 122 | + else: |
| 123 | + logger.debug(f"Ignoring character 0x{key:02x} on stdin") |
| 124 | + |
| 125 | + finally: |
| 126 | + logger.debug("Restoring stdin") |
| 127 | + termios.tcsetattr(fd, termios.TCSADRAIN, termios_saved) |
| 128 | + fcntl.fcntl(sys.stdin, fcntl.F_SETFL, fnctl_flags) |
| 129 | + |
| 130 | +except ImportError: |
| 131 | + |
| 132 | + async def _monitor_stdin(itc: ITC, key_to_cmd: KeyCmdMapType) -> None: |
| 133 | + _ = itc, key_to_cmd |
| 134 | + logger.warning("The 'debug' plugin does not work on this platform") |
| 135 | + return None |
| 136 | + |
| 137 | + |
| 138 | +@asynccontextmanager |
| 139 | +async def monitor_stdin_for_debug_commands(itc: ITC) -> PluginLifespan: |
| 140 | + increase_loglevel = partial(adjust_loglevel, change=-10) |
| 141 | + increase_loglevel.__doc__ = "Increase the logging level" |
| 142 | + decrease_loglevel = partial(adjust_loglevel, change=10) |
| 143 | + decrease_loglevel.__doc__ = "Decrease the logging level" |
| 144 | + |
| 145 | + key_to_cmd = { |
| 146 | + 0xA: KeyAndFunc(r"\n", echo_newline), |
| 147 | + 0x12: KeyAndFunc("^R", simulate_reload_tpdata), |
| 148 | + 0x1B: KeyAndFunc("<Esc>", terminal_block), |
| 149 | + 0x4: KeyAndFunc("^D", debug_info), |
| 150 | + 0x2B: KeyAndFunc("+", increase_loglevel), |
| 151 | + 0x2D: KeyAndFunc("-", decrease_loglevel), |
| 152 | + } |
| 153 | + yield _monitor_stdin(itc, key_to_cmd) |
| 154 | + |
| 155 | + |
| 156 | +@plugin |
| 157 | +@pass_clictx |
| 158 | +async def debug(clictx: CliContext) -> PluginLifespan: |
| 159 | + """Monitor stdin for keypresses to trigger debugging functions |
| 160 | +
|
| 161 | + Press '?' to get a list of possible keys. |
| 162 | + """ |
| 163 | + |
| 164 | + async with monitor_stdin_for_debug_commands(clictx.itc) as task: |
| 165 | + yield task |
0 commit comments