From e0a60ff457210b0c10c84085ab8474627c6cf4bc Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Wed, 18 Nov 2026 18:58:57 +0100 Subject: [PATCH 1/4] fix: do not mirror the latest version for multi-line requirements A requirement can list its specifiers on continuation lines: [requirements] foo = ==2.0 ==2.1 configparser returns the value of this key as "\n==2.0\n==2.1", and splitlines() turns it into ["", "==2.0", "==2.1"]. mirror() called Mirrorer.mirror() once for each entry, so the empty first entry mirrored "foo" without a specifier. morgan therefore downloaded the latest release of foo in addition to 2.0 and 2.1. Drop empty lines before mirroring. A key without any value, such as "morgan =", still mirrors the latest version. Co-Authored-By: Claude Fable 5.2 --- morgan/__init__.py | 7 ++++-- tests/test_init.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/morgan/__init__.py b/morgan/__init__.py index 535eb76..8dc7a3c 100644 --- a/morgan/__init__.py +++ b/morgan/__init__.py @@ -892,7 +892,10 @@ def mirror(args: argparse.Namespace): msg = f"Config file {args.config} has no [requirements] section" raise ValueError(msg) 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 +907,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() diff --git a/tests/test_init.py b/tests/test_init.py index a7b229d..2d1a60a 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1353,3 +1353,57 @@ 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, + 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" + ) From 1bd8f99e17e111f02b2e932f4b3cd1d2a10b41a2 Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Wed, 18 Nov 2026 18:58:57 +0100 Subject: [PATCH 2/4] feat: add --no-deps to mirror only the listed requirements morgan mirrors the dependencies of every requirement, and for each dependency it downloads the latest version that matches the dependency's specifier. This is unwanted when the [requirements] section already is a complete set of pinned versions, for example one generated from a lock file. With "bar = ==1.0" and "foo = ==2.0" in the config, and bar depending on "foo>=2.0", morgan downloads foo 2.0 and also the latest release of foo. Add the --no-deps flag to "morgan mirror". With the flag, Mirrorer._process_file returns no dependencies, so only the packages listed in [requirements] are mirrored. This also leaves out extras and the build requirements of source distributions. The .metadata file next to each downloaded file is still written, so that clients can resolve dependencies without downloading the archive (PEP 658). With --use-pypi-metadata, the request to PyPI's JSON API is skipped, because morgan uses its response only to find dependencies. Mirrorer reads the option with getattr(), because library callers build the argparse.Namespace by hand, and reading a missing attribute directly would raise an AttributeError for them. Suggested-by: shamilbi Link: https://github.com/python-morgan/morgan/issues/112 Co-Authored-By: Claude Fable 5.2 --- morgan/__init__.py | 24 +++ tests/test_init.py | 236 +++++++++++++++++++++++++++++ tests/test_pypi_metadata_parser.py | 1 + 3 files changed, 261 insertions(+) diff --git a/morgan/__init__.py b/morgan/__init__.py index 8dc7a3c..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,6 +902,8 @@ 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"]: # The multiline form below starts with a blank line, which would # mirror the latest version of the package. @@ -1034,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 2d1a60a..24e9b9f 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 @@ -1407,3 +1410,236 @@ def fake_mirror(_self, requirement_string): "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 From 35f5e4a4c055eb9fbd694e454bcc0e8701bb6139 Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Wed, 18 Nov 2026 18:58:57 +0100 Subject: [PATCH 3/4] docs: describe --no-deps in the README The README describes the mirroring of dependencies as unconditional and does not mention the --no-deps flag. Add the section "Mirroring Only the Listed Requirements". It says when to use the flag. It also says that morgan then does not mirror the build requirements of source distributions, because a lock file usually does not list them and clients that build a package from source fail without them. Mention the flag in the feature list as well. Co-Authored-By: Claude Fable 5.2 --- README.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) 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 From 408c6bb1d724a2c61467c801c9b192d4465030cf Mon Sep 17 00:00:00 2001 From: Christian Schmidbauer Date: Mon, 23 Nov 2026 14:23:23 +0100 Subject: [PATCH 4/4] fixup! fix: do not mirror the latest version for multi-line requirements --- tests/test_init.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_init.py b/tests/test_init.py index 24e9b9f..d9ca305 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1386,6 +1386,7 @@ def test_mirror_splits_requirement_lines(self, tmp_path, monkeypatch): 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,