diff --git a/README.md b/README.md index 42209a2..b8d0d21 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ * [Setting Up Multiple Mirrors](#setting-up-multiple-mirrors) * [Mirroring From Other Indexes](#mirroring-from-other-indexes) * [Prereleases](#prereleases) + * [Mirroring Only the Listed Requirements](#mirroring-only-the-listed-requirements) * [How Does Morgan Resolve Dependencies?](#how-does-morgan-resolve-dependencies) * [Limitations](#limitations) * [Why Not Use X?](#why-not-use-x) @@ -47,7 +48,7 @@ the mirror instead of pypi.org, which they can't access anyway. - Package index contains a **configuration file** that lists **markers** for different client **environments** and a list of **package requirement strings** as per [PEP 508](https://peps.python.org/pep-0508/). - Mirrorer automatically and **recursively mirrors dependencies** of all direct - requirements. + requirements. This can be turned off with `--no-deps`. - Only mirrors **optional dependencies** if they were part of the requirement strings (a.k.a "extras"), or are relevant to the environment markers. This is true for direct requirements and for dependencies of dependencies. @@ -193,6 +194,18 @@ mirrored only if one of the following applies: 3. No final release satisfies the requirement, e.g. because the package has only published prereleases. +### Mirroring Only the Listed Requirements + +Morgan also mirrors the latest matching version of every dependency, even if +the `[requirements]` section pins that dependency to another version. If the +section already is a complete set of pinned versions, for example one +generated from a lock file, provide the `--no-deps` flag to mirror only the +listed requirements. + +Morgan then does not mirror the build requirements of source distributions +either, such as setuptools or hatchling. Add them to `[requirements]` if the +clients have to build a package from source. + ## How Does Morgan Resolve Dependencies? Dependency resolution in Python is hard. The standard for specifying dependencies diff --git a/morgan/__init__.py b/morgan/__init__.py index 535eb76..e38a028 100644 --- a/morgan/__init__.py +++ b/morgan/__init__.py @@ -140,10 +140,14 @@ def __init__(self, args: argparse.Namespace): self._processed_pkgs = Cache(allow_prereleases=self.prerelease) self.target_registry: Registry = self._find_target_registry(args) self.use_pypi_metadata: bool = args.use_pypi_metadata or False + # Library callers build the Namespace by hand, so no_deps may be missing. + self.no_deps: bool = getattr(args, "no_deps", False) def mirror(self, requirement_string: str): """ Mirror a package according to a PEP 508-compliant requirement string. + Dependencies of the package are mirrored recursively, unless no_deps + is set. """ requirement = parse_requirement(requirement_string) @@ -670,6 +674,13 @@ def _process_file( ): self._download_file(fileinfo, filepath, hashalg) + if self.no_deps: + if not self.use_pypi_metadata: + # The result is not needed, but the call writes the .metadata + # file that the server serves to clients. + self._extract_metadata_from_file(filepath) + return None + if self.use_pypi_metadata: pkg_metadata = self._extract_metadata_from_pypi( requirement.name, @@ -891,8 +902,13 @@ def mirror(args: argparse.Namespace): if not m.config.has_section("requirements"): msg = f"Config file {args.config} has no [requirements] section" raise ValueError(msg) + if m.no_deps: + print("Not following dependencies (--no-deps)") for package in m.config["requirements"]: - reqs = m.config["requirements"][package].splitlines() + # The multiline form below starts with a blank line, which would + # mirror the latest version of the package. + reqs = [req.strip() for req in m.config["requirements"][package].splitlines()] + reqs = [req for req in reqs if req] if not reqs: # empty requirements # morgan = @@ -904,7 +920,7 @@ def mirror(args: argparse.Namespace): # >=2 # [brotli] # noqa: ERA001 for req in reqs: - m.mirror(f"{package}{req.strip()}") + m.mirror(f"{package}{req}") if not args.skip_server_copy: m.copy_server() @@ -1031,6 +1047,17 @@ def my_url(arg): "dependencies like poetry) are not considered package dependencies by PyPI." ), ) + parser.add_argument( + "--no-deps", + dest="no_deps", + action="store_true", + help=( + "Only mirror the packages listed in the [requirements] section and do " + "not follow their dependencies (including extras and build " + "requirements). Use this when the requirements are a complete, pinned " + "set, e.g. generated from a lock file." + ), + ) server.add_arguments(parser) configurator.add_arguments(parser) diff --git a/tests/test_init.py b/tests/test_init.py index a7b229d..d9ca305 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -4,6 +4,7 @@ # pylint: disable=missing-function-docstring,missing-class-docstring,missing-module-docstring from __future__ import annotations +import argparse import contextlib import email.message import hashlib @@ -11,8 +12,10 @@ import json import os import re +import sys import urllib.error import urllib.request +import zipfile import packaging.requirements import packaging.tags @@ -1353,3 +1356,291 @@ def test_mirror_reports_missing_requirements_section( with pytest.raises(ValueError, match=r"no \[requirements\] section"): morgan.mirror(args) + + +class TestMirrorRequirementLines: + def test_mirror_splits_requirement_lines(self, tmp_path, monkeypatch): + config_path = os.path.join(tmp_path, "morgan.ini") + with open(config_path, "w", encoding="utf-8") as f: + f.write( + """ + [env.test_env] + python_version = 3.10 + sys_platform = linux + platform_machine = x86_64 + + [requirements] + foo = + ==2.0 + ==2.1 + qux = ==1 + qux = ==2 + bar = ==1.0 + baz = + """, + ) + args = argparse.Namespace( + index_path=str(tmp_path), + index_url=PYPI_ADDRESS, + config=config_path, + mirror_all_versions=False, + package_type_regex=r"(whl|zip|tar\.gz)", + mirror_all_wheels=False, + prerelease=False, + target_url=None, + use_pypi_metadata=False, + skip_server_copy=True, + ) + recorded = [] + + def fake_mirror(_self, requirement_string): + recorded.append(requirement_string) + + monkeypatch.setattr(Mirrorer, "mirror", fake_mirror) + + morgan.mirror(args) + + assert recorded == [ + "foo==2.0", + "foo==2.1", + "qux==1", + "qux==2", + "bar==1.0", + "baz", + ], ( + "mirror() must be called once for every non-empty line, and not " + "for an empty line" + ) + + +class _FakeResponse: + """Replaces the HTTP response that urllib.request.urlopen returns.""" + + def __init__(self, url, body): + self.url = url + self._body = body + + def read(self): + return self._body + + def __enter__(self): + return self + + def __exit__(self, *_exc_info): + return None + + +class _FakeMetadata: + """Replaces metadata.MetadataParser and returns fixed dependencies.""" + + def __init__(self, deps): + self._deps = deps + + def dependencies(self, extras, envs): + return {parse_requirement(dep) for dep in self._deps} + + +# The versions of each package that the fake index in TestNoDeps serves. +NO_DEPS_INDEX = { + "bar": ["1.0"], + "foo": ["2.0", "2.1"], +} +# The dependencies that each package declares in TestNoDeps. +NO_DEPS_DEPENDENCIES = { + "bar": ["foo>=2.0"], + "foo": [], +} + + +class TestNoDeps: + @pytest.fixture + def config_path(self, tmp_path): + config_path = os.path.join(tmp_path, "morgan.ini") + with open(config_path, "w", encoding="utf-8") as f: + f.write( + """ + [env.test_env] + python_version = 3.10 + sys_platform = linux + platform_machine = x86_64 + + [requirements] + bar = ==1.0 + foo = ==2.0 + """, + ) + return config_path + + @pytest.fixture + def make_args(self, tmp_path, config_path): + def _make_args(**overrides): + kwargs = { + "index_path": str(tmp_path), + "index_url": PYPI_ADDRESS, + "config": config_path, + "mirror_all_versions": False, + "package_type_regex": r"(whl|zip|tar\.gz)", + "mirror_all_wheels": False, + "prerelease": False, + "target_url": None, + "use_pypi_metadata": False, + "skip_server_copy": True, + } + kwargs.update(overrides) + return argparse.Namespace(**kwargs) + + return _make_args + + @pytest.fixture + def downloads(self, monkeypatch): + """ + Replace the index, the download and the metadata parser with fakes + that serve the packages in NO_DEPS_INDEX. Return the list that + collects the name of every file the mirrorer downloads. + """ + downloaded = [] + + def fake_urlopen(request, timeout=None): + name = request.full_url.rstrip("/").rsplit("/", 1)[-1] + files = [ + { + "filename": f"{name}-{version}-py3-none-any.whl", + "url": f"{name}-{version}-py3-none-any.whl", + "hashes": {"sha256": "0" * 64}, + } + for version in NO_DEPS_INDEX[name] + ] + body = json.dumps( + {"meta": {"api-version": "1.0"}, "name": name, "files": files}, + ).encode() + return _FakeResponse(request.full_url, body) + + def fake_download_file(_self, fileinfo, target, hashalg): + downloaded.append(fileinfo["filename"]) + return True + + def fake_extract_metadata_from_file(_self, filepath): + name = os.path.basename(filepath).split("-", 1)[0] + return _FakeMetadata(NO_DEPS_DEPENDENCIES[name]) + + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + monkeypatch.setattr(Mirrorer, "_download_file", fake_download_file) + monkeypatch.setattr( + Mirrorer, + "_extract_metadata_from_file", + fake_extract_metadata_from_file, + ) + return downloaded + + @staticmethod + def make_fileinfo(filename): + return { + "filename": filename, + "url": f"https://example.com/{filename}", + "hashes": {"sha256": "0" * 64}, + "version": packaging.version.Version("1.0"), + } + + @pytest.mark.parametrize( + ("no_deps", "expected"), + [ + ( + True, + ["bar-1.0-py3-none-any.whl", "foo-2.0-py3-none-any.whl"], + ), + ( + False, + [ + "bar-1.0-py3-none-any.whl", + "foo-2.0-py3-none-any.whl", + "foo-2.1-py3-none-any.whl", + ], + ), + ], + ids=["no_deps", "with_deps"], + ) + def test_mirror_only_listed_requirements( + self, + make_args, + downloads, + no_deps, + expected, + ): + morgan.mirror(make_args(no_deps=no_deps)) + + assert sorted(downloads) == expected + + def test_dependencies_followed_without_attribute(self, make_args, downloads): + # library callers may build the Namespace without no_deps + morgan.mirror(make_args()) + + assert "foo-2.1-py3-none-any.whl" in downloads + + def test_metadata_file_is_written(self, make_args, tmp_path, monkeypatch): + filename = "x-1.0-py3-none-any.whl" + pkgdir = os.path.join(tmp_path, "x") + os.makedirs(pkgdir) + filepath = os.path.join(pkgdir, filename) + with zipfile.ZipFile(filepath, "w") as whl: + whl.writestr( + "x-1.0.dist-info/METADATA", + "Metadata-Version: 2.1\n" + "Name: x\n" + "Version: 1.0\n" + "Requires-Dist: foo>=2.0\n", + ) + + mirrorer = Mirrorer(make_args(no_deps=True)) + monkeypatch.setattr(mirrorer, "_download_file", lambda *_args: True) + + # pylint: disable=W0212 + result = mirrorer._process_file( # noqa: SLF001 + parse_requirement("x==1.0"), + self.make_fileinfo(filename), + ) + + assert result is None + assert os.path.isfile(f"{filepath}.metadata") + + def test_no_pypi_metadata_request(self, make_args, monkeypatch): + mirrorer = Mirrorer(make_args(no_deps=True, use_pypi_metadata=True)) + monkeypatch.setattr(mirrorer, "_download_file", lambda *_args: True) + pypi_requests = [] + + def fake_extract_metadata_from_pypi(package, version): + pypi_requests.append(package) + return _FakeMetadata(["foo>=2.0"]) + + monkeypatch.setattr( + mirrorer, + "_extract_metadata_from_pypi", + fake_extract_metadata_from_pypi, + ) + + # pylint: disable=W0212 + result = mirrorer._process_file( # noqa: SLF001 + parse_requirement("x==1.0"), + self.make_fileinfo("x-1.0-py3-none-any.whl"), + ) + + assert result is None + assert pypi_requests == [] + + @pytest.mark.parametrize( + ("extra_argv", "expected"), + [([], False), (["--no-deps"], True)], + ids=["without_flag", "with_flag"], + ) + def test_cli_flag(self, config_path, tmp_path, monkeypatch, extra_argv, expected): + captured: list[argparse.Namespace] = [] + monkeypatch.setattr(morgan, "mirror", captured.append) + monkeypatch.setattr( + sys, + "argv", + ["morgan", "-i", str(tmp_path), *extra_argv, "mirror"], + ) + + morgan.main() + + assert len(captured) == 1 + assert captured[0].no_deps is expected diff --git a/tests/test_pypi_metadata_parser.py b/tests/test_pypi_metadata_parser.py index be50b09..c7c8811 100644 --- a/tests/test_pypi_metadata_parser.py +++ b/tests/test_pypi_metadata_parser.py @@ -277,6 +277,7 @@ def mirrorer_args(self): args.config = "morgan.ini" args.target_url = None args.use_pypi_metadata = True + args.no_deps = False return args @pytest.fixture