Skip to content
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
19 changes: 19 additions & 0 deletions ci/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,31 @@ class Finding:
fix: str = ""


# The variables that point git at one repository. A git hook sets them to the repository it runs for, so a temporary
# repository created with them inherits that repository and can rewrite its config.
_REPOSITORY_VARIABLES = (
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_PREFIX",
)


def clean_git_env() -> dict:
"""The environment for git that finds its repository from the working directory, as in a shell."""
return {k: v for k, v in os.environ.items() if k not in _REPOSITORY_VARIABLES}


def git(root: Path, *args: str) -> Tuple[int, str]:
"""Run git in the repository and return its exit code and standard output."""
try:
done = subprocess.run(
["git", *args],
cwd=root,
env=clean_git_env(),
capture_output=True,
text=True,
encoding="utf-8",
Expand Down
69 changes: 65 additions & 4 deletions ci/ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,61 @@ def fingerprint(*parts: object) -> str:
return digest.hexdigest()


def ensure_venv(ctx: Context, stage: str, venv: Path, source: Path, requirement: str) -> Optional[Result]:
"""Create the stage's virtual environment and install `requirement` into it, only when its stamp is stale."""
# The python stage builds its virtual environment with Python 3.11, the version CI pins. On Windows, Python 3.13 hangs
# in tests/test_overlay.py::test_a_session_runs_over_real_sockets_after_the_handshake (a known issue, not diagnosed yet);
# the suite passes on 3.11.
PYTHON_STAGE_VERSION = "3.11"


def python_stage_interpreter() -> Optional[Tuple[str, ...]]:
"""The command for a Python 3.11: the Windows launcher's 3.11, or whichever python on the PATH is 3.11."""
for command in (("py", "-3.11"), ("python3.11",), ("python3",), ("python",)):
try:
done = subprocess.run(
[*command, "-c", "import sys; print('%d.%d' % sys.version_info[:2])"],
capture_output=True,
text=True,
timeout=60,
check=False,
)
except (OSError, subprocess.SubprocessError):
continue
if done.returncode == 0 and done.stdout.strip() == PYTHON_STAGE_VERSION:
return command
return None


def venv_version(venv: Path) -> Optional[str]:
"""The Python version a virtual environment was created with, from its pyvenv.cfg."""
cfg = venv / "pyvenv.cfg"
if not cfg.exists():
return None
for line in cfg.read_text(encoding="utf-8").splitlines():
key, _, value = line.partition("=")
if key.strip() in ("version_info", "version"):
return value.strip()
return None


def ensure_venv(
ctx: Context,
stage: str,
venv: Path,
source: Path,
requirement: str,
interpreter: Optional[Sequence[str]] = None,
version: Optional[str] = None,
) -> Optional[Result]:
"""Create the stage's virtual environment and install `requirement` into it, only when its stamp is stale.

With `version`, an environment built with another Python is rebuilt, so the stage runs on the version it pins."""
python = venv_python(venv)
if version is not None and python.exists():
if not (venv_version(venv) or "").startswith(version + "."):
shutil.rmtree(venv)
if not python.exists():
if ctx.run(stage, Step((sys.executable, "-m", "venv", str(venv)), timeout=300)) != 0:
command = tuple(interpreter) if interpreter else (sys.executable,)
if ctx.run(stage, Step((*command, "-m", "venv", str(venv)), timeout=300)) != 0:
return Result(FAIL, f"could not create the virtual environment in {venv} (log: {Context.log_name(stage)})")
stamp_value = fingerprint(source, sys.version, requirement)
stamp = venv / ".ci-stamp"
Expand Down Expand Up @@ -195,8 +245,19 @@ def _relay_build(ctx: Context) -> Result:


def _python(ctx: Context) -> Result:
interpreter = python_stage_interpreter()
if interpreter is None:
return Result(FAIL, "the python stage needs Python 3.11: install it, and make `py -3.11` or `python3.11` available")
venv = ctx.root / "target" / "ci" / "venv-python"
failure = ensure_venv(ctx, "python", venv, ctx.root / "python" / "pyproject.toml", "python[test]")
failure = ensure_venv(
ctx,
"python",
venv,
ctx.root / "python" / "pyproject.toml",
"python[test]",
interpreter=interpreter,
version=PYTHON_STAGE_VERSION,
)
if failure is not None:
return failure
step = Step((str(venv_python(venv)), "-m", "pytest", "python/tests", "-q"), env=interop_env(ctx), timeout=1200)
Expand Down
9 changes: 5 additions & 4 deletions ci/tests/test_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from checks import ( # noqa: E402
clean_git_env,
eol_findings,
git_bash,
hooks_findings,
Expand Down Expand Up @@ -188,29 +189,29 @@ def repo(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
root = Path(tmp.name)
subprocess.run(["git", "init", "-q"], cwd=root, check=True)
subprocess.run(["git", "init", "-q"], cwd=root, check=True, env=clean_git_env())
return root

def test_a_staged_key_and_trailing_whitespace_are_found(self):
root = self.repo()
(root / "keys.txt").write_text(KEY_HEADER + "\n", encoding="utf-8")
(root / "notes.txt").write_text("trailing \n", encoding="utf-8")
subprocess.run(["git", "add", "-A"], cwd=root, check=True)
subprocess.run(["git", "add", "-A"], cwd=root, check=True, env=clean_git_env())
found = messages(staged_findings(root))
self.assertTrue(any("private key added to keys.txt" in m for m in found), found)
self.assertTrue(any("staged changes have problems" in m for m in found), found)

def test_a_large_staged_file_is_an_error(self):
root = self.repo()
(root / "big.bin").write_bytes(b"x" * 2048)
subprocess.run(["git", "add", "-A"], cwd=root, check=True)
subprocess.run(["git", "add", "-A"], cwd=root, check=True, env=clean_git_env())
found = staged_findings(root, limit=1024)
self.assertTrue(any("big.bin" in m and "staged" in m for m in messages(found)))

def test_a_clean_stage_has_no_findings(self):
root = self.repo()
(root / "ok.txt").write_text("plain text\n", encoding="utf-8")
subprocess.run(["git", "add", "-A"], cwd=root, check=True)
subprocess.run(["git", "add", "-A"], cwd=root, check=True, env=clean_git_env())
self.assertEqual(staged_findings(root), [])


Expand Down
Loading