1use 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
28const 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
46fn install_distutils_patch(interpreter: &Interpreter) -> bool {
51 interpreter.python_tuple() < (3, 10)
52}
53
54fn 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
62pub(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 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 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 if absolute.simplified().to_str().is_none() {
109 return Err(Error::NonUtf8Path { path: absolute });
110 }
111
112 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 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 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 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 None => {
177 return Err(Error::Exists {
178 name,
179 path: location.to_path_buf(),
180 });
181 }
182 }
183 }
184 }
185 }
186 Ok(_) => {
187 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 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 cachedir::ensure_tag(&location)?;
213
214 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 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 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 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 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 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 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 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 copy_launcher_windows(
430 WindowsExecutable::Pythonw,
431 interpreter,
432 &base_python,
433 &scripts,
434 python_home,
435 )?;
436
437 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 for (name, template) in ACTIVATE_TEMPLATES {
466 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 _ => 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 template = if *name == "activate" {
526 Cow::Owned(template.replace(
527 "{{ RELOCATABLE }}",
528 if relocatable { "true" } else { "false" },
529 ))
530 } else {
531 Cow::Borrowed(*template)
532 };
533 let activator = template
534 .replace("{{ VIRTUAL_ENV_DIR }}", &virtual_env_dir)
535 .replace("{{ BIN_NAME }}", &bin_name)
536 .replace("{{ VIRTUAL_PROMPT }}", &virtual_prompt)
537 .replace("{{ PATH_SEP }}", path_sep)
538 .replace("{{ RELATIVE_SITE_PACKAGES }}", &relative_site_packages);
539 fs_err::write(scripts.join(name), activator)?;
540 }
541
542 let mut pyvenv_cfg_data: Vec<(String, String)> = vec![
543 (
544 "home".to_string(),
545 python_home.simplified_display().to_string(),
546 ),
547 (
548 "implementation".to_string(),
549 interpreter
550 .markers()
551 .platform_python_implementation()
552 .to_string(),
553 ),
554 ("uv".to_string(), version().to_string()),
555 (
556 "version_info".to_string(),
557 if using_minor_version_link {
558 interpreter.python_minor_version().to_string()
559 } else {
560 interpreter.markers().python_full_version().string.clone()
561 },
562 ),
563 (
564 "include-system-site-packages".to_string(),
565 if system_site_packages {
566 "true".to_string()
567 } else {
568 "false".to_string()
569 },
570 ),
571 ];
572
573 if relocatable {
574 pyvenv_cfg_data.push(("relocatable".to_string(), "true".to_string()));
575 }
576
577 match seed {
578 Seed::Enabled => pyvenv_cfg_data.push(("seed".to_string(), "true".to_string())),
579 Seed::Disabled => {}
580 }
581
582 if let Some(prompt) = prompt {
583 pyvenv_cfg_data.push(("prompt".to_string(), prompt));
584 }
585
586 if cfg!(windows) && interpreter.markers().implementation_name() == "graalpy" {
587 pyvenv_cfg_data.push((
588 "venvlauncher_command".to_string(),
589 python_home
590 .join("graalpy.exe")
591 .simplified_display()
592 .to_string(),
593 ));
594 }
595
596 let mut pyvenv_cfg = BufWriter::new(File::create(location.join("pyvenv.cfg"))?);
597 write_cfg(&mut pyvenv_cfg, &pyvenv_cfg_data)?;
598 drop(pyvenv_cfg);
599
600 let site_packages = location.join(&interpreter.virtualenv().purelib);
602 fs_err::create_dir_all(&site_packages)?;
603
604 #[cfg(unix)]
607 if interpreter.pointer_size().is_64()
608 && interpreter.markers().os_name() == "posix"
609 && interpreter.markers().sys_platform() != "darwin"
610 {
611 match fs_err::os::unix::fs::symlink("lib", location.join("lib64")) {
612 Ok(()) => {}
613 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
614 Err(err) => {
615 return Err(err.into());
616 }
617 }
618 }
619
620 if install_distutils_patch(interpreter) {
621 fs_err::write(site_packages.join("_virtualenv.py"), VIRTUALENV_PATCH)?;
622 fs_err::write(site_packages.join("_virtualenv.pth"), "import _virtualenv")?;
623 }
624
625 Ok(VirtualEnvironment {
626 scheme: Scheme {
627 purelib: location.join(&interpreter.virtualenv().purelib),
628 platlib: location.join(&interpreter.virtualenv().platlib),
629 scripts: location.join(&interpreter.virtualenv().scripts),
630 data: location.join(&interpreter.virtualenv().data),
631 include: location.join(&interpreter.virtualenv().include),
632 },
633 root: location,
634 executable,
635 base_executable: base_python,
636 })
637}
638
639fn confirm_clear(location: &Path, name: &'static str) -> Result<Option<bool>, io::Error> {
643 let term = Term::stderr();
644 if term.is_term() {
645 let prompt = format!(
646 "A {name} already exists at `{}`. Do you want to replace it?",
647 location.user_display(),
648 );
649 let hint = format!(
650 "Use the `{}` flag or set `{}` to skip this prompt",
651 "--clear".green(),
652 "UV_VENV_CLEAR=1".green()
653 );
654 Ok(Some(uv_console::confirm_with_hint(
655 &prompt, &hint, &term, true,
656 )?))
657 } else {
658 Ok(None)
659 }
660}
661
662#[derive(Debug, Copy, Clone, Eq, PartialEq)]
663pub enum ClearNonVirtualenv {
664 Allow,
666 Error,
668}
669
670#[derive(Debug, Copy, Clone, Eq, PartialEq)]
671pub enum RemovalReason {
672 UserRequest(ClearNonVirtualenv),
674 TemporaryEnvironment,
677 ManagedEnvironment,
680}
681
682impl std::fmt::Display for RemovalReason {
683 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
684 match self {
685 Self::UserRequest(_) => f.write_str("requested with `--clear`"),
686 Self::ManagedEnvironment => f.write_str("environment is managed by uv"),
687 Self::TemporaryEnvironment => f.write_str("environment is temporary"),
688 }
689 }
690}
691
692#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
693pub enum OnExisting {
694 #[default]
698 Prompt,
699 Fail,
701 Allow,
704 Remove(RemovalReason),
706}
707
708impl OnExisting {
709 pub fn from_args(
710 allow_existing: bool,
711 clear: bool,
712 no_clear: bool,
713 clear_non_virtualenv: ClearNonVirtualenv,
714 ) -> Self {
715 if allow_existing {
716 Self::Allow
717 } else if clear {
718 Self::Remove(RemovalReason::UserRequest(clear_non_virtualenv))
719 } else if no_clear {
720 Self::Fail
721 } else {
722 Self::Prompt
723 }
724 }
725}
726
727#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
728pub enum Seed {
729 Enabled,
731 #[default]
733 Disabled,
734}
735
736impl Seed {
737 pub fn from_args(seed: bool) -> Self {
739 if seed { Self::Enabled } else { Self::Disabled }
740 }
741}
742
743#[derive(Debug, Copy, Clone)]
744enum WindowsExecutable {
745 Python,
747 PythonMajor,
749 PythonMajorMinor,
751 PythonMajorMinort,
753 Pythonw,
755 PythonwMajorMinort,
757 PyPy,
759 PyPyMajor,
761 PyPyMajorMinor,
763 PyPyw,
765 PyPyMajorMinorw,
767 GraalPy,
769}
770
771impl WindowsExecutable {
772 fn exe(self, interpreter: &Interpreter) -> Cow<'static, OsStr> {
774 match self {
775 Self::Python => Cow::Borrowed(OsStr::new("python.exe")),
776 Self::PythonMajor => Cow::Owned(OsString::from(format!(
777 "python{}.exe",
778 interpreter.python_major()
779 ))),
780 Self::PythonMajorMinor => Cow::Owned(OsString::from(format!(
781 "python{}.{}.exe",
782 interpreter.python_major(),
783 interpreter.python_minor()
784 ))),
785 Self::PythonMajorMinort => Cow::Owned(OsString::from(format!(
786 "python{}.{}t.exe",
787 interpreter.python_major(),
788 interpreter.python_minor()
789 ))),
790 Self::Pythonw => Cow::Borrowed(OsStr::new("pythonw.exe")),
791 Self::PythonwMajorMinort => Cow::Owned(OsString::from(format!(
792 "pythonw{}.{}t.exe",
793 interpreter.python_major(),
794 interpreter.python_minor()
795 ))),
796 Self::PyPy => Cow::Borrowed(OsStr::new("pypy.exe")),
797 Self::PyPyMajor => Cow::Owned(OsString::from(format!(
798 "pypy{}.exe",
799 interpreter.python_major()
800 ))),
801 Self::PyPyMajorMinor => Cow::Owned(OsString::from(format!(
802 "pypy{}.{}.exe",
803 interpreter.python_major(),
804 interpreter.python_minor()
805 ))),
806 Self::PyPyw => Cow::Borrowed(OsStr::new("pypyw.exe")),
807 Self::PyPyMajorMinorw => Cow::Owned(OsString::from(format!(
808 "pypy{}.{}w.exe",
809 interpreter.python_major(),
810 interpreter.python_minor()
811 ))),
812 Self::GraalPy => Cow::Borrowed(OsStr::new("graalpy.exe")),
813 }
814 }
815
816 fn launcher(self, interpreter: &Interpreter) -> &'static str {
818 match self {
819 Self::Python | Self::PythonMajor | Self::PythonMajorMinor
820 if interpreter.gil_disabled() =>
821 {
822 "venvlaunchert.exe"
823 }
824 Self::Python | Self::PythonMajor | Self::PythonMajorMinor => "venvlauncher.exe",
825 Self::Pythonw if interpreter.gil_disabled() => "venvwlaunchert.exe",
826 Self::Pythonw => "venvwlauncher.exe",
827 Self::PythonMajorMinort => "venvlaunchert.exe",
828 Self::PythonwMajorMinort => "venvwlaunchert.exe",
829 Self::PyPy | Self::PyPyMajor | Self::PyPyMajorMinor => "venvlauncher.exe",
832 Self::PyPyw | Self::PyPyMajorMinorw => "venvwlauncher.exe",
833 Self::GraalPy => "venvlauncher.exe",
834 }
835 }
836}
837
838fn copy_launcher_windows(
844 executable: WindowsExecutable,
845 interpreter: &Interpreter,
846 base_python: &Path,
847 scripts: &Path,
848 python_home: &Path,
849) -> Result<(), Error> {
850 let shim = interpreter
852 .stdlib()
853 .join("venv")
854 .join("scripts")
855 .join("nt")
856 .join(executable.exe(interpreter));
857 match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
858 Ok(_) => return Ok(()),
859 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
860 Err(err) => {
861 return Err(err.into());
862 }
863 }
864
865 let shim = interpreter
869 .stdlib()
870 .join("venv")
871 .join("scripts")
872 .join("nt")
873 .join(executable.launcher(interpreter));
874 match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
875 Ok(_) => return Ok(()),
876 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
877 Err(err) => {
878 return Err(err.into());
879 }
880 }
881
882 let shim = base_python.with_file_name(executable.launcher(interpreter));
885 match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
886 Ok(_) => return Ok(()),
887 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
888 Err(err) => {
889 return Err(err.into());
890 }
891 }
892
893 match fs_err::copy(
897 base_python.with_file_name(executable.exe(interpreter)),
898 scripts.join(executable.exe(interpreter)),
899 ) {
900 Ok(_) => {
901 for directory in [
904 python_home,
905 interpreter.sys_base_prefix().join("DLLs").as_path(),
906 ] {
907 let entries = match fs_err::read_dir(directory) {
908 Ok(read_dir) => read_dir,
909 Err(err) if err.kind() == io::ErrorKind::NotFound => {
910 continue;
911 }
912 Err(err) => {
913 return Err(err.into());
914 }
915 };
916 for entry in entries {
917 let entry = entry?;
918 let path = entry.path();
919 if path.extension().is_some_and(|ext| {
920 ext.eq_ignore_ascii_case("dll") || ext.eq_ignore_ascii_case("pyd")
921 }) {
922 if let Some(file_name) = path.file_name() {
923 fs_err::copy(&path, scripts.join(file_name))?;
924 }
925 }
926 }
927 }
928
929 match fs_err::read_dir(python_home) {
931 Ok(entries) => {
932 for entry in entries {
933 let entry = entry?;
934 let path = entry.path();
935 if path
936 .extension()
937 .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
938 {
939 if let Some(file_name) = path.file_name() {
940 fs_err::copy(&path, scripts.join(file_name))?;
941 }
942 }
943 }
944 }
945 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
946 Err(err) => {
947 return Err(err.into());
948 }
949 }
950
951 return Ok(());
952 }
953 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
954 Err(err) => {
955 return Err(err.into());
956 }
957 }
958
959 Err(Error::NotFound(base_python.user_display().to_string()))
960}