For some reason, my code below is giving inconsistent results. The files in files do not ever change. However, the result of hasher.hexdigest() is giving different values each time this function runs. My goal with this code is to only generate a new settings file if and only if the checksum/hash in the current settings file does not match the result of the three settings files hashed with hashlib. Does anyone see what I might be doing wrong?
def should_generate_new_settings(qt_settings_generated_path: Path) -> tuple[bool, str]:
""" compare checksum of user_settings.json and the current ini file to what is stored in the currently generated settings file """
generate = False
hasher = hashlib.new('md5')
if not qt_settings_generated_path.exists():
generate = True
try:
# if the file is corrupt, it may have a filesize of 0.
generated_file = qt_settings_generated_path.stat()
if generated_file.st_size < 1:
generate = True
files = [paths.user_settings_path, paths.settings_generated_path, Path(__file__)]
for path in files:
file_contents = path.read_bytes()
hasher.update(file_contents)
with qt_settings_generated_path.open('r') as file:
lines = file.read().splitlines()
checksum_prefix = '# checksum: '
for line in lines:
if line.startswith(checksum_prefix):
file_checksum = line.lstrip(checksum_prefix)
if file_checksum != hasher.hexdigest():
generate = True
break
except FileNotFoundError:
generate = True
return (generate, hasher.hexdigest())
hash()function, to reduce the risk of denial-of-service attacks. It does not apply to the stuff inhashlib.file_checksum != hasher.hexdigest()ever be false givenfile_checksumis per file andhasheris all bytes for all files combined. Also, you might want to print the exception as who knows what file might not be found and at the moment you eat that information.