Refactor: blake3 hasing util functions

This commit is contained in:
Aroy-Art 2025-02-24 21:46:35 +01:00
parent 5806519e01
commit d4f08aa8b2
Signed by: Aroy
GPG key ID: 583642324A1D2070

View file

@ -1,29 +1,47 @@
from blake3 import blake3
from tqdm.auto import tqdm
def compute_file_hash_black3(self, file_path):
"""Compute BLAKE3 hash of the file"""
def compute_blake3_hash(data, is_file=False, logger=None):
"""
Compute BLAKE3 hash of a file or string.
Args:
data (str): File path (if is_file=True) or raw string.
is_file (bool): Whether the input is a file path. Defaults to False.
logger: Optional logger for error messages (e.g., Django `self` or `tqdm`).
Returns:
str: BLAKE3 hash or None if an error occurs.
"""
try:
hasher = blake3()
with open(file_path, "rb") as f:
while chunk := f.read(65536):
hasher.update(chunk)
if is_file:
with open(data, "rb") as f:
while chunk := f.read(65536):
hasher.update(chunk)
else:
hasher.update(data.encode())
return hasher.hexdigest()
except Exception as e:
# self.stdout.write(self.style.WARNING(f"Error computing file hash: {e}"))
tqdm.write(self.style.WARNING(f"Error computing file hash: {e}"))
error_message = f"Error computing hash: {e}"
if logger:
if hasattr(logger, "style") and hasattr(logger, "stdout"): # Django command
logger.stdout.write(logger.style.WARNING(error_message))
else: # Default to tqdm
tqdm.write(error_message)
return None
def compute_string_hash_black3(self, string):
"""Compute BLAKE3 hash of the string"""
try:
hasher = blake3()
hasher.update(string.encode())
return hasher.hexdigest()
except Exception as e:
# self.stdout.write(self.style.WARNING(f"Error computing string hash: {e}"))
tqdm.write(self.style.WARNING(f"Error computing string hash: {e}"))
return None
# Convenience wrappers for readability
def compute_file_hash_blake3(file_path, logger=None):
return compute_blake3_hash(file_path, is_file=True, logger=logger)
def compute_string_hash_blake3(string, logger=None):
return compute_blake3_hash(string, is_file=False, logger=logger)