| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import enum |
| 5 |
import typing as t |
| 6 |
|
| 7 |
from ansible.utils.display import Display |
| 8 |
from ansible.constants import config |
| 9 |
|
| 10 |
display = Display() |
| 11 |
|
| 12 |
# FUTURE: add sanity test to detect use of skip_on_ignore without Skippable (and vice versa) |
| 13 |
|
| 14 |
|
| 15 |
class ErrorAction(enum.Enum): |
| 16 |
"""Action to take when an error is encountered.""" |
| 17 |
|
| 18 |
IGNORE = enum.auto() |
| 19 |
WARNING = enum.auto() |
| 20 |
ERROR = enum.auto() |
| 21 |
|
| 22 |
@classmethod |
| 23 |
def from_config(cls, setting: str, variables: dict[str, t.Any] | None = None) -> t.Self: |
| 24 |
"""Return an `ErrorAction` enum from the specified Ansible config setting.""" |
| 25 |
return cls[config.get_config_value(setting, variables=variables).upper()] |
| 26 |
|
| 27 |
|
| 28 |
class _SkipException(BaseException): |
| 29 |
"""Internal flow control exception for skipping code blocks within a `Skippable` context manager.""" |
| 30 |
|
| 31 |
def __init__(self) -> None: |
| 32 |
super().__init__('Skipping ignored action due to use of `skip_on_ignore`. It is a bug to encounter this message outside of debugging.') |
| 33 |
|
| 34 |
|
| 35 |
class _SkippableContextManager: |
| 36 |
"""Internal context manager to support flow control for skipping code blocks.""" |
| 37 |
|
| 38 |
def __enter__(self) -> None: |
| 39 |
pass |
| 40 |
|
| 41 |
def __exit__(self, exc_type, _exc_val, _exc_tb) -> bool: |
| 42 |
if exc_type is None: |
| 43 |
raise RuntimeError('A `Skippable` context manager was entered, but a `skip_on_ignore` handler was never invoked.') |
| 44 |
|
| 45 |
return exc_type is _SkipException # only mask a _SkipException, allow all others to raise |
| 46 |
|
| 47 |
|
| 48 |
Skippable = _SkippableContextManager() |
| 49 |
"""Context manager singleton required to enclose `ErrorHandler.handle` invocations when `skip_on_ignore` is `True`.""" |
| 50 |
|
| 51 |
|
| 52 |
class ErrorHandler: |
| 53 |
""" |
| 54 |
Provides a configurable error handler context manager for a specific list of exception types. |
| 55 |
Unhandled errors leaving the context manager can be ignored, treated as warnings, or allowed to raise by setting `ErrorAction`. |
| 56 |
""" |
| 57 |
|
| 58 |
def __init__(self, action: ErrorAction) -> None: |
| 59 |
self.action = action |
| 60 |
|
| 61 |
@contextlib.contextmanager |
| 62 |
def handle(self, *args: type[BaseException], skip_on_ignore: bool = False) -> t.Iterator[None]: |
| 63 |
""" |
| 64 |
Handle the specified exception(s) using the defined error action. |
| 65 |
If `skip_on_ignore` is `True`, the body of the context manager will be skipped for `ErrorAction.IGNORE`. |
| 66 |
Use of `skip_on_ignore` requires enclosure within the `Skippable` context manager. |
| 67 |
""" |
| 68 |
if not args: |
| 69 |
raise ValueError('At least one exception type is required.') |
| 70 |
|
| 71 |
if skip_on_ignore and self.action == ErrorAction.IGNORE: |
| 72 |
raise _SkipException() # skipping ignored action |
| 73 |
|
| 74 |
try: |
| 75 |
yield |
| 76 |
except args as ex: |
| 77 |
match self.action: |
| 78 |
case ErrorAction.WARNING: |
| 79 |
display.error_as_warning(msg=None, exception=ex) |
| 80 |
case ErrorAction.ERROR: |
| 81 |
raise |
| 82 |
case _: # ErrorAction.IGNORE |
| 83 |
pass |
| 84 |
|
| 85 |
if skip_on_ignore: |
| 86 |
raise _SkipException() # completed skippable action, ensures the `Skippable` context was used |
| 87 |
|
| 88 |
@classmethod |
| 89 |
def from_config(cls, setting: str, variables: dict[str, t.Any] | None = None) -> t.Self: |
| 90 |
"""Return an `ErrorHandler` instance configured using the specified Ansible config setting.""" |
| 91 |
return cls(ErrorAction.from_config(setting, variables=variables)) |