From d4f08aa8b2559d2fdcdc7b0c022595e72f98d814 Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Mon, 24 Feb 2025 21:46:35 +0100 Subject: [PATCH] Refactor: blake3 hasing util functions --- backend/utils/hash.py | 54 ++++++++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/backend/utils/hash.py b/backend/utils/hash.py index d3910df..376c04a 100644 --- a/backend/utils/hash.py +++ b/backend/utils/hash.py @@ -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)