|
| 1 | +import contextlib |
| 2 | +import inspect |
| 3 | +import warnings |
| 4 | + |
| 5 | +from reframe.core.exceptions import ReframeFatalError |
| 6 | + |
| 7 | + |
| 8 | +class ReframeDeprecationWarning(DeprecationWarning): |
| 9 | + '''Warning raised for deprecated features of the framework.''' |
| 10 | + |
| 11 | + |
| 12 | +warnings.filterwarnings('default', category=ReframeDeprecationWarning) |
| 13 | + |
| 14 | + |
| 15 | +_format_warning_orig = warnings.formatwarning |
| 16 | + |
| 17 | + |
| 18 | +def _format_warning(message, category, filename, lineno, line=None): |
| 19 | + import reframe.core.runtime as rt |
| 20 | + import reframe.utility.color as color |
| 21 | + |
| 22 | + if category != ReframeDeprecationWarning: |
| 23 | + return _format_warning_orig(message, category, filename, lineno, line) |
| 24 | + |
| 25 | + if line is None: |
| 26 | + # Read in the line from the file |
| 27 | + with open(filename) as fp: |
| 28 | + try: |
| 29 | + line = fp.readlines()[lineno-1] |
| 30 | + except IndexError: |
| 31 | + line = '<no line information>' |
| 32 | + |
| 33 | + message = f'{filename}:{lineno}: WARNING: {message}\n{line}\n' |
| 34 | + |
| 35 | + # Ignore coloring if runtime has not been initialized; this can happen |
| 36 | + # when generating the documentation of deprecated APIs |
| 37 | + with contextlib.suppress(ReframeFatalError): |
| 38 | + if rt.runtime().get_option('general/0/colorize'): |
| 39 | + message = color.colorize(message, color.YELLOW) |
| 40 | + |
| 41 | + return message |
| 42 | + |
| 43 | + |
| 44 | +warnings.formatwarning = _format_warning |
| 45 | + |
| 46 | + |
| 47 | +def user_deprecation_warning(message): |
| 48 | + '''Raise a deprecation warning at the user stack frame that eventually |
| 49 | + calls this function. |
| 50 | +
|
| 51 | + As "user stack frame" is considered a stack frame that is outside the |
| 52 | + :py:mod:`reframe` base module. |
| 53 | + ''' |
| 54 | + |
| 55 | + # Unroll the stack and issue the warning from the first stack frame that is |
| 56 | + # outside the framework. |
| 57 | + stack_level = 1 |
| 58 | + for s in inspect.stack(): |
| 59 | + module = inspect.getmodule(s.frame) |
| 60 | + if module is None or not module.__name__.startswith('reframe'): |
| 61 | + break |
| 62 | + |
| 63 | + stack_level += 1 |
| 64 | + |
| 65 | + warnings.warn(message, ReframeDeprecationWarning, stacklevel=stack_level) |
0 commit comments