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