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

cachi2 wheels: allow dependencies with only wheel distributions #319

Merged
merged 1 commit into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
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
153 changes: 77 additions & 76 deletions cachi2/core/package_managers/pip.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,7 @@
from dataclasses import dataclass, field
from os import PathLike
from pathlib import Path
from typing import (
IO,
TYPE_CHECKING,
Any,
Iterable,
Iterator,
Literal,
Optional,
Union,
no_type_check,
)
from typing import IO, TYPE_CHECKING, Any, Iterable, Iterator, Optional, Union, cast, no_type_check

import tomli
from packageurl import PackageURL
Expand Down Expand Up @@ -1424,6 +1414,19 @@ def _download_dependencies(
if allow_binary:
to_download.extend(w for w in wheels if not w.path.exists())

if source is None:
# at least one wheel exists -> report in the SBOM
downloaded.append(
{
"package": req.package,
"version": req.version_specs[0][1],
"kind": req.kind,
"hash_verified": require_hashes,
"requirement_file": str(requirements_file.file_path.subpath_from_root),
}
)
continue

download_binary_file(source.url, source.path, auth=None)
_check_metadata_in_sdist(source.path)
download_info = source.download_info
Expand Down Expand Up @@ -1657,7 +1660,7 @@ class DistributionPackageInfo:

name: str
version: str
package_type: Literal["sdist", "wheel"]
package_type: str
path: Path
url: str
is_yanked: bool
Expand Down Expand Up @@ -1721,7 +1724,7 @@ def download_info(self) -> dict[str, Any]:

def _process_package_distributions(
requirement: PipRequirement, pip_deps_dir: RootedPath, allow_binary: bool = False
) -> tuple[DistributionPackageInfo, list[DistributionPackageInfo]]:
) -> tuple[Optional[DistributionPackageInfo], list[DistributionPackageInfo]]:
name = requirement.package
version = requirement.version_specs[0][1]
normalized_version = canonicalize_version(version)
Expand All @@ -1734,78 +1737,76 @@ def _process_package_distributions(
except (requests.RequestException, pypi_simple.NoSuchProjectError) as e:
raise FetchError(f"PyPI query failed: {e}")

wheels = []
if allow_binary:
filtered = [
p
for p in packages
if p.version
and canonicalize_version(p.version) == normalized_version
and p.package_type == "wheel"
]
allowed_distros = ["sdist", "wheel"] if allow_binary else ["sdist"]
filtered_packages = filter(
lambda x: x.version is not None
and canonicalize_version(x.version) == normalized_version
and x.package_type is not None
and x.package_type in allowed_distros,
packages,
)

user_checksums = set(map(_to_checksum_info, requirement.hashes))
for wheel in filtered:
pypi_checksums = {
ChecksumInfo(algorithm, digest) for algorithm, digest in wheel.digests.items()
}
wheel_info = DistributionPackageInfo(
name,
version,
"wheel",
pip_deps_dir.join_within_root(wheel.filename).path,
wheel.url,
wheel.is_yanked,
pypi_checksums=pypi_checksums,
user_checksums=user_checksums,
)
sdists: list[DistributionPackageInfo] = []
wheels: list[DistributionPackageInfo] = []

if wheel_info.should_download_wheel():
wheels.append(wheel_info)
else:
log.info("Filtering out %s due to checksum mismatch", wheel.filename)
user_checksums = set(map(_to_checksum_info, requirement.hashes))

if len(filtered) > 0 and len(wheels) == 0:
log.warning("All %s wheel distributions were filtered out", name)
for package in filtered_packages:
pypi_checksums = {
ChecksumInfo(algorithm, digest) for algorithm, digest in package.digests.items()
}

sdists = [
DistributionPackageInfo(
dpi = DistributionPackageInfo(
name,
version,
"sdist",
pip_deps_dir.join_within_root(p.filename).path,
p.url,
p.is_yanked,
cast(str, package.package_type),
pip_deps_dir.join_within_root(package.filename).path,
package.url,
package.is_yanked,
pypi_checksums,
user_checksums,
)
for p in packages
if p.version
and canonicalize_version(p.version) == normalized_version
and p.package_type == "sdist"
]

if not sdists:
raise PackageRejected(
f"No sdists found for package {name}=={version}",
solution=(
"It seems that this version does not exist or isn't published as a sdist "
"(a zip or a tarball).\n"
"You may be able to specify the dependency directly via a URL instead, "
"for example the tarball for a GitHub release."
),
docs=PIP_NO_SDIST_DOC,
)
if dpi.package_type == "sdist":
sdists.append(dpi)
else:
if dpi.should_download_wheel():
wheels.append(dpi)
else:
log.info("Filtering out %s due to checksum mismatch", package.filename)

best_sdist = max(sdists, key=_sdist_preference)
if best_sdist.is_yanked:
raise PackageRejected(
f"All sdists for package {name}=={version} are yanked",
solution=(
f"Please update the {name} version in your requirements file.\n"
"Usually, when a version gets yanked from PyPI, there will already "
"be a fixed version available.\n"
"Otherwise, you may need to pin to the previous version."
),
)
if len(sdists) != 0:
best_sdist = max(sdists, key=_sdist_preference)
if best_sdist.is_yanked:
raise PackageRejected(
f"All sdists for package {name}=={version} are yanked",
Comment on lines +1780 to +1782
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, being yanked is another thing we handle for sdists but not for wheels.

It might be hard to come up with any sane way to handle yanked-ness in an allow_binary context. Maybe we should just log a warning and download yanked things anyway (for consistency: even when allow_binary=False). That's how 'yanked' is supposed to work when the version is pinned, after all. https://peps.python.org/pep-0592/#installers

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But that's probably something for a follow-up story

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, in the scenario that a package has wheels but all sdists are yanked, the request would still fail, right?

Should we file the follow-up story right away so we don't forget about it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

solution=(
f"Please update the {name} version in your requirements file.\n"
"Usually, when a version gets yanked from PyPI, there will already "
"be a fixed version available.\n"
"Otherwise, you may need to pin to the previous version."
),
)
else:
log.warning("No source distributions found for package %s==%s", name, version)
best_sdist = None

if len(wheels) == 0:
if allow_binary:
solution = "Please check that the package exists on PyPI or that the name and version are correct.\n"
docs = None
else:
solution = (
"It seems that this version does not exist or isn't published as a source distribution.\n"
"Try to specify the dependency directly via a URL instead, for example, the tarball for a GitHub release."
)
docs = PIP_NO_SDIST_DOC

raise PackageRejected(
f"No distributions found for package {name}=={version}",
solution=solution,
docs=docs,
)

return best_sdist, wheels

Expand Down
59 changes: 54 additions & 5 deletions tests/unit/package_managers/test_pip.py
Original file line number Diff line number Diff line change
Expand Up @@ -2687,22 +2687,71 @@ def test_process_non_existing_package_distributions(
)

@mock.patch.object(pypi_simple.PyPISimple, "get_project_page")
def test_process_existing_package_without_distributions(
def test_process_existing_package_without_source_distributions(
self,
mock_get_project_page: mock.Mock,
rooted_tmp_path: RootedPath,
caplog: pytest.LogCaptureFixture,
) -> None:
package_name = "aiowsgi"
version = "0.1.0"
mock_requirement = self.mock_requirement(
package_name, "pypi", version_specs=[("==", version)]
)

file_1 = package_name + "-" + version + "-py3-none-any.whl"
file_2 = package_name + "-" + version + "-manylinux1_x86_64.whl"

mock_get_project_page.return_value = pypi_simple.ProjectPage(
package_name,
[
self.mock_pypi_simple_package(file_1, version, "wheel"),
self.mock_pypi_simple_package(file_2, version, "wheel"),
],
None,
None,
)
source, wheels = pip._process_package_distributions(
mock_requirement, rooted_tmp_path, allow_binary=True
)
assert source is None
assert len(wheels) == 2
assert f"No source distributions found for package {package_name}=={version}" in caplog.text

@pytest.mark.parametrize("allow_binary", (True, False))
@mock.patch.object(pypi_simple.PyPISimple, "get_project_page")
def test_process_existing_package_without_any_distributions(
self,
mock_get_project_page: mock.Mock,
allow_binary: bool,
rooted_tmp_path: RootedPath,
caplog: pytest.LogCaptureFixture,
) -> None:
package_name = "aiowsgi"
version = "0.1.0"
mock_requirement = self.mock_requirement(
package_name, "pypi", version_specs=[("==", version)]
)

mock_get_project_page.return_value = pypi_simple.ProjectPage(package_name, [], None, None)
with pytest.raises(PackageRejected) as exc_info:
pip._process_package_distributions(mock_requirement, rooted_tmp_path)
pip._process_package_distributions(
mock_requirement, rooted_tmp_path, allow_binary=allow_binary
)

assert f"No source distributions found for package {package_name}=={version}" in caplog.text
assert (
str(exc_info.value) == f"No distributions found for package {package_name}=={version}"
)

assert str(exc_info.value) == f"No sdists found for package {package_name}=={version}"
if allow_binary:
assert str(exc_info.value.solution) == (
"Please check that the package exists on PyPI or that the name and version are correct.\n"
)
else:
assert str(exc_info.value.solution) == (
"It seems that this version does not exist or isn't published as a source distribution.\n"
"Try to specify the dependency directly via a URL instead, for example, the tarball for a GitHub release."
)

@mock.patch.object(pypi_simple.PyPISimple, "get_project_page")
def test_process_yanked_package_distributions(
Expand Down Expand Up @@ -2834,7 +2883,6 @@ def test_process_package_distributions_with_different_checksums(

assert len(wheels) == 0
assert f"Filtering out {package_name} due to checksum mismatch" in caplog.text
assert f"All {package_name} wheel distributions were filtered out" in caplog.text

@pytest.mark.parametrize(
"noncanonical_version, canonical_version",
Expand Down Expand Up @@ -2885,6 +2933,7 @@ def test_process_package_distributions_noncanonical_version(
)

source, wheels = pip._process_package_distributions(mock_requirement, rooted_tmp_path)
assert source is not None
assert source.version == requested_version
assert all(w.version == requested_version for w in wheels)

Expand Down