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            (true, "activate.fish") => {
500                Cow::Borrowed(r"'(dirname -- (dirname -- (realpath -- (status -f))))'")
501            }
502            (true, "activate.nu") => Cow::Borrowed(r"(path self | path dirname | path dirname)"),
503            (false, "activate.nu") => Cow::Owned(format!(
504                "'{}'",
505                escape_posix_for_single_quotes(location_string)
506            )),
507            // Note: `activate.ps1` is already relocatable by default.
508            _ => escape_posix_for_single_quotes(location_string),
509        };
510
511        let virtual_prompt = prompt.as_deref().unwrap_or_default();
512        let virtual_prompt = match *name {
513            "activate.xsh" => Cow::Owned(format!(
514                r#"b"{}".decode("utf-8")"#,
515                virtual_prompt.as_bytes().escape_ascii(),
516            )),
517            _ => Cow::Borrowed(virtual_prompt),
518        };
519
520        let bin_name = match *name {
521            "activate.xsh" => Cow::Owned(bin_name.escape_for_python()),
522            _ => Cow::Borrowed(bin_name),
523        };
524
525        let activator = template
526            .replace("{{ VIRTUAL_ENV_DIR }}", &virtual_env_dir)
527            .replace("{{ BIN_NAME }}", &bin_name)
528            .replace("{{ VIRTUAL_PROMPT }}", &virtual_prompt)
529            .replace("{{ PATH_SEP }}", path_sep)
530            .replace("{{ RELATIVE_SITE_PACKAGES }}", &relative_site_packages);
531        fs_err::write(scripts.join(name), activator)?;
532    }
533
534    let mut pyvenv_cfg_data: Vec<(String, String)> = vec![
535        (
536            "home".to_string(),
537            python_home.simplified_display().to_string(),
538        ),
539        (
540            "implementation".to_string(),
541            interpreter
542                .markers()
543                .platform_python_implementation()
544                .to_string(),
545        ),
546        ("uv".to_string(), version().to_string()),
547        (
548            "version_info".to_string(),
549            if using_minor_version_link {
550                interpreter.python_minor_version().to_string()
551            } else {
552                interpreter.markers().python_full_version().string.clone()
553            },
554        ),
555        (
556            "include-system-site-packages".to_string(),
557            if system_site_packages {
558                "true".to_string()
559            } else {
560                "false".to_string()
561            },
562        ),
563    ];
564
565    if relocatable {
566        pyvenv_cfg_data.push(("relocatable".to_string(), "true".to_string()));
567    }
568
569    match seed {
570        Seed::Enabled => pyvenv_cfg_data.push(("seed".to_string(), "true".to_string())),
571        Seed::Disabled => {}
572    }
573
574    if let Some(prompt) = prompt {
575        pyvenv_cfg_data.push(("prompt".to_string(), prompt));
576    }
577
578    if cfg!(windows) && interpreter.markers().implementation_name() == "graalpy" {
579        pyvenv_cfg_data.push((
580            "venvlauncher_command".to_string(),
581            python_home
582                .join("graalpy.exe")
583                .simplified_display()
584                .to_string(),
585        ));
586    }
587
588    let mut pyvenv_cfg = BufWriter::new(File::create(location.join("pyvenv.cfg"))?);
589    write_cfg(&mut pyvenv_cfg, &pyvenv_cfg_data)?;
590    drop(pyvenv_cfg);
591
592    // Construct the path to the `site-packages` directory.
593    let site_packages = location.join(&interpreter.virtualenv().purelib);
594    fs_err::create_dir_all(&site_packages)?;
595
596    // If necessary, create a symlink from `lib64` to `lib`.
597    // See: https://github.com/python/cpython/blob/b228655c227b2ca298a8ffac44d14ce3d22f6faa/Lib/venv/__init__.py#L135C11-L135C16
598    #[cfg(unix)]
599    if interpreter.pointer_size().is_64()
600        && interpreter.markers().os_name() == "posix"
601        && interpreter.markers().sys_platform() != "darwin"
602    {
603        match fs_err::os::unix::fs::symlink("lib", location.join("lib64")) {
604            Ok(()) => {}
605            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
606            Err(err) => {
607                return Err(err.into());
608            }
609        }
610    }
611
612    if install_distutils_patch(interpreter) {
613        fs_err::write(site_packages.join("_virtualenv.py"), VIRTUALENV_PATCH)?;
614        fs_err::write(site_packages.join("_virtualenv.pth"), "import _virtualenv")?;
615    }
616
617    Ok(VirtualEnvironment {
618        scheme: Scheme {
619            purelib: location.join(&interpreter.virtualenv().purelib),
620            platlib: location.join(&interpreter.virtualenv().platlib),
621            scripts: location.join(&interpreter.virtualenv().scripts),
622            data: location.join(&interpreter.virtualenv().data),
623            include: location.join(&interpreter.virtualenv().include),
624        },
625        root: location,
626        executable,
627        base_executable: base_python,
628    })
629}
630
631/// Prompt a confirmation that the virtual environment should be cleared.
632///
633/// If not a TTY, returns `None`.
634fn confirm_clear(location: &Path, name: &'static str) -> Result<Option<bool>, io::Error> {
635    let term = Term::stderr();
636    if term.is_term() {
637        let prompt = format!(
638            "A {name} already exists at `{}`. Do you want to replace it?",
639            location.user_display(),
640        );
641        let hint = format!(
642            "Use the `{}` flag or set `{}` to skip this prompt",
643            "--clear".green(),
644            "UV_VENV_CLEAR=1".green()
645        );
646        Ok(Some(uv_console::confirm_with_hint(
647            &prompt, &hint, &term, true,
648        )?))
649    } else {
650        Ok(None)
651    }
652}
653
654#[derive(Debug, Copy, Clone, Eq, PartialEq)]
655pub enum ClearNonVirtualenv {
656    /// Allow clearing a non-virtual environment directory.
657    Allow,
658    /// Refuse to clear a non-virtual environment directory.
659    Error,
660}
661
662#[derive(Debug, Copy, Clone, Eq, PartialEq)]
663pub enum RemovalReason {
664    /// The removal was explicitly requested, i.e., with `--clear`.
665    UserRequest(ClearNonVirtualenv),
666    /// The environment can be removed because it is considered temporary, e.g., a build
667    /// environment.
668    TemporaryEnvironment,
669    /// The environment can be removed because it is managed by uv, e.g., a project or tool
670    /// environment.
671    ManagedEnvironment,
672}
673
674impl std::fmt::Display for RemovalReason {
675    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
676        match self {
677            Self::UserRequest(_) => f.write_str("requested with `--clear`"),
678            Self::ManagedEnvironment => f.write_str("environment is managed by uv"),
679            Self::TemporaryEnvironment => f.write_str("environment is temporary"),
680        }
681    }
682}
683
684#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
685pub enum OnExisting {
686    /// Prompt before removing an existing directory.
687    ///
688    /// If a TTY is not available, fail.
689    #[default]
690    Prompt,
691    /// Fail if the directory already exists and is non-empty.
692    Fail,
693    /// Allow an existing directory, overwriting virtual environment files while retaining other
694    /// files in the directory.
695    Allow,
696    /// Remove an existing directory.
697    Remove(RemovalReason),
698}
699
700impl OnExisting {
701    pub fn from_args(
702        allow_existing: bool,
703        clear: bool,
704        no_clear: bool,
705        clear_non_virtualenv: ClearNonVirtualenv,
706    ) -> Self {
707        if allow_existing {
708            Self::Allow
709        } else if clear {
710            Self::Remove(RemovalReason::UserRequest(clear_non_virtualenv))
711        } else if no_clear {
712            Self::Fail
713        } else {
714            Self::Prompt
715        }
716    }
717}
718
719#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
720pub enum Seed {
721    /// Seed the virtual environment with one or more of `pip`, `setuptools`, and `wheel`.
722    Enabled,
723    /// Do not seed the virtual environment.
724    #[default]
725    Disabled,
726}
727
728impl Seed {
729    /// Determine the [`Seed`] setting based on the command-line arguments.
730    pub fn from_args(seed: bool) -> Self {
731        if seed { Self::Enabled } else { Self::Disabled }
732    }
733}
734
735#[derive(Debug, Copy, Clone)]
736enum WindowsExecutable {
737    /// The `python.exe` executable (or `venvlauncher.exe` launcher shim).
738    Python,
739    /// The `python3.exe` executable (or `venvlauncher.exe` launcher shim).
740    PythonMajor,
741    /// The `python3.<minor>.exe` executable (or `venvlauncher.exe` launcher shim).
742    PythonMajorMinor,
743    /// The `python3.<minor>t.exe` executable (or `venvlaunchert.exe` launcher shim).
744    PythonMajorMinort,
745    /// The `pythonw.exe` executable (or `venvwlauncher.exe` launcher shim).
746    Pythonw,
747    /// The `pythonw3.<minor>t.exe` executable (or `venvwlaunchert.exe` launcher shim).
748    PythonwMajorMinort,
749    /// The `pypy.exe` executable.
750    PyPy,
751    /// The `pypy3.exe` executable.
752    PyPyMajor,
753    /// The `pypy3.<minor>.exe` executable.
754    PyPyMajorMinor,
755    /// The `pypyw.exe` executable.
756    PyPyw,
757    /// The `pypy3.<minor>w.exe` executable.
758    PyPyMajorMinorw,
759    /// The `graalpy.exe` executable.
760    GraalPy,
761}
762
763impl WindowsExecutable {
764    /// The name of the Python executable.
765    fn exe(self, interpreter: &Interpreter) -> Cow<'static, OsStr> {
766        match self {
767            Self::Python => Cow::Borrowed(OsStr::new("python.exe")),
768            Self::PythonMajor => Cow::Owned(OsString::from(format!(
769                "python{}.exe",
770                interpreter.python_major()
771            ))),
772            Self::PythonMajorMinor => Cow::Owned(OsString::from(format!(
773                "python{}.{}.exe",
774                interpreter.python_major(),
775                interpreter.python_minor()
776            ))),
777            Self::PythonMajorMinort => Cow::Owned(OsString::from(format!(
778                "python{}.{}t.exe",
779                interpreter.python_major(),
780                interpreter.python_minor()
781            ))),
782            Self::Pythonw => Cow::Borrowed(OsStr::new("pythonw.exe")),
783            Self::PythonwMajorMinort => Cow::Owned(OsString::from(format!(
784                "pythonw{}.{}t.exe",
785                interpreter.python_major(),
786                interpreter.python_minor()
787            ))),
788            Self::PyPy => Cow::Borrowed(OsStr::new("pypy.exe")),
789            Self::PyPyMajor => Cow::Owned(OsString::from(format!(
790                "pypy{}.exe",
791                interpreter.python_major()
792            ))),
793            Self::PyPyMajorMinor => Cow::Owned(OsString::from(format!(
794                "pypy{}.{}.exe",
795                interpreter.python_major(),
796                interpreter.python_minor()
797            ))),
798            Self::PyPyw => Cow::Borrowed(OsStr::new("pypyw.exe")),
799            Self::PyPyMajorMinorw => Cow::Owned(OsString::from(format!(
800                "pypy{}.{}w.exe",
801                interpreter.python_major(),
802                interpreter.python_minor()
803            ))),
804            Self::GraalPy => Cow::Borrowed(OsStr::new("graalpy.exe")),
805        }
806    }
807
808    /// The name of the launcher shim.
809    fn launcher(self, interpreter: &Interpreter) -> &'static str {
810        match self {
811            Self::Python | Self::PythonMajor | Self::PythonMajorMinor
812                if interpreter.gil_disabled() =>
813            {
814                "venvlaunchert.exe"
815            }
816            Self::Python | Self::PythonMajor | Self::PythonMajorMinor => "venvlauncher.exe",
817            Self::Pythonw if interpreter.gil_disabled() => "venvwlaunchert.exe",
818            Self::Pythonw => "venvwlauncher.exe",
819            Self::PythonMajorMinort => "venvlaunchert.exe",
820            Self::PythonwMajorMinort => "venvwlaunchert.exe",
821            // From 3.13 on these should replace the `python.exe` and `pythonw.exe` shims.
822            // These are not relevant as of now for PyPy as it doesn't yet support Python 3.13.
823            Self::PyPy | Self::PyPyMajor | Self::PyPyMajorMinor => "venvlauncher.exe",
824            Self::PyPyw | Self::PyPyMajorMinorw => "venvwlauncher.exe",
825            Self::GraalPy => "venvlauncher.exe",
826        }
827    }
828}
829
830/// <https://github.com/python/cpython/blob/d457345bbc6414db0443819290b04a9a4333313d/Lib/venv/__init__.py#L261-L267>
831/// <https://github.com/pypa/virtualenv/blob/d9fdf48d69f0d0ca56140cf0381edbb5d6fe09f5/src/virtualenv/create/via_global_ref/builtin/cpython/cpython3.py#L78-L83>
832///
833/// There's two kinds of applications on windows: Those that allocate a console (python.exe)
834/// and those that don't because they use window(s) (pythonw.exe).
835fn copy_launcher_windows(
836    executable: WindowsExecutable,
837    interpreter: &Interpreter,
838    base_python: &Path,
839    scripts: &Path,
840    python_home: &Path,
841) -> Result<(), Error> {
842    // First priority: the `python.exe` and `pythonw.exe` shims.
843    let shim = interpreter
844        .stdlib()
845        .join("venv")
846        .join("scripts")
847        .join("nt")
848        .join(executable.exe(interpreter));
849    match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
850        Ok(_) => return Ok(()),
851        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
852        Err(err) => {
853            return Err(err.into());
854        }
855    }
856
857    // Second priority: the `venvlauncher.exe` and `venvwlauncher.exe` shims.
858    // These are equivalent to the `python.exe` and `pythonw.exe` shims, which were
859    // renamed in Python 3.13.
860    let shim = interpreter
861        .stdlib()
862        .join("venv")
863        .join("scripts")
864        .join("nt")
865        .join(executable.launcher(interpreter));
866    match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
867        Ok(_) => return Ok(()),
868        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
869        Err(err) => {
870            return Err(err.into());
871        }
872    }
873
874    // Third priority: on Conda at least, we can look for the launcher shim next to
875    // the Python executable itself.
876    let shim = base_python.with_file_name(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    // Fourth priority: if the launcher shim doesn't exist, assume this is
886    // an embedded Python. Copy the Python executable itself, along with
887    // the DLLs, `.pyd` files, and `.zip` files in the same directory.
888    match fs_err::copy(
889        base_python.with_file_name(executable.exe(interpreter)),
890        scripts.join(executable.exe(interpreter)),
891    ) {
892        Ok(_) => {
893            // Copy `.dll` and `.pyd` files from the top-level, and from the
894            // `DLLs` subdirectory (if it exists).
895            for directory in [
896                python_home,
897                interpreter.sys_base_prefix().join("DLLs").as_path(),
898            ] {
899                let entries = match fs_err::read_dir(directory) {
900                    Ok(read_dir) => read_dir,
901                    Err(err) if err.kind() == io::ErrorKind::NotFound => {
902                        continue;
903                    }
904                    Err(err) => {
905                        return Err(err.into());
906                    }
907                };
908                for entry in entries {
909                    let entry = entry?;
910                    let path = entry.path();
911                    if path.extension().is_some_and(|ext| {
912                        ext.eq_ignore_ascii_case("dll") || ext.eq_ignore_ascii_case("pyd")
913                    }) {
914                        if let Some(file_name) = path.file_name() {
915                            fs_err::copy(&path, scripts.join(file_name))?;
916                        }
917                    }
918                }
919            }
920
921            // Copy `.zip` files from the top-level.
922            match fs_err::read_dir(python_home) {
923                Ok(entries) => {
924                    for entry in entries {
925                        let entry = entry?;
926                        let path = entry.path();
927                        if path
928                            .extension()
929                            .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
930                        {
931                            if let Some(file_name) = path.file_name() {
932                                fs_err::copy(&path, scripts.join(file_name))?;
933                            }
934                        }
935                    }
936                }
937                Err(err) if err.kind() == io::ErrorKind::NotFound => {}
938                Err(err) => {
939                    return Err(err.into());
940                }
941            }
942
943            return Ok(());
944        }
945        Err(err) if err.kind() == io::ErrorKind::NotFound => {}
946        Err(err) => {
947            return Err(err.into());
948        }
949    }
950
951    Err(Error::NotFound(base_python.user_display().to_string()))
952}