Coretex
intercept.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Any
19 
20 import logging
21 
22 import click
23 
24 
25 class ClickExceptionInterceptor(click.Group):
26 
27  def invoke(self, ctx: click.Context) -> Any:
28  try:
29  return super().invoke(ctx)
30  except BaseException as exc:
31  if isinstance(exc, KeyboardInterrupt):
32  raise
33 
34  if isinstance(exc, click.exceptions.Exit) and exc.exit_code == 0:
35  raise
36 
37  self.handleException(ctx, exc)
38 
39  def handleException(self, ctx: click.Context, exc: BaseException) -> None:
40  click.echo(click.style(str(exc), fg = "red"))
41  logging.getLogger("cli").debug(exc, exc_info = exc)