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_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
29const 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
47fn install_distutils_patch(interpreter: &Interpreter) -> bool {
52 interpreter.python_tuple() < (3, 10)
53 || !uv_preview::is_enabled(PreviewFeature::NoDistutilsPatch)
54}
55
56fn 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
64pub(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 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 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 if absolute.simplified().to_str().is_none() {
106 return Err(Error::NonUtf8Path { path: absolute });
107 }
108
109 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 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 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 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 None => {
174 return Err(Error::Exists {
175 name,
176 path: location.to_path_buf(),
177 });
178 }
179 }
180 }
181 }
182 }
183 Ok(_) => {
184 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 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 cachedir::ensure_tag(&location)?;
210
211 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 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 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 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 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 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 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 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 copy_launcher_windows(
420 WindowsExecutable::Pythonw,
421 interpreter,
422 &base_python,
423 &scripts,
424 python_home,
425 )?;
426
427 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 for (name, template) in ACTIVATE_TEMPLATES {
456 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 _ => 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 let site_packages = location.join(&interpreter.virtualenv().purelib);
584 fs_err::create_dir_all(&site_packages)?;
585
586 #[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
621fn 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,
648 Error,
650}
651
652#[derive(Debug, Copy, Clone, Eq, PartialEq)]
653pub enum RemovalReason {
654 UserRequest(ClearNonVirtualenv),
656 TemporaryEnvironment,
659 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 #[default]
680 Prompt,
681 Fail,
683 Allow,
686 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 Enabled,
713 #[default]
715 Disabled,
716}
717
718impl Seed {
719 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 Python,
729 PythonMajor,
731 PythonMajorMinor,
733 PythonMajorMinort,
735 Pythonw,
737 PythonwMajorMinort,
739 PyPy,
741 PyPyMajor,
743 PyPyMajorMinor,
745 PyPyw,
747 PyPyMajorMinorw,
749 GraalPy,
751}
752
753impl WindowsExecutable {
754 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 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 Self::PyPy | Self::PyPyMajor | Self::PyPyMajorMinor => "venvlauncher.exe",
814 Self::PyPyw | Self::PyPyMajorMinorw => "venvwlauncher.exe",
815 Self::GraalPy => "venvlauncher.exe",
816 }
817 }
818}
819
820fn copy_launcher_windows(
826 executable: WindowsExecutable,
827 interpreter: &Interpreter,
828 base_python: &Path,
829 scripts: &Path,
830 python_home: &Path,
831) -> Result<(), Error> {
832 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 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 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 match fs_err::copy(
879 base_python.with_file_name(executable.exe(interpreter)),
880 scripts.join(executable.exe(interpreter)),
881 ) {
882 Ok(_) => {
883 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 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}