core: add warnings helper to highlight warnings so they are more visible in the output

This commit is contained in:
Dima Gerasimov 2020-09-27 17:29:43 +02:00 committed by karlicoss
parent cd40fc75c3
commit fbaa8e0b44
3 changed files with 51 additions and 5 deletions

View file

@ -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 * from ..kobo import *

46
my/core/warnings.py Normal file
View file

@ -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)

View file

@ -11,10 +11,10 @@ except ImportError as e:
try: try:
from my.config import twitter as user_config from my.config import twitter as user_config
except ImportError: except ImportError:
raise e # raise the original exception.. must be somethingelse raise e # raise the original exception.. must be something else
else: else:
import warnings from ..core import warnings
warnings.warn('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config') warnings.high('my.config.twitter is deprecated! Please rename it to my.config.twitter_archive in your config')
from dataclasses import dataclass from dataclasses import dataclass