Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use external pip if available #736

Merged
merged 3 commits into from
Feb 26, 2024
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
54 changes: 40 additions & 14 deletions src/build/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,26 +70,42 @@ def _minimum_pip_version() -> str:
return '19.1.0'


def _has_valid_pip(purelib: str) -> bool:
def _has_valid_pip(**distargs: object) -> bool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather we didn't lose the typing here, but Python doesn't make it easy:

if typing.TYPE_CHECKING:
    from typing_extensions import NotRequired, TypedDict, Unpack

    class _Distargs(TypedDict):
        path: NotRequired[list[str]]

...

def _has_valid_pip(**distargs: Unpack[_Distargs]) -> bool:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left it along for now, would prefer a _compat/typing module if we add it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can do that in a separate PR. I also usually have _compat/tomllib (https://github.com/scikit-build/scikit-build-core/tree/main/src/scikit_build_core/_compat for example).

"""
Given a path, see if Pip is present and return True if the version is
sufficient for build, False if it is not.
sufficient for build, False if it is not. ModuleNotFoundError is thrown if
pip is not present.
"""

import packaging.version

if sys.version_info < (3, 8):
import importlib_metadata as metadata
else:
from importlib import metadata
from ._importlib import metadata

name = 'pip'

pip_distribution = next(iter(metadata.distributions(name='pip', path=[purelib])))
try:
pip_distribution = next(iter(metadata.distributions(name=name, **distargs)))
except StopIteration:
raise ModuleNotFoundError(name) from None

current_pip_version = packaging.version.Version(pip_distribution.version)

return current_pip_version >= packaging.version.Version(_minimum_pip_version())


@functools.lru_cache(maxsize=None)
def _valid_global_pip() -> bool | None:
"""
This checks for a valid global pip. Returns None if pip is missing, False
if Pip is too old, and True if it can be used.
"""

try:
return _has_valid_pip()
except ModuleNotFoundError:
return None


def _subprocess(cmd: list[str]) -> None:
"""Invoke subprocess and output stdout and stderr if it fails."""
try:
Expand Down Expand Up @@ -139,6 +155,12 @@ def python_executable(self) -> str:
"""The python executable of the isolated build environment."""
return self._python_executable

def _pip_args(self) -> list[str]:
if _valid_global_pip():
return [sys.executable, '-Im', 'pip', '--python', self.python_executable]
else:
return [self.python_executable, '-Im', 'pip']

def make_extra_environ(self) -> dict[str, str]:
path = os.environ.get('PATH')
return {'PATH': os.pathsep.join([self._scripts_dir, path]) if path is not None else self._scripts_dir}
Expand All @@ -163,9 +185,7 @@ def install(self, requirements: Collection[str]) -> None:
req_file.write(os.linesep.join(requirements))
try:
cmd = [
self.python_executable,
'-Im',
'pip',
*self._pip_args(),
'install',
'--use-pep517',
'--no-warn-script-location',
Expand Down Expand Up @@ -201,7 +221,11 @@ def _create_isolated_env_virtualenv(path: str) -> tuple[str, str]:
"""
import virtualenv

cmd = [str(path), '--no-setuptools', '--no-wheel', '--activators', '']
if _valid_global_pip():
cmd = [path, '--no-seed', '--activators', '']
else:
cmd = [path, '--no-setuptools', '--no-wheel', '--activators', '']

result = virtualenv.cli_run(cmd, setup_logging=False)
executable = str(result.creator.exe)
script_dir = str(result.creator.script_dir)
Expand Down Expand Up @@ -240,18 +264,20 @@ def _create_isolated_env_venv(path: str) -> tuple[str, str]:
with warnings.catch_warnings():
if sys.version_info[:3] == (3, 11, 0):
warnings.filterwarnings('ignore', 'check_home argument is deprecated and ignored.', DeprecationWarning)
venv.EnvBuilder(with_pip=True, symlinks=symlinks).create(path)
venv.EnvBuilder(with_pip=not _valid_global_pip(), symlinks=symlinks).create(path)
except subprocess.CalledProcessError as exc:
raise FailedProcessError(exc, 'Failed to create venv. Maybe try installing virtualenv.') from None

executable, script_dir, purelib = _find_executable_and_scripts(path)

# Get the version of pip in the environment
if not _has_valid_pip(purelib):
if not _valid_global_pip() and not _has_valid_pip(path=[purelib]):
_subprocess([executable, '-m', 'pip', 'install', f'pip>={_minimum_pip_version()}'])

# Avoid the setuptools from ensurepip to break the isolation
_subprocess([executable, '-m', 'pip', 'uninstall', 'setuptools', '-y'])
if not _valid_global_pip():
_subprocess([executable, '-m', 'pip', 'uninstall', 'setuptools', '-y'])

return executable, script_dir


Expand Down
5 changes: 5 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ def is_integration(item):
return os.path.basename(item.location[0]) == 'test_integration.py'


@pytest.fixture()
def local_pip(monkeypatch):
monkeypatch.setattr(build.env, '_valid_global_pip', lambda: None)


@pytest.fixture(scope='session', autouse=True)
def ensure_syconfig_vars_created():
# the config vars are globally cached and may use get_path, make sure they are created
Expand Down
6 changes: 4 additions & 2 deletions tests/test_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def test_isolation():


@pytest.mark.isolated
@pytest.mark.usefixtures('local_pip')
def test_isolated_environment_install(mocker):
with build.env.DefaultIsolatedEnv() as env:
mocker.patch('build.env._subprocess')
Expand Down Expand Up @@ -117,6 +118,7 @@ def test_isolated_env_log(mocker, caplog, package_test_flit):


@pytest.mark.isolated
@pytest.mark.usefixtures('local_pip')
def test_default_pip_is_never_too_old():
with build.env.DefaultIsolatedEnv() as env:
version = subprocess.check_output(
Expand All @@ -130,15 +132,15 @@ def test_default_pip_is_never_too_old():
@pytest.mark.isolated
@pytest.mark.parametrize('pip_version', ['20.2.0', '20.3.0', '21.0.0', '21.0.1'])
@pytest.mark.parametrize('arch', ['x86_64', 'arm64'])
@pytest.mark.usefixtures('local_pip')
def test_pip_needs_upgrade_mac_os_11(mocker, pip_version, arch):
SimpleNamespace = collections.namedtuple('SimpleNamespace', 'version')

_subprocess = mocker.patch('build.env._subprocess')
mocker.patch('platform.system', return_value='Darwin')
mocker.patch('platform.machine', return_value=arch)
mocker.patch('platform.mac_ver', return_value=('11.0', ('', '', ''), ''))
metadata_name = 'importlib_metadata' if sys.version_info < (3, 8) else 'importlib.metadata'
mocker.patch(metadata_name + '.distributions', return_value=(SimpleNamespace(version=pip_version),))
mocker.patch('build._importlib.metadata.distributions', return_value=(SimpleNamespace(version=pip_version),))

min_version = Version('20.3' if arch == 'x86_64' else '21.0.1')
with build.env.DefaultIsolatedEnv():
Expand Down
1 change: 1 addition & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ def main_reload_styles():
],
ids=['no-color', 'color'],
)
@pytest.mark.usefixtures('local_pip')
def test_output_env_subprocess_error(
mocker,
monkeypatch,
Expand Down
Loading