|
| 1 | +"""Patches for the click_repl package.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import shlex |
| 6 | +import sys |
| 7 | +from typing import Any |
| 8 | +from typing import Dict |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +import click |
| 12 | +import click_repl # type: ignore |
| 13 | +from click.exceptions import Exit as ClickExit |
| 14 | +from click_repl import ExitReplException # type: ignore |
| 15 | +from click_repl import bootstrap_prompt # type: ignore |
| 16 | +from click_repl import dispatch_repl_commands # type: ignore |
| 17 | +from click_repl import handle_internal_commands # type: ignore |
| 18 | +from prompt_toolkit.shortcuts import prompt |
| 19 | + |
| 20 | +from harbor_cli._patches.common import get_patcher |
| 21 | +from harbor_cli.exceptions import handle_exception |
| 22 | + |
| 23 | +patcher = get_patcher(f"click_repl version: {click_repl.__version__}") |
| 24 | + |
| 25 | + |
| 26 | +def patch_exception_handling() -> None: |
| 27 | + """Patch click_repl's exception handling to fall back on the |
| 28 | + CLI's exception handlers instead of propagating them. |
| 29 | +
|
| 30 | + Without this patch, any exceptions other than SystemExit and ClickExit |
| 31 | + will cause the REPL to exit. This is not desirable, as we want |
| 32 | + raise exceptions for control flow purposes in commands to abort them, |
| 33 | + but not terminate the CLi completely. |
| 34 | +
|
| 35 | + A failed command should return to the REPL prompt instead of exiting |
| 36 | + the REPL. |
| 37 | + """ |
| 38 | + |
| 39 | + def repl( # noqa: C901 |
| 40 | + old_ctx: click.Context, |
| 41 | + prompt_kwargs: Optional[Dict[str, Any]] = None, |
| 42 | + allow_system_commands: bool = True, |
| 43 | + allow_internal_commands: bool = True, |
| 44 | + ) -> Any: |
| 45 | + """ |
| 46 | + Start an interactive shell. All subcommands are available in it. |
| 47 | +
|
| 48 | + :param old_ctx: The current Click context. |
| 49 | + :param prompt_kwargs: Parameters passed to |
| 50 | + :py:func:`prompt_toolkit.shortcuts.prompt`. |
| 51 | +
|
| 52 | + If stdin is not a TTY, no prompt will be printed, but only commands read |
| 53 | + from stdin. |
| 54 | +
|
| 55 | + """ |
| 56 | + # parent should be available, but we're not going to bother if not |
| 57 | + group_ctx = old_ctx.parent or old_ctx |
| 58 | + group = group_ctx.command |
| 59 | + isatty = sys.stdin.isatty() |
| 60 | + |
| 61 | + # Delete the REPL command from those available, as we don't want to allow |
| 62 | + # nesting REPLs (note: pass `None` to `pop` as we don't want to error if |
| 63 | + # REPL command already not present for some reason). |
| 64 | + repl_command_name = old_ctx.command.name |
| 65 | + if isinstance(group_ctx.command, click.CommandCollection): |
| 66 | + available_commands = { # type: ignore |
| 67 | + cmd_name: cmd_obj |
| 68 | + for source in group_ctx.command.sources |
| 69 | + for cmd_name, cmd_obj in source.commands.items() # type: ignore |
| 70 | + } |
| 71 | + else: |
| 72 | + available_commands = group_ctx.command.commands # type: ignore |
| 73 | + available_commands.pop(repl_command_name, None) # type: ignore |
| 74 | + |
| 75 | + prompt_kwargs = bootstrap_prompt(prompt_kwargs, group) |
| 76 | + |
| 77 | + if isatty: |
| 78 | + |
| 79 | + def get_command(): |
| 80 | + return prompt(**prompt_kwargs) |
| 81 | + |
| 82 | + else: |
| 83 | + get_command = sys.stdin.readline |
| 84 | + |
| 85 | + while True: |
| 86 | + try: |
| 87 | + command = get_command() |
| 88 | + except KeyboardInterrupt: |
| 89 | + continue |
| 90 | + except EOFError: |
| 91 | + break |
| 92 | + |
| 93 | + if not command: |
| 94 | + if isatty: |
| 95 | + continue |
| 96 | + else: |
| 97 | + break |
| 98 | + |
| 99 | + if allow_system_commands and dispatch_repl_commands(command): |
| 100 | + continue |
| 101 | + |
| 102 | + if allow_internal_commands: |
| 103 | + try: |
| 104 | + result = handle_internal_commands(command) # type: ignore |
| 105 | + if isinstance(result, str): |
| 106 | + click.echo(result) |
| 107 | + continue |
| 108 | + except ExitReplException: |
| 109 | + break |
| 110 | + |
| 111 | + try: |
| 112 | + args = shlex.split(command) |
| 113 | + except ValueError as e: |
| 114 | + click.echo(f"{type(e).__name__}: {e}") |
| 115 | + continue |
| 116 | + |
| 117 | + try: |
| 118 | + with group.make_context(None, args, parent=group_ctx) as ctx: |
| 119 | + group.invoke(ctx) |
| 120 | + ctx.exit() |
| 121 | + except click.ClickException as e: |
| 122 | + e.show() |
| 123 | + except ClickExit: |
| 124 | + pass |
| 125 | + except SystemExit: |
| 126 | + pass |
| 127 | + except ExitReplException: |
| 128 | + break |
| 129 | + # PATCH: Patched to handle zabbix-cli exceptions |
| 130 | + except Exception as e: |
| 131 | + try: |
| 132 | + handle_exception(e) # this could be dangerous? Infinite looping? |
| 133 | + except SystemExit: |
| 134 | + pass |
| 135 | + # PATCH: Patched to continue on keyboard interrupt |
| 136 | + except KeyboardInterrupt: |
| 137 | + from harbor_cli.output.console import err_console |
| 138 | + |
| 139 | + # User likely pressed Ctrl+C during a prompt or when a spinner |
| 140 | + # was active. Ensure message is printed on a new line. |
| 141 | + # TODO: determine if last char in terminal was newline somehow! Can we? |
| 142 | + err_console.print("\n[red]Aborted.[/]") |
| 143 | + pass |
| 144 | + |
| 145 | + with patcher("click_repl.repl"): |
| 146 | + click_repl.repl = repl |
| 147 | + |
| 148 | + |
| 149 | +def patch() -> None: |
| 150 | + """Apply all patches.""" |
| 151 | + patch_exception_handling() |
0 commit comments