Download tasks/data/forward/adamchainz__pip-lock.be3d69f/solution/golden.patch from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adamchainz__pip-lock.be3d69f/solution/golden.patch
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adamchainz__pip-lock.be3d69f/solution/golden.patch
-
curl -L -o golden.patch https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adamchainz__pip-lock.be3d69f/solution/golden.patch
12.7 kB
| diff --git a/src/pip_lock/__init__.py b/src/pip_lock/__init__.py | |
| new file mode 100644 | |
| index 0000000000000000000000000000000000000000..9c5ef0a731b13b98451ecd95c563d9a6f0df2d4a | |
| --- /dev/null | |
| +++ b/src/pip_lock/__init__.py | |
| +from __future__ import annotations | |
| + | |
| +import os | |
| +import re | |
| +import sys | |
| +from collections.abc import Iterable | |
| +from importlib.metadata import distributions as get_distributions | |
| + | |
| + | |
| +def read_pip(filename: str) -> list[str]: | |
| + """Return lines in pip file, concatenating included requirement files.""" | |
| + with open(filename) as f: | |
| + lines = [line.strip() for line in f.readlines()] | |
| + for line in lines: | |
| + if line.startswith("-r "): | |
| + orig_dirpath = os.path.dirname(os.path.realpath(filename)) | |
| + sub_filename = line.split(" ")[1] | |
| + sub_filepath = os.path.join(orig_dirpath, sub_filename) | |
| + lines.extend(read_pip(sub_filepath)) | |
| + return lines | |
| + | |
| + | |
| +VCS_RE = re.compile(r"(|[^ ]+ @ )[\w+]+://") | |
| + | |
| + | |
| +def parse_pip(lines: Iterable[str]) -> dict[str, str]: | |
| + """Return a dictionary of package versions.""" | |
| + versions = {} | |
| + for line in lines: | |
| + line = line.strip() | |
| + | |
| + if len(line) == 0 or line.startswith(("#", "-")): | |
| + continue | |
| + | |
| + if line.startswith(("http://", "https://")): | |
| + continue | |
| + | |
| + if VCS_RE.match(line): | |
| + continue | |
| + | |
| + full_name, version_and_extras = line.split("==", 1) | |
| + # Strip extras and normalize | |
| + name = normalize_name(full_name.split("[", 1)[0]) | |
| + version = version_and_extras.split(" ", 1)[0] | |
| + versions[name] = version | |
| + | |
| + return versions | |
| + | |
| + | |
| +def get_installed() -> dict[str, str]: | |
| + return {normalize_name(d.metadata["Name"]): d.version for d in get_distributions()} | |
| + | |
| + | |
| +def normalize_name(name: str) -> str: | |
| + return name.lower().replace("_", "-").replace(".", "-") | |
| + | |
| + | |
| +def get_mismatches(requirements_file_path: str) -> dict[str, tuple[str, str | None]]: | |
| + """Return a dictionary of requirement mismatches.""" | |
| + pip_lines = read_pip(requirements_file_path) | |
| + expected = parse_pip(pip_lines) | |
| + installed = get_installed() | |
| + | |
| + mismatches: dict[str, tuple[str, str | None]] = {} | |
| + for name, expected_version in expected.items(): | |
| + installed_version = installed.get(name) | |
| + if installed_version is None: | |
| + mismatches[name] = (expected_version, None) | |
| + elif installed_version != expected_version: | |
| + mismatches[name] = (expected_version, installed_version) | |
| + | |
| + return mismatches | |
| + | |
| + | |
| +def print_errors( | |
| + errors: list[str], | |
| + pre_text: str | None = None, | |
| + post_text: str | None = None, | |
| +) -> None: | |
| + """Print list of errors to stderr with optional pre_text and post_text.""" | |
| + sys.stderr.write("\033[91m") # red text | |
| + if pre_text: | |
| + sys.stderr.write(pre_text + "\n") | |
| + for message in errors: | |
| + sys.stderr.write(f" * {message}\n") | |
| + if post_text: | |
| + sys.stderr.write(post_text) | |
| + sys.stderr.write("\033[0m") | |
| + | |
| + | |
| +def check_requirements(requirements_file_path: str, post_text: str = "") -> None: | |
| + """ | |
| + Print errors and exit program if there are mismatches with the requirements | |
| + file. | |
| + """ | |
| + mismatches = get_mismatches(requirements_file_path) | |
| + if mismatches: | |
| + errors = [] | |
| + for name, (expected, actual) in mismatches.items(): | |
| + if actual is None: | |
| + errors.append( | |
| + f"Package {name} is in {requirements_file_path} but not in virtualenv" | |
| + ) | |
| + continue | |
| + | |
| + if expected != actual: | |
| + msg = ( | |
| + "Package {0} has version {1} but you have version {2} " | |
| + + "installed." | |
| + ).format(name, expected, actual) | |
| + errors.append(msg) | |
| + | |
| + print_errors( | |
| + errors, | |
| + f"There are requirement mismatches with {requirements_file_path}", | |
| + post_text, | |
| + ) | |
| + sys.exit(1) | |
| diff --git a/tests/__init__.py b/tests/__init__.py | |
| new file mode 100644 | |
| index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 | |
| diff --git a/tests/test_pip_lock.py b/tests/test_pip_lock.py | |
| new file mode 100644 | |
| index 0000000000000000000000000000000000000000..f6f15ad9eba3318e2994e9aea1cce19ef63ed2b9 | |
| --- /dev/null | |
| +++ b/tests/test_pip_lock.py | |
| +from __future__ import annotations | |
| + | |
| +from collections.abc import Generator | |
| +from contextlib import contextmanager | |
| +from email.message import EmailMessage | |
| +from types import SimpleNamespace | |
| +from unittest import mock | |
| + | |
| +import pytest | |
| + | |
| +from pip_lock import ( | |
| + check_requirements, | |
| + get_installed, | |
| + get_mismatches, | |
| + parse_pip, | |
| + print_errors, | |
| + read_pip, | |
| +) | |
| + | |
| + | |
| +@contextmanager | |
| +def mock_get_distributions(versions: dict[str, str]) -> Generator[None]: | |
| + def fake_get_distributions(): | |
| + dists = [] | |
| + for name, version in versions.items(): | |
| + metadata = EmailMessage() | |
| + metadata["Name"] = name | |
| + dists.append(SimpleNamespace(metadata=metadata, version=version)) | |
| + return iter(dists) | |
| + | |
| + with mock.patch("pip_lock.get_distributions", fake_get_distributions): | |
| + yield | |
| + | |
| + | |
| +class TestReadPip: | |
| + def test_read(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package1==1.0\npackage2==1.1\n") | |
| + assert read_pip(str(requirements)) == ["package1==1.0", "package2==1.1"] | |
| + | |
| + def test_include(self, tmp_path): | |
| + requirements_inc = tmp_path / "requirements_inc.txt" | |
| + requirements_inc.write_text("other-package==1.0\n") | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text(f"-r {requirements_inc}\n") | |
| + | |
| + assert read_pip(str(requirements)) == [ | |
| + f"-r {requirements_inc}", | |
| + "other-package==1.0", | |
| + ] | |
| + | |
| + def test_empty(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("\n") | |
| + assert read_pip(str(requirements)) == [""] | |
| + | |
| + | |
| +class TestParsePip: | |
| + def test_version(self): | |
| + assert parse_pip(["package1==1.0", "package2==1.1"]) == { | |
| + "package1": "1.0", | |
| + "package2": "1.1", | |
| + } | |
| + | |
| + def test_normalize_dashes(self): | |
| + assert parse_pip(["package_one==1.0"]) == { | |
| + "package-one": "1.0", | |
| + } | |
| + | |
| + def test_normalize_dots(self): | |
| + assert parse_pip(["foo.bar==1.0"]) == { | |
| + "foo-bar": "1.0", | |
| + } | |
| + | |
| + def test_ignore_empty(self): | |
| + assert parse_pip([""]) == {} | |
| + | |
| + def test_ignore_comments(self): | |
| + assert parse_pip(["# Comment"]) == {} | |
| + | |
| + def test_ignore_includes(self): | |
| + assert parse_pip(["-r example.txt"]) == {} | |
| + | |
| + def test_ignore_arguments(self): | |
| + assert parse_pip(["--find-links file:./wheels"]) == {} | |
| + | |
| + def test_ignore_http_urls(self): | |
| + assert parse_pip(["http://www.google.com"]) == {} | |
| + | |
| + def test_ignore_https_urls(self): | |
| + assert parse_pip(["https://www.google.com"]) == {} | |
| + | |
| + def test_ignore_bzr_http_urls(self): | |
| + url = "bzr+http://bzr.example.com" | |
| + assert parse_pip([url]) == {} | |
| + | |
| + def test_ignore_git_https_urls(self): | |
| + url = "git+https://git@github.com/adamchainz/pip-lock.git@80361b8#egg=pip-lock" | |
| + assert parse_pip([url]) == {} | |
| + | |
| + def test_ignore_at_git_ssh_urls(self): | |
| + assert parse_pip(["foo @ git+ssh://example.com"]) == {} | |
| + | |
| + def test_ignore_at_https_urls(self): | |
| + assert parse_pip(["foo @ https://example.com"]) == {} | |
| + | |
| + | |
| +class TestGetInstalled: | |
| + def test_single(self): | |
| + with mock_get_distributions({"package": "1.0.0"}): | |
| + result = get_installed() | |
| + | |
| + assert result == {"package": "1.0.0"} | |
| + | |
| + def test_several(self): | |
| + versions = {"package-one": "1.0.0", "package-two": "2.0.0"} | |
| + with mock_get_distributions(versions): | |
| + result = get_installed() | |
| + | |
| + assert result == {"package-one": "1.0.0", "package-two": "2.0.0"} | |
| + | |
| + def test_normalize_case(self): | |
| + # importlib.metadata should already lowercase names, but we do so to | |
| + # be sure | |
| + with mock_get_distributions({"Package": "1.0.0"}): | |
| + result = get_installed() | |
| + | |
| + assert result == {"package": "1.0.0"} | |
| + | |
| + def test_normalize_underscore(self): | |
| + with mock_get_distributions({"package_one": "1.0.0"}): | |
| + result = get_installed() | |
| + | |
| + assert result == {"package-one": "1.0.0"} | |
| + | |
| + def test_normalize_dots(self): | |
| + with mock_get_distributions({"package.one": "1.0.0"}): | |
| + result = get_installed() | |
| + | |
| + assert result == {"package-one": "1.0.0"} | |
| + | |
| + | |
| +class TestGetMismatches: | |
| + def test_relative_requirements_file(self, monkeypatch, tmp_path): | |
| + monkeypatch.chdir(tmp_path) | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package==1.2\n") | |
| + | |
| + with mock_get_distributions({"package": "1.1"}): | |
| + result = get_mismatches("requirements.txt") | |
| + | |
| + assert result == {"package": ("1.2", "1.1")} | |
| + | |
| + def test_version_mismatch(self, monkeypatch, tmp_path): | |
| + monkeypatch.chdir(tmp_path) | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package==1.2\n") | |
| + | |
| + with mock_get_distributions({"package": "1.1"}): | |
| + result = get_mismatches("requirements.txt") | |
| + | |
| + assert result == {"package": ("1.2", "1.1")} | |
| + | |
| + def test_missing(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package==1.1\n") | |
| + | |
| + with mock_get_distributions({}): | |
| + result = get_mismatches(str(requirements)) | |
| + | |
| + assert result == {"package": ("1.1", None)} | |
| + | |
| + def test_no_mismatches(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package==1.1\n") | |
| + | |
| + with mock_get_distributions({"package": "1.1"}): | |
| + result = get_mismatches(str(requirements)) | |
| + | |
| + assert result == {} | |
| + | |
| + def test_no_mismatches_case_insensitive(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package==1.1\n") | |
| + | |
| + with mock_get_distributions({"Package": "1.1"}): | |
| + result = get_mismatches(str(requirements)) | |
| + | |
| + assert result == {} | |
| + | |
| + def test_empty(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("\n") | |
| + | |
| + with mock_get_distributions({}): | |
| + result = get_mismatches(str(requirements)) | |
| + | |
| + assert result == {} | |
| + | |
| + def test_package_with_extra(self, tmp_path): | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package[anextra]==1.1\n") | |
| + | |
| + with mock_get_distributions({"package": "1.1"}): | |
| + result = get_mismatches(str(requirements)) | |
| + | |
| + assert result == {} | |
| + | |
| + | |
| +class TestPrintErrors: | |
| + def test_errors(self, capsys): | |
| + print_errors(["error message 1", "error message 2"]) | |
| + _, err = capsys.readouterr() | |
| + assert "error message 1" in err | |
| + assert "error message 2" in err | |
| + | |
| + def test_pre_post_text(self, capsys): | |
| + print_errors(["error message"], "pre text", "post text") | |
| + _, err = capsys.readouterr() | |
| + assert "error message" in err | |
| + assert "pre text" in err | |
| + assert "post text" in err | |
| + | |
| + | |
| +class TestCheckRequirements: | |
| + @mock.patch("pip_lock.get_mismatches") | |
| + def test_no_mismatches(self, get_mismatches): | |
| + get_mismatches.return_value = {} | |
| + check_requirements("requirements.txt") | |
| + | |
| + @mock.patch("pip_lock.get_mismatches") | |
| + def test_mismatches(self, get_mismatches, capsys): | |
| + get_mismatches.return_value = { | |
| + "package1": ("1.1", "1.0"), | |
| + "package2": ("1.0", None), | |
| + } | |
| + with pytest.raises(SystemExit): | |
| + check_requirements("requirements.txt") | |
| + | |
| + _, err = capsys.readouterr() | |
| + assert "package1 has version 1.1 but you have version 1.0 installed" in err | |
| + assert "package2 is in requirements.txt but not in virtualenv" in err | |
| + | |
| + def test_relative_requirements_file(self, monkeypatch, tmp_path): | |
| + monkeypatch.chdir(tmp_path) | |
| + requirements = tmp_path / "requirements.txt" | |
| + requirements.write_text("package==1.2\n") | |
| + with mock_get_distributions({"package": "1.2"}): | |
| + check_requirements("requirements.txt") | |