1#![allow(dead_code, unreachable_pub)]
3
4pub mod archive;
5pub mod find_links;
6mod http_server;
7pub mod packse;
8pub mod pypi_proxy;
9mod vendor;
10
11use std::borrow::BorrowMut;
12use std::ffi::OsString;
13use std::io::Write as _;
14use std::iter::Iterator;
15use std::path::{Path, PathBuf};
16use std::process::{Command, Output, Stdio};
17use std::str::FromStr;
18use std::{env, io};
19use uv_python::downloads::ManagedPythonDownloadList;
20
21use assert_cmd::assert::{Assert, OutputAssertExt};
22use assert_fs::assert::PathAssert;
23use assert_fs::fixture::{
24 ChildPath, FileWriteStr, PathChild, PathCopy, PathCreateDir, SymlinkToFile,
25};
26use base64::{Engine, prelude::BASE64_STANDARD as base64};
27use futures::StreamExt;
28use indoc::{formatdoc, indoc};
29use itertools::Itertools;
30use predicates::prelude::predicate;
31use regex::{Regex, regex};
32use tokio::io::AsyncWriteExt;
33
34use uv_cache::{Cache, CacheBucket};
35use uv_fs::Simplified;
36use uv_python::managed::ManagedPythonInstallations;
37use uv_python::{
38 EnvironmentPreference, PythonInstallation, PythonPreference, PythonRequest, PythonVersion,
39};
40use uv_static::EnvVars;
41
42static TEST_TIMESTAMP: &str = "2024-03-25T00:00:00Z";
44
45pub const DEFAULT_PYTHON_VERSION: &str = "3.12";
46
47const LATEST_PYTHON_3_15: &str = "3.15.0rc1";
49const LATEST_PYTHON_3_14: &str = "3.14.7";
50const LATEST_PYTHON_3_13: &str = "3.13.15";
51pub const LATEST_PYTHON_3_12: &str = "3.12.14";
52const LATEST_PYTHON_3_11: &str = "3.11.16";
53const LATEST_PYTHON_3_10: &str = "3.10.21";
54
55#[macro_export]
62macro_rules! test_context {
63 ($python_version:expr) => {
64 $crate::TestContext::new_with_bin(
65 $python_version,
66 std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv")),
67 )
68 };
69}
70
71#[macro_export]
78macro_rules! test_context_with_versions {
79 ($python_versions:expr) => {
80 $crate::TestContext::new_with_versions_and_bin(
81 $python_versions,
82 std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv")),
83 )
84 };
85}
86
87#[macro_export]
92macro_rules! get_bin {
93 () => {
94 std::path::PathBuf::from(env!("CARGO_BIN_EXE_uv"))
95 };
96}
97
98#[doc(hidden)] pub const INSTA_FILTERS: &[(&str, &str)] = &[
100 (r"--cache-dir [^\s]+", "--cache-dir [CACHE_DIR]"),
101 (r"(\s|\()(\d+m )?(\d+\.)?\d+(ms|s)", "$1[TIME]"),
103 (r"tv_sec: \d+", "tv_sec: [TIME]"),
105 (r"tv_nsec: \d+", "tv_nsec: [TIME]"),
106 (r"\\([\w\d]|\.)", "/$1"),
108 (r"uv\.exe", "uv"),
109 (
111 r"uv(-.*)? \d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?( \([^)]*\))?",
112 r"uv [VERSION] ([COMMIT] DATE)",
113 ),
114 (r"([^\s])[ \t]+(\r?\n)", "$1$2"),
116 (
118 r"(?ms)^([ \t]*custom_certificates: )(?:None|Some\(\n.*?^[ \t]*\),\n[ \t]*\)),",
119 "${1}[CERTIFICATES],",
120 ),
121 (r"DEBUG Loaded \d+ certificate\(s\) from [^\n]+\n", ""),
123];
124
125pub struct TestContext {
132 pub root: ChildPath,
133 pub temp_dir: ChildPath,
134 pub cache_dir: ChildPath,
135 python_dir: ChildPath,
136 pub home_dir: ChildPath,
137 pub user_config_dir: ChildPath,
138 pub bin_dir: ChildPath,
139 pub venv: ChildPath,
140 pub workspace_root: PathBuf,
141
142 python_version: Option<PythonVersion>,
144
145 pub python_versions: Vec<(PythonVersion, PathBuf)>,
147
148 uv_bin: PathBuf,
150
151 filters: Vec<(String, String)>,
153
154 extra_env: Vec<(OsString, OsString)>,
156
157 #[allow(dead_code)]
158 _root: tempfile::TempDir,
159
160 #[allow(dead_code)]
163 _extra_tempdirs: Vec<tempfile::TempDir>,
164}
165
166impl TestContext {
167 pub fn new_with_bin(python_version: &str, uv_bin: PathBuf) -> Self {
171 let new = Self::new_with_versions_and_bin(&[python_version], uv_bin);
172 new.create_venv();
173 new
174 }
175
176 #[must_use]
180 pub fn with_cache_dir(mut self, cache_dir: impl AsRef<Path>) -> Self {
181 let cache_dir = if cache_dir.as_ref().is_absolute() {
182 cache_dir.as_ref().to_path_buf()
183 } else {
184 self.temp_dir
185 .join(cache_dir.as_ref().components().collect::<PathBuf>())
186 };
187
188 self.filters
189 .retain(|(_, replacement)| replacement != "[CACHE_DIR]/");
190 self.cache_dir = ChildPath::new(cache_dir);
191
192 for pattern in Self::path_patterns(&self.cache_dir) {
193 self.filters
194 .insert(0, (pattern, "[CACHE_DIR]/".to_string()));
195 }
196
197 self
198 }
199
200 #[must_use]
202 pub fn with_exclude_newer(mut self, exclude_newer: &str) -> Self {
203 self.extra_env
204 .push((EnvVars::UV_EXCLUDE_NEWER.into(), exclude_newer.into()));
205 self
206 }
207
208 #[must_use]
210 pub fn with_http_timeout(mut self, http_timeout: &str) -> Self {
211 self.extra_env
212 .push((EnvVars::UV_HTTP_TIMEOUT.into(), http_timeout.into()));
213 self
214 }
215
216 #[must_use]
218 pub fn with_http_retries(mut self, http_retries: &str) -> Self {
219 self.extra_env
220 .push((EnvVars::UV_HTTP_RETRIES.into(), http_retries.into()));
221 self
222 }
223
224 #[must_use]
226 pub fn with_fast_http_retry(self) -> Self {
227 self.with_http_timeout("1").with_http_retries("1")
228 }
229
230 #[must_use]
232 pub fn with_concurrent_installs(mut self, concurrent_installs: &str) -> Self {
233 self.extra_env.push((
234 EnvVars::UV_CONCURRENT_INSTALLS.into(),
235 concurrent_installs.into(),
236 ));
237 self
238 }
239
240 #[must_use]
245 pub fn with_filtered_counts(mut self) -> Self {
246 for verb in &[
247 "Resolved",
248 "Prepared",
249 "Installed",
250 "Uninstalled",
251 "Checked",
252 ] {
253 self.filters.push((
254 format!("{verb} \\d+ packages?"),
255 format!("{verb} [N] packages"),
256 ));
257 }
258 self.with_filtered_file_counts()
259 }
260
261 #[must_use]
263 pub fn with_filtered_file_counts(mut self) -> Self {
264 self.filters.push((
265 "Removed \\d+ files?".to_string(),
266 "Removed [N] files".to_string(),
267 ));
268 self
269 }
270
271 #[must_use]
273 pub fn with_filtered_sizes(mut self) -> Self {
274 self.filters.push((
275 r"(\s|\()(\d+\.)?\d+(([KMGT]i)?B)".to_string(),
276 "$1[SIZE]$3".to_string(),
277 ));
278 self
279 }
280
281 #[must_use]
283 pub fn with_filtered_sizes_and_units(mut self) -> Self {
284 self.filters.push((
285 r"(\s|\()(\d+\.)?\d+([KMGT]i)?B".to_string(),
286 "$1[SIZE]".to_string(),
287 ));
288 self
289 }
290
291 #[must_use]
293 pub fn with_filtered_cache_size(mut self) -> Self {
294 self.filters
296 .push((r"(?m)^\d+\n".to_string(), "[SIZE]\n".to_string()));
297 self.filters.push((
299 r"(?m)^\d+(\.\d+)?( ?[KMGT]i?B)\n".to_string(),
300 "[SIZE]$2\n".to_string(),
301 ));
302 self
303 }
304
305 #[must_use]
307 pub fn with_filtered_centralized_environment_hashes(mut self) -> Self {
308 self.filters.push((
309 r"`([\w.\[\]-]+)-[a-f0-9]{16}`".to_string(),
310 "`$1-[HASH]`".to_string(),
311 ));
312 self
313 }
314
315 #[must_use]
317 pub fn with_filtered_missing_file_error(mut self) -> Self {
318 self.filters.push((
321 r"[^:\n]* \(os error 2\)".to_string(),
322 " [OS ERROR 2]".to_string(),
323 ));
324 self.filters.push((
328 r"[^:\n]* \(os error 3\)".to_string(),
329 " [OS ERROR 2]".to_string(),
330 ));
331 self
332 }
333
334 #[must_use]
337 pub fn with_filtered_exe_suffix(mut self) -> Self {
338 self.filters
339 .push((regex::escape(env::consts::EXE_SUFFIX), String::new()));
340 self
341 }
342
343 #[must_use]
345 pub fn with_filtered_python_sources(mut self) -> Self {
346 self.filters.push((
347 "virtual environments, managed installations, or search path".to_string(),
348 "[PYTHON SOURCES]".to_string(),
349 ));
350 self.filters.push((
351 "virtual environments, managed installations, search path, or registry".to_string(),
352 "[PYTHON SOURCES]".to_string(),
353 ));
354 self.filters.push((
355 "virtual environments, search path, or registry".to_string(),
356 "[PYTHON SOURCES]".to_string(),
357 ));
358 self.filters.push((
359 "virtual environments, registry, or search path".to_string(),
360 "[PYTHON SOURCES]".to_string(),
361 ));
362 self.filters.push((
363 "virtual environments or search path".to_string(),
364 "[PYTHON SOURCES]".to_string(),
365 ));
366 self.filters.push((
367 "managed installations or search path".to_string(),
368 "[PYTHON SOURCES]".to_string(),
369 ));
370 self.filters.push((
371 "managed installations, search path, or registry".to_string(),
372 "[PYTHON SOURCES]".to_string(),
373 ));
374 self.filters.push((
375 "search path or registry".to_string(),
376 "[PYTHON SOURCES]".to_string(),
377 ));
378 self.filters.push((
379 "registry or search path".to_string(),
380 "[PYTHON SOURCES]".to_string(),
381 ));
382 self.filters
383 .push(("search path".to_string(), "[PYTHON SOURCES]".to_string()));
384 self
385 }
386
387 #[must_use]
390 pub fn with_filtered_python_names(mut self) -> Self {
391 for name in ["python", "pypy"] {
392 let suffix = if cfg!(windows) {
395 let exe_suffix = regex::escape(env::consts::EXE_SUFFIX);
399 format!(r"(\d\.\d+|\d)?{exe_suffix}")
400 } else {
401 if name == "python" {
403 r"(\d\.\d+|\d)?(t|d|td)?".to_string()
405 } else {
406 r"(\d\.\d+|\d)(t|d|td)?".to_string()
408 }
409 };
410
411 self.filters.push((
412 format!(r"[\\/]{name}{suffix}"),
415 format!("/[{}]", name.to_uppercase()),
416 ));
417 }
418
419 self
420 }
421
422 #[must_use]
425 pub fn with_filtered_virtualenv_bin(mut self) -> Self {
426 self.filters.push((
427 format!(
428 r"[\\/]{}[\\/]",
429 venv_bin_path(PathBuf::new()).to_string_lossy()
430 ),
431 "/[BIN]/".to_string(),
432 ));
433 self.filters.push((
434 format!(r"[\\/]{}", venv_bin_path(PathBuf::new()).to_string_lossy()),
435 "/[BIN]".to_string(),
436 ));
437 self
438 }
439
440 #[must_use]
444 pub fn with_filtered_python_install_bin(mut self) -> Self {
445 let suffix = if cfg!(windows) {
448 let exe_suffix = regex::escape(env::consts::EXE_SUFFIX);
449 format!(r"(\d\.\d+|\d)?{exe_suffix}")
451 } else {
452 r"\d\.\d+|\d".to_string()
454 };
455
456 if cfg!(unix) {
457 self.filters.push((
458 format!(r"[\\/]bin/python({suffix})"),
459 "/[INSTALL-BIN]/python$1".to_string(),
460 ));
461 self.filters.push((
462 format!(r"[\\/]bin/pypy({suffix})"),
463 "/[INSTALL-BIN]/pypy$1".to_string(),
464 ));
465 } else {
466 self.filters.push((
467 format!(r"[\\/]python({suffix})"),
468 "/[INSTALL-BIN]/python$1".to_string(),
469 ));
470 self.filters.push((
471 format!(r"[\\/]pypy({suffix})"),
472 "/[INSTALL-BIN]/pypy$1".to_string(),
473 ));
474 }
475 self
476 }
477
478 #[must_use]
483 pub fn with_pyvenv_cfg_filters(mut self) -> Self {
484 let added_filters = [
485 (r"home = .+".to_string(), "home = [PYTHON_HOME]".to_string()),
486 (
487 r"uv = \d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?".to_string(),
488 "uv = [UV_VERSION]".to_string(),
489 ),
490 ];
491 for filter in added_filters {
492 self.filters.insert(0, filter);
493 }
494 self
495 }
496
497 #[must_use]
500 pub fn with_filtered_python_symlinks(mut self) -> Self {
501 for (version, executable) in &self.python_versions {
502 if fs_err::symlink_metadata(executable).unwrap().is_symlink() {
503 self.filters.extend(
504 Self::path_patterns(executable.read_link().unwrap())
505 .into_iter()
506 .map(|pattern| (format! {" -> {pattern}"}, String::new())),
507 );
508 }
509 self.filters.push((
511 regex::escape(&format!(" -> [PYTHON-{version}]")),
512 String::new(),
513 ));
514 }
515 self
516 }
517
518 #[must_use]
520 pub fn with_filtered_path(mut self, path: &Path, name: &str) -> Self {
521 for pattern in Self::path_patterns(path)
525 .into_iter()
526 .map(|pattern| (pattern, format!("[{name}]/")))
527 {
528 self.filters.insert(0, pattern);
529 }
530 self
531 }
532
533 #[inline]
541 #[must_use]
542 pub fn with_filtered_link_mode_warning(mut self) -> Self {
543 let pattern = "warning: Failed to hardlink files; .*\n.*\n.*\n";
544 self.filters.push((pattern.to_string(), String::new()));
545 self
546 }
547
548 #[inline]
550 #[must_use]
551 pub fn with_filtered_not_executable(mut self) -> Self {
552 let pattern = if cfg!(unix) {
553 r"Permission denied \(os error 13\)"
554 } else {
555 r"\%1 is not a valid Win32 application. \(os error 193\)"
556 };
557 self.filters
558 .push((pattern.to_string(), "[PERMISSION DENIED]".to_string()));
559 self
560 }
561
562 #[must_use]
564 pub fn with_filtered_python_keys(mut self) -> Self {
565 let platform_re = r"(?x)
567 ( # We capture the group before the platform
568 (?:cpython|pypy|graalpy)# Python implementation
569 -
570 \d+\.\d+ # Major and minor version
571 (?: # The patch version is handled separately
572 \.
573 (?:
574 \[X\] # A previously filtered patch version [X]
575 | # OR
576 \[LATEST\] # A previously filtered latest patch version [LATEST]
577 | # OR
578 \d+ # An actual patch version
579 )
580 )? # (we allow the patch version to be missing entirely, e.g., in a request)
581 (?:(?:a|b|rc)[0-9]+)? # Pre-release version component, e.g., `a6` or `rc2`
582 (?:[td])? # A short variant, such as `t` (for freethreaded) or `d` (for debug)
583 (?:(\+[a-z]+)+)? # A long variant, such as `+freethreaded` or `+freethreaded+debug`
584 )
585 -
586 [a-z0-9]+ # Operating system (e.g., 'macos')
587 -
588 [a-z0-9_]+ # Architecture (e.g., 'aarch64')
589 -
590 [a-z]+ # Libc (e.g., 'none')
591";
592 self.filters
593 .push((platform_re.to_string(), "$1-[PLATFORM]".to_string()));
594 self
595 }
596
597 #[must_use]
599 pub fn with_filtered_latest_python_versions(mut self) -> Self {
600 for (minor, patch) in [
603 ("3.15", LATEST_PYTHON_3_15.strip_prefix("3.15.").unwrap()),
604 ("3.14", LATEST_PYTHON_3_14.strip_prefix("3.14.").unwrap()),
605 ("3.13", LATEST_PYTHON_3_13.strip_prefix("3.13.").unwrap()),
606 ("3.12", LATEST_PYTHON_3_12.strip_prefix("3.12.").unwrap()),
607 ("3.11", LATEST_PYTHON_3_11.strip_prefix("3.11.").unwrap()),
608 ("3.10", LATEST_PYTHON_3_10.strip_prefix("3.10.").unwrap()),
609 ] {
610 let pattern = format!(r"(\b){minor}\.{patch}(\b)");
612 let replacement = format!("${{1}}{minor}.[LATEST]${{2}}");
613 self.filters.push((pattern, replacement));
614 }
615 self
616 }
617
618 #[must_use]
620 #[cfg(windows)]
621 pub fn with_filtered_windows_temp_dir(mut self) -> Self {
622 let pattern = regex::escape(
623 &self
624 .temp_dir
625 .simplified_display()
626 .to_string()
627 .replace('/', "\\"),
628 );
629 self.filters.push((pattern, "[TEMP_DIR]".to_string()));
630 self
631 }
632
633 #[must_use]
635 pub fn with_filtered_compiled_file_count(mut self) -> Self {
636 self.filters.push((
637 r"compiled \d+ files".to_string(),
638 "compiled [COUNT] files".to_string(),
639 ));
640 self
641 }
642
643 #[must_use]
645 pub fn with_filtered_current_version(mut self) -> Self {
646 self.filters.push((
647 regex::escape(&format!("v{}", env!("CARGO_PKG_VERSION"))),
648 "v[CURRENT_VERSION]".to_string(),
649 ));
650 self
651 }
652
653 #[must_use]
655 pub fn with_cyclonedx_filters(mut self) -> Self {
656 self.filters.push((
657 r"urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}".to_string(),
658 "[SERIAL_NUMBER]".to_string(),
659 ));
660 self.filters.push((
661 r#""timestamp": "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+Z""#
662 .to_string(),
663 r#""timestamp": "[TIMESTAMP]""#.to_string(),
664 ));
665 self.filters.push((
666 r#""name": "uv",\s*"version": "\d+\.\d+\.\d+(-(alpha|beta|rc)\.\d+)?(\+\d+)?""#
667 .to_string(),
668 r#""name": "uv",
669 "version": "[VERSION]""#
670 .to_string(),
671 ));
672 self
673 }
674
675 #[must_use]
677 pub fn with_collapsed_whitespace(mut self) -> Self {
678 self.filters.push((r"[ \t]+".to_string(), " ".to_string()));
679 self
680 }
681
682 #[must_use]
684 pub fn with_python_download_cache(mut self) -> Self {
685 self.extra_env.push((
686 EnvVars::UV_PYTHON_CACHE_DIR.into(),
687 env::var_os(EnvVars::UV_PYTHON_CACHE_DIR).unwrap_or_else(|| {
689 uv_cache::Cache::from_settings(false, None)
690 .unwrap()
691 .bucket(CacheBucket::Python)
692 .into()
693 }),
694 ));
695 self
696 }
697
698 #[must_use]
699 pub fn with_empty_python_install_mirror(mut self) -> Self {
700 self.extra_env.push((
701 EnvVars::UV_PYTHON_INSTALL_MIRROR.into(),
702 String::new().into(),
703 ));
704 self
705 }
706
707 #[must_use]
709 pub fn with_managed_python_dirs(mut self) -> Self {
710 let managed = self.temp_dir.join("managed");
711
712 self.extra_env.push((
713 EnvVars::UV_PYTHON_BIN_DIR.into(),
714 self.bin_dir.as_os_str().to_owned(),
715 ));
716 self.extra_env
717 .push((EnvVars::UV_PYTHON_INSTALL_DIR.into(), managed.into()));
718 self.extra_env
719 .push((EnvVars::UV_PYTHON_DOWNLOADS.into(), "automatic".into()));
720
721 self
722 }
723
724 #[must_use]
726 pub fn with_tool_dirs(mut self) -> Self {
727 self.extra_env.push((
728 EnvVars::UV_TOOL_DIR.into(),
729 self.temp_dir.join("tools").into(),
730 ));
731 self.extra_env.push((
732 EnvVars::XDG_BIN_HOME.into(),
733 self.temp_dir.join("bin").into(),
734 ));
735
736 self
737 }
738
739 #[must_use]
740 pub fn with_versions_as_managed(mut self, versions: &[&str]) -> Self {
741 self.extra_env.push((
742 EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED.into(),
743 versions.iter().join(" ").into(),
744 ));
745
746 self
747 }
748
749 #[must_use]
751 pub fn with_filter(mut self, filter: (impl Into<String>, impl Into<String>)) -> Self {
752 self.filters.push((filter.0.into(), filter.1.into()));
753 self
754 }
755
756 #[must_use]
758 pub fn with_unset_git_credential_helper(self) -> Self {
759 let git_config = self.home_dir.child(".gitconfig");
760 git_config
761 .write_str(indoc! {r"
762 [credential]
763 helper =
764 "})
765 .expect("Failed to unset git credential helper");
766
767 self
768 }
769
770 #[must_use]
772 #[cfg(windows)]
773 pub fn clear_filters(mut self) -> Self {
774 self.filters.clear();
775 self
776 }
777
778 pub fn with_cache_on_cow_fs(self) -> anyhow::Result<Option<Self>> {
783 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_COW_FS).ok() else {
784 return Ok(None);
785 };
786 self.with_cache_on_fs(&dir, "COW_FS").map(Some)
787 }
788
789 pub fn with_cache_on_alt_fs(self) -> anyhow::Result<Option<Self>> {
794 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_ALT_FS).ok() else {
795 return Ok(None);
796 };
797 self.with_cache_on_fs(&dir, "ALT_FS").map(Some)
798 }
799
800 pub fn with_cache_on_lowlinks_fs(self) -> anyhow::Result<Option<Self>> {
805 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_LOWLINKS_FS).ok() else {
806 return Ok(None);
807 };
808 self.with_cache_on_fs(&dir, "LOWLINKS_FS").map(Some)
809 }
810
811 pub fn with_cache_on_nocow_fs(self) -> anyhow::Result<Option<Self>> {
816 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_NOCOW_FS).ok() else {
817 return Ok(None);
818 };
819 self.with_cache_on_fs(&dir, "NOCOW_FS").map(Some)
820 }
821
822 pub fn with_working_dir_on_cow_fs(self) -> anyhow::Result<Option<Self>> {
829 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_COW_FS).ok() else {
830 return Ok(None);
831 };
832 self.with_working_dir_on_fs(&dir, "COW_FS").map(Some)
833 }
834
835 pub fn with_working_dir_on_nocow_fs(self) -> anyhow::Result<Option<Self>> {
842 let Some(dir) = env::var(EnvVars::UV_INTERNAL__TEST_NOCOW_FS).ok() else {
843 return Ok(None);
844 };
845 self.with_working_dir_on_fs(&dir, "NOCOW_FS").map(Some)
846 }
847
848 fn with_cache_on_fs(mut self, dir: &str, name: &str) -> anyhow::Result<Self> {
849 fs_err::create_dir_all(dir)?;
850 let tmp = tempfile::TempDir::new_in(dir)?;
851 self.cache_dir = ChildPath::new(tmp.path()).child("cache");
852 fs_err::create_dir_all(&self.cache_dir)?;
853 let replacement = format!("[{name}]/[CACHE_DIR]/");
854 for pattern in Self::path_patterns(&self.cache_dir) {
855 self.filters.insert(0, (pattern, replacement.clone()));
856 }
857 self._extra_tempdirs.push(tmp);
858 Ok(self)
859 }
860
861 fn with_working_dir_on_fs(mut self, dir: &str, name: &str) -> anyhow::Result<Self> {
862 fs_err::create_dir_all(dir)?;
863 let tmp = tempfile::TempDir::new_in(dir)?;
864 self.temp_dir = ChildPath::new(tmp.path()).child("temp");
865 fs_err::create_dir_all(&self.temp_dir)?;
866 let canonical_temp_dir = self.temp_dir.canonicalize()?;
869 self.venv = ChildPath::new(canonical_temp_dir.join(".venv"));
870 let temp_replacement = format!("[{name}]/[TEMP_DIR]/");
871 self.filters.extend(
872 Self::path_patterns(&self.temp_dir)
873 .into_iter()
874 .map(|pattern| (pattern, temp_replacement.clone())),
875 );
876 let venv_replacement = format!("[{name}]/[VENV]/");
877 self.filters.extend(
878 Self::path_patterns(&self.venv)
879 .into_iter()
880 .map(|pattern| (pattern, venv_replacement.clone())),
881 );
882 self._extra_tempdirs.push(tmp);
883 Ok(self)
884 }
885
886 pub fn test_bucket_dir() -> PathBuf {
895 std::env::temp_dir()
896 .simple_canonicalize()
897 .expect("failed to canonicalize temp dir")
898 .join("uv")
899 .join("tests")
900 }
901
902 pub fn new_with_versions_and_bin(python_versions: &[&str], uv_bin: PathBuf) -> Self {
909 let bucket = Self::test_bucket_dir();
910 fs_err::create_dir_all(&bucket).expect("Failed to create test bucket");
911
912 let root = tempfile::TempDir::new_in(bucket).expect("Failed to create test root directory");
913
914 fs_err::create_dir_all(root.path().join(".git"))
917 .expect("Failed to create `.git` placeholder in test root directory");
918
919 let temp_dir = ChildPath::new(root.path()).child("temp");
920 fs_err::create_dir_all(&temp_dir).expect("Failed to create test working directory");
921
922 let cache_dir = ChildPath::new(root.path()).child("cache");
923 fs_err::create_dir_all(&cache_dir).expect("Failed to create test cache directory");
924
925 let python_dir = ChildPath::new(root.path()).child("python");
926 fs_err::create_dir_all(&python_dir).expect("Failed to create test Python directory");
927
928 let bin_dir = ChildPath::new(root.path()).child("bin");
929 fs_err::create_dir_all(&bin_dir).expect("Failed to create test bin directory");
930
931 if cfg!(not(feature = "git")) {
933 Self::disallow_git_cli(&bin_dir).expect("Failed to setup disallowed `git` command");
934 }
935
936 let home_dir = ChildPath::new(root.path()).child("home");
937 fs_err::create_dir_all(&home_dir).expect("Failed to create test home directory");
938
939 let user_config_dir = if cfg!(windows) {
940 ChildPath::new(home_dir.path())
941 } else {
942 ChildPath::new(home_dir.path()).child(".config")
943 };
944
945 let canonical_temp_dir = temp_dir.canonicalize().unwrap();
947 let venv = ChildPath::new(canonical_temp_dir.join(".venv"));
948
949 let python_version = python_versions
950 .first()
951 .map(|version| PythonVersion::from_str(version).unwrap());
952
953 let site_packages = python_version
954 .as_ref()
955 .map(|version| site_packages_path(&venv, &format!("python{version}")));
956
957 let workspace_root = Path::new(&env::var(EnvVars::CARGO_MANIFEST_DIR).unwrap())
960 .parent()
961 .expect("CARGO_MANIFEST_DIR should be nested in workspace")
962 .parent()
963 .expect("CARGO_MANIFEST_DIR should be doubly nested in workspace")
964 .to_path_buf();
965
966 let download_list = ManagedPythonDownloadList::new_only_embedded().unwrap();
967
968 let python_versions: Vec<_> = python_versions
969 .iter()
970 .map(|version| PythonVersion::from_str(version).unwrap())
971 .zip(
972 python_installations_for_versions(&temp_dir, python_versions, &download_list)
973 .expect("Failed to find test Python versions"),
974 )
975 .collect();
976
977 if cfg!(unix) {
980 for (version, executable) in &python_versions {
981 let parent = python_dir.child(version.to_string());
982 parent.create_dir_all().unwrap();
983 parent.child("python3").symlink_to_file(executable).unwrap();
984 }
985 }
986
987 let mut filters = Vec::new();
988
989 filters.extend(
990 Self::path_patterns(&uv_bin)
991 .into_iter()
992 .map(|pattern| (pattern, "[UV]".to_string())),
993 );
994
995 if cfg!(windows) {
997 filters.push((" --link-mode <LINK_MODE>".to_string(), String::new()));
998 filters.push((r#"link-mode = "copy"\n"#.to_string(), String::new()));
999 filters.push((r"exit code: ".to_string(), "exit status: ".to_string()));
1001 }
1002
1003 for (version, executable) in &python_versions {
1004 filters.extend(
1006 Self::path_patterns(executable)
1007 .into_iter()
1008 .map(|pattern| (pattern, format!("[PYTHON-{version}]"))),
1009 );
1010
1011 filters.extend(
1013 Self::path_patterns(python_dir.join(version.to_string()))
1014 .into_iter()
1015 .map(|pattern| {
1016 (
1017 format!("{pattern}[a-zA-Z0-9]*"),
1018 format!("[PYTHON-{version}]"),
1019 )
1020 }),
1021 );
1022
1023 if version.patch().is_none() {
1026 filters.push((
1027 format!(r"({})\.\d+", regex::escape(version.to_string().as_str())),
1028 "$1.[X]".to_string(),
1029 ));
1030 }
1031 }
1032
1033 filters.extend(
1034 Self::path_patterns(&bin_dir)
1035 .into_iter()
1036 .map(|pattern| (pattern, "[BIN]/".to_string())),
1037 );
1038 filters.extend(
1039 Self::path_patterns(&cache_dir)
1040 .into_iter()
1041 .map(|pattern| (pattern, "[CACHE_DIR]/".to_string())),
1042 );
1043 if let Some(ref site_packages) = site_packages {
1044 filters.extend(
1045 Self::path_patterns(site_packages)
1046 .into_iter()
1047 .map(|pattern| (pattern, "[SITE_PACKAGES]/".to_string())),
1048 );
1049 }
1050 filters.extend(
1051 Self::path_patterns(&venv)
1052 .into_iter()
1053 .map(|pattern| (pattern, "[VENV]/".to_string())),
1054 );
1055
1056 if let Some(site_packages) = site_packages {
1058 filters.push((
1059 Self::path_pattern(
1060 site_packages
1061 .strip_prefix(&canonical_temp_dir)
1062 .expect("The test site-packages directory is always in the tempdir"),
1063 ),
1064 "[SITE_PACKAGES]/".to_string(),
1065 ));
1066 }
1067
1068 filters.push((
1070 r"[\\/]lib[\\/]python\d+\.\d+[\\/]".to_string(),
1071 "/[PYTHON-LIB]/".to_string(),
1072 ));
1073 filters.push((r"[\\/]Lib[\\/]".to_string(), "/[PYTHON-LIB]/".to_string()));
1074
1075 filters.extend(
1076 Self::path_patterns(&temp_dir)
1077 .into_iter()
1078 .map(|pattern| (pattern, "[TEMP_DIR]/".to_string())),
1079 );
1080 filters.extend(
1081 Self::path_patterns(&python_dir)
1082 .into_iter()
1083 .map(|pattern| (pattern, "[PYTHON_DIR]/".to_string())),
1084 );
1085 let mut uv_user_config_dir = PathBuf::from(user_config_dir.path());
1086 uv_user_config_dir.push("uv");
1087 filters.extend(
1088 Self::path_patterns(&uv_user_config_dir)
1089 .into_iter()
1090 .map(|pattern| (pattern, "[UV_USER_CONFIG_DIR]/".to_string())),
1091 );
1092 filters.extend(
1093 Self::path_patterns(&user_config_dir)
1094 .into_iter()
1095 .map(|pattern| (pattern, "[USER_CONFIG_DIR]/".to_string())),
1096 );
1097 filters.extend(
1098 Self::path_patterns(&home_dir)
1099 .into_iter()
1100 .map(|pattern| (pattern, "[HOME]/".to_string())),
1101 );
1102 filters.extend(
1103 Self::path_patterns(&workspace_root)
1104 .into_iter()
1105 .map(|pattern| (pattern, "[WORKSPACE]/".to_string())),
1106 );
1107
1108 filters.push((
1110 r"Activate with: (.*)\\Scripts\\activate".to_string(),
1111 "Activate with: source $1/[BIN]/activate".to_string(),
1112 ));
1113 filters.push((
1114 r"Activate with: Scripts\\activate".to_string(),
1115 "Activate with: source [BIN]/activate".to_string(),
1116 ));
1117 filters.push((
1118 r"Activate with: source (.*/|)bin/activate(?:\.\w+)?".to_string(),
1119 "Activate with: source $1[BIN]/activate".to_string(),
1120 ));
1121
1122 filters.push((
1125 r#"(\\|/)\.tmp[^\\/\s"'`]*"#.to_string(),
1126 "/[TMP]".to_string(),
1127 ));
1128
1129 filters.push((r"file:///".to_string(), "file://".to_string()));
1131
1132 filters.push((r"\\\\\?\\".to_string(), String::new()));
1134
1135 filters.push((r"127\.0\.0\.1:\d*".to_string(), "[LOCALHOST]".to_string()));
1137 filters.push((
1139 format!(
1140 r#"requires = \["uv_build>={},<[0-9.]+"\]"#,
1141 uv_version::version()
1142 ),
1143 r#"requires = ["uv_build>=[CURRENT_VERSION],<[NEXT_BREAKING]"]"#.to_string(),
1144 ));
1145 filters.push((
1147 r"environments-v(\d+)[\\/]([\w.\[\]-]+)-[a-f0-9]{16}".to_string(),
1148 "environments-v$1/$2-[HASH]".to_string(),
1149 ));
1150 filters.push((
1152 r"archive-v(\d+)[\\/][A-Za-z0-9\-\_]+".to_string(),
1153 "archive-v$1/[HASH]".to_string(),
1154 ));
1155
1156 Self {
1157 root: ChildPath::new(root.path()),
1158 temp_dir,
1159 cache_dir,
1160 python_dir,
1161 home_dir,
1162 user_config_dir,
1163 bin_dir,
1164 venv,
1165 workspace_root,
1166 python_version,
1167 python_versions,
1168 uv_bin,
1169 filters,
1170 extra_env: vec![],
1171 _root: root,
1172 _extra_tempdirs: vec![],
1173 }
1174 }
1175
1176 pub fn command(&self) -> Command {
1178 let mut command = self.new_command();
1179 self.add_shared_options(&mut command, true);
1180 command
1181 }
1182
1183 pub fn disallow_git_cli(bin_dir: &Path) -> std::io::Result<()> {
1184 let contents = r"#!/bin/sh
1185 echo 'error: `git` operations are not allowed — are you missing a cfg for the `git` feature?' >&2
1186 exit 127";
1187 let git = bin_dir.join(format!("git{}", env::consts::EXE_SUFFIX));
1188 fs_err::write(&git, contents)?;
1189
1190 #[cfg(unix)]
1191 {
1192 use std::os::unix::fs::PermissionsExt;
1193 let mut perms = fs_err::metadata(&git)?.permissions();
1194 perms.set_mode(0o755);
1195 fs_err::set_permissions(&git, perms)?;
1196 }
1197
1198 Ok(())
1199 }
1200
1201 #[must_use]
1206 pub fn with_git_lfs_config(mut self) -> Self {
1207 let git_lfs_config = self.root.child(".gitconfig");
1208 git_lfs_config
1209 .write_str(indoc! {r#"
1210 [filter "lfs"]
1211 clean = git-lfs clean -- %f
1212 smudge = git-lfs smudge -- %f
1213 process = git-lfs filter-process
1214 required = true
1215 "#})
1216 .expect("Failed to setup `git-lfs` filters");
1217
1218 self.extra_env.push((
1221 EnvVars::GIT_CONFIG_GLOBAL.into(),
1222 git_lfs_config.as_os_str().into(),
1223 ));
1224 self
1225 }
1226
1227 pub fn add_shared_options(&self, command: &mut Command, activate_venv: bool) {
1239 self.add_shared_args(command);
1240 self.add_shared_env(command, activate_venv);
1241 }
1242
1243 fn add_shared_args(&self, command: &mut Command) {
1245 command.arg("--cache-dir").arg(self.cache_dir.path());
1246 }
1247
1248 pub fn add_shared_env(&self, command: &mut Command, activate_venv: bool) {
1250 let path = env::join_paths(std::iter::once(self.bin_dir.to_path_buf()).chain(
1252 env::split_paths(&env::var(EnvVars::PATH).unwrap_or_default()),
1253 ))
1254 .unwrap();
1255
1256 if cfg!(not(windows)) {
1259 command.env(EnvVars::SHELL, "bash");
1260 }
1261
1262 command
1263 .env_remove(EnvVars::VIRTUAL_ENV)
1265 .env(EnvVars::UV_NO_WRAP, "1")
1267 .env(EnvVars::UV_NO_SYSTEM_CONFIG, "1")
1269 .env(EnvVars::COLUMNS, "100")
1272 .env(EnvVars::PATH, path)
1273 .env(EnvVars::HOME, self.home_dir.as_os_str())
1274 .env(EnvVars::APPDATA, self.home_dir.as_os_str())
1275 .env(EnvVars::USERPROFILE, self.home_dir.as_os_str())
1276 .env(
1277 EnvVars::XDG_CONFIG_DIRS,
1278 self.home_dir.join("config").as_os_str(),
1279 )
1280 .env(
1281 EnvVars::XDG_DATA_HOME,
1282 self.home_dir.join("data").as_os_str(),
1283 )
1284 .env(EnvVars::UV_NO_SYSTEM_CONFIG, "1")
1285 .env(EnvVars::UV_PYTHON_INSTALL_DIR, "")
1286 .env(EnvVars::UV_PYTHON_DOWNLOADS, "never")
1288 .env(EnvVars::UV_PYTHON_SEARCH_PATH, self.python_path())
1289 .env(EnvVars::UV_EXCLUDE_NEWER, TEST_TIMESTAMP)
1290 .env(EnvVars::UV_TEST_CURRENT_TIMESTAMP, TEST_TIMESTAMP)
1291 .env(EnvVars::UV_TEST_AVAILABLE_VERSION_CUTOFF, TEST_TIMESTAMP)
1292 .env(EnvVars::UV_PYTHON_NO_REGISTRY, "1")
1295 .env(EnvVars::UV_PYTHON_INSTALL_REGISTRY, "0")
1296 .env(EnvVars::UV_TEST_NO_CLI_PROGRESS, "1")
1299 .env(EnvVars::GIT_CEILING_DIRECTORIES, self.root.path())
1313 .current_dir(self.temp_dir.path());
1314
1315 for (key, value) in &self.extra_env {
1316 command.env(key, value);
1317 }
1318
1319 if activate_venv {
1320 command.env(EnvVars::VIRTUAL_ENV, self.venv.as_os_str());
1321 }
1322
1323 if cfg!(unix) {
1324 command.env(EnvVars::LC_ALL, "C");
1326 }
1327 }
1328
1329 pub fn pip_compile(&self) -> Command {
1331 let mut command = self.new_command();
1332 command.arg("pip").arg("compile");
1333 self.add_shared_options(&mut command, true);
1334 command
1335 }
1336
1337 pub fn pip_sync(&self) -> Command {
1339 let mut command = self.new_command();
1340 command.arg("pip").arg("sync");
1341 self.add_shared_options(&mut command, true);
1342 command
1343 }
1344
1345 pub fn pip_show(&self) -> Command {
1346 let mut command = self.new_command();
1347 command.arg("pip").arg("show");
1348 self.add_shared_options(&mut command, true);
1349 command
1350 }
1351
1352 pub fn pip_freeze(&self) -> Command {
1354 let mut command = self.new_command();
1355 command.arg("pip").arg("freeze");
1356 self.add_shared_options(&mut command, true);
1357 command
1358 }
1359
1360 pub fn pip_check(&self) -> Command {
1362 let mut command = self.new_command();
1363 command.arg("pip").arg("check");
1364 self.add_shared_options(&mut command, true);
1365 command
1366 }
1367
1368 pub fn pip_list(&self) -> Command {
1369 let mut command = self.new_command();
1370 command.arg("pip").arg("list");
1371 self.add_shared_options(&mut command, true);
1372 command
1373 }
1374
1375 pub fn venv(&self) -> Command {
1377 let mut command = self.new_command();
1378 command.arg("venv");
1379 self.add_shared_options(&mut command, false);
1380 command
1381 }
1382
1383 pub fn pip_install(&self) -> Command {
1385 let mut command = self.new_command();
1386 command.arg("pip").arg("install");
1387 self.add_shared_options(&mut command, true);
1388 command
1389 }
1390
1391 pub fn pip_uninstall(&self) -> Command {
1393 let mut command = self.new_command();
1394 command.arg("pip").arg("uninstall");
1395 self.add_shared_options(&mut command, true);
1396 command
1397 }
1398
1399 pub fn pip_tree(&self) -> Command {
1401 let mut command = self.new_command();
1402 command.arg("pip").arg("tree");
1403 self.add_shared_options(&mut command, true);
1404 command
1405 }
1406
1407 pub fn pip_debug(&self) -> Command {
1409 let mut command = self.new_command();
1410 command.arg("pip").arg("debug");
1411 self.add_shared_options(&mut command, true);
1412 command
1413 }
1414
1415 pub fn help(&self) -> Command {
1417 let mut command = self.new_command();
1418 command.arg("help");
1419 self.add_shared_env(&mut command, false);
1420 command
1421 }
1422
1423 pub fn init(&self) -> Command {
1426 let mut command = self.new_command();
1427 command.arg("init");
1428 self.add_shared_options(&mut command, false);
1429 command
1430 }
1431
1432 pub fn sync(&self) -> Command {
1434 let mut command = self.new_command();
1435 command.arg("sync");
1436 self.add_shared_options(&mut command, false);
1437 command
1438 }
1439
1440 pub fn lock(&self) -> Command {
1442 let mut command = self.new_command();
1443 command.arg("lock");
1444 self.add_shared_options(&mut command, false);
1445 command
1446 }
1447
1448 pub fn upgrade(&self) -> Command {
1450 let mut command = self.new_command();
1451 command.arg("upgrade");
1452 self.add_shared_options(&mut command, false);
1453 command
1454 }
1455
1456 pub fn audit(&self) -> Command {
1458 let mut command = self.new_command();
1459 command.arg("audit");
1460 self.add_shared_options(&mut command, false);
1461 command
1462 }
1463
1464 pub fn workspace_metadata(&self) -> Command {
1466 let mut command = self.new_command();
1467 command.arg("workspace").arg("metadata");
1468 self.add_shared_options(&mut command, false);
1469 command
1470 }
1471
1472 pub fn workspace_dir(&self) -> Command {
1474 let mut command = self.new_command();
1475 command.arg("workspace").arg("dir");
1476 self.add_shared_options(&mut command, false);
1477 command
1478 }
1479
1480 pub fn workspace_list(&self) -> Command {
1482 let mut command = self.new_command();
1483 command.arg("workspace").arg("list");
1484 self.add_shared_options(&mut command, false);
1485 command
1486 }
1487
1488 pub fn export(&self) -> Command {
1490 let mut command = self.new_command();
1491 command.arg("export");
1492 self.add_shared_options(&mut command, false);
1493 command
1494 }
1495
1496 pub fn format(&self) -> Command {
1498 let mut command = self.new_command();
1499 command.arg("format");
1500 self.add_shared_options(&mut command, false);
1501 command.env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z");
1503 command
1504 }
1505
1506 pub fn check(&self) -> Command {
1508 let mut command = self.new_command();
1509 command.arg("check");
1510 self.add_shared_options(&mut command, false);
1511 command.env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z");
1513 command
1514 }
1515
1516 pub fn build(&self) -> Command {
1518 let mut command = self.new_command();
1519 command.arg("build");
1520 self.add_shared_options(&mut command, false);
1521 command
1522 }
1523
1524 pub fn version(&self) -> Command {
1525 let mut command = self.new_command();
1526 command.arg("version");
1527 self.add_shared_options(&mut command, false);
1528 command
1529 }
1530
1531 pub fn self_version(&self) -> Command {
1532 let mut command = self.new_command();
1533 command.arg("self").arg("version");
1534 self.add_shared_options(&mut command, false);
1535 command
1536 }
1537
1538 pub fn self_update(&self) -> Command {
1539 let mut command = self.new_command();
1540 command.arg("self").arg("update");
1541 self.add_shared_options(&mut command, false);
1542 command
1543 }
1544
1545 pub fn publish(&self) -> Command {
1547 let mut command = self.new_command();
1548 command.arg("publish");
1549 self.add_shared_options(&mut command, false);
1550 command
1551 }
1552
1553 pub fn python_find(&self) -> Command {
1555 let mut command = self.new_command();
1556 command
1557 .arg("python")
1558 .arg("find")
1559 .env(EnvVars::UV_PREVIEW, "1")
1560 .env(EnvVars::UV_PYTHON_INSTALL_DIR, "");
1561 self.add_shared_options(&mut command, false);
1562 command
1563 }
1564
1565 pub fn python_list(&self) -> Command {
1567 let mut command = self.new_command();
1568 command
1569 .arg("python")
1570 .arg("list")
1571 .env(EnvVars::UV_PYTHON_INSTALL_DIR, "");
1572 self.add_shared_options(&mut command, false);
1573 command
1574 }
1575
1576 pub fn python_install(&self) -> Command {
1578 let mut command = self.new_command();
1579 command.arg("python").arg("install");
1580 self.add_shared_options(&mut command, true);
1581 command
1582 }
1583
1584 pub fn python_uninstall(&self) -> Command {
1586 let mut command = self.new_command();
1587 command.arg("python").arg("uninstall");
1588 self.add_shared_options(&mut command, true);
1589 command
1590 }
1591
1592 pub fn python_upgrade(&self) -> Command {
1594 let mut command = self.new_command();
1595 command.arg("python").arg("upgrade");
1596 self.add_shared_options(&mut command, true);
1597 command
1598 }
1599
1600 pub fn python_pin(&self) -> Command {
1602 let mut command = self.new_command();
1603 command.arg("python").arg("pin");
1604 self.add_shared_options(&mut command, true);
1605 command
1606 }
1607
1608 pub fn python_dir(&self) -> Command {
1610 let mut command = self.new_command();
1611 command.arg("python").arg("dir");
1612 self.add_shared_options(&mut command, true);
1613 command
1614 }
1615
1616 pub fn run(&self) -> Command {
1618 let mut command = self.new_command();
1619 command.arg("run").env(EnvVars::UV_SHOW_RESOLUTION, "1");
1620 self.add_shared_options(&mut command, true);
1621 command
1622 }
1623
1624 pub fn tool_run(&self) -> Command {
1626 let mut command = self.new_command();
1627 command
1628 .arg("tool")
1629 .arg("run")
1630 .env(EnvVars::UV_SHOW_RESOLUTION, "1");
1631 self.add_shared_options(&mut command, false);
1632 command
1633 }
1634
1635 pub fn tool_upgrade(&self) -> Command {
1637 let mut command = self.new_command();
1638 command.arg("tool").arg("upgrade");
1639 self.add_shared_options(&mut command, false);
1640 command
1641 }
1642
1643 pub fn tool_install(&self) -> Command {
1645 let mut command = self.new_command();
1646 command.arg("tool").arg("install");
1647 self.add_shared_options(&mut command, false);
1648 command
1649 }
1650
1651 pub fn tool_list(&self) -> Command {
1653 let mut command = self.new_command();
1654 command.arg("tool").arg("list");
1655 self.add_shared_options(&mut command, false);
1656 command
1657 }
1658
1659 pub fn tool_audit(&self) -> Command {
1661 let mut command = self.new_command();
1662 command.arg("tool").arg("audit");
1663 self.add_shared_options(&mut command, false);
1664 command
1665 }
1666
1667 pub fn tool_dir(&self) -> Command {
1669 let mut command = self.new_command();
1670 command.arg("tool").arg("dir");
1671 self.add_shared_options(&mut command, false);
1672 command
1673 }
1674
1675 pub fn tool_uninstall(&self) -> Command {
1677 let mut command = self.new_command();
1678 command.arg("tool").arg("uninstall");
1679 self.add_shared_options(&mut command, false);
1680 command
1681 }
1682
1683 pub fn add(&self) -> Command {
1685 let mut command = self.new_command();
1686 command.arg("add");
1687 self.add_shared_options(&mut command, false);
1688 command
1689 }
1690
1691 pub fn remove(&self) -> Command {
1693 let mut command = self.new_command();
1694 command.arg("remove");
1695 self.add_shared_options(&mut command, false);
1696 command
1697 }
1698
1699 pub fn tree(&self) -> Command {
1701 let mut command = self.new_command();
1702 command.arg("tree");
1703 self.add_shared_options(&mut command, false);
1704 command
1705 }
1706
1707 pub fn clean(&self) -> Command {
1709 let mut command = self.new_command();
1710 command.arg("cache").arg("clean");
1711 self.add_shared_options(&mut command, false);
1712 command
1713 }
1714
1715 pub fn prune(&self) -> Command {
1717 let mut command = self.new_command();
1718 command.arg("cache").arg("prune");
1719 self.add_shared_options(&mut command, false);
1720 command
1721 }
1722
1723 pub fn cache_size(&self) -> Command {
1725 let mut command = self.new_command();
1726 command.arg("cache").arg("size");
1727 self.add_shared_options(&mut command, false);
1728 command
1729 }
1730
1731 pub fn build_backend(&self) -> Command {
1735 let mut command = self.new_command();
1736 command.arg("build-backend");
1737 self.add_shared_options(&mut command, false);
1738 command
1739 }
1740
1741 pub fn interpreter(&self) -> PathBuf {
1745 let venv = &self.venv;
1746 if cfg!(unix) {
1747 venv.join("bin").join("python")
1748 } else if cfg!(windows) {
1749 venv.join("Scripts").join("python.exe")
1750 } else {
1751 unimplemented!("Only Windows and Unix are supported")
1752 }
1753 }
1754
1755 pub fn python_command(&self) -> Command {
1756 let mut interpreter = self.interpreter();
1757
1758 if !interpreter.exists() {
1760 interpreter.clone_from(
1761 &self
1762 .python_versions
1763 .first()
1764 .expect("At least one Python version is required")
1765 .1,
1766 );
1767 }
1768
1769 let mut command = Self::new_command_with(&interpreter);
1770 command
1771 .arg("-B")
1774 .env(EnvVars::PYTHONUTF8, "1");
1776
1777 self.add_shared_env(&mut command, false);
1778
1779 command
1780 }
1781
1782 pub fn auth_login(&self) -> Command {
1784 let mut command = self.new_command();
1785 command.arg("auth").arg("login");
1786 self.add_shared_options(&mut command, false);
1787 command
1788 }
1789
1790 pub fn auth_logout(&self) -> Command {
1792 let mut command = self.new_command();
1793 command.arg("auth").arg("logout");
1794 self.add_shared_options(&mut command, false);
1795 command
1796 }
1797
1798 pub fn auth_helper(&self) -> Command {
1800 let mut command = self.new_command();
1801 command.arg("auth").arg("helper");
1802 self.add_shared_options(&mut command, false);
1803 command
1804 }
1805
1806 pub fn auth_token(&self) -> Command {
1808 let mut command = self.new_command();
1809 command.arg("auth").arg("token");
1810 self.add_shared_options(&mut command, false);
1811 command
1812 }
1813
1814 #[must_use]
1818 pub fn with_real_home(mut self) -> Self {
1819 if let Some(home) = env::var_os(EnvVars::HOME) {
1820 self.extra_env
1821 .push((EnvVars::HOME.to_string().into(), home));
1822 }
1823 self.extra_env.push((
1826 EnvVars::XDG_CONFIG_HOME.into(),
1827 self.user_config_dir.as_os_str().into(),
1828 ));
1829 self
1830 }
1831
1832 pub fn assert_command(&self, command: &str) -> Assert {
1834 self.python_command()
1835 .arg("-c")
1836 .arg(command)
1837 .current_dir(&self.temp_dir)
1838 .assert()
1839 }
1840
1841 pub fn assert_file(&self, file: impl AsRef<Path>) -> Assert {
1843 self.python_command()
1844 .arg(file.as_ref())
1845 .current_dir(&self.temp_dir)
1846 .assert()
1847 }
1848
1849 pub fn assert_installed(&self, package: &'static str, version: &'static str) {
1851 self.assert_command(
1852 format!("import {package} as package; print(package.__version__, end='')").as_str(),
1853 )
1854 .success()
1855 .stdout(version);
1856 }
1857
1858 pub fn assert_not_installed(&self, package: &'static str) {
1860 self.assert_command(format!("import {package}").as_str())
1861 .failure();
1862 }
1863
1864 pub fn path_patterns(path: impl AsRef<Path>) -> Vec<String> {
1866 let mut patterns = Vec::new();
1867
1868 if path.as_ref().exists() {
1870 patterns.push(Self::path_pattern(
1871 path.as_ref()
1872 .canonicalize()
1873 .expect("Failed to create canonical path"),
1874 ));
1875 }
1876
1877 patterns.push(Self::path_pattern(path));
1879
1880 patterns
1881 }
1882
1883 fn path_pattern(path: impl AsRef<Path>) -> String {
1885 format!(
1886 r"{}\\?/?",
1888 regex::escape(&path.as_ref().simplified_display().to_string())
1889 .replace(r"\\", r"(\\|\/)")
1892 )
1893 }
1894
1895 pub fn python_path(&self) -> OsString {
1896 if cfg!(unix) {
1897 env::join_paths(
1899 self.python_versions
1900 .iter()
1901 .map(|(version, _)| self.python_dir.join(version.to_string())),
1902 )
1903 .unwrap()
1904 } else {
1905 env::join_paths(
1907 self.python_versions
1908 .iter()
1909 .map(|(_, executable)| executable.parent().unwrap().to_path_buf()),
1910 )
1911 .unwrap()
1912 }
1913 }
1914
1915 pub fn filters(&self) -> Vec<(&str, &str)> {
1917 self.filters
1920 .iter()
1921 .map(|(p, r)| (p.as_str(), r.as_str()))
1922 .chain(INSTA_FILTERS.iter().copied())
1923 .collect()
1924 }
1925
1926 #[cfg(windows)]
1928 pub fn filters_without_standard_filters(&self) -> Vec<(&str, &str)> {
1929 self.filters
1930 .iter()
1931 .map(|(p, r)| (p.as_str(), r.as_str()))
1932 .collect()
1933 }
1934
1935 pub fn python_kind(&self) -> &'static str {
1937 "python"
1938 }
1939
1940 pub fn site_packages(&self) -> PathBuf {
1942 site_packages_path(
1943 &self.venv,
1944 &format!(
1945 "{}{}",
1946 self.python_kind(),
1947 self.python_version.as_ref().expect(
1948 "A Python version must be provided to retrieve the test site packages path"
1949 )
1950 ),
1951 )
1952 }
1953
1954 pub fn reset_venv(&self) {
1956 self.create_venv();
1957 }
1958
1959 fn create_venv(&self) {
1961 let executable = get_python(
1962 self.python_version
1963 .as_ref()
1964 .expect("A Python version must be provided to create a test virtual environment"),
1965 );
1966 create_venv_from_executable(&self.venv, &self.cache_dir, &executable, &self.uv_bin);
1967 }
1968
1969 pub fn copy_ecosystem_project(&self, name: &str) {
1980 let project_dir = PathBuf::from(format!("../../test/ecosystem/{name}"));
1981 self.temp_dir.copy_from(project_dir, &["**/*"]).unwrap();
1982 if let Err(err) = fs_err::remove_file(self.temp_dir.join("uv.lock")) {
1984 assert_eq!(
1985 err.kind(),
1986 io::ErrorKind::NotFound,
1987 "Failed to remove uv.lock: {err}"
1988 );
1989 }
1990 }
1991
1992 pub fn diff_lock(&self, change: impl Fn(&Self) -> Command) -> String {
2001 let lock_path = ChildPath::new(self.temp_dir.join("uv.lock"));
2002 let old_lock = fs_err::read_to_string(&lock_path).unwrap();
2003 let (snapshot, output) = run_and_format(
2004 change(self),
2005 self.filters(),
2006 "diff_lock",
2007 Some(WindowsFilters::Platform),
2008 None,
2009 );
2010 assert!(output.status.success(), "{snapshot}");
2011 let new_lock = fs_err::read_to_string(&lock_path).unwrap();
2012 diff_snapshot(&old_lock, &new_lock, 10)
2013 }
2014
2015 pub fn read(&self, file: impl AsRef<Path>) -> String {
2017 fs_err::read_to_string(self.temp_dir.join(&file))
2018 .unwrap_or_else(|_| panic!("Missing file: `{}`", file.user_display()))
2019 }
2020
2021 fn new_command(&self) -> Command {
2024 Self::new_command_with(&self.uv_bin)
2025 }
2026
2027 fn new_command_with(bin: &Path) -> Command {
2033 let mut command = Command::new(bin);
2034
2035 let passthrough = [
2036 EnvVars::PATH,
2038 EnvVars::RUST_LOG,
2040 EnvVars::RUST_BACKTRACE,
2041 EnvVars::SYSTEMDRIVE,
2043 EnvVars::RUST_MIN_STACK,
2045 EnvVars::UV_STACK_SIZE,
2046 EnvVars::ALL_PROXY,
2048 EnvVars::HTTPS_PROXY,
2049 EnvVars::HTTP_PROXY,
2050 EnvVars::NO_PROXY,
2051 EnvVars::SSL_CERT_DIR,
2052 EnvVars::SSL_CERT_FILE,
2053 EnvVars::UV_NATIVE_TLS,
2054 EnvVars::UV_SYSTEM_CERTS,
2055 ];
2056
2057 for env_var in EnvVars::all_names()
2058 .iter()
2059 .filter(|name| !passthrough.contains(name))
2060 {
2061 command.env_remove(env_var);
2062 }
2063
2064 command
2065 }
2066}
2067
2068pub fn diff_snapshot(old: &str, new: &str, context_radius: usize) -> String {
2071 let diff = similar::TextDiff::from_lines(old, new);
2072 let unified = diff
2073 .unified_diff()
2074 .context_radius(context_radius)
2075 .header("old", "new")
2076 .to_string();
2077 regex!(r"(?m)^\s+$").replace_all(&unified, "").into_owned()
2081}
2082
2083#[macro_export]
2087macro_rules! diff_uv_snapshot {
2088 ($filters:expr, $old:expr, $spawnable:expr, @$snapshot:literal) => {{
2089 let new = $crate::capture_uv_snapshot!($filters, $spawnable);
2090 let snapshot = $crate::diff_snapshot($old, &new, 3);
2091 let mut settings = ::insta::Settings::clone_current();
2092 let description = match settings.description() {
2094 Some(description) => format!("{description}\n\nUnfiltered diff:\n{snapshot}"),
2095 None => format!("Unfiltered diff:\n{snapshot}"),
2096 };
2097 settings.set_description(description);
2098 settings.add_filter(r"^--- old\n\+\+\+ new\n", "");
2099 settings.add_filter(r"(?m)^@@.*$", "...");
2100 settings.add_filter(r"\n$", "\n...\n");
2101 settings.bind(|| {
2102 ::insta::assert_snapshot!(snapshot, @$snapshot);
2103 });
2104 new
2105 }};
2106}
2107
2108#[macro_export]
2110macro_rules! capture_uv_snapshot {
2111 ($filters:expr, $spawnable:expr) => {{
2112 let (snapshot, _) = $crate::run_and_format_silent(
2114 $spawnable,
2115 &$filters,
2116 $crate::function_name!(),
2117 Some($crate::WindowsFilters::Platform),
2118 None,
2119 );
2120 snapshot
2121 }};
2122 ($filters:expr, $spawnable:expr, @$snapshot:literal) => {{
2123 let (snapshot, _) = $crate::run_and_format(
2124 $spawnable,
2125 &$filters,
2126 $crate::function_name!(),
2127 Some($crate::WindowsFilters::Platform),
2128 None,
2129 );
2130 ::insta::assert_snapshot!(snapshot, @$snapshot);
2131 snapshot
2132 }};
2133}
2134
2135pub fn site_packages_path(venv: &Path, python: &str) -> PathBuf {
2136 if cfg!(unix) {
2137 venv.join("lib").join(python).join("site-packages")
2138 } else if cfg!(windows) {
2139 venv.join("Lib").join("site-packages")
2140 } else {
2141 unimplemented!("Only Windows and Unix are supported")
2142 }
2143}
2144
2145pub fn venv_bin_path(venv: impl AsRef<Path>) -> PathBuf {
2146 if cfg!(unix) {
2147 venv.as_ref().join("bin")
2148 } else if cfg!(windows) {
2149 venv.as_ref().join("Scripts")
2150 } else {
2151 unimplemented!("Only Windows and Unix are supported")
2152 }
2153}
2154
2155fn get_python(version: &PythonVersion) -> PathBuf {
2157 ManagedPythonInstallations::from_settings(None)
2158 .map(|installed_pythons| {
2159 installed_pythons
2160 .find_version(version)
2161 .expect("Tests are run on a supported platform")
2162 .next()
2163 .as_ref()
2164 .map(|python| python.executable(false))
2165 })
2166 .unwrap_or_default()
2169 .unwrap_or(PathBuf::from(version.to_string()))
2170}
2171
2172fn create_venv_from_executable<P: AsRef<Path>>(
2174 path: P,
2175 cache_dir: &ChildPath,
2176 python: &Path,
2177 uv_bin: &Path,
2178) {
2179 TestContext::new_command_with(uv_bin)
2180 .arg("venv")
2181 .arg(path.as_ref().as_os_str())
2182 .arg("--clear")
2183 .arg("--cache-dir")
2184 .arg(cache_dir.path())
2185 .arg("--python")
2186 .arg(python)
2187 .current_dir(path.as_ref().parent().unwrap())
2188 .assert()
2189 .success();
2190 ChildPath::new(path.as_ref()).assert(predicate::path::is_dir());
2191}
2192
2193pub fn python_path_with_versions(
2197 temp_dir: &ChildPath,
2198 python_versions: &[&str],
2199) -> anyhow::Result<OsString> {
2200 let download_list = ManagedPythonDownloadList::new_only_embedded().unwrap();
2201 Ok(env::join_paths(
2202 python_installations_for_versions(temp_dir, python_versions, &download_list)?
2203 .into_iter()
2204 .map(|path| path.parent().unwrap().to_path_buf()),
2205 )?)
2206}
2207
2208fn python_installations_for_versions(
2212 temp_dir: &ChildPath,
2213 python_versions: &[&str],
2214 download_list: &ManagedPythonDownloadList,
2215) -> anyhow::Result<Vec<PathBuf>> {
2216 let cache = Cache::from_path(temp_dir.child("cache").to_path_buf())
2217 .init_no_wait()?
2218 .expect("No cache contention when setting up Python in tests");
2219 let _preview = uv_preview::test::with_features(&[]);
2220 let selected_pythons = python_versions
2221 .iter()
2222 .map(|python_version| {
2223 if let Ok(python) = PythonInstallation::find(
2224 &PythonRequest::parse(python_version),
2225 EnvironmentPreference::OnlySystem,
2226 PythonPreference::Managed,
2227 download_list,
2228 &cache,
2229 ) {
2230 python.into_interpreter().sys_executable().to_owned()
2231 } else {
2232 panic!("Could not find Python {python_version} for test\nTry `cargo run python install` first, or refer to CONTRIBUTING.md");
2233 }
2234 })
2235 .collect::<Vec<_>>();
2236
2237 assert!(
2238 python_versions.is_empty() || !selected_pythons.is_empty(),
2239 "Failed to fulfill requested test Python versions: {selected_pythons:?}"
2240 );
2241
2242 Ok(selected_pythons)
2243}
2244
2245#[derive(Debug, Copy, Clone)]
2246pub enum WindowsFilters {
2247 Platform,
2248 Universal,
2249}
2250
2251pub fn apply_filters<T: AsRef<str>>(mut snapshot: String, filters: impl AsRef<[(T, T)]>) -> String {
2253 for (matcher, replacement) in filters.as_ref() {
2254 let re = Regex::new(matcher.as_ref()).expect("Do you need to regex::escape your filter?");
2256 if re.is_match(&snapshot) {
2257 snapshot = re.replace_all(&snapshot, replacement.as_ref()).to_string();
2258 }
2259 }
2260 snapshot
2261}
2262
2263#[expect(clippy::print_stderr)]
2267pub fn run_and_format<T: AsRef<str>>(
2268 command: impl BorrowMut<Command>,
2269 filters: impl AsRef<[(T, T)]>,
2270 function_name: &str,
2271 windows_filters: Option<WindowsFilters>,
2272 input: Option<&str>,
2273) -> (String, Output) {
2274 let (snapshot, output) =
2275 run_and_format_silent(command, filters, function_name, windows_filters, input);
2276 eprintln!("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Unfiltered output ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
2277 eprintln!(
2278 "----- exit status -----\n{}\n----- stdout -----\n{}\n----- stderr -----\n{}",
2279 output.status,
2280 String::from_utf8_lossy(&output.stdout),
2281 String::from_utf8_lossy(&output.stderr),
2282 );
2283 eprintln!("────────────────────────────────────────────────────────────────────────────────\n");
2284 (snapshot, output)
2285}
2286
2287#[doc(hidden)]
2289pub fn run_and_format_silent<T: AsRef<str>>(
2290 mut command: impl BorrowMut<Command>,
2291 filters: impl AsRef<[(T, T)]>,
2292 function_name: &str,
2293 windows_filters: Option<WindowsFilters>,
2294 input: Option<&str>,
2295) -> (String, Output) {
2296 assert_effective_cache_directory(command.borrow_mut());
2297
2298 let program = command
2299 .borrow_mut()
2300 .get_program()
2301 .to_string_lossy()
2302 .to_string();
2303
2304 if let Ok(root) = env::var(EnvVars::TRACING_DURATIONS_TEST_ROOT) {
2306 #[expect(clippy::assertions_on_constants)]
2308 {
2309 assert!(
2310 cfg!(feature = "tracing-durations-export"),
2311 "You need to enable the tracing-durations-export feature to use `TRACING_DURATIONS_TEST_ROOT`"
2312 );
2313 }
2314 command.borrow_mut().env(
2315 EnvVars::TRACING_DURATIONS_FILE,
2316 Path::new(&root).join(function_name).with_extension("jsonl"),
2317 );
2318 }
2319
2320 let output = if let Some(input) = input {
2321 let mut child = command
2322 .borrow_mut()
2323 .stdin(Stdio::piped())
2324 .stdout(Stdio::piped())
2325 .stderr(Stdio::piped())
2326 .spawn()
2327 .unwrap_or_else(|err| panic!("Failed to spawn {program}: {err}"));
2328 child
2329 .stdin
2330 .as_mut()
2331 .expect("Failed to open stdin")
2332 .write_all(input.as_bytes())
2333 .expect("Failed to write to stdin");
2334
2335 child
2336 .wait_with_output()
2337 .unwrap_or_else(|err| panic!("Failed to read output from {program}: {err}"))
2338 } else {
2339 command
2340 .borrow_mut()
2341 .output()
2342 .unwrap_or_else(|err| panic!("Failed to spawn {program}: {err}"))
2343 };
2344
2345 let mut snapshot = format!(
2346 "exit_code: {} ({})\n",
2347 output.status.code().unwrap_or(!0),
2348 if output.status.success() {
2349 "success"
2350 } else {
2351 "failure"
2352 },
2353 );
2354 if output.status.code().is_none() {
2355 snapshot.push_str("exit_status: ");
2356 snapshot.push_str(&output.status.to_string());
2357 snapshot.push('\n');
2358 }
2359 if !output.stdout.is_empty() {
2360 snapshot.push_str("----- stdout -----\n");
2361 snapshot.push_str(&String::from_utf8_lossy(&output.stdout));
2362 }
2363 if !output.stderr.is_empty() {
2364 if !output.stdout.is_empty() {
2365 snapshot.push('\n');
2366 }
2367 snapshot.push_str("----- stderr -----\n");
2368 snapshot.push_str(&String::from_utf8_lossy(&output.stderr));
2369 }
2370 let mut snapshot = apply_filters(snapshot, filters);
2371
2372 if cfg!(windows) {
2377 if let Some(windows_filters) = windows_filters {
2378 let windows_only_deps = [
2380 (r"( ?[-+~] ?)?colorama==\d+(\.\d+)+( [\\]\n\s+--hash=.*)?\n(\s+# via .*\n)?"),
2381 (r"( ?[-+~] ?)?colorama==\d+(\.\d+)+(\s+[-+~]?\s+# via .*)?\n"),
2382 (r"( ?[-+~] ?)?tzdata==\d+(\.\d+)+( [\\]\n\s+--hash=.*)?\n(\s+# via .*\n)?"),
2383 (r"( ?[-+~] ?)?tzdata==\d+(\.\d+)+(\s+[-+~]?\s+# via .*)?\n"),
2384 ];
2385 let mut removed_packages = 0;
2386 for windows_only_dep in windows_only_deps {
2387 let re = Regex::new(windows_only_dep).unwrap();
2389 if re.is_match(&snapshot) {
2390 snapshot = re.replace(&snapshot, "").to_string();
2391 removed_packages += 1;
2392 }
2393 }
2394 if removed_packages > 0 {
2395 for i in 1..20 {
2396 for verb in match windows_filters {
2397 WindowsFilters::Platform => [
2398 "Resolved",
2399 "Prepared",
2400 "Installed",
2401 "Checked",
2402 "Uninstalled",
2403 ]
2404 .iter(),
2405 WindowsFilters::Universal => {
2406 ["Prepared", "Installed", "Checked", "Uninstalled"].iter()
2407 }
2408 } {
2409 snapshot = snapshot.replace(
2410 &format!("{verb} {} packages", i + removed_packages),
2411 &format!("{verb} {} package{}", i, if i > 1 { "s" } else { "" }),
2412 );
2413 }
2414 }
2415 }
2416 }
2417 }
2418
2419 (snapshot, output)
2420}
2421
2422fn assert_effective_cache_directory(command: &Command) {
2428 let cache_directory_override = command
2429 .get_envs()
2430 .find(|(name, value)| *name == EnvVars::UV_CACHE_DIR && value.is_some());
2431
2432 if cache_directory_override.is_none() {
2433 return;
2434 }
2435
2436 let explicit_cache_directory = command.get_args().any(|argument| {
2437 argument == "--cache-dir"
2438 || argument
2439 .to_str()
2440 .is_some_and(|argument| argument.starts_with("--cache-dir="))
2441 });
2442
2443 assert!(
2444 !explicit_cache_directory,
2445 "`UV_CACHE_DIR` is ignored because this command already supplies `--cache-dir`; configure `TestContext::cache_dir` instead"
2446 );
2447}
2448
2449pub fn copy_dir_ignore(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
2451 for entry in ignore::Walk::new(&src) {
2452 let entry = entry?;
2453 let relative = entry.path().strip_prefix(&src)?;
2454 let ty = entry.file_type().unwrap();
2455 if ty.is_dir() {
2456 fs_err::create_dir(dst.as_ref().join(relative))?;
2457 } else {
2458 fs_err::copy(entry.path(), dst.as_ref().join(relative))?;
2459 }
2460 }
2461 Ok(())
2462}
2463
2464pub fn make_project(dir: &Path, name: &str, body: &str) -> anyhow::Result<()> {
2466 let pyproject_toml = formatdoc! {r#"
2467 [project]
2468 name = "{name}"
2469 version = "0.1.0"
2470 requires-python = ">=3.11,<3.13"
2471 {body}
2472
2473 [build-system]
2474 requires = ["uv_build>=0.9.0,<10000"]
2475 build-backend = "uv_build"
2476 "#
2477 };
2478 fs_err::create_dir_all(dir)?;
2479 fs_err::write(dir.join("pyproject.toml"), pyproject_toml)?;
2480 fs_err::create_dir_all(dir.join("src").join(name))?;
2481 fs_err::write(dir.join("src").join(name).join("__init__.py"), "")?;
2482 Ok(())
2483}
2484
2485pub const READ_ONLY_GITHUB_TOKEN: &[&str] = &[
2487 "Z2l0aHViCg==",
2488 "cGF0Cg==",
2489 "MTFBQlVDUjZBMERMUTQ3aVphN3hPdV9qQmhTMkZUeHZ4ZE13OHczakxuZndsV2ZlZjc2cE53eHBWS2tiRUFwdnpmUk8zV0dDSUhicDFsT01aago=",
2490];
2491
2492#[cfg(not(windows))]
2494pub const READ_ONLY_GITHUB_TOKEN_2: &[&str] = &[
2495 "Z2l0aHViCg==",
2496 "cGF0Cg==",
2497 "MTFBQlVDUjZBMDJTOFYwMTM4YmQ0bV9uTXpueWhxZDBrcllROTQ5SERTeTI0dENKZ2lmdzIybDFSR2s1SE04QW8xTUVYQ1I0Q1YxYUdPRGpvZQo=",
2498];
2499
2500pub const READ_ONLY_GITHUB_SSH_DEPLOY_KEY: &str = "LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFNd0FBQUF0emMyZ3RaVwpReU5UVXhPUUFBQUNBeTF1SnNZK1JXcWp1NkdIY3Z6a3AwS21yWDEwdmo3RUZqTkpNTkRqSGZPZ0FBQUpqWUpwVnAyQ2FWCmFRQUFBQXR6YzJndFpXUXlOVFV4T1FBQUFDQXkxdUpzWStSV3FqdTZHSGN2emtwMEttclgxMHZqN0VGak5KTU5EakhmT2cKQUFBRUMwbzBnd1BxbGl6TFBJOEFXWDVaS2dVZHJyQ2ptMDhIQm9FenB4VDg3MXBqTFc0bXhqNUZhcU83b1lkeS9PU25RcQphdGZYUytQc1FXTTBrdzBPTWQ4NkFBQUFFR3R2Ym5OMGFVQmhjM1J5WVd3dWMyZ0JBZ01FQlE9PQotLS0tLUVORCBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0K";
2501
2502pub fn decode_token(content: &[&str]) -> String {
2505 content
2506 .iter()
2507 .map(|part| base64.decode(part).unwrap())
2508 .map(|decoded| {
2509 std::str::from_utf8(decoded.as_slice())
2510 .unwrap()
2511 .trim_end()
2512 .to_string()
2513 })
2514 .join("_")
2515}
2516
2517#[tokio::main(flavor = "current_thread")]
2520pub async fn download_to_disk(url: &str, path: &Path) {
2521 let trusted_hosts: Vec<_> = env::var(EnvVars::UV_INSECURE_HOST)
2522 .unwrap_or_default()
2523 .split(' ')
2524 .map(|h| uv_configuration::TrustedHost::from_str(h).unwrap())
2525 .collect();
2526
2527 let client = uv_client::BaseClientBuilder::default()
2528 .allow_insecure_host(trusted_hosts)
2529 .build()
2530 .expect("failed to build base client");
2531 let url = url.parse().unwrap();
2532 let response = client
2533 .for_host(&url)
2534 .get(reqwest::Url::from(url))
2535 .send()
2536 .await
2537 .unwrap();
2538
2539 let mut file = fs_err::tokio::File::create(path).await.unwrap();
2540 let mut stream = response.bytes_stream();
2541 while let Some(chunk) = stream.next().await {
2542 file.write_all(&chunk.unwrap()).await.unwrap();
2543 }
2544 file.sync_all().await.unwrap();
2545}
2546
2547#[cfg(unix)]
2552pub struct ReadOnlyDirectoryGuard {
2553 path: PathBuf,
2554 original_mode: u32,
2555}
2556
2557#[cfg(unix)]
2558impl ReadOnlyDirectoryGuard {
2559 pub fn new(path: impl Into<PathBuf>) -> std::io::Result<Self> {
2562 use std::os::unix::fs::PermissionsExt;
2563 let path = path.into();
2564 let metadata = fs_err::metadata(&path)?;
2565 let original_mode = metadata.permissions().mode();
2566 let readonly_mode = original_mode & !0o222;
2568 fs_err::set_permissions(&path, std::fs::Permissions::from_mode(readonly_mode))?;
2569 Ok(Self {
2570 path,
2571 original_mode,
2572 })
2573 }
2574}
2575
2576#[cfg(unix)]
2577impl Drop for ReadOnlyDirectoryGuard {
2578 fn drop(&mut self) {
2579 use std::os::unix::fs::PermissionsExt;
2580 let _ = fs_err::set_permissions(
2581 &self.path,
2582 std::fs::Permissions::from_mode(self.original_mode),
2583 );
2584 }
2585}
2586
2587#[doc(hidden)]
2591#[macro_export]
2592macro_rules! function_name {
2593 () => {{
2594 fn f() {}
2595 fn type_name_of_val<T>(_: T) -> &'static str {
2596 std::any::type_name::<T>()
2597 }
2598 let mut name = type_name_of_val(f).strip_suffix("::f").unwrap_or("");
2599 while let Some(rest) = name.strip_suffix("::{{closure}}") {
2600 name = rest;
2601 }
2602 name
2603 }};
2604}
2605
2606#[macro_export]
2611macro_rules! uv_snapshot {
2612 ($spawnable:expr, @$snapshot:literal) => {{
2613 uv_snapshot!($crate::INSTA_FILTERS.to_vec(), $spawnable, @$snapshot)
2614 }};
2615 ($filters:expr, $spawnable:expr, @$snapshot:literal) => {{
2616 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Platform), None);
2618 ::insta::assert_snapshot!(snapshot, @$snapshot);
2619 output
2620 }};
2621 ($filters:expr, $spawnable:expr, input=$input:expr, @$snapshot:literal) => {{
2622 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Platform), Some($input));
2624 ::insta::assert_snapshot!(snapshot, @$snapshot);
2625 output
2626 }};
2627 ($filters:expr, windows_filters=false, $spawnable:expr, @$snapshot:literal) => {{
2628 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), None, None);
2630 ::insta::assert_snapshot!(snapshot, @$snapshot);
2631 output
2632 }};
2633 ($filters:expr, universal_windows_filters=true, $spawnable:expr, @$snapshot:literal) => {{
2634 let (snapshot, output) = $crate::run_and_format($spawnable, &$filters, $crate::function_name!(), Some($crate::WindowsFilters::Universal), None);
2636 ::insta::assert_snapshot!(snapshot, @$snapshot);
2637 output
2638 }};
2639}
2640
2641#[cfg(all(test, unix))]
2642mod process_status_tests {
2643 use std::process::Command;
2644
2645 use super::run_and_format_silent;
2646
2647 #[test]
2648 fn reports_signal() {
2649 let mut command = Command::new("sh");
2650 command.args(["-c", "kill -TERM $$"]);
2651 let filters: &[(&str, &str)] = &[];
2652 let (snapshot, _) = run_and_format_silent(command, filters, "reports_signal", None, None);
2653
2654 insta::assert_snapshot!(snapshot, @"
2655 exit_code: -1 (failure)
2656 exit_status: signal: 15 (SIGTERM)
2657 ");
2658 }
2659
2660 #[test]
2661 fn preserves_exit_code() {
2662 let mut command = Command::new("sh");
2663 command.args(["-c", "exit 7"]);
2664 let filters: &[(&str, &str)] = &[];
2665 let (snapshot, _) =
2666 run_and_format_silent(command, filters, "preserves_exit_code", None, None);
2667
2668 insta::assert_snapshot!(snapshot, @"exit_code: 7 (failure)");
2669 }
2670}
2671
2672#[cfg(test)]
2673mod cache_directory_tests {
2674 use std::process::Command;
2675
2676 use uv_static::EnvVars;
2677
2678 use super::assert_effective_cache_directory;
2679
2680 #[test]
2681 #[should_panic(expected = "`UV_CACHE_DIR` is ignored")]
2682 fn rejects_environment_override_with_explicit_cache_argument() {
2683 let mut command = Command::new("uv");
2684 command
2685 .arg("--cache-dir")
2686 .arg("context-cache")
2687 .env(EnvVars::UV_CACHE_DIR, "ignored-cache");
2688
2689 assert_effective_cache_directory(&command);
2690 }
2691
2692 #[test]
2693 #[should_panic(expected = "`UV_CACHE_DIR` is ignored")]
2694 fn rejects_environment_override_with_inline_cache_argument() {
2695 let mut command = Command::new("uv");
2696 command
2697 .arg("--cache-dir=context-cache")
2698 .env(EnvVars::UV_CACHE_DIR, "ignored-cache");
2699
2700 assert_effective_cache_directory(&command);
2701 }
2702
2703 #[test]
2704 fn allows_environment_override_without_explicit_cache_argument() {
2705 let mut command = Command::new("uv");
2706 command
2707 .arg("cache")
2708 .arg("dir")
2709 .env(EnvVars::UV_CACHE_DIR, "effective-cache");
2710
2711 assert_effective_cache_directory(&command);
2712 }
2713
2714 #[test]
2715 fn allows_removed_environment_override_with_explicit_cache_argument() {
2716 let mut command = Command::new("uv");
2717 command
2718 .arg("--cache-dir")
2719 .arg("context-cache")
2720 .env_remove(EnvVars::UV_CACHE_DIR);
2721
2722 assert_effective_cache_directory(&command);
2723 }
2724}