Skip to content

Instantly share code, notes, and snippets.

@kousu
Last active September 30, 2022 18:57
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 kousu/b04e67c351c9867262fb9e511a7bd3ed to your computer and use it in GitHub Desktop.
Save kousu/b04e67c351c9867262fb9e511a7bd3ed to your computer and use it in GitHub Desktop.
The missing `pip integrity` command
#!/usr/bin/env python3
#
# The missing 'pip integrity' command.
#
# This verifies the correctness of an unpacked pip package
# by examining the file hashes in the 'RECORD' file.
# spec at https://peps.python.org/pep-0427/#the-dist-info-directory
import sys
import base64
import hashlib
from importlib.metadata import files
def integrity(package):
valid = True
for content in files(package):
if content.hash:
H = None
try:
H = hashlib.new(content.hash.mode)
size = 0
with open(content.locate(), "rb") as fd:
while True:
B = fd.read(H.block_size)
size += len(B)
if not B: break
H.update(B)
H = H.digest()
# wheel stores hashes in unpadded base64, so convert to that
H = base64.urlsafe_b64encode(H).decode().rstrip("=")
except Exception:
pass
if H == content.hash.value:
print(f"{content.locate()}: passed")
else:
print(f"{content.locate()}: failed")
valid = False
return valid
if __name__ == '__main__':
valid = True
for file in sys.argv[1:]:
if not integrity(file):
valid = False
if not valid:
raise SystemExit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment