Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions crates/uv-environment-operations/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use uv_preview::{Preview, PreviewFeature};
use uv_pypi_types::{ConflictItem, ConflictKind, ConflictSet, Conflicts};
use uv_python_discovery::ConfigDiscovery;
use uv_python_discovery::PythonInstallation;
use uv_python_interpreter::{BrokenLink, Interpreter, InvalidEnvironmentKind, PythonEnvironment};
use uv_python_interpreter::{Interpreter, InvalidEnvironmentKind, PythonEnvironment};
use uv_python_managed::{PythonMinorVersionLink, UpgradePolicy};
use uv_python_types::{
EnvironmentPreference, LenientImplementationName, PythonArchitecture, PythonDownloads,
Expand Down Expand Up @@ -239,23 +239,18 @@ fn existing_project_environment(
return Ok(None);
}
Err(uv_python_interpreter::PythonEnvironmentError::Query(
uv_python_interpreter::InterpreterError::BrokenLink(BrokenLink {
path,
unix,
venv: _,
}),
uv_python_interpreter::InterpreterError::BrokenLink(broken_link),
)) => {
if unix {
let target_path = fs_err::read_link(&path)?;
if let Some(target_path) = broken_link.missing_target() {
warn_user!(
"Ignoring existing virtual environment linked to non-existent Python interpreter: `{}` -> `{}`",
path.user_display().cyan(),
broken_link.path.user_display().cyan(),
target_path.user_display().cyan(),
);
} else {
warn_user!(
"Ignoring existing virtual environment linked to non-existent Python interpreter: {}",
path.user_display().cyan(),
broken_link.path.user_display().cyan(),
);
}
return Ok(None);
Expand Down
90 changes: 89 additions & 1 deletion crates/uv-python-interpreter/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,34 @@ pub struct BrokenLink {
pub venv: bool,
}

impl BrokenLink {
/// Return the absolute missing target of a broken symlink, if it can be determined.
///
/// This is best-effort: cyclic, excessively long, repaired, or unreadable chains have no
/// missing target to display. Windows trampolines do not expose a symlink target.
pub fn missing_target(&self) -> Option<PathBuf> {
if !self.unix {
return None;
}

let mut path = std::path::absolute(&self.path).ok()?;
for depth in 0..=40 {
match fs::read_link(&path) {
Ok(target) if depth < 40 => {
// Resolve relative targets against the link, not the working directory. Do
// not collapse `..` lexically, since the parent may contain symlinks.
path = path.parent()?.join(target);
}
Err(err) if err.kind() == io::ErrorKind::NotFound && depth > 0 => {
return Some(path);
}
Ok(_) | Err(_) => return None,
}
}
None
}
}

impl Display for BrokenLink {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.unix {
Expand Down Expand Up @@ -1622,8 +1650,68 @@ mod tests {
use uv_cache_info::Timestamp;
use uv_pep440::Version;

use crate::Interpreter;
use crate::interpreter::{InterpreterInfo, canonicalize_executable};
use crate::{BrokenLink, Interpreter};

#[test]
fn broken_link_missing_target() -> Result<()> {
let temp_dir = tempdir()?;
let link = BrokenLink {
path: temp_dir.path().join("python"),
unix: true,
venv: true,
};
let missing = temp_dir.path().join("missing");
fs::os::unix::fs::symlink("intermediate", &link.path)?;
fs::os::unix::fs::symlink(&missing, temp_dir.path().join("intermediate"))?;

assert_eq!(link.missing_target(), Some(missing.clone()));

// A repaired chain no longer has a missing target.
fs::write(missing, "")?;
assert_eq!(link.missing_target(), None);

Ok(())
}

#[test]
fn broken_link_missing_target_cycles() -> Result<()> {
let temp_dir = tempdir()?;
let link = BrokenLink {
path: temp_dir.path().join("python"),
unix: true,
venv: true,
};
fs::os::unix::fs::symlink("intermediate", &link.path)?;
fs::os::unix::fs::symlink("python", temp_dir.path().join("intermediate"))?;

assert_eq!(link.missing_target(), None);

Ok(())
}

#[test]
fn broken_link_missing_target_depth_limit() -> Result<()> {
let temp_dir = tempdir()?;
let link = BrokenLink {
path: temp_dir.path().join("0"),
unix: true,
venv: true,
};
for index in 0..40 {
fs::os::unix::fs::symlink(
(index + 1).to_string(),
temp_dir.path().join(index.to_string()),
)?;
}

assert_eq!(link.missing_target(), Some(temp_dir.path().join("40")));

fs::os::unix::fs::symlink("41", temp_dir.path().join("40"))?;
assert_eq!(link.missing_target(), None);

Ok(())
}

fn mocked_interpreter_response() -> &'static str {
indoc! {r##"
Expand Down
15 changes: 5 additions & 10 deletions crates/uv-tool/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use uv_install_wheel::read_record;
use uv_installer::SitePackages;
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_python_interpreter::{BrokenLink, Interpreter, PythonEnvironment};
use uv_python_interpreter::{Interpreter, PythonEnvironment};
use uv_state::{StateBucket, StateStore};
use uv_static::EnvVars;
use uv_virtualenv::UpgradePolicy;
Expand Down Expand Up @@ -295,23 +295,18 @@ impl InstalledTools {
Ok(None)
}
Err(uv_python_interpreter::PythonEnvironmentError::Query(
uv_python_interpreter::InterpreterError::BrokenLink(BrokenLink {
path,
unix,
venv: _,
}),
uv_python_interpreter::InterpreterError::BrokenLink(broken_link),
)) => {
if unix {
let target_path = fs_err::read_link(&path)?;
if let Some(target_path) = broken_link.missing_target() {
warn!(
"Ignoring existing virtual environment linked to non-existent Python interpreter: `{}` -> `{}`",
path.user_display().cyan(),
broken_link.path.user_display().cyan(),
target_path.user_display().cyan(),
);
} else {
warn!(
"Ignoring existing virtual environment linked to non-existent Python interpreter: {}",
path.user_display().cyan(),
broken_link.path.user_display().cyan(),
);
}

Expand Down
40 changes: 40 additions & 0 deletions crates/uv/tests/sync/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11198,6 +11198,46 @@ fn build_system_requires_path() -> Result<()> {
Ok(())
}

#[test]
#[cfg(unix)]
fn sync_broken_interpreter_symlink_chain() -> Result<()> {
let context = uv_test::test_context!("3.12")
.with_filtered_virtualenv_bin()
.with_filtered_python_names();

context
.temp_dir
.child("pyproject.toml")
.write_str(indoc! {r#"
[project]
name = "project"
version = "0.1.0"
requires-python = ">=3.12"
"#})?;

// Follow relative and absolute links, including a relative target outside the environment.
let bin = venv_bin_path(context.temp_dir.join(".venv"));
let links = context.temp_dir.child("links");
links.create_dir_all()?;
fs_err::remove_file(bin.join("python"))?;
fs_err::os::unix::fs::symlink("../../links/intermediate", bin.join("python"))?;
fs_err::os::unix::fs::symlink(links.join("other"), links.join("intermediate"))?;
fs_err::os::unix::fs::symlink("missing-python", links.join("other"))?;

uv_snapshot!(context.filters(), context.sync(), @"
exit_code: 0 (success)
----- stderr -----
warning: Ignoring existing virtual environment linked to non-existent Python interpreter: `.venv/[BIN]/[PYTHON]` -> `links/missing-python`
Using CPython 3.12.[X] interpreter at: [PYTHON-3.12]
Removed virtual environment at: .venv
Creating virtual environment at: .venv
Resolved 1 package in [TIME]
Checked in [TIME]
");

Ok(())
}

#[test]
fn sync_invalid_environment() -> Result<()> {
let context = uv_test::test_context_with_versions!(&["3.11", "3.12"])
Expand Down
Loading