Skip to main content

uv_virtualenv/
virtualenv.rs

1//! Create a virtual environment.
2
3use std::borrow::Cow;
4use std::env::consts::EXE_SUFFIX;
5use std::ffi::{OsStr, OsString};
6use std::io;
7use std::io::{BufWriter, Write};
8use std::path::Path;
9
10use console::Term;
11use fs_err::File;
12use itertools::Itertools;
13use owo_colors::OwoColorize;
14use regex::{Captures, regex};
15
16use tracing::{debug, trace};
17
18use crate::{Error, Prompt};
19use uv_fs::{CWD, PythonExt, Simplified, cachedir};
20use uv_platform_tags::Os;
21use uv_pypi_types::Scheme;
22use uv_python_interpreter::{Interpreter, VirtualEnvironment};
23use uv_python_managed::{
24    PythonExecutable, PythonMinorVersionLink, UpgradePolicy, replace_link_to_executable,
25};
26use uv_shell::escape_posix_for_single_quotes;
27use uv_version::version;
28
29/// Activation scripts for the environment, with dependent paths templated out.
30const ACTIVATE_TEMPLATES: &[(&str, &str)] = &[
31    ("activate", include_str!("activator/activate")),
32    ("activate.csh", include_str!("activator/activate.csh")),
33    ("activate.fish", include_str!("activator/activate.fish")),
34    ("activate.nu", include_str!("activator/activate.nu")),
35    ("activate.xsh", include_str!("activator/activate.xsh")),
36    ("activate.ps1", include_str!("activator/activate.ps1")),
37    ("activate.bat", include_str!("activator/activate.bat")),
38    ("deactivate.bat", include_str!("activator/deactivate.bat")),
39    ("pydoc.bat", include_str!("activator/pydoc.bat")),
40    (
41        "activate_this.py",
42        include_str!("activator/activate_this.py"),
43    ),
44];
45const VIRTUALENV_PATCH: &str = include_str!("_virtualenv.py");
46
47/// Replace `{{ NAME }}` placeholders.
48fn render_template<'a>(template: &'a str, replacements: &[(&str, &str)]) -> Cow<'a, str> {
49    regex!(r"\{\{ ([A-Z0-9_]+) \}\}").replace_all(template, |captures: &Captures<'_>| {
50        let (placeholder, [key]) = captures.extract();
51        match replacements.iter().find(|(name, _)| *name == key) {
52            Some((_, value)) => Cow::Borrowed(*value),
53            None => Cow::Owned(placeholder.to_owned()),
54        }
55    })
56}
57
58/// Python 3.10 and later already ignore the distutils install config keys this hook guards
59/// against, while the last pip release supporting Python 3.9 still needs the workaround.
60///
61/// See <https://github.com/pypa/virtualenv/issues/3181>
62fn install_distutils_patch(interpreter: &Interpreter) -> bool {
63    interpreter.python_tuple() < (3, 10)
64}
65
66/// Very basic `.cfg` file format writer.
67fn write_cfg(f: &mut impl Write, data: &[(String, String)]) -> io::Result<()> {
68    for (key, value) in data {
69        writeln!(f, "{key} = {value}")?;
70    }
71    Ok(())
72}
73
74/// Create a [`VirtualEnvironment`] at the given location.
75pub(crate) fn create(
76    location: &Path,
77    interpreter: &Interpreter,
78    prompt: Prompt,
79    system_site_packages: bool,
80    on_existing: OnExisting,
81    relocatable: bool,
82    seed: Seed,
83    upgrade_policy: UpgradePolicy,
84) -> Result<VirtualEnvironment, Error> {
85    // Determine the base Python executable; that is, the Python executable that should be
86    // considered the "base" for the virtual environment.
87    //
88    // For consistency with the standard library, rely on `sys._base_executable`, _unless_ we're
89    // using a uv-managed Python (in which case, we can do better for symlinked executables).
90    let base_python = cfg_select! {
91        unix => {
92            if interpreter.is_standalone() {
93                interpreter.find_base_python()?
94            } else {
95                interpreter.to_base_python()?
96            }
97        }
98        _ => { interpreter.to_base_python()? }
99    };
100
101    debug!(
102        "Using base executable for virtual environment: {}",
103        base_python.display()
104    );
105
106    // Extract the prompt and compute the absolute path prior to validating the location; otherwise,
107    // we risk deleting (and recreating) the current working directory, which would cause the `CWD`
108    // queries to fail.
109    let prompt = match prompt {
110        Prompt::CurrentDirectoryName => CWD
111            .file_name()
112            .map(|name| name.to_string_lossy().to_string()),
113        Prompt::Static(value) => Some(value),
114        Prompt::None => None,
115    };
116    let absolute = std::path::absolute(location)?;
117
118    // Validate the path before creating the virtual environment, since some filesystems, e.g.,
119    // APFS, reject non-UTF-8 paths before the activation scripts are generated.
120    if absolute.simplified().to_str().is_none() {
121        return Err(Error::NonUtf8Path { path: absolute });
122    }
123
124    // Validate the existing location.
125    match location.metadata() {
126        Ok(metadata) if metadata.is_file() => {
127            return Err(Error::Io(io::Error::new(
128                io::ErrorKind::AlreadyExists,
129                format!("File exists at `{}`", location.user_display()),
130            )));
131        }
132        Ok(metadata)
133            if metadata.is_dir()
134                && location
135                    .read_dir()
136                    .is_ok_and(|mut dir| dir.next().is_none()) =>
137        {
138            // If it's an empty directory, we can proceed
139            trace!(
140                "Using empty directory at `{}` for virtual environment",
141                location.user_display()
142            );
143        }
144        Ok(metadata) if metadata.is_dir() => {
145            let is_virtualenv = uv_fs::is_virtualenv_base(location);
146            let name = if is_virtualenv {
147                "virtual environment"
148            } else {
149                "directory"
150            };
151            // TODO(zanieb): We may want to consider omitting the hint in some of these cases, e.g.,
152            // when `--no-clear` is used do we want to suggest `--clear`?
153            let err = Err(Error::Exists {
154                name,
155                path: location.to_path_buf(),
156            });
157            match on_existing {
158                OnExisting::Allow => {
159                    debug!("Allowing existing {name} due to `--allow-existing`");
160                }
161                OnExisting::Remove(reason) => {
162                    if !is_virtualenv
163                        && let RemovalReason::UserRequest(clear_non_virtualenv) = reason
164                    {
165                        match clear_non_virtualenv {
166                            ClearNonVirtualenv::Allow => {}
167                            ClearNonVirtualenv::Error => {
168                                return Err(Error::ClearNonVirtualenv {
169                                    path: location.to_path_buf(),
170                                });
171                            }
172                        }
173                    }
174                    debug!("Removing existing {name} ({reason})");
175                    uv_fs::clear_virtualenv(location)?;
176                }
177                OnExisting::Fail => return err,
178                // If not a virtual environment, fail without prompting.
179                OnExisting::Prompt if !is_virtualenv => return err,
180                OnExisting::Prompt => {
181                    match confirm_clear(location, name)? {
182                        Some(true) => {
183                            debug!("Removing existing {name} due to confirmation");
184                            uv_fs::clear_virtualenv(location)?;
185                        }
186                        Some(false) => return err,
187                        // When we don't have a TTY, require `--clear` explicitly.
188                        None => {
189                            return Err(Error::Exists {
190                                name,
191                                path: location.to_path_buf(),
192                            });
193                        }
194                    }
195                }
196            }
197        }
198        Ok(_) => {
199            // It's not a file or a directory
200            return Err(Error::Io(io::Error::new(
201                io::ErrorKind::AlreadyExists,
202                format!("Object already exists at `{}`", location.user_display()),
203            )));
204        }
205        Err(err) if err.kind() == io::ErrorKind::NotFound => {
206            fs_err::create_dir_all(location)?;
207        }
208        Err(err) => return Err(Error::Io(err)),
209    }
210
211    // Use the absolute path for all further operations.
212    let location = absolute;
213
214    let bin_name = if cfg!(unix) {
215        "bin"
216    } else if cfg!(windows) {
217        "Scripts"
218    } else {
219        unimplemented!("Only Windows and Unix are supported")
220    };
221    let scripts = location.join(&interpreter.virtualenv().scripts);
222
223    // Add the CACHEDIR.TAG.
224    cachedir::ensure_tag(&location)?;
225
226    // Create a `.gitignore` file to ignore all files in the venv.
227    fs_err::write(location.join(".gitignore"), "*")?;
228
229    let minor_version_link = PythonMinorVersionLink::from_interpreter(interpreter, upgrade_policy);
230    let using_minor_version_link = minor_version_link.is_some();
231    let executable_target = if let Some(minor_version_link) = minor_version_link {
232        let debug_symlink_term = if cfg!(windows) {
233            "junction"
234        } else {
235            "symlink directory"
236        };
237        debug!(
238            "Using {} `{}` instead of base Python path `{}`",
239            debug_symlink_term,
240            &minor_version_link.symlink_directory.display(),
241            &base_python.display()
242        );
243        minor_version_link.symlink_executable
244    } else {
245        base_python.clone()
246    };
247
248    // Per PEP 405, the Python `home` is the parent directory of the interpreter.
249    // For standalone interpreters, this `home` value will include a
250    // symlink directory on Unix or junction on Windows to enable transparent Python patch
251    // upgrades.
252    let python_home = executable_target
253        .parent()
254        .ok_or_else(|| {
255            io::Error::new(
256                io::ErrorKind::NotFound,
257                "The Python interpreter needs to have a parent directory",
258            )
259        })?
260        .to_path_buf();
261    let python_home = python_home.as_path();
262
263    // Different names for the python interpreter
264    fs_err::create_dir_all(&scripts)?;
265    let executable = scripts.join(format!("python{EXE_SUFFIX}"));
266
267    #[cfg(unix)]
268    {
269        uv_fs::replace_symlink(&executable_target, &executable)?;
270        uv_fs::replace_symlink(
271            "python",
272            scripts.join(format!("python{}", interpreter.python_major())),
273        )?;
274        uv_fs::replace_symlink(
275            "python",
276            scripts.join(format!(
277                "python{}.{}",
278                interpreter.python_major(),
279                interpreter.python_minor(),
280            )),
281        )?;
282        if interpreter.gil_disabled() {
283            uv_fs::replace_symlink(
284                "python",
285                scripts.join(format!(
286                    "python{}.{}t",
287                    interpreter.python_major(),
288                    interpreter.python_minor(),
289                )),
290            )?;
291        }
292
293        if interpreter.markers().implementation_name() == "pypy" {
294            uv_fs::replace_symlink(
295                "python",
296                scripts.join(format!("pypy{}", interpreter.python_major())),
297            )?;
298            uv_fs::replace_symlink("python", scripts.join("pypy"))?;
299        }
300
301        if interpreter.markers().implementation_name() == "graalpy" {
302            uv_fs::replace_symlink("python", scripts.join("graalpy"))?;
303        }
304    }
305
306    // On Windows, we use trampolines that point to an executable target. For standalone
307    // interpreters, this target path includes a minor version junction to enable
308    // transparent upgrades.
309    if cfg!(windows) {
310        if using_minor_version_link {
311            let target = scripts.join(WindowsExecutable::Python.exe(interpreter));
312            replace_link_to_executable(
313                target.as_path(),
314                PythonExecutable::console(&executable_target),
315            )
316            .map_err(Error::Python)?;
317            let windowed_executable_name = WindowsExecutable::Pythonw.exe(interpreter);
318            let targetw = scripts.join(&windowed_executable_name);
319            let windowed_executable_target =
320                executable_target.with_file_name(windowed_executable_name);
321            replace_link_to_executable(
322                targetw.as_path(),
323                PythonExecutable::windowed(&windowed_executable_target),
324            )
325            .map_err(Error::Python)?;
326            if interpreter.gil_disabled() {
327                let targett = scripts.join(WindowsExecutable::PythonMajorMinort.exe(interpreter));
328                replace_link_to_executable(
329                    targett.as_path(),
330                    PythonExecutable::console(&executable_target),
331                )
332                .map_err(Error::Python)?;
333                let targetwt = scripts.join(WindowsExecutable::PythonwMajorMinort.exe(interpreter));
334                replace_link_to_executable(
335                    targetwt.as_path(),
336                    PythonExecutable::windowed(&windowed_executable_target),
337                )
338                .map_err(Error::Python)?;
339            }
340        } else if matches!(
341            interpreter.platform().os(),
342            Os::Pyodide { .. } | Os::PyEmscripten { .. }
343        ) {
344            // For PyEmscripten, link only `python.exe`.
345            // This should not be copied as `python.exe` is a wrapper that launches Pyodide.
346            let target = scripts.join(WindowsExecutable::Python.exe(interpreter));
347            replace_link_to_executable(
348                target.as_path(),
349                PythonExecutable::console(&executable_target),
350            )
351            .map_err(Error::Python)?;
352        } else {
353            // Always copy `python.exe`.
354            copy_launcher_windows(
355                WindowsExecutable::Python,
356                interpreter,
357                &base_python,
358                &scripts,
359                python_home,
360            )?;
361
362            match interpreter.implementation_name() {
363                "graalpy" => {
364                    // For GraalPy, copy `graalpy.exe` and `python3.exe`.
365                    copy_launcher_windows(
366                        WindowsExecutable::GraalPy,
367                        interpreter,
368                        &base_python,
369                        &scripts,
370                        python_home,
371                    )?;
372                    copy_launcher_windows(
373                        WindowsExecutable::PythonMajor,
374                        interpreter,
375                        &base_python,
376                        &scripts,
377                        python_home,
378                    )?;
379                }
380                "pypy" => {
381                    // For PyPy, copy all versioned executables and all PyPy-specific executables.
382                    copy_launcher_windows(
383                        WindowsExecutable::PythonMajor,
384                        interpreter,
385                        &base_python,
386                        &scripts,
387                        python_home,
388                    )?;
389                    copy_launcher_windows(
390                        WindowsExecutable::PythonMajorMinor,
391                        interpreter,
392                        &base_python,
393                        &scripts,
394                        python_home,
395                    )?;
396                    copy_launcher_windows(
397                        WindowsExecutable::Pythonw,
398                        interpreter,
399                        &base_python,
400                        &scripts,
401                        python_home,
402                    )?;
403                    copy_launcher_windows(
404                        WindowsExecutable::PyPy,
405                        interpreter,
406                        &base_python,
407                        &scripts,
408                        python_home,
409                    )?;
410                    copy_launcher_windows(
411                        WindowsExecutable::PyPyMajor,
412                        interpreter,
413                        &base_python,
414                        &scripts,
415                        python_home,
416                    )?;
417                    copy_launcher_windows(
418                        WindowsExecutable::PyPyMajorMinor,
419                        interpreter,
420                        &base_python,
421                        &scripts,
422                        python_home,
423                    )?;
424                    copy_launcher_windows(
425                        WindowsExecutable::PyPyw,
426                        interpreter,
427                        &base_python,
428                        &scripts,
429                        python_home,
430                    )?;
431                    copy_launcher_windows(
432                        WindowsExecutable::PyPyMajorMinorw,
433                        interpreter,
434                        &base_python,
435                        &scripts,
436                        python_home,
437                    )?;
438                }
439                _ => {
440                    // For all other interpreters, copy `pythonw.exe`.
441                    copy_launcher_windows(
442                        WindowsExecutable::Pythonw,
443                        interpreter,
444                        &base_python,
445                        &scripts,
446                        python_home,
447                    )?;
448
449                    // If the GIL is disabled, copy `venvlaunchert.exe` and `venvwlaunchert.exe`.
450                    if interpreter.gil_disabled() {
451                        copy_launcher_windows(
452                            WindowsExecutable::PythonMajorMinort,
453                            interpreter,
454                            &base_python,
455                            &scripts,
456                            python_home,
457                        )?;
458                        copy_launcher_windows(
459                            WindowsExecutable::PythonwMajorMinort,
460                            interpreter,
461                            &base_python,
462                            &scripts,
463                            python_home,
464                        )?;
465                    }
466                }
467            }
468        }
469    }
470
471    #[cfg(not(any(unix, windows)))]
472    {
473        compile_error!("Only Windows and Unix are supported")
474    }
475
476    // Add all the activate scripts for different shells
477    for (name, template) in ACTIVATE_TEMPLATES {
478        // csh has no way to determine its own script location, so a relocatable
479        // activate.csh is not possible. Skip it entirely instead of generating a
480        // non-functional script.
481        if relocatable && *name == "activate.csh" {
482            continue;
483        }
484
485        let path_sep = if cfg!(windows) { ";" } else { ":" };
486
487        let relative_site_packages = [
488            interpreter.virtualenv().purelib.as_path(),
489            interpreter.virtualenv().platlib.as_path(),
490        ]
491        .iter()
492        .dedup()
493        .map(|path| {
494            pathdiff::diff_paths(path, &interpreter.virtualenv().scripts)
495                .expect("Failed to calculate relative path to site-packages")
496        })
497        .map(|path| path.simplified().to_str().unwrap().replace('\\', "\\\\"))
498        .join(path_sep);
499
500        let location_string = location
501            .simplified()
502            .to_str()
503            .ok_or_else(|| Error::NonUtf8Path {
504                path: location.clone(),
505            })?;
506        let virtual_env_dir = match (relocatable, name.to_owned()) {
507            (true, "activate") => Cow::Borrowed(
508                r#"'"$(dirname -- "$(dirname -- "$(realpath -- "$SCRIPT_PATH")")")"'"#,
509            ),
510            (true, "activate.bat") => Cow::Borrowed(r"%~dp0.."),
511            // Batch files use double-quoted paths, so POSIX single-quote escaping
512            // would become part of the value (for example, around apostrophes).
513            (false, "activate.bat") => Cow::Borrowed(location_string),
514            (true, "activate.fish") => {
515                Cow::Borrowed(r"'(dirname -- (dirname -- (realpath -- (status -f))))'")
516            }
517            (true, "activate.nu") => Cow::Borrowed(r"(path self | path dirname | path dirname)"),
518            (false, "activate.nu") => Cow::Owned(format!(
519                "'{}'",
520                escape_posix_for_single_quotes(location_string)
521            )),
522            // Note: `activate.ps1` is already relocatable by default.
523            _ => escape_posix_for_single_quotes(location_string),
524        };
525
526        let virtual_prompt = prompt.as_deref().unwrap_or_default();
527        let virtual_prompt = match *name {
528            "activate.xsh" => Cow::Owned(format!(
529                r#"b"{}".decode("utf-8")"#,
530                virtual_prompt.as_bytes().escape_ascii(),
531            )),
532            _ => Cow::Borrowed(virtual_prompt),
533        };
534
535        let bin_name = match *name {
536            "activate.xsh" => Cow::Owned(bin_name.escape_for_python()),
537            _ => Cow::Borrowed(bin_name),
538        };
539
540        let activator = render_template(
541            template,
542            &[
543                ("RELOCATABLE", if relocatable { "true" } else { "false" }),
544                ("VIRTUAL_ENV_DIR", &virtual_env_dir),
545                ("BIN_NAME", &bin_name),
546                ("VIRTUAL_PROMPT", &virtual_prompt),
547                ("PATH_SEP", path_sep),
548                ("RELATIVE_SITE_PACKAGES", &relative_site_packages),
549            ],
550        );
551        fs_err::write(scripts.join(name), activator.as_bytes())?;
552    }
553
554    let mut pyvenv_cfg_data: Vec<(String, String)> = vec![
555        (
556            "home".to_string(),
557            python_home.simplified_display().to_string(),
558        ),
559        (
560            "implementation".to_string(),
561            interpreter
562                .markers()
563                .platform_python_implementation()
564                .to_string(),
565        ),
566        ("uv".to_string(), version().to_string()),
567        (
568            "version_info".to_string(),
569            if using_minor_version_link {
570                interpreter.python_minor_version().to_string()
571            } else {
572                interpreter.markers().python_full_version().string.clone()
573            },
574        ),
575        (
576            "include-system-site-packages".to_string(),
577            if system_site_packages {
578                "true".to_string()
579            } else {
580                "false".to_string()
581            },
582        ),
583    ];
584
585    if relocatable {
586        pyvenv_cfg_data.push(("relocatable".to_string(), "true".to_string()));
587    }
588
589    match seed {
590        Seed::Enabled => pyvenv_cfg_data.push(("seed".to_string(), "true".to_string())),
591        Seed::Disabled => {}
592    }
593
594    if let Some(prompt) = prompt {
595        pyvenv_cfg_data.push(("prompt".to_string(), prompt));
596    }
597
598    if cfg!(windows) && interpreter.markers().implementation_name() == "graalpy" {
599        pyvenv_cfg_data.push((
600            "venvlauncher_command".to_string(),
601            python_home
602                .join("graalpy.exe")
603                .simplified_display()
604                .to_string(),
605        ));
606    }
607
608    let mut pyvenv_cfg = BufWriter::new(File::create(location.join("pyvenv.cfg"))?);
609    write_cfg(&mut pyvenv_cfg, &pyvenv_cfg_data)?;
610    drop(pyvenv_cfg);
611
612    // Construct the path to the `site-packages` directory.
613    let site_packages = location.join(&interpreter.virtualenv().purelib);
614    fs_err::create_dir_all(&site_packages)?;
615
616    // If necessary, create a symlink from `lib64` to `lib`.
617    // See: https://github.com/python/cpython/blob/b228655c227b2ca298a8ffac44d14ce3d22f6faa/Lib/venv/__init__.py#L135C11-L135C16
618    #[cfg(unix)]
619    if interpreter.pointer_size().is_64()
620        && interpreter.markers().os_name() == "posix"
621        && interpreter.markers().sys_platform() != "darwin"
622    {
623        match fs_err::os::unix::fs::symlink("lib", location.join("lib64")) {
624            Ok(()) => {}
625            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
626            Err(err) => {
627                return Err(err.into());
628            }
629        }
630    }
631
632    if install_distutils_patch(interpreter) {
633        fs_err::write(site_packages.join("_virtualenv.py"), VIRTUALENV_PATCH)?;
634        fs_err::write(site_packages.join("_virtualenv.pth"), "import _virtualenv")?;
635    }
636
637    Ok(VirtualEnvironment {
638        scheme: Scheme {
639            purelib: location.join(&interpreter.virtualenv().purelib),
640            platlib: location.join(&interpreter.virtualenv().platlib),
641            scripts: location.join(&interpreter.virtualenv().scripts),
642            data: location.join(&interpreter.virtualenv().data),
643            include: location.join(&interpreter.virtualenv().include),
644        },
645        root: location,
646        executable,
647        base_executable: base_python,
648    })
649}
650
651/// Prompt a confirmation that the virtual environment should be cleared.
652///
653/// If not a TTY, returns `None`.
654fn confirm_clear(location: &Path, name: &'static str) -> Result<Option<bool>, io::Error> {
655    let term = Term::stderr();
656    if term.is_term() {
657        let prompt = format!(
658            "A {name} already exists at `{}`. Do you want to replace it?",
659            location.user_display(),
660        );
661        let hint = format!(
662            "Use the `{}` flag or set `{}` to skip this prompt",
663            "--clear".green(),
664            "UV_VENV_CLEAR=1".green()
665        );
666        Ok(Some(uv_console::confirm_with_hint(
667            &prompt, &hint, &term, true,
668        )?))
669    } else {
670        Ok(None)
671    }
672}
673
674#[derive(Debug, Copy, Clone, Eq, PartialEq)]
675pub enum ClearNonVirtualenv {
676    /// Allow clearing a non-virtual environment directory.
677    Allow,
678    /// Refuse to clear a non-virtual environment directory.
679    Error,
680}
681
682#[derive(Debug, Copy, Clone, Eq, PartialEq)]
683pub enum RemovalReason {
684    /// The removal was explicitly requested, i.e., with `--clear`.
685    UserRequest(ClearNonVirtualenv),
686    /// The environment can be removed because it is considered temporary, e.g., a build
687    /// environment.
688    TemporaryEnvironment,
689    /// The environment can be removed because it is managed by uv, e.g., a project or tool
690    /// environment.
691    ManagedEnvironment,
692}
693
694impl std::fmt::Display for RemovalReason {
695    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
696        match self {
697            Self::UserRequest(_) => f.write_str("requested with `--clear`"),
698            Self::ManagedEnvironment => f.write_str("environment is managed by uv"),
699            Self::TemporaryEnvironment => f.write_str("environment is temporary"),
700        }
701    }
702}
703
704#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
705pub enum OnExisting {
706    /// Prompt before removing an existing directory.
707    ///
708    /// If a TTY is not available, fail.
709    #[default]
710    Prompt,
711    /// Fail if the directory already exists and is non-empty.
712    Fail,
713    /// Allow an existing directory, overwriting virtual environment files while retaining other
714    /// files in the directory.
715    Allow,
716    /// Remove an existing directory.
717    Remove(RemovalReason),
718}
719
720impl OnExisting {
721    pub fn from_args(
722        allow_existing: bool,
723        clear: bool,
724        no_clear: bool,
725        clear_non_virtualenv: ClearNonVirtualenv,
726    ) -> Self {
727        if allow_existing {
728            Self::Allow
729        } else if clear {
730            Self::Remove(RemovalReason::UserRequest(clear_non_virtualenv))
731        } else if no_clear {
732            Self::Fail
733        } else {
734            Self::Prompt
735        }
736    }
737}
738
739#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
740pub enum Seed {
741    /// Seed the virtual environment with one or more of `pip`, `setuptools`, and `wheel`.
742    Enabled,
743    /// Do not seed the virtual environment.
744    #[default]
745    Disabled,
746}
747
748impl Seed {
749    /// Determine the [`Seed`] setting based on the command-line arguments.
750    pub fn from_args(seed: bool) -> Self {
751        if seed { Self::Enabled } else { Self::Disabled }
752    }
753}
754
755#[derive(Debug, Copy, Clone)]
756enum WindowsExecutable {
757    /// The `python.exe` executable (or `venvlauncher.exe` launcher shim).
758    Python,
759    /// The `python3.exe` executable (or `venvlauncher.exe` launcher shim).
760    PythonMajor,
761    /// The `python3.<minor>.exe` executable (or `venvlauncher.exe` launcher shim).
762    PythonMajorMinor,
763    /// The `python3.<minor>t.exe` executable (or `venvlaunchert.exe` launcher shim).
764    PythonMajorMinort,
765    /// The `pythonw.exe` executable (or `venvwlauncher.exe` launcher shim).
766    Pythonw,
767    /// The `pythonw3.<minor>t.exe` executable (or `venvwlaunchert.exe` launcher shim).
768    PythonwMajorMinort,
769    /// The `pypy.exe` executable.
770    PyPy,
771    /// The `pypy3.exe` executable.
772    PyPyMajor,
773    /// The `pypy3.<minor>.exe` executable.
774    PyPyMajorMinor,
775    /// The `pypyw.exe` executable.
776    PyPyw,
777    /// The `pypy3.<minor>w.exe` executable.
778    PyPyMajorMinorw,
779    /// The `graalpy.exe` executable.
780    GraalPy,
781}
782
783impl WindowsExecutable {
784    /// The name of the Python executable.
785    fn exe(self, interpreter: &Interpreter) -> Cow<'static, OsStr> {
786        match self {
787            Self::Python => Cow::Borrowed(OsStr::new("python.exe")),
788            Self::PythonMajor => Cow::Owned(OsString::from(format!(
789                "python{}.exe",
790                interpreter.python_major()
791            ))),
792            Self::PythonMajorMinor => Cow::Owned(OsString::from(format!(
793                "python{}.{}.exe",
794                interpreter.python_major(),
795                interpreter.python_minor()
796            ))),
797            Self::PythonMajorMinort => Cow::Owned(OsString::from(format!(
798                "python{}.{}t.exe",
799                interpreter.python_major(),
800                interpreter.python_minor()
801            ))),
802            Self::Pythonw => Cow::Borrowed(OsStr::new("pythonw.exe")),
803            Self::PythonwMajorMinort => Cow::Owned(OsString::from(format!(
804                "pythonw{}.{}t.exe",
805                interpreter.python_major(),
806                interpreter.python_minor()
807            ))),
808            Self::PyPy => Cow::Borrowed(OsStr::new("pypy.exe")),
809            Self::PyPyMajor => Cow::Owned(OsString::from(format!(
810                "pypy{}.exe",
811                interpreter.python_major()
812            ))),
813            Self::PyPyMajorMinor => Cow::Owned(OsString::from(format!(
814                "pypy{}.{}.exe",
815                interpreter.python_major(),
816                interpreter.python_minor()
817            ))),
818            Self::PyPyw => Cow::Borrowed(OsStr::new("pypyw.exe")),
819            Self::PyPyMajorMinorw => Cow::Owned(OsString::from(format!(
820                "pypy{}.{}w.exe",
821                interpreter.python_major(),
822                interpreter.python_minor()
823            ))),
824            Self::GraalPy => Cow::Borrowed(OsStr::new("graalpy.exe")),
825        }
826    }
827
828    /// The name of the launcher shim.
829    fn launcher(self, interpreter: &Interpreter) -> &'static str {
830        match self {
831            Self::Python | Self::PythonMajor | Self::PythonMajorMinor
832                if interpreter.gil_disabled() =>
833            {
834                "venvlaunchert.exe"
835            }
836            Self::Python | Self::PythonMajor | Self::PythonMajorMinor => "venvlauncher.exe",
837            Self::Pythonw if interpreter.gil_disabled() => "venvwlaunchert.exe",
838            Self::Pythonw => "venvwlauncher.exe",
839            Self::PythonMajorMinort => "venvlaunchert.exe",
840            Self::PythonwMajorMinort => "venvwlaunchert.exe",
841            // From 3.13 on these should replace the `python.exe` and `pythonw.exe` shims.
842            // These are not relevant as of now for PyPy as it doesn't yet support Python 3.13.
843            Self::PyPy | Self::PyPyMajor | Self::PyPyMajorMinor => "venvlauncher.exe",
844            Self::PyPyw | Self::PyPyMajorMinorw => "venvwlauncher.exe",
845            Self::GraalPy => "venvlauncher.exe",
846        }
847    }
848}
849
850/// <https://github.com/python/cpython/blob/d457345bbc6414db0443819290b04a9a4333313d/Lib/venv/__init__.py#L261-L267>
851/// <https://github.com/pypa/virtualenv/blob/d9fdf48d69f0d0ca56140cf0381edbb5d6fe09f5/src/virtualenv/create/via_global_ref/builtin/cpython/cpython3.py#L78-L83>
852///
853/// There's two kinds of applications on windows: Those that allocate a console (python.exe)
854/// and those that don't because they use window(s) (pythonw.exe).
855fn copy_launcher_windows(
856    executable: WindowsExecutable,
857    interpreter: &Interpreter,
858    base_python: &Path,
859    scripts: &Path,
860    python_home: &Path,
861) -> Result<(), Error> {
862    // First priority: the `python.exe` and `pythonw.exe` shims.
863    let shim = interpreter
864        .stdlib()
865        .join("venv")
866        .join("scripts")
867        .join("nt")
868        .join(executable.exe(interpreter));
869    match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
870        Ok(_) => return Ok(()),
871        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
872        Err(err) => {
873            return Err(err.into());
874        }
875    }
876
877    // Second priority: the `venvlauncher.exe` and `venvwlauncher.exe` shims.
878    // These are equivalent to the `python.exe` and `pythonw.exe` shims, which were
879    // renamed in Python 3.13.
880    let shim = interpreter
881        .stdlib()
882        .join("venv")
883        .join("scripts")
884        .join("nt")
885        .join(executable.launcher(interpreter));
886    match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
887        Ok(_) => return Ok(()),
888        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
889        Err(err) => {
890            return Err(err.into());
891        }
892    }
893
894    // Third priority: on Conda at least, we can look for the launcher shim next to
895    // the Python executable itself.
896    let shim = base_python.with_file_name(executable.launcher(interpreter));
897    match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
898        Ok(_) => return Ok(()),
899        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
900        Err(err) => {
901            return Err(err.into());
902        }
903    }
904
905    // Fourth priority: if the launcher shim doesn't exist, assume this is
906    // an embedded Python. Copy the Python executable itself, along with
907    // the DLLs, `.pyd` files, and `.zip` files in the same directory.
908    match fs_err::copy(
909        base_python.with_file_name(executable.exe(interpreter)),
910        scripts.join(executable.exe(interpreter)),
911    ) {
912        Ok(_) => {
913            // Copy `.dll` and `.pyd` files from the top-level, and from the
914            // `DLLs` subdirectory (if it exists).
915            for directory in [
916                python_home,
917                interpreter.sys_base_prefix().join("DLLs").as_path(),
918            ] {
919                let entries = match fs_err::read_dir(directory) {
920                    Ok(read_dir) => read_dir,
921                    Err(err) if err.kind() == io::ErrorKind::NotFound => {
922                        continue;
923                    }
924                    Err(err) => {
925                        return Err(err.into());
926                    }
927                };
928                for entry in entries {
929                    let entry = entry?;
930                    let path = entry.path();
931                    if path.extension().is_some_and(|ext| {
932                        ext.eq_ignore_ascii_case("dll") || ext.eq_ignore_ascii_case("pyd")
933                    }) {
934                        if let Some(file_name) = path.file_name() {
935                            fs_err::copy(&path, scripts.join(file_name))?;
936                        }
937                    }
938                }
939            }
940
941            // Copy `.zip` files from the top-level.
942            match fs_err::read_dir(python_home) {
943                Ok(entries) => {
944                    for entry in entries {
945                        let entry = entry?;
946                        let path = entry.path();
947                        if path
948                            .extension()
949                            .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
950                        {
951                            if let Some(file_name) = path.file_name() {
952                                fs_err::copy(&path, scripts.join(file_name))?;
953                            }
954                        }
955                    }
956                }
957                Err(err) if err.kind() == io::ErrorKind::NotFound => {}
958                Err(err) => {
959                    return Err(err.into());
960                }
961            }
962
963            return Ok(());
964        }
965        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
966        Err(err) => {
967            return Err(err.into());
968        }
969    }
970
971    Err(Error::NotFound(base_python.user_display().to_string()))
972}