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_interpreter::{Interpreter, VirtualEnvironment};
23use uv_python_managed::{
24 PythonExecutable, PythonMinorVersionLink, UpgradePolicy, replace_link_to_executable,
25};
26use uv_shell::escape_posix_for_single_quotes;
27use uv_version::version;
28
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 upgrade_policy: UpgradePolicy,
74) -> Result<VirtualEnvironment, Error> {
75 let base_python = cfg_select! {
81 unix => {
82 if interpreter.is_standalone() {
83 interpreter.find_base_python()?
84 } else {
85 interpreter.to_base_python()?
86 }
87 }
88 _ => { interpreter.to_base_python()? }
89 };
90
91 debug!(
92 "Using base executable for virtual environment: {}",
93 base_python.display()
94 );
95
96 let prompt = match prompt {
100 Prompt::CurrentDirectoryName => CWD
101 .file_name()
102 .map(|name| name.to_string_lossy().to_string()),
103 Prompt::Static(value) => Some(value),
104 Prompt::None => None,
105 };
106 let absolute = std::path::absolute(location)?;
107
108 if absolute.simplified().to_str().is_none() {
111 return Err(Error::NonUtf8Path { path: absolute });
112 }
113
114 match location.metadata() {
116 Ok(metadata) if metadata.is_file() => {
117 return Err(Error::Io(io::Error::new(
118 io::ErrorKind::AlreadyExists,
119 format!("File exists at `{}`", location.user_display()),
120 )));
121 }
122 Ok(metadata)
123 if metadata.is_dir()
124 && location
125 .read_dir()
126 .is_ok_and(|mut dir| dir.next().is_none()) =>
127 {
128 trace!(
130 "Using empty directory at `{}` for virtual environment",
131 location.user_display()
132 );
133 }
134 Ok(metadata) if metadata.is_dir() => {
135 let is_virtualenv = uv_fs::is_virtualenv_base(location);
136 let name = if is_virtualenv {
137 "virtual environment"
138 } else {
139 "directory"
140 };
141 let err = Err(Error::Exists {
144 name,
145 path: location.to_path_buf(),
146 });
147 match on_existing {
148 OnExisting::Allow => {
149 debug!("Allowing existing {name} due to `--allow-existing`");
150 }
151 OnExisting::Remove(reason) => {
152 if !is_virtualenv
153 && let RemovalReason::UserRequest(clear_non_virtualenv) = reason
154 {
155 match clear_non_virtualenv {
156 ClearNonVirtualenv::Allow => {}
157 ClearNonVirtualenv::Error => {
158 return Err(Error::ClearNonVirtualenv {
159 path: location.to_path_buf(),
160 });
161 }
162 }
163 }
164 debug!("Removing existing {name} ({reason})");
165 uv_fs::clear_virtualenv(location)?;
166 }
167 OnExisting::Fail => return err,
168 OnExisting::Prompt if !is_virtualenv => return err,
170 OnExisting::Prompt => {
171 match confirm_clear(location, name)? {
172 Some(true) => {
173 debug!("Removing existing {name} due to confirmation");
174 uv_fs::clear_virtualenv(location)?;
175 }
176 Some(false) => return err,
177 None => {
179 return Err(Error::Exists {
180 name,
181 path: location.to_path_buf(),
182 });
183 }
184 }
185 }
186 }
187 }
188 Ok(_) => {
189 return Err(Error::Io(io::Error::new(
191 io::ErrorKind::AlreadyExists,
192 format!("Object already exists at `{}`", location.user_display()),
193 )));
194 }
195 Err(err) if err.kind() == io::ErrorKind::NotFound => {
196 fs_err::create_dir_all(location)?;
197 }
198 Err(err) => return Err(Error::Io(err)),
199 }
200
201 let location = absolute;
203
204 let bin_name = if cfg!(unix) {
205 "bin"
206 } else if cfg!(windows) {
207 "Scripts"
208 } else {
209 unimplemented!("Only Windows and Unix are supported")
210 };
211 let scripts = location.join(&interpreter.virtualenv().scripts);
212
213 cachedir::ensure_tag(&location)?;
215
216 fs_err::write(location.join(".gitignore"), "*")?;
218
219 let minor_version_link = PythonMinorVersionLink::from_interpreter(interpreter, upgrade_policy);
220 let using_minor_version_link = minor_version_link.is_some();
221 let executable_target = if let Some(minor_version_link) = minor_version_link {
222 let debug_symlink_term = if cfg!(windows) {
223 "junction"
224 } else {
225 "symlink directory"
226 };
227 debug!(
228 "Using {} `{}` instead of base Python path `{}`",
229 debug_symlink_term,
230 &minor_version_link.symlink_directory.display(),
231 &base_python.display()
232 );
233 minor_version_link.symlink_executable
234 } else {
235 base_python.clone()
236 };
237
238 let python_home = executable_target
243 .parent()
244 .ok_or_else(|| {
245 io::Error::new(
246 io::ErrorKind::NotFound,
247 "The Python interpreter needs to have a parent directory",
248 )
249 })?
250 .to_path_buf();
251 let python_home = python_home.as_path();
252
253 fs_err::create_dir_all(&scripts)?;
255 let executable = scripts.join(format!("python{EXE_SUFFIX}"));
256
257 #[cfg(unix)]
258 {
259 uv_fs::replace_symlink(&executable_target, &executable)?;
260 uv_fs::replace_symlink(
261 "python",
262 scripts.join(format!("python{}", interpreter.python_major())),
263 )?;
264 uv_fs::replace_symlink(
265 "python",
266 scripts.join(format!(
267 "python{}.{}",
268 interpreter.python_major(),
269 interpreter.python_minor(),
270 )),
271 )?;
272 if interpreter.gil_disabled() {
273 uv_fs::replace_symlink(
274 "python",
275 scripts.join(format!(
276 "python{}.{}t",
277 interpreter.python_major(),
278 interpreter.python_minor(),
279 )),
280 )?;
281 }
282
283 if interpreter.markers().implementation_name() == "pypy" {
284 uv_fs::replace_symlink(
285 "python",
286 scripts.join(format!("pypy{}", interpreter.python_major())),
287 )?;
288 uv_fs::replace_symlink("python", scripts.join("pypy"))?;
289 }
290
291 if interpreter.markers().implementation_name() == "graalpy" {
292 uv_fs::replace_symlink("python", scripts.join("graalpy"))?;
293 }
294 }
295
296 if cfg!(windows) {
300 if using_minor_version_link {
301 let target = scripts.join(WindowsExecutable::Python.exe(interpreter));
302 replace_link_to_executable(
303 target.as_path(),
304 PythonExecutable::console(&executable_target),
305 )
306 .map_err(Error::Python)?;
307 let windowed_executable_name = WindowsExecutable::Pythonw.exe(interpreter);
308 let targetw = scripts.join(&windowed_executable_name);
309 let windowed_executable_target =
310 executable_target.with_file_name(windowed_executable_name);
311 replace_link_to_executable(
312 targetw.as_path(),
313 PythonExecutable::windowed(&windowed_executable_target),
314 )
315 .map_err(Error::Python)?;
316 if interpreter.gil_disabled() {
317 let targett = scripts.join(WindowsExecutable::PythonMajorMinort.exe(interpreter));
318 replace_link_to_executable(
319 targett.as_path(),
320 PythonExecutable::console(&executable_target),
321 )
322 .map_err(Error::Python)?;
323 let targetwt = scripts.join(WindowsExecutable::PythonwMajorMinort.exe(interpreter));
324 replace_link_to_executable(
325 targetwt.as_path(),
326 PythonExecutable::windowed(&windowed_executable_target),
327 )
328 .map_err(Error::Python)?;
329 }
330 } else if matches!(
331 interpreter.platform().os(),
332 Os::Pyodide { .. } | Os::PyEmscripten { .. }
333 ) {
334 let target = scripts.join(WindowsExecutable::Python.exe(interpreter));
337 replace_link_to_executable(
338 target.as_path(),
339 PythonExecutable::console(&executable_target),
340 )
341 .map_err(Error::Python)?;
342 } else {
343 copy_launcher_windows(
345 WindowsExecutable::Python,
346 interpreter,
347 &base_python,
348 &scripts,
349 python_home,
350 )?;
351
352 match interpreter.implementation_name() {
353 "graalpy" => {
354 copy_launcher_windows(
356 WindowsExecutable::GraalPy,
357 interpreter,
358 &base_python,
359 &scripts,
360 python_home,
361 )?;
362 copy_launcher_windows(
363 WindowsExecutable::PythonMajor,
364 interpreter,
365 &base_python,
366 &scripts,
367 python_home,
368 )?;
369 }
370 "pypy" => {
371 copy_launcher_windows(
373 WindowsExecutable::PythonMajor,
374 interpreter,
375 &base_python,
376 &scripts,
377 python_home,
378 )?;
379 copy_launcher_windows(
380 WindowsExecutable::PythonMajorMinor,
381 interpreter,
382 &base_python,
383 &scripts,
384 python_home,
385 )?;
386 copy_launcher_windows(
387 WindowsExecutable::Pythonw,
388 interpreter,
389 &base_python,
390 &scripts,
391 python_home,
392 )?;
393 copy_launcher_windows(
394 WindowsExecutable::PyPy,
395 interpreter,
396 &base_python,
397 &scripts,
398 python_home,
399 )?;
400 copy_launcher_windows(
401 WindowsExecutable::PyPyMajor,
402 interpreter,
403 &base_python,
404 &scripts,
405 python_home,
406 )?;
407 copy_launcher_windows(
408 WindowsExecutable::PyPyMajorMinor,
409 interpreter,
410 &base_python,
411 &scripts,
412 python_home,
413 )?;
414 copy_launcher_windows(
415 WindowsExecutable::PyPyw,
416 interpreter,
417 &base_python,
418 &scripts,
419 python_home,
420 )?;
421 copy_launcher_windows(
422 WindowsExecutable::PyPyMajorMinorw,
423 interpreter,
424 &base_python,
425 &scripts,
426 python_home,
427 )?;
428 }
429 _ => {
430 copy_launcher_windows(
432 WindowsExecutable::Pythonw,
433 interpreter,
434 &base_python,
435 &scripts,
436 python_home,
437 )?;
438
439 if interpreter.gil_disabled() {
441 copy_launcher_windows(
442 WindowsExecutable::PythonMajorMinort,
443 interpreter,
444 &base_python,
445 &scripts,
446 python_home,
447 )?;
448 copy_launcher_windows(
449 WindowsExecutable::PythonwMajorMinort,
450 interpreter,
451 &base_python,
452 &scripts,
453 python_home,
454 )?;
455 }
456 }
457 }
458 }
459 }
460
461 #[cfg(not(any(unix, windows)))]
462 {
463 compile_error!("Only Windows and Unix are supported")
464 }
465
466 for (name, template) in ACTIVATE_TEMPLATES {
468 if relocatable && *name == "activate.csh" {
472 continue;
473 }
474
475 let path_sep = if cfg!(windows) { ";" } else { ":" };
476
477 let relative_site_packages = [
478 interpreter.virtualenv().purelib.as_path(),
479 interpreter.virtualenv().platlib.as_path(),
480 ]
481 .iter()
482 .dedup()
483 .map(|path| {
484 pathdiff::diff_paths(path, &interpreter.virtualenv().scripts)
485 .expect("Failed to calculate relative path to site-packages")
486 })
487 .map(|path| path.simplified().to_str().unwrap().replace('\\', "\\\\"))
488 .join(path_sep);
489
490 let location_string = location
491 .simplified()
492 .to_str()
493 .ok_or_else(|| Error::NonUtf8Path {
494 path: location.clone(),
495 })?;
496 let virtual_env_dir = match (relocatable, name.to_owned()) {
497 (true, "activate") => Cow::Borrowed(
498 r#"'"$(dirname -- "$(dirname -- "$(realpath -- "$SCRIPT_PATH")")")"'"#,
499 ),
500 (true, "activate.bat") => Cow::Borrowed(r"%~dp0.."),
501 (true, "activate.fish") => {
502 Cow::Borrowed(r"'(dirname -- (dirname -- (realpath -- (status -f))))'")
503 }
504 (true, "activate.nu") => Cow::Borrowed(r"(path self | path dirname | path dirname)"),
505 (false, "activate.nu") => Cow::Owned(format!(
506 "'{}'",
507 escape_posix_for_single_quotes(location_string)
508 )),
509 _ => escape_posix_for_single_quotes(location_string),
511 };
512
513 let virtual_prompt = prompt.as_deref().unwrap_or_default();
514 let virtual_prompt = match *name {
515 "activate.xsh" => Cow::Owned(format!(
516 r#"b"{}".decode("utf-8")"#,
517 virtual_prompt.as_bytes().escape_ascii(),
518 )),
519 _ => Cow::Borrowed(virtual_prompt),
520 };
521
522 let bin_name = match *name {
523 "activate.xsh" => Cow::Owned(bin_name.escape_for_python()),
524 _ => Cow::Borrowed(bin_name),
525 };
526
527 let activator = template
528 .replace("{{ VIRTUAL_ENV_DIR }}", &virtual_env_dir)
529 .replace("{{ BIN_NAME }}", &bin_name)
530 .replace("{{ VIRTUAL_PROMPT }}", &virtual_prompt)
531 .replace("{{ PATH_SEP }}", path_sep)
532 .replace("{{ RELATIVE_SITE_PACKAGES }}", &relative_site_packages);
533 fs_err::write(scripts.join(name), activator)?;
534 }
535
536 let mut pyvenv_cfg_data: Vec<(String, String)> = vec![
537 (
538 "home".to_string(),
539 python_home.simplified_display().to_string(),
540 ),
541 (
542 "implementation".to_string(),
543 interpreter
544 .markers()
545 .platform_python_implementation()
546 .to_string(),
547 ),
548 ("uv".to_string(), version().to_string()),
549 (
550 "version_info".to_string(),
551 if using_minor_version_link {
552 interpreter.python_minor_version().to_string()
553 } else {
554 interpreter.markers().python_full_version().string.clone()
555 },
556 ),
557 (
558 "include-system-site-packages".to_string(),
559 if system_site_packages {
560 "true".to_string()
561 } else {
562 "false".to_string()
563 },
564 ),
565 ];
566
567 if relocatable {
568 pyvenv_cfg_data.push(("relocatable".to_string(), "true".to_string()));
569 }
570
571 match seed {
572 Seed::Enabled => pyvenv_cfg_data.push(("seed".to_string(), "true".to_string())),
573 Seed::Disabled => {}
574 }
575
576 if let Some(prompt) = prompt {
577 pyvenv_cfg_data.push(("prompt".to_string(), prompt));
578 }
579
580 if cfg!(windows) && interpreter.markers().implementation_name() == "graalpy" {
581 pyvenv_cfg_data.push((
582 "venvlauncher_command".to_string(),
583 python_home
584 .join("graalpy.exe")
585 .simplified_display()
586 .to_string(),
587 ));
588 }
589
590 let mut pyvenv_cfg = BufWriter::new(File::create(location.join("pyvenv.cfg"))?);
591 write_cfg(&mut pyvenv_cfg, &pyvenv_cfg_data)?;
592 drop(pyvenv_cfg);
593
594 let site_packages = location.join(&interpreter.virtualenv().purelib);
596 fs_err::create_dir_all(&site_packages)?;
597
598 #[cfg(unix)]
601 if interpreter.pointer_size().is_64()
602 && interpreter.markers().os_name() == "posix"
603 && interpreter.markers().sys_platform() != "darwin"
604 {
605 match fs_err::os::unix::fs::symlink("lib", location.join("lib64")) {
606 Ok(()) => {}
607 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
608 Err(err) => {
609 return Err(err.into());
610 }
611 }
612 }
613
614 if install_distutils_patch(interpreter) {
615 fs_err::write(site_packages.join("_virtualenv.py"), VIRTUALENV_PATCH)?;
616 fs_err::write(site_packages.join("_virtualenv.pth"), "import _virtualenv")?;
617 }
618
619 Ok(VirtualEnvironment {
620 scheme: Scheme {
621 purelib: location.join(&interpreter.virtualenv().purelib),
622 platlib: location.join(&interpreter.virtualenv().platlib),
623 scripts: location.join(&interpreter.virtualenv().scripts),
624 data: location.join(&interpreter.virtualenv().data),
625 include: location.join(&interpreter.virtualenv().include),
626 },
627 root: location,
628 executable,
629 base_executable: base_python,
630 })
631}
632
633fn confirm_clear(location: &Path, name: &'static str) -> Result<Option<bool>, io::Error> {
637 let term = Term::stderr();
638 if term.is_term() {
639 let prompt = format!(
640 "A {name} already exists at `{}`. Do you want to replace it?",
641 location.user_display(),
642 );
643 let hint = format!(
644 "Use the `{}` flag or set `{}` to skip this prompt",
645 "--clear".green(),
646 "UV_VENV_CLEAR=1".green()
647 );
648 Ok(Some(uv_console::confirm_with_hint(
649 &prompt, &hint, &term, true,
650 )?))
651 } else {
652 Ok(None)
653 }
654}
655
656#[derive(Debug, Copy, Clone, Eq, PartialEq)]
657pub enum ClearNonVirtualenv {
658 Allow,
660 Error,
662}
663
664#[derive(Debug, Copy, Clone, Eq, PartialEq)]
665pub enum RemovalReason {
666 UserRequest(ClearNonVirtualenv),
668 TemporaryEnvironment,
671 ManagedEnvironment,
674}
675
676impl std::fmt::Display for RemovalReason {
677 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
678 match self {
679 Self::UserRequest(_) => f.write_str("requested with `--clear`"),
680 Self::ManagedEnvironment => f.write_str("environment is managed by uv"),
681 Self::TemporaryEnvironment => f.write_str("environment is temporary"),
682 }
683 }
684}
685
686#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
687pub enum OnExisting {
688 #[default]
692 Prompt,
693 Fail,
695 Allow,
698 Remove(RemovalReason),
700}
701
702impl OnExisting {
703 pub fn from_args(
704 allow_existing: bool,
705 clear: bool,
706 no_clear: bool,
707 clear_non_virtualenv: ClearNonVirtualenv,
708 ) -> Self {
709 if allow_existing {
710 Self::Allow
711 } else if clear {
712 Self::Remove(RemovalReason::UserRequest(clear_non_virtualenv))
713 } else if no_clear {
714 Self::Fail
715 } else {
716 Self::Prompt
717 }
718 }
719}
720
721#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
722pub enum Seed {
723 Enabled,
725 #[default]
727 Disabled,
728}
729
730impl Seed {
731 pub fn from_args(seed: bool) -> Self {
733 if seed { Self::Enabled } else { Self::Disabled }
734 }
735}
736
737#[derive(Debug, Copy, Clone)]
738enum WindowsExecutable {
739 Python,
741 PythonMajor,
743 PythonMajorMinor,
745 PythonMajorMinort,
747 Pythonw,
749 PythonwMajorMinort,
751 PyPy,
753 PyPyMajor,
755 PyPyMajorMinor,
757 PyPyw,
759 PyPyMajorMinorw,
761 GraalPy,
763}
764
765impl WindowsExecutable {
766 fn exe(self, interpreter: &Interpreter) -> Cow<'static, OsStr> {
768 match self {
769 Self::Python => Cow::Borrowed(OsStr::new("python.exe")),
770 Self::PythonMajor => Cow::Owned(OsString::from(format!(
771 "python{}.exe",
772 interpreter.python_major()
773 ))),
774 Self::PythonMajorMinor => Cow::Owned(OsString::from(format!(
775 "python{}.{}.exe",
776 interpreter.python_major(),
777 interpreter.python_minor()
778 ))),
779 Self::PythonMajorMinort => Cow::Owned(OsString::from(format!(
780 "python{}.{}t.exe",
781 interpreter.python_major(),
782 interpreter.python_minor()
783 ))),
784 Self::Pythonw => Cow::Borrowed(OsStr::new("pythonw.exe")),
785 Self::PythonwMajorMinort => Cow::Owned(OsString::from(format!(
786 "pythonw{}.{}t.exe",
787 interpreter.python_major(),
788 interpreter.python_minor()
789 ))),
790 Self::PyPy => Cow::Borrowed(OsStr::new("pypy.exe")),
791 Self::PyPyMajor => Cow::Owned(OsString::from(format!(
792 "pypy{}.exe",
793 interpreter.python_major()
794 ))),
795 Self::PyPyMajorMinor => Cow::Owned(OsString::from(format!(
796 "pypy{}.{}.exe",
797 interpreter.python_major(),
798 interpreter.python_minor()
799 ))),
800 Self::PyPyw => Cow::Borrowed(OsStr::new("pypyw.exe")),
801 Self::PyPyMajorMinorw => Cow::Owned(OsString::from(format!(
802 "pypy{}.{}w.exe",
803 interpreter.python_major(),
804 interpreter.python_minor()
805 ))),
806 Self::GraalPy => Cow::Borrowed(OsStr::new("graalpy.exe")),
807 }
808 }
809
810 fn launcher(self, interpreter: &Interpreter) -> &'static str {
812 match self {
813 Self::Python | Self::PythonMajor | Self::PythonMajorMinor
814 if interpreter.gil_disabled() =>
815 {
816 "venvlaunchert.exe"
817 }
818 Self::Python | Self::PythonMajor | Self::PythonMajorMinor => "venvlauncher.exe",
819 Self::Pythonw if interpreter.gil_disabled() => "venvwlaunchert.exe",
820 Self::Pythonw => "venvwlauncher.exe",
821 Self::PythonMajorMinort => "venvlaunchert.exe",
822 Self::PythonwMajorMinort => "venvwlaunchert.exe",
823 Self::PyPy | Self::PyPyMajor | Self::PyPyMajorMinor => "venvlauncher.exe",
826 Self::PyPyw | Self::PyPyMajorMinorw => "venvwlauncher.exe",
827 Self::GraalPy => "venvlauncher.exe",
828 }
829 }
830}
831
832fn copy_launcher_windows(
838 executable: WindowsExecutable,
839 interpreter: &Interpreter,
840 base_python: &Path,
841 scripts: &Path,
842 python_home: &Path,
843) -> Result<(), Error> {
844 let shim = interpreter
846 .stdlib()
847 .join("venv")
848 .join("scripts")
849 .join("nt")
850 .join(executable.exe(interpreter));
851 match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
852 Ok(_) => return Ok(()),
853 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
854 Err(err) => {
855 return Err(err.into());
856 }
857 }
858
859 let shim = interpreter
863 .stdlib()
864 .join("venv")
865 .join("scripts")
866 .join("nt")
867 .join(executable.launcher(interpreter));
868 match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
869 Ok(_) => return Ok(()),
870 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
871 Err(err) => {
872 return Err(err.into());
873 }
874 }
875
876 let shim = base_python.with_file_name(executable.launcher(interpreter));
879 match fs_err::copy(shim, scripts.join(executable.exe(interpreter))) {
880 Ok(_) => return Ok(()),
881 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
882 Err(err) => {
883 return Err(err.into());
884 }
885 }
886
887 match fs_err::copy(
891 base_python.with_file_name(executable.exe(interpreter)),
892 scripts.join(executable.exe(interpreter)),
893 ) {
894 Ok(_) => {
895 for directory in [
898 python_home,
899 interpreter.sys_base_prefix().join("DLLs").as_path(),
900 ] {
901 let entries = match fs_err::read_dir(directory) {
902 Ok(read_dir) => read_dir,
903 Err(err) if err.kind() == io::ErrorKind::NotFound => {
904 continue;
905 }
906 Err(err) => {
907 return Err(err.into());
908 }
909 };
910 for entry in entries {
911 let entry = entry?;
912 let path = entry.path();
913 if path.extension().is_some_and(|ext| {
914 ext.eq_ignore_ascii_case("dll") || ext.eq_ignore_ascii_case("pyd")
915 }) {
916 if let Some(file_name) = path.file_name() {
917 fs_err::copy(&path, scripts.join(file_name))?;
918 }
919 }
920 }
921 }
922
923 match fs_err::read_dir(python_home) {
925 Ok(entries) => {
926 for entry in entries {
927 let entry = entry?;
928 let path = entry.path();
929 if path
930 .extension()
931 .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
932 {
933 if let Some(file_name) = path.file_name() {
934 fs_err::copy(&path, scripts.join(file_name))?;
935 }
936 }
937 }
938 }
939 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
940 Err(err) => {
941 return Err(err.into());
942 }
943 }
944
945 return Ok(());
946 }
947 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
948 Err(err) => {
949 return Err(err.into());
950 }
951 }
952
953 Err(Error::NotFound(base_python.user_display().to_string()))
954}