Skip to main content

uv_virtualenv/
lib.rs

1use std::io;
2use std::path::{Path, PathBuf};
3
4use thiserror::Error;
5
6use uv_fs::Simplified;
7use uv_python_interpreter::{Interpreter, PythonEnvironment};
8pub use uv_python_managed::UpgradePolicy;
9
10pub use virtualenv::{ClearNonVirtualenv, OnExisting, RemovalReason, Seed};
11
12mod virtualenv;
13
14#[derive(Debug, Error)]
15pub enum Error {
16    #[error(transparent)]
17    Io(#[from] io::Error),
18    #[error(
19        "Could not find a suitable Python executable for the virtual environment based on the interpreter: {0}"
20    )]
21    NotFound(String),
22    #[error(transparent)]
23    Python(#[from] uv_python_managed::Error),
24    #[error("A {name} already exists at: {}", path.user_display())]
25    Exists {
26        /// The type of environment (e.g., "virtual environment" or "directory").
27        name: &'static str,
28        /// The path to the existing environment.
29        path: PathBuf,
30    },
31    #[error("uv will not clear a directory that is not a virtual environment")]
32    ClearNonVirtualenv {
33        /// The non-virtual environment directory that would have been cleared.
34        path: PathBuf,
35    },
36    #[error("Virtual environment path is not valid UTF-8: {}", path.user_display())]
37    NonUtf8Path {
38        /// The non-UTF-8 virtual environment path.
39        path: PathBuf,
40    },
41}
42
43impl uv_errors::Hinted for Error {
44    fn hints(&self) -> uv_errors::Hints<'_> {
45        match self {
46            Self::Exists { name, .. } => uv_errors::Hints::from(format!(
47                "Use the `--clear` flag or set `UV_VENV_CLEAR=1` to replace the existing {name}",
48            )),
49            Self::ClearNonVirtualenv { .. } => uv_errors::Hints::from(
50                "Use the `--force` flag to remove the existing directory anyway",
51            ),
52            _ => uv_errors::Hints::none(),
53        }
54    }
55}
56
57/// The value to use for the shell prompt when inside a virtual environment.
58#[derive(Debug)]
59pub enum Prompt {
60    /// Use the current directory name as the prompt.
61    CurrentDirectoryName,
62    /// Use the fixed string as the prompt.
63    Static(String),
64    /// Default to no prompt. The prompt is then set by the activator script
65    /// to the virtual environment's directory name.
66    None,
67}
68
69impl Prompt {
70    /// Determine the prompt value to be used from the command line arguments.
71    pub fn from_args(prompt: Option<String>) -> Self {
72        match prompt {
73            Some(prompt) if prompt == "." => Self::CurrentDirectoryName,
74            Some(prompt) => Self::Static(prompt),
75            None => Self::None,
76        }
77    }
78}
79
80/// Create a virtualenv.
81pub fn create_venv(
82    location: &Path,
83    interpreter: Interpreter,
84    prompt: Prompt,
85    system_site_packages: bool,
86    on_existing: OnExisting,
87    relocatable: bool,
88    seed: Seed,
89    upgrade_policy: UpgradePolicy,
90) -> Result<PythonEnvironment, Error> {
91    // Create the virtualenv at the given location.
92    let virtualenv = virtualenv::create(
93        location,
94        &interpreter,
95        prompt,
96        system_site_packages,
97        on_existing,
98        relocatable,
99        seed,
100        upgrade_policy,
101    )?;
102
103    // Create the corresponding `PythonEnvironment`.
104    let interpreter = interpreter.with_virtualenv(virtualenv);
105    Ok(PythonEnvironment::from_interpreter(interpreter))
106}