Skip to content

Commit

Permalink
feature: allow local runs on windows/macOS (#974)
Browse files Browse the repository at this point in the history
* feature: allow local runs on windows/macOS

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.

Co-authored-by: Joe Rickerby <joerick@mac.com>
  • Loading branch information
mayeut and joerick committed Jan 8, 2022
1 parent 8124333 commit ab13f7a
Show file tree
Hide file tree
Showing 14 changed files with 505 additions and 230 deletions.
2 changes: 0 additions & 2 deletions README.md
Expand Up @@ -59,8 +59,6 @@ Usage

<sup>鹿 [Requires emulation](https://cibuildwheel.readthedocs.io/en/stable/faq/#emulation), distributed separately. Other services may also support Linux ARM through emulation or third-party build hosts, but these are not tested in our CI.</sup><br>

`cibuildwheel` is not intended to run on your development machine. Because it uses system Python from Python.org on macOS and Windows, it will try to install packages globally - not what you expect from a build tool! Instead, isolated CI services like those mentioned above are ideal. For Linux builds, it uses manylinux docker images, so those can be done locally for testing in a pinch.

<!--intro-end-->

Example setup
Expand Down
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()
55 changes: 37 additions & 18 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 All @@ -32,12 +41,11 @@ def main() -> None:
choices=["auto", "linux", "macos", "windows"],
default=os.environ.get("CIBW_PLATFORM", "auto"),
help="""
Platform to build for. For "linux" you need docker running, on Mac
or Linux. For "macos", you need a Mac machine, and note that this
script is going to automatically install MacPython on your system,
so don't run on your development machine. For "windows", you need to
run in Windows, and it will build and test for all versions of
Python. Default: auto.
Platform to build for. Use this option to override the
auto-detected platform or to run cibuildwheel on your development
machine. Specifying "macos" or "windows" only works on that
operating system, but "linux" works on all three, as long as
Docker is installed. Default: auto.
""",
)

Expand Down Expand Up @@ -165,6 +173,9 @@ def main() -> None:
# Python is buffering by default when running on the CI platforms, giving problems interleaving subprocess call output with unflushed calls to 'print'
sys.stdout = Unbuffered(sys.stdout) # type: ignore[assignment]

# create the cache dir before it gets printed & builds performed
CIBW_CACHE_PATH.mkdir(parents=True, exist_ok=True)

print_preamble(platform=platform, options=options, identifiers=identifiers)

try:
Expand All @@ -187,17 +198,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 +235,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 ab13f7a

Please sign in to comment.