in main.py [0:0]
def verify_checksum(filepath: str, method: str) -> list:
"""Verifies a filepath against its checksum file, given a checksum method. Returns a list of errors if any found"""
filename = os.path.basename(filepath)
checksum_filepath = filepath + "." + method # foo.sha256
if not os.path.exists(checksum_filepath):
checksum_filepath = filepath + "." + method.upper() # foo.SHA256 fallback
checksum_filename = os.path.basename(checksum_filepath)
errors = []
try:
try:
checksum_value = open(checksum_filepath, "r", encoding="utf-8").read()
except UnicodeDecodeError: # UTF-16??
checksum_value = open(checksum_filepath, "r", encoding="utf-16").read()
except UnicodeError as e:
errors.append(f"[CHK06] Checksum file {checksum_filename} contains garbage characters: {e}")
return errors
checksum_value_trimmed = ""
# Strip away comment lines first
for line in checksum_value.split("\n"):
if not line.startswith("//") and not line.startswith("#"):
checksum_value_trimmed += line.strip() + " "
checksum_options = checksum_value_trimmed.split(" ")
checksum_on_disk = "".join(x.strip() for x in checksum_options if all(c in string.hexdigits for c in x.strip())).lower()
checksum_calculated = digest(filepath, method)
if checksum_on_disk != checksum_calculated:
errors.append(f"[CHK06] Checksum does not match checksum file {checksum_filename}!")
errors.append(f"[CHK06] Calculated {method} checksum of {filename} was: {checksum_calculated}")
errors.append(f"[CHK06] Checksum file {checksum_filename} said it should have been: {checksum_on_disk}")
# Simple check for whether this file is just typoed.
if len(checksum_on_disk) != CHECKSUM_LENGTHS[method]/4: # Wrong filetype??
for m, l in CHECKSUM_LENGTHS.items():
if len(checksum_on_disk) == l/4:
errors.append(f"[CHK06] {checksum_filename} looks like it could be a {m} checksum, but has a {method} extension!")
break
return errors