From 6b0e8a2077403880d6e7675bb8debb812cf04296 Mon Sep 17 00:00:00 2001 From: Alex Thompson Date: Wed, 12 Jun 2019 19:25:15 -0400 Subject: [PATCH] The resolve module now computes a sha256 sum if the link doesn't already have one Resolves #22 --- src/piprules/resolve.py | 14 +++++++++++--- src/piprules/util.py | 16 +++++++++++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/piprules/resolve.py b/src/piprules/resolve.py index 26ac6af..925ef0c 100644 --- a/src/piprules/resolve.py +++ b/src/piprules/resolve.py @@ -168,9 +168,12 @@ def _create_resolved_requirement(self, requirement): link = requirement.link source = ResolvedRequirementSource(link.url_without_fragment) - if link.hash: - # TODO this assumes the hash is sha256 - source.sha256 = link.hash + + source.sha256 = ( + link.hash + if link.hash and link.hash_name == "sha256" + else self._compute_sha256_sum(requirement) + ) return ResolvedRequirement( pipcompat.canonicalize_name(requirement.name), @@ -199,6 +202,11 @@ def _set_link_to_local_wheel(self, requirement): session=self._session, ) + def _compute_sha256_sum(self, requirement): + LOG.debug(f"Computing sha256 sum for {requirement.name}") + temp_wheel_path = _find_wheel(self._work_dirs.wheel, requirement.name) + return util.compute_file_hash(temp_wheel_path) + def _find_wheel(directory, name): canon_name = pipcompat.canonicalize_name(name) diff --git a/src/piprules/util.py b/src/piprules/util.py index 7ff5a88..9f27b9e 100644 --- a/src/piprules/util.py +++ b/src/piprules/util.py @@ -1,5 +1,6 @@ -import errno import contextlib +import errno +import hashlib import itertools import os @@ -42,3 +43,16 @@ def prepend_to_pythonpath(paths): def full_groupby(iterable, key=None): """Like itertools.groupby(), but sorts the input on the group key first.""" return itertools.groupby(sorted(iterable, key=key), key=key) + + +def compute_file_hash(path, algorithm="sha256"): + hasher = hashlib.new(algorithm) + block_size = 4096 + + with open(path, mode='rb') as file_: + buf = file_.read(block_size) + while buf: + hasher.update(buf) + buf = file_.read(block_size) + + return hasher.hexdigest()