Skip to content

Instantly share code, notes, and snippets.

@xcsrz
Last active December 20, 2021 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xcsrz/f8bf2cb5bf6b1e500478afdecec694fd to your computer and use it in GitHub Desktop.
Save xcsrz/f8bf2cb5bf6b1e500478afdecec694fd to your computer and use it in GitHub Desktop.
Python port of the getContentHash() function from PHP's Composer. Useful when updating composer.lock from php when composer is available. Granted this "shouldn't be done" and is "doing it wrong", but sometimes running composer commands in your deployment chain is overkill and redundent.
import hashlib
from json import dumps
from collections import OrderedDict
# composerFileContents should be the dict version of the composer.json file
def getContentHash(composerFileContents):
relevant = OrderedDict((key, composerFileContents[key]) for key in composerFileContents.keys() if key in ['name','version','require','require-dev','conflict','replace','provide','minimum-stability','prefer-stable','repositories','extra'])
if 'config' in composerFileContents and 'platform' in composerFileContents['config']:
relevant['config']['platform'] = composerFileContents['config']['platform']
# hacky fix to cover the differences between JSON encoding in Python vs PHP
encstr = dumps(OrderedDict((key, relevant[key]) for key in sorted(relevant.keys())),separators=(',', ':')).replace("/", "\\/").encode()
return hashlib.md5(encstr).hexdigest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment