Last active
September 30, 2022 18:57
-
-
Save kousu/b04e67c351c9867262fb9e511a7bd3ed to your computer and use it in GitHub Desktop.
The missing `pip integrity` command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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