|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.12" |
| 3 | +# /// |
| 4 | +"""Run one released downstream project's GitPython tests in an isolated uv environment.""" |
| 5 | + |
| 6 | +import argparse |
| 7 | +import hashlib |
| 8 | +import json |
| 9 | +import os |
| 10 | +from pathlib import Path |
| 11 | +import re |
| 12 | +import shlex |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +import tarfile |
| 16 | +import tempfile |
| 17 | +from urllib.parse import quote, urlparse |
| 18 | +from urllib.request import urlopen |
| 19 | +import xml.etree.ElementTree as ET |
| 20 | + |
| 21 | + |
| 22 | +HERE = Path(__file__).resolve().parent |
| 23 | +CHECKOUT = HERE.parent.parent |
| 24 | + |
| 25 | + |
| 26 | +def run(command, *, cwd=None, env=None, check=True, **kwargs): |
| 27 | + print("+", shlex.join(map(str, command)), flush=True) |
| 28 | + return subprocess.run(command, cwd=cwd, env=env, check=check, **kwargs) |
| 29 | + |
| 30 | + |
| 31 | +def release_metadata(distribution, version): |
| 32 | + suffix = "" if version is None else "/" + quote(version, safe="") |
| 33 | + url = f"https://pypi.org/pypi/{distribution}{suffix}/json" |
| 34 | + with urlopen(url, timeout=60) as response: |
| 35 | + metadata = json.load(response) |
| 36 | + version = metadata["info"]["version"] |
| 37 | + if not re.fullmatch(r"[0-9][A-Za-z0-9.!+_-]*", version): |
| 38 | + raise ValueError(f"Unexpected release version: {version!r}") |
| 39 | + return metadata, version |
| 40 | + |
| 41 | + |
| 42 | +def source_tree(profile, metadata, version, work, env): |
| 43 | + source = work / "source" |
| 44 | + if profile["source"] == "git": |
| 45 | + tag = profile["tag"].format(version=version) |
| 46 | + run( |
| 47 | + [ |
| 48 | + "git", |
| 49 | + "-c", |
| 50 | + f"core.hooksPath={os.devnull}", |
| 51 | + "clone", |
| 52 | + "--depth=1", |
| 53 | + "--branch", |
| 54 | + tag, |
| 55 | + "--", |
| 56 | + profile["repository"], |
| 57 | + str(source), |
| 58 | + ], |
| 59 | + env=env, |
| 60 | + ) |
| 61 | + commit = run( |
| 62 | + ["git", "-C", str(source), "rev-parse", "HEAD"], env=env, capture_output=True, text=True |
| 63 | + ).stdout.strip() |
| 64 | + return source, {"repository": profile["repository"], "tag": tag, "commit": commit} |
| 65 | + |
| 66 | + sdist = next(item for item in metadata["urls"] if item["packagetype"] == "sdist" and not item["yanked"]) |
| 67 | + url = urlparse(sdist["url"]) |
| 68 | + if url.scheme != "https" or url.hostname != "files.pythonhosted.org": |
| 69 | + raise ValueError("Expected an HTTPS source archive hosted by PyPI") |
| 70 | + archive = work / "source.tar.gz" |
| 71 | + digest = hashlib.sha256() |
| 72 | + with urlopen(sdist["url"], timeout=60) as response, archive.open("wb") as output: |
| 73 | + while block := response.read(1024 * 1024): |
| 74 | + digest.update(block) |
| 75 | + output.write(block) |
| 76 | + if digest.hexdigest() != sdist["digests"]["sha256"]: |
| 77 | + raise ValueError("Source archive does not match PyPI's SHA-256 digest") |
| 78 | + source.mkdir() |
| 79 | + with tarfile.open(archive) as contents: |
| 80 | + contents.extractall(source, filter="data") |
| 81 | + roots = list(source.iterdir()) |
| 82 | + if len(roots) != 1 or not roots[0].is_dir(): |
| 83 | + raise ValueError("Expected one source directory in the release archive") |
| 84 | + return roots[0], {"url": sdist["url"], "sha256": digest.hexdigest()} |
| 85 | + |
| 86 | + |
| 87 | +def main(): |
| 88 | + profiles = json.loads((HERE / "projects.json").read_text()) |
| 89 | + parser = argparse.ArgumentParser(description=__doc__) |
| 90 | + parser.add_argument("project", choices=profiles) |
| 91 | + parser.add_argument("--version", help="Release to reproduce; defaults to PyPI's latest release") |
| 92 | + parser.add_argument("--python", default="3.12", help="Python used by the isolated test environment") |
| 93 | + parser.add_argument("--work-dir", type=Path, help="New directory for retained source, environment, and results") |
| 94 | + args = parser.parse_args() |
| 95 | + profile = profiles[args.project] |
| 96 | + metadata, version = release_metadata(profile["distribution"], args.version) |
| 97 | + if args.work_dir: |
| 98 | + work = args.work_dir.resolve() |
| 99 | + work.mkdir(parents=True) |
| 100 | + else: |
| 101 | + cache = CHECKOUT / ".cache" / "downstream" |
| 102 | + cache.mkdir(parents=True, exist_ok=True) |
| 103 | + work = Path(tempfile.mkdtemp(prefix=f"{args.project}-{version}-", dir=cache)) |
| 104 | + print(f"Testing {args.project} {version}; retained work directory: {work}", flush=True) |
| 105 | + |
| 106 | + config = work / "gitconfig" |
| 107 | + config.write_text( |
| 108 | + "[user]\n\tname = GitPython downstream tests\n\temail = tests@example.invalid\n" |
| 109 | + "[init]\n\tdefaultBranch = master\n[commit]\n\tgpgSign = false\n" |
| 110 | + ) |
| 111 | + # Do not let inherited Git settings redirect upstream resets or commits into |
| 112 | + # the caller's repository, index, object database, configuration, or hooks. |
| 113 | + env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} |
| 114 | + env.pop("PYTHONPATH", None) |
| 115 | + env.pop("PYTHONHOME", None) |
| 116 | + env.update(GIT_CONFIG_GLOBAL=str(config), GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0") |
| 117 | + source, provenance = source_tree(profile, metadata, version, work, env) |
| 118 | + venv = work / "venv" |
| 119 | + run(["uv", "venv", "--python", args.python, str(venv)], env=env) |
| 120 | + bin_dir = venv / ("Scripts" if os.name == "nt" else "bin") |
| 121 | + python = bin_dir / ("python.exe" if os.name == "nt" else "python") |
| 122 | + env["PATH"] = str(bin_dir) + os.pathsep + env["PATH"] |
| 123 | + env["GITPYTHON_CHECKOUT"] = str(CHECKOUT) |
| 124 | + for key in profile.get("unset_env", []): |
| 125 | + env.pop(key, None) |
| 126 | + env.update(profile.get("env", {})) |
| 127 | + |
| 128 | + def expand(value): |
| 129 | + return value.format(version=version, source=source, checks=HERE / "checks") |
| 130 | + |
| 131 | + install = ["uv", "pip", "install", "--python", str(python)] |
| 132 | + run(install + list(map(expand, profile["install"])), env=env) |
| 133 | + if profile.get("no_deps"): |
| 134 | + run(install + ["--no-deps"] + list(map(expand, profile["no_deps"])), env=env) |
| 135 | + # Replace the released dependency even if the downstream pins another version. |
| 136 | + run(install + ["--reinstall-package", "gitpython", "-e", str(CHECKOUT)], env=env) |
| 137 | + |
| 138 | + # Check the import used by tests and by downstream Python subprocesses. |
| 139 | + run( |
| 140 | + [ |
| 141 | + str(python), |
| 142 | + "-c", |
| 143 | + "import os, pathlib, git; " |
| 144 | + "expected = pathlib.Path(os.environ['GITPYTHON_CHECKOUT']) / 'git' / '__init__.py'; " |
| 145 | + "assert pathlib.Path(git.__file__).resolve() == expected.resolve(), git.__file__; " |
| 146 | + "print('GitPython:', git.__file__); print(git.Git().version()); " |
| 147 | + "assert git.Git().version_info >= (2, 52), 'Git 2.52 or newer is required'", |
| 148 | + ], |
| 149 | + cwd=source, |
| 150 | + env=env, |
| 151 | + ) |
| 152 | + with (work / "requirements-frozen.txt").open("w") as output: |
| 153 | + run(["uv", "pip", "freeze", "--python", str(python)], env=env, stdout=output) |
| 154 | + result = {"project": args.project, "version": version, "source": provenance, "gitpython": str(CHECKOUT)} |
| 155 | + result_path = work / "result.json" |
| 156 | + result_path.write_text(json.dumps(result, indent=2) + "\n") |
| 157 | + report = work / "junit.xml" |
| 158 | + # Bandit's CLI tests inspect sys.argv and reserve the short spelling `-o`. |
| 159 | + command = [str(python), "-m", "pytest", "-q", "--override-ini=addopts=", "--tb=short", f"--junitxml={report}"] |
| 160 | + command += list(map(expand, profile["tests"])) + profile.get("pytest_args", []) |
| 161 | + completed = run(command, cwd=source / profile.get("cwd", ""), env=env, check=False) |
| 162 | + result["exit_code"] = completed.returncode |
| 163 | + if report.exists(): |
| 164 | + cases = list(ET.parse(report).iter("testcase")) |
| 165 | + result["passed"] = sum( |
| 166 | + not any(case.find(tag) is not None for tag in ("failure", "error", "skipped")) for case in cases |
| 167 | + ) |
| 168 | + result["skipped"] = sum(case.find("skipped") is not None for case in cases) |
| 169 | + result_path.write_text(json.dumps(result, indent=2) + "\n") |
| 170 | + print(json.dumps(result, indent=2), flush=True) |
| 171 | + if completed.returncode: |
| 172 | + return completed.returncode |
| 173 | + if not result.get("passed"): |
| 174 | + raise RuntimeError("No downstream tests passed; an empty or entirely skipped suite is not validation") |
| 175 | + return 0 |
| 176 | + |
| 177 | + |
| 178 | +if __name__ == "__main__": |
| 179 | + sys.exit(main()) |
0 commit comments