From fbaa8e0b44ce21047ccf2f216ff13ad39b713d42 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Sun, 27 Sep 2020 17:29:43 +0200 Subject: [PATCH] core: add warnings helper to highlight warnings so they are more visible in the output --- my/books/kobo.py | 4 ++-- my/core/warnings.py | 46 +++++++++++++++++++++++++++++++++++++++++++ my/twitter/archive.py | 6 +++--- 3 files changed, 51 insertions(+), 5 deletions(-) create mode 100644 my/core/warnings.py diff --git a/my/books/kobo.py b/my/books/kobo.py index 10b0352..2ab6692 100644 --- a/my/books/kobo.py +++ b/my/books/kobo.py @@ -1,5 +1,5 @@ -import warnings +from ..core import warnings -warnings.warn('my.books.kobo is deprecated! Please use my.kobo instead!') +warnings.high('my.books.kobo is deprecated! Please use my.kobo instead!') from ..kobo import * diff --git a/my/core/warnings.py b/my/core/warnings.py new file mode 100644 index 0000000..3d95095 --- /dev/null +++ b/my/core/warnings.py @@ -0,0 +1,46 @@ +''' +A helper to make warnings a bit more visible. +TODO ideally would be great to replace with some existing solution, or find a better way, +since who looks at the terminal output? +E.g. would be nice to propagate the warnings in the UI (it's even a subclass of Exception!) +''' + +import sys +import warnings + + +def _colorize(x: str, color=None) -> str: + if color is None: + return x + + if not sys.stdout.isatty(): + return x + + # I'm not sure about this approach yet, so don't want to introduce a hard dependency yet + try: + import termcolor # type: ignore[import] + import colorama # type: ignore[import] + colorama.init() + return termcolor.colored(x, color) + except: + # todo log something? + return x + + +def _warn(message: str, *args, color=None, **kwargs) -> None: + if 'stacklevel' not in kwargs: + kwargs['stacklevel'] = 3 # 1 for this function, 1 for medium/high wrapper + warnings.warn(_colorize(message, color=color), *args, **kwargs) + + +def medium(message: str, *args, **kwargs) -> None: + kwargs['color'] = 'yellow' + _warn(message, *args, **kwargs) + + +def high(message: str, *args, **kwargs) -> None: + ''' + Meant for deprecations, i.e. things that better get some user attention + ''' + kwargs['color'] = 'red' + _warn(message, *args, **kwargs) diff --git a/my/twitter/archive.py b/my/twitter/archive.py index f3550d3..8fa93db 100755 --- a/my/twitter/archive.py +++ b/my/twitter/archive.py @@ -11,10 +11,10 @@ except ImportError as e: try: from my.config import twitter as user_config except ImportError: - raise e # raise the original exception.. must be somethingelse + raise e # raise the original exception.. must be something else else: - import warnings - warnings.warn('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') + from ..core import warnings + warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') from dataclasses import dataclass