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