Source code for scoutbot.utils

# -*- coding: utf-8 -*-
"""
Scoutbot utilities file for common and handy functions.
"""

import atexit
import hashlib
import logging
import os
from logging.handlers import TimedRotatingFileHandler

DAYS = 21
VERBOSE = os.getenv('VERBOSE', None) is not None
DEFAULT_LOG_LEVEL = logging.DEBUG if VERBOSE else logging.INFO


[docs] def check_file_integrity(filepath, expected_hash): """ Verifies that the file at filepath matches the expected sha256 hash. Returns True if matches, False otherwise. """ if not os.path.exists(filepath): return False if expected_hash is None: return True sha256_hash = hashlib.sha256() with open(filepath, 'rb') as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096), b''): sha256_hash.update(byte_block) return sha256_hash.hexdigest() == expected_hash
[docs] def init_logging(): """ Setup Python's built in logging functionality with on-disk logging, and prettier logging with Rich """ # Import Rich import rich from rich.logging import RichHandler from rich.style import Style from rich.theme import Theme name = 'scoutbot' # Setup placeholder for logging handlers handlers = [] # Configuration arguments for console, handlers, and logging console_kwargs = { 'theme': Theme( { 'logging.keyword': Style(bold=True, color='yellow'), 'logging.level.notset': Style(dim=True), 'logging.level.debug': Style(color='cyan'), 'logging.level.info': Style(color='green'), 'logging.level.warning': Style(color='yellow'), 'logging.level.error': Style(color='red', bold=True), 'logging.level.critical': Style(color='red', bold=True, reverse=True), 'log.time': Style(color='white'), } ) } handler_kwargs = { 'rich_tracebacks': True, 'tracebacks_show_locals': True, } logging_kwargs = { 'level': DEFAULT_LOG_LEVEL, 'format': '[%(name)s] %(message)s', 'datefmt': '[%X]', } # Add file-based log handler; register explicit close so the file is released # even when pytest initialises logging first (making basicConfig a no-op). file_handler = TimedRotatingFileHandler( filename=f'{name}.log', when='midnight', backupCount=DAYS, ) atexit.register(file_handler.close) handlers.append(file_handler) # Add rich (fancy logging) log handler rich.reconfigure(**console_kwargs) handlers.append(RichHandler(**handler_kwargs)) # Setup global logger with the handlers and set the default level to INFO logging.basicConfig(handlers=handlers, **logging_kwargs) logger = logging.getLogger() logger.setLevel(DEFAULT_LOG_LEVEL) log = logging.getLogger(name) return log