logging.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. __package__ = 'archivebox.misc'
  2. # TODO: merge/dedupe this file with archivebox/logging_util.py
  3. import sys
  4. from typing import Optional, Union, Tuple, List
  5. from collections import defaultdict
  6. from benedict import benedict
  7. from rich.console import Console
  8. from ..config_stubs import ConfigDict
  9. # SETUP RICH CONSOLE / TTY detection / COLOR / PROGRESS BARS
  10. CONSOLE = Console()
  11. IS_TTY = CONSOLE.is_interactive
  12. DEFAULT_CLI_COLORS = benedict(
  13. {
  14. "reset": "\033[00;00m",
  15. "lightblue": "\033[01;30m",
  16. "lightyellow": "\033[01;33m",
  17. "lightred": "\033[01;35m",
  18. "red": "\033[01;31m",
  19. "green": "\033[01;32m",
  20. "blue": "\033[01;34m",
  21. "white": "\033[01;37m",
  22. "black": "\033[01;30m",
  23. }
  24. )
  25. ANSI = benedict({k: '' for k in DEFAULT_CLI_COLORS.keys()})
  26. COLOR_DICT = defaultdict(lambda: [(0, 0, 0), (0, 0, 0)], {
  27. '00': [(0, 0, 0), (0, 0, 0)],
  28. '30': [(0, 0, 0), (0, 0, 0)],
  29. '31': [(255, 0, 0), (128, 0, 0)],
  30. '32': [(0, 200, 0), (0, 128, 0)],
  31. '33': [(255, 255, 0), (128, 128, 0)],
  32. '34': [(0, 0, 255), (0, 0, 128)],
  33. '35': [(255, 0, 255), (128, 0, 128)],
  34. '36': [(0, 255, 255), (0, 128, 128)],
  35. '37': [(255, 255, 255), (255, 255, 255)],
  36. })
  37. # Logging Helpers
  38. def stdout(*args, color: Optional[str]=None, prefix: str='', config: Optional[ConfigDict]=None) -> None:
  39. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  40. if color:
  41. strs = [ansi[color], ' '.join(str(a) for a in args), ansi['reset'], '\n']
  42. else:
  43. strs = [' '.join(str(a) for a in args), '\n']
  44. sys.stdout.write(prefix + ''.join(strs))
  45. def stderr(*args, color: Optional[str]=None, prefix: str='', config: Optional[ConfigDict]=None) -> None:
  46. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  47. if color:
  48. strs = [ansi[color], ' '.join(str(a) for a in args), ansi['reset'], '\n']
  49. else:
  50. strs = [' '.join(str(a) for a in args), '\n']
  51. sys.stderr.write(prefix + ''.join(strs))
  52. def hint(text: Union[Tuple[str, ...], List[str], str], prefix=' ', config: Optional[ConfigDict]=None) -> None:
  53. ansi = DEFAULT_CLI_COLORS if (config or {}).get('USE_COLOR') else ANSI
  54. if isinstance(text, str):
  55. stderr('{}{lightred}Hint:{reset} {}'.format(prefix, text, **ansi))
  56. else:
  57. stderr('{}{lightred}Hint:{reset} {}'.format(prefix, text[0], **ansi))
  58. for line in text[1:]:
  59. stderr('{} {}'.format(prefix, line))