Refactor: blake3 hasing util functions
This commit is contained in:
parent
5806519e01
commit
d4f08aa8b2
1 changed files with 36 additions and 18 deletions
|
@ -1,29 +1,47 @@
|
||||||
from blake3 import blake3
|
from blake3 import blake3
|
||||||
|
|
||||||
from tqdm.auto import tqdm
|
from tqdm.auto import tqdm
|
||||||
|
|
||||||
|
|
||||||
def compute_file_hash_black3(self, file_path):
|
def compute_blake3_hash(data, is_file=False, logger=None):
|
||||||
"""Compute BLAKE3 hash of the file"""
|
"""
|
||||||
|
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:
|
try:
|
||||||
hasher = blake3()
|
hasher = blake3()
|
||||||
with open(file_path, "rb") as f:
|
|
||||||
while chunk := f.read(65536):
|
if is_file:
|
||||||
hasher.update(chunk)
|
with open(data, "rb") as f:
|
||||||
|
while chunk := f.read(65536):
|
||||||
|
hasher.update(chunk)
|
||||||
|
else:
|
||||||
|
hasher.update(data.encode())
|
||||||
|
|
||||||
return hasher.hexdigest()
|
return hasher.hexdigest()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# self.stdout.write(self.style.WARNING(f"Error computing file hash: {e}"))
|
error_message = f"Error computing hash: {e}"
|
||||||
tqdm.write(self.style.WARNING(f"Error computing file 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
|
return None
|
||||||
|
|
||||||
|
|
||||||
def compute_string_hash_black3(self, string):
|
# Convenience wrappers for readability
|
||||||
"""Compute BLAKE3 hash of the string"""
|
def compute_file_hash_blake3(file_path, logger=None):
|
||||||
try:
|
return compute_blake3_hash(file_path, is_file=True, logger=logger)
|
||||||
hasher = blake3()
|
|
||||||
hasher.update(string.encode())
|
|
||||||
return hasher.hexdigest()
|
def compute_string_hash_blake3(string, logger=None):
|
||||||
except Exception as e:
|
return compute_blake3_hash(string, is_file=False, logger=logger)
|
||||||
# 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
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue