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