Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Robust version hash generator #77

Merged
merged 1 commit into from
Dec 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions messgen/version_protocol.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
import hashlib

import json

class VersionProtocol:
def __init__(self, module):
self._module = module

# Returns true for key-value pairs that should not affect proto version hash
def should_discard(self, key, value):
return (key in ['descr', 'name']) and isinstance(value, str)

# Recursively sort the dictionary by keys, excluding certain keys, and return its sorted JSON representation.
def _sorted_purified_dict(self, obj):
if isinstance(obj, dict):
return {k: self._sorted_purified_dict(obj[k]) for k in sorted(obj) if not self.should_discard(k, obj[k])}
elif isinstance(obj, list):
return sorted([self._sorted_purified_dict(x) for x in obj], key=lambda x: json.dumps(x))
else:
return obj

def generate(self):
result = hashlib.md5(str(self._module).encode())
# Sort the module dictionary recursively, excluding certain keys
sorted_module = self._sorted_purified_dict(self._module)

# Convert the sorted dictionary to a JSON string and encode it
encoded_module = json.dumps(sorted_module, separators=(',', ':')).encode()

# Create the hash and return the first 6 characters
result = hashlib.md5(encoded_module)
return result.hexdigest()[0:6]