Skip to content
Draft
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
2 changes: 1 addition & 1 deletion conan/tools/system/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from conan.tools.system.pip_manager import PipEnv
from conan.tools.system.pip_manager import PipEnv, UVEnv
113 changes: 87 additions & 26 deletions conan/tools/system/pip_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from conan.errors import ConanException


class PipEnv:
class PythonVirtualEnv:

def __init__(self, conanfile, folder=None, name=""):
"""
Expand All @@ -23,7 +23,30 @@ def __init__(self, conanfile, folder=None, name=""):
self.bin_dir = os.path.join(self._env_dir, bins)
pyexe = "python.exe" if platform.system() == "Windows" else "python"
self._python_exe = os.path.join(self.bin_dir, pyexe)
self._create_venv()

@property
def python(self):
return self._get_env_python(self._env_dir)

@property
def _default_python(self):
_config_python = self._conanfile.conf.get("tools.system.pipenv:python_interpreter")
python = "python" if platform.system() == "Windows" else "python3"
default_python = shutil.which(python)
_system_python = os.path.realpath(default_python) if default_python else None
_python = _config_python or _system_python
if _python:
return _python
else:
raise ConanException("Conan could not find a Python executable path. Please, install "
"Python system-wide or set the "
"'tools.system.pipenv:python_interpreter' "
"conf to the full path of a Python executable")

@staticmethod
def _get_env_python(env_dir):
_env_bin_dir = os.path.join(env_dir, "Scripts" if platform.system() == "Windows" else "bin")
return os.path.join(_env_bin_dir, "python.exe" if platform.system() == "Windows" else "python")

def generate(self):
"""
Expand All @@ -33,27 +56,8 @@ def generate(self):
env.prepend_path("PATH", self.bin_dir)
env.vars(self._conanfile).save_script(self.env_name)

@staticmethod
def _default_python():
python = "python" if platform.system() == "Windows" else "python3"
default_python = shutil.which(python)
return os.path.realpath(default_python) if default_python else None

def _create_venv(self):
python_interpreter = self._conanfile.conf.get("tools.system.pipenv:python_interpreter")
python_interpreter = python_interpreter or self._default_python()
if not python_interpreter:
raise ConanException("PipEnv could not find a Python executable path. Please, install "
"Python system-wide or set the "
"'tools.system.pipenv:python_interpreter' "
"conf to the full path of a Python executable")

try:
self._conanfile.run(cmd_args_to_string([python_interpreter, '-m', 'venv',
self._env_dir]))
except ConanException as e:
raise ConanException(f"PipEnv could not create a Python virtual "
f"environment using '{python_interpreter}': {e}")
def run(self, args):
return self._conanfile.run(cmd_args_to_string([self.python] + list(args)))

def install(self, packages, pip_args=None):
"""
Expand All @@ -65,9 +69,66 @@ def install(self, packages, pip_args=None):
Defaults to ``None``.
:return: the return code of the executed pip command.
"""
args = [self._python_exe, "-m", "pip", "install", "--disable-pip-version-check"]
args = ["-m", "pip", "install", "--disable-pip-version-check"]
if pip_args:
args += list(pip_args)
args += list(packages)
command = cmd_args_to_string(args)
return self._conanfile.run(command)
return self.run(args)


class PipEnv(PythonVirtualEnv):

def __init__(self, conanfile, folder=None, name=""):
"""
:param conanfile: The current conanfile "self"
:param folder: Optional folder, by default the "build_folder"
:param name: Optional name for the virtualenv, by default "conan_pipenv"
"""
super().__init__(conanfile, folder, name)
self._create_venv()

def _create_venv(self):
try:
self._conanfile.run(cmd_args_to_string([self._default_python, '-m', 'venv',
self._env_dir]))
except ConanException as e:
raise ConanException(f"PipEnv could not create a Python virtual "
f"environment using '{self._default_python}': {e}")


class UVEnv(PythonVirtualEnv):
Copy link
Contributor

@czoido czoido Dec 18, 2025

Choose a reason for hiding this comment

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

Have you considered not exposing a new UVEnv class? Because in the end uv is just the method we use for creating the environment but the functionality is the same for both exposed public classes. Maybe it should be a single class that you instance like this?

pip = PipEnv(self, backend="uv", ...)

If we keep the two different public classes (which I think is fine) maybe you should consider composition instead of inheritance for the common functionality.

Copy link
Member

Choose a reason for hiding this comment

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

Could make sense, maybe that would also be a rename of the class to PyEnv?
We could do an alias first, deprecate the PipEnv with a warning to not break existing usage.


def __init__(self, conanfile, py_version, folder=None, name=""):
"""
:param conanfile: The current conanfile "self"
:param folder: Optional folder, by default the "build_folder"
:param name: Optional name for the virtualenv, by default "conan_uvenv"
:param py_version: Optional python version for the virtualenv using UV
Copy link
Contributor

Choose a reason for hiding this comment

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

Here says it's optional but it's not

"""
super().__init__(conanfile, folder, name)
self._base_env_dir = os.path.abspath(os.path.join(folder or conanfile.build_folder))
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
self._base_env_dir = os.path.abspath(os.path.join(folder or conanfile.build_folder))
self._base_env_dir = os.path.abspath(folder or conanfile.build_folder)

self._uv_env_dir = os.path.join(self._base_env_dir, f"uv_{self.env_name}")
self._create_uv_venv(py_version)

def _create_uv_venv(self, py_version):
try:
self._conanfile.run(cmd_args_to_string(
[self._default_python, '-m', 'venv', self._uv_env_dir])
)
_python_exe = self._get_env_python(self._uv_env_dir)
self._conanfile.run(cmd_args_to_string(
[_python_exe, "-m", "pip", "install", "--disable-pip-version-check", "uv"])
)
self._conanfile.run(cmd_args_to_string(
[_python_exe, '-m', 'uv', 'venv', '--seed', '--python', py_version, self._env_dir])
)
self._conanfile.output.info(f"Virtual environment for Python "
f"{py_version} created successfully using UV.")
except Exception as e:
raise ConanException(f"UVEnv could not create a Python {py_version} virtual "
f"environment using UV and '{self._default_python}': {e}")

def uvx(self, args):
return self._conanfile.run(
cmd_args_to_string([self._get_env_python(self._uv_env_dir), '-m', "uv", "tool", "run"] + list(args))
)
151 changes: 151 additions & 0 deletions test/functional/tools/system/uv_manager_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import textwrap
import platform
from conan.test.utils.tools import TestClient
from conan.internal.util.files import save_files
from conan.test.utils.test_files import temp_folder


def _create_py_hello_world(folder):
setup_py = textwrap.dedent("""
from setuptools import setup, find_packages

setup(
name='hello',
version='0.1.0',
packages=find_packages(include=['hello', 'hello.*']),
entry_points={'console_scripts': ['hello-world = hello:hello']}
)
""")
hello_py = textwrap.dedent("""
def hello():
print("Hello Test World!")
""")

save_files(folder, {"setup.py": setup_py, "hello/__init__.py": hello_py})


def test_build_uv_manager():

pip_package_folder = temp_folder(path_with_spaces=True)
_create_py_hello_world(pip_package_folder)
pip_package_folder = pip_package_folder.replace('\\', '/')

conanfile_pip = textwrap.dedent(f"""
from conan import ConanFile
from conan.tools.system import UVEnv
from conan.tools.layout import basic_layout
import platform
import os


class PipPackage(ConanFile):
name = "pip_hello_test"
version = "0.1"

def layout(self):
basic_layout(self)

def generate(self):
pip_env = UVEnv(self, py_version="3.11.6")
pip_env.install(["{pip_package_folder}"])
pip_env.generate()
pip_env.run(["--version"])

def build(self):
self.run("hello-world")
""")

client = TestClient(path_with_spaces=False)
# FIXME: the python shebang inside vitual env packages fails when using path_with_spaces
client.save({"pip/conanfile.py": conanfile_pip})
client.run("build pip/conanfile.py")
assert "Using CPython 3.11.6" in client.out
assert "Creating virtual environment with seed packages" in client.out
assert "Virtual environment for Python 3.11.6 created successfully using UV." in client.out
if platform.system() == "Windows":
assert "python.exe --version\nPython 3.11.6" in client.out
else:
assert "python --version\nPython 3.11.6" in client.out
assert "RUN: hello-world" in client.out
assert "Hello Test World!" in client.out


def test_fail_build_uv_manager():

pip_package_folder = temp_folder(path_with_spaces=True)
_create_py_hello_world(pip_package_folder)
pip_package_folder = pip_package_folder.replace('\\', '/')

conanfile_pip = textwrap.dedent(f"""
from conan import ConanFile
from conan.tools.system import UVEnv
from conan.tools.layout import basic_layout
import platform
import os


class PipPackage(ConanFile):
name = "pip_hello_test"
version = "0.1"

def layout(self):
basic_layout(self)

def generate(self):
pip_env = UVEnv(self, py_version="3.11.86")
pip_env.install(["{pip_package_folder}"])
pip_env.generate()

def build(self):
self.run("hello-world")
""")

client = TestClient(path_with_spaces=False)
# FIXME: the python shebang inside vitual env packages fails when using path_with_spaces
client.save({"pip/conanfile.py": conanfile_pip})
client.run("build pip/conanfile.py", assert_error=True)
print(client.out)
assert "UVEnv could not create a Python 3.11.86 virtual environment using UV" in client.out


def test_run_uvx():

pip_package_folder = temp_folder(path_with_spaces=True)
_create_py_hello_world(pip_package_folder)
pip_package_folder = pip_package_folder.replace('\\', '/')

conanfile_pip = textwrap.dedent(f"""
from conan import ConanFile
from conan.tools.system import UVEnv
from conan.tools.layout import basic_layout
import platform
import os


class PipPackage(ConanFile):
name = "pip_hello_test"
version = "0.1"

def layout(self):
basic_layout(self)

def generate(self):
pip_env = UVEnv(self, py_version="3.11.6")
pip_env.install(["{pip_package_folder}"])
pip_env.generate()
pip_env.uvx(["ruff==0.14.9", "--version"])

def build(self):
self.run("hello-world")
""")

client = TestClient(path_with_spaces=False)
# FIXME: the python shebang inside vitual env packages fails when using path_with_spaces
client.save({"pip/conanfile.py": conanfile_pip})
client.run("build pip/conanfile.py")
assert "Using CPython 3.11.6" in client.out
assert "Creating virtual environment with seed packages" in client.out
assert "Virtual environment for Python 3.11.6 created successfully using UV." in client.out
assert "ruff 0.14.9" in client.out
assert "RUN: hello-world" in client.out
assert "Hello Test World!" in client.out
Loading