Skip to content

Commit

Permalink
feature: allow local runs on windows/macOS
Browse files Browse the repository at this point in the history
Cache python installations to a user cache folder using platformdirs.
The build environment is now a virtual environment to allow proper isolation.
Allows to run tests in parallel.
  • Loading branch information
mayeut committed Jan 5, 2022
1 parent 9e18cb8 commit 3c6d509
Show file tree
Hide file tree
Showing 12 changed files with 471 additions and 194 deletions.
4 changes: 1 addition & 3 deletions bin/run_tests.py
Expand Up @@ -16,15 +16,13 @@
unit_test_args += ["--run-docker"]
subprocess.run(unit_test_args, check=True)

xdist_test_args = ["-n", "2"] if sys.platform.startswith("linux") else []

# run the integration tests
subprocess.run(
[
sys.executable,
"-m",
"pytest",
*xdist_test_args,
"--numprocesses=2",
"-x",
"--durations",
"0",
Expand Down
120 changes: 120 additions & 0 deletions bin/update_virtualenv.py
@@ -0,0 +1,120 @@
#!/usr/bin/env python3

from __future__ import annotations

import difflib
import logging
import subprocess
from pathlib import Path
from typing import NamedTuple

import click
import rich
import tomli
from packaging.version import InvalidVersion, Version
from rich.logging import RichHandler
from rich.syntax import Syntax

from cibuildwheel.typing import Final

log = logging.getLogger("cibw")

# Looking up the dir instead of using utils.resources_dir
# since we want to write to it.
DIR: Final[Path] = Path(__file__).parent.parent.resolve()
RESOURCES_DIR: Final[Path] = DIR / "cibuildwheel/resources"

GET_VIRTUALENV_GITHUB: Final[str] = "https://github.com/pypa/get-virtualenv"
GET_VIRTUALENV_URL_TEMPLATE: Final[
str
] = f"{GET_VIRTUALENV_GITHUB}/blob/{{version}}/public/virtualenv.pyz?raw=true"


class VersionTuple(NamedTuple):
version: Version
version_string: str


def git_ls_remote_versions(url) -> list[VersionTuple]:
versions: list[VersionTuple] = []
tags = subprocess.run(
["git", "ls-remote", "--tags", url], check=True, text=True, capture_output=True
).stdout.splitlines()
for tag in tags:
_, ref = tag.split()
assert ref.startswith("refs/tags/")
version_string = ref[10:]
try:
version = Version(version_string)
if version.is_devrelease:
log.info(f"Ignoring development release '{version}'")
continue
if version.is_prerelease:
log.info(f"Ignoring pre-release '{version}'")
continue
versions.append(VersionTuple(version, version_string))
except InvalidVersion:
log.warning(f"Ignoring ref '{ref}'")
versions.sort(reverse=True)
return versions


@click.command()
@click.option("--force", is_flag=True)
@click.option(
"--level", default="INFO", type=click.Choice(["WARNING", "INFO", "DEBUG"], case_sensitive=False)
)
def update_virtualenv(force: bool, level: str) -> None:

logging.basicConfig(
level="INFO",
format="%(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True, markup=True)],
)
log.setLevel(level)

toml_file_path = RESOURCES_DIR / "virtualenv.toml"

original_toml = toml_file_path.read_text()
with toml_file_path.open("rb") as f:
loaded_file = tomli.load(f)
version = str(loaded_file["version"])
versions = git_ls_remote_versions(GET_VIRTUALENV_GITHUB)
if versions[0].version > Version(version):
version = versions[0].version_string

result_toml = (
f'version = "{version}"\n'
f'url = "{GET_VIRTUALENV_URL_TEMPLATE.format(version=version)}"\n'
)

rich.print() # spacer

if original_toml == result_toml:
rich.print("[green]Check complete, virtualenv version unchanged.")
return

rich.print("virtualenv version updated.")
rich.print("Changes:")
rich.print()

toml_relpath = toml_file_path.relative_to(DIR).as_posix()
diff_lines = difflib.unified_diff(
original_toml.splitlines(keepends=True),
result_toml.splitlines(keepends=True),
fromfile=toml_relpath,
tofile=toml_relpath,
)
rich.print(Syntax("".join(diff_lines), "diff", theme="ansi_light"))
rich.print()

if force:
toml_file_path.write_text(result_toml)
rich.print("[green]TOML file updated.")
else:
rich.print("[yellow]File left unchanged. Use --force flag to update.")


if __name__ == "__main__":
update_virtualenv()
41 changes: 29 additions & 12 deletions cibuildwheel/__main__.py
@@ -1,7 +1,10 @@
import argparse
import os
import shutil
import sys
import textwrap
from pathlib import Path
from tempfile import mkdtemp
from typing import List, Set, Union

import cibuildwheel
Expand All @@ -10,9 +13,15 @@
import cibuildwheel.util
import cibuildwheel.windows
from cibuildwheel.architecture import Architecture, allowed_architectures_check
from cibuildwheel.logger import log
from cibuildwheel.options import CommandLineArguments, Options, compute_options
from cibuildwheel.typing import PLATFORMS, PlatformName, assert_never
from cibuildwheel.util import BuildSelector, Unbuffered, detect_ci_provider
from cibuildwheel.util import (
CIBW_CACHE_PATH,
BuildSelector,
Unbuffered,
detect_ci_provider,
)


def main() -> None:
Expand Down Expand Up @@ -187,17 +196,23 @@ def main() -> None:
if not output_dir.exists():
output_dir.mkdir(parents=True)

with cibuildwheel.util.print_new_wheels(
"\n{n} wheels produced in {m:.0f} minutes:", output_dir
):
if platform == "linux":
cibuildwheel.linux.build(options)
elif platform == "windows":
cibuildwheel.windows.build(options)
elif platform == "macos":
cibuildwheel.macos.build(options)
else:
assert_never(platform)
tmp_path = Path(mkdtemp(prefix="cibw-run-")).resolve(strict=True)
try:
with cibuildwheel.util.print_new_wheels(
"\n{n} wheels produced in {m:.0f} minutes:", output_dir
):
if platform == "linux":
cibuildwheel.linux.build(options, tmp_path)
elif platform == "windows":
cibuildwheel.windows.build(options, tmp_path)
elif platform == "macos":
cibuildwheel.macos.build(options, tmp_path)
else:
assert_never(platform)
finally:
shutil.rmtree(tmp_path, ignore_errors=sys.platform.startswith("win"))
if tmp_path.exists():
log.warning(f"Can't delete temporary folder '{str(tmp_path)}'")


def print_preamble(platform: str, options: Options, identifiers: List[str]) -> None:
Expand All @@ -218,6 +233,8 @@ def print_preamble(platform: str, options: Options, identifiers: List[str]) -> N
print(f" platform: {platform!r}")
print(textwrap.indent(options.summary(identifiers), " "))

print(f"Cache folder: {CIBW_CACHE_PATH}")

warnings = detect_warnings(platform=platform, options=options, identifiers=identifiers)
if warnings:
print("\nWarnings:")
Expand Down
2 changes: 1 addition & 1 deletion cibuildwheel/linux.py
Expand Up @@ -303,7 +303,7 @@ def build_on_docker(
log.step_end()


def build(options: Options) -> None:
def build(options: Options, tmp_path: Path) -> None:
try:
# check docker is installed
subprocess.run(["docker", "--version"], check=True, stdout=subprocess.DEVNULL)
Expand Down

0 comments on commit 3c6d509

Please sign in to comment.