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 name: &'static str,
28 path: PathBuf,
30 },
31 #[error("uv will not clear a directory that is not a virtual environment")]
32 ClearNonVirtualenv {
33 path: PathBuf,
35 },
36 #[error("Virtual environment path is not valid UTF-8: {}", path.user_display())]
37 NonUtf8Path {
38 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#[derive(Debug)]
59pub enum Prompt {
60 CurrentDirectoryName,
62 Static(String),
64 None,
67}
68
69impl Prompt {
70 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
80pub 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 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 let interpreter = interpreter.with_virtualenv(virtualenv);
105 Ok(PythonEnvironment::from_interpreter(interpreter))
106}