diff --git a/crates/uv-settings/src/lib.rs b/crates/uv-settings/src/lib.rs index 84da74133e2..f66abcc3b7f 100644 --- a/crates/uv-settings/src/lib.rs +++ b/crates/uv-settings/src/lib.rs @@ -714,6 +714,8 @@ impl EnvFlag { /// the CLI level, however there are limited semantics in that context. #[derive(Debug, Clone)] pub struct EnvironmentOptions { + pub ruff_path: Option, + pub ty_path: Option, pub skip_wheel_filename_check: Option, pub hide_build_output: Option, pub python_install_bin: Option, @@ -788,6 +790,8 @@ impl EnvironmentOptions { .map(Duration::from_secs); Ok(Self { + ruff_path: parse_path_environment_variable(EnvVars::RUFF), + ty_path: parse_path_environment_variable(EnvVars::TY), skip_wheel_filename_check: parse_boolish_environment_variable( EnvVars::UV_SKIP_WHEEL_FILENAME_CHECK, )?, @@ -1037,7 +1041,6 @@ where } } -#[cfg(feature = "tracing-durations-export")] /// Parse a path environment variable. fn parse_path_environment_variable(name: &'static str) -> Option { let value = std::env::var_os(name)?; diff --git a/crates/uv-static/src/env_vars.rs b/crates/uv-static/src/env_vars.rs index bf0a03e85b9..18bff1bda72 100644 --- a/crates/uv-static/src/env_vars.rs +++ b/crates/uv-static/src/env_vars.rs @@ -19,6 +19,14 @@ impl EnvVars { #[attr_added_in("0.6.0")] pub const UV: &'static str = "UV"; + /// The path to the Ruff binary used by `uv format`. + #[attr_added_in("next release")] + pub const RUFF: &'static str = "RUFF"; + + /// The path to the ty binary used by `uv check`. + #[attr_added_in("next release")] + pub const TY: &'static str = "TY"; + /// Equivalent to the `--offline` command-line argument. If set, uv will disable network access. #[attr_added_in("0.5.9")] pub const UV_OFFLINE: &'static str = "UV_OFFLINE"; diff --git a/crates/uv/src/commands/project/check.rs b/crates/uv/src/commands/project/check.rs index 7bc65fdf443..974ad3c1936 100644 --- a/crates/uv/src/commands/project/check.rs +++ b/crates/uv/src/commands/project/check.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; use anyhow::Result; use tracing::debug; @@ -38,6 +38,7 @@ mod ty; #[expect(clippy::fn_params_excessive_bools)] pub(crate) async fn check( project_dir: &Path, + ty_path: Option, lock_check: LockCheck, frozen: Option, no_sync: bool, @@ -381,6 +382,7 @@ pub(crate) async fn check( ty::run( ty_version, + ty_path, &target_dir, venv_path.as_deref(), workspace_metadata, diff --git a/crates/uv/src/commands/project/check/ty.rs b/crates/uv/src/commands/project/check/ty.rs index a8db9ed79b3..c087682c883 100644 --- a/crates/uv/src/commands/project/check/ty.rs +++ b/crates/uv/src/commands/project/check/ty.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::Stdio; use std::str::FromStr; use std::time::Duration; @@ -37,6 +37,7 @@ async fn write_workspace_metadata(mut stdin: ChildStdin, workspace_metadata: Str /// Run a type check powered by ty. pub(super) async fn run( version: Option, + ty_path: Option, target_dir: &Path, venv_path: Option<&Path>, workspace_metadata: Option, @@ -45,74 +46,94 @@ pub(super) async fn run( cache: &Cache, printer: Printer, ) -> Result { - let retry_policy = client_builder.retry_policy(); - let ty_client = client_builder.clone().retries(0).build()?; + let ty_path = if let Some(ty_path) = ty_path { + if tracing::enabled!(tracing::Level::DEBUG) { + let output = Command::new(&ty_path) + .arg("--version") + .output() + .await + .context("Failed to query ty version")?; + if !output.status.success() { + anyhow::bail!("Failed to query ty version"); + } + debug!("Using `{}`", String::from_utf8_lossy(&output.stdout).trim()); + } + ty_path + } else { + let retry_policy = client_builder.retry_policy(); + let ty_client = client_builder.clone().retries(0).build()?; - let reporter = BinaryDownloadReporter::single(printer); - let bin_version = version - .as_deref() - .map(BinVersion::from_str) - .transpose()? - .unwrap_or(BinVersion::Default); + let reporter = BinaryDownloadReporter::single(printer); + let bin_version = version + .as_deref() + .map(BinVersion::from_str) + .transpose()? + .unwrap_or(BinVersion::Default); - let resolved = match bin_version { - BinVersion::Default => { - let constraints = Binary::Ty.default_constraints(); - let resolved = find_matching_version( - Binary::Ty, - Some(&constraints), - exclude_newer, - &ty_client, - &retry_policy, - ) - .await - .with_context(|| { - format!("Failed to find ty version matching default constraints: {constraints}") - })?; - debug!("Resolved `ty@{constraints}` to `ty=={}`", resolved.version); - resolved - } - BinVersion::Pinned(version) => { - if exclude_newer.is_some() { - debug!("`--exclude-newer` is ignored for pinned version `{version}`"); + let resolved = match bin_version { + BinVersion::Default => { + let constraints = Binary::Ty.default_constraints(); + let resolved = find_matching_version( + Binary::Ty, + Some(&constraints), + exclude_newer, + &ty_client, + &retry_policy, + ) + .await + .with_context(|| { + format!("Failed to find ty version matching default constraints: {constraints}") + })?; + debug!("Resolved `ty@{constraints}` to `ty=={}`", resolved.version); + resolved } - let resolved = ResolvedVersion::from_version(Binary::Ty, version)?; - debug!("Using `ty=={}`", resolved.version); - resolved - } - BinVersion::Latest => { - let resolved = - find_matching_version(Binary::Ty, None, exclude_newer, &ty_client, &retry_policy) - .await - .with_context(|| "Failed to find latest ty version")?; - debug!("Resolved `ty@latest` to `ty=={}`", resolved.version); - resolved - } - BinVersion::Constraint(constraints) => { - let resolved = find_matching_version( - Binary::Ty, - Some(&constraints), - exclude_newer, - &ty_client, - &retry_policy, - ) - .await - .with_context(|| format!("Failed to find ty version matching: {constraints}"))?; - debug!("Resolved `ty@{constraints}` to `ty=={}`", resolved.version); - resolved - } - }; + BinVersion::Pinned(version) => { + if exclude_newer.is_some() { + debug!("`--exclude-newer` is ignored for pinned version `{version}`"); + } + let resolved = ResolvedVersion::from_version(Binary::Ty, version)?; + debug!("Using `ty=={}`", resolved.version); + resolved + } + BinVersion::Latest => { + let resolved = find_matching_version( + Binary::Ty, + None, + exclude_newer, + &ty_client, + &retry_policy, + ) + .await + .with_context(|| "Failed to find latest ty version")?; + debug!("Resolved `ty@latest` to `ty=={}`", resolved.version); + resolved + } + BinVersion::Constraint(constraints) => { + let resolved = find_matching_version( + Binary::Ty, + Some(&constraints), + exclude_newer, + &ty_client, + &retry_policy, + ) + .await + .with_context(|| format!("Failed to find ty version matching: {constraints}"))?; + debug!("Resolved `ty@{constraints}` to `ty=={}`", resolved.version); + resolved + } + }; - let ty_path = bin_install( - Binary::Ty, - &resolved, - &ty_client, - &retry_policy, - cache, - &reporter, - ) - .await - .with_context(|| format!("Failed to install ty {}", resolved.version))?; + bin_install( + Binary::Ty, + &resolved, + &ty_client, + &retry_policy, + cache, + &reporter, + ) + .await + .with_context(|| format!("Failed to install ty {}", resolved.version))? + }; let mut command = Command::new(&ty_path); command.current_dir(target_dir); diff --git a/crates/uv/src/commands/project/format.rs b/crates/uv/src/commands/project/format.rs index 65a3fc10e98..a7e67e0271d 100644 --- a/crates/uv/src/commands/project/format.rs +++ b/crates/uv/src/commands/project/format.rs @@ -1,5 +1,5 @@ use std::fmt::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::str::FromStr; use anyhow::{Context, Result}; @@ -22,6 +22,7 @@ use crate::printer::Printer; #[expect(clippy::fn_params_excessive_bools)] pub(crate) async fn format( project_dir: &Path, + ruff_path: Option, check: bool, diff: bool, extra_args: Vec, @@ -74,89 +75,115 @@ pub(crate) async fn format( } }; - let retry_policy = client_builder.retry_policy(); - // Python downloads are performing their own retries to catch stream errors, disable the - // default retries to avoid the middleware from performing uncontrolled retries. - let client = client_builder.retries(0).build()?; - // Determine the version to use and get the path to Ruff. - let reporter = BinaryDownloadReporter::single(printer); - let bin_version = version - .as_deref() - .map(BinVersion::from_str) - .transpose()? - .unwrap_or(BinVersion::Default); - - let resolved = match bin_version { - BinVersion::Default => { - // Find the best version matching the default constraints - let constraints = Binary::Ruff.default_constraints(); - let resolved = find_matching_version( - Binary::Ruff, - Some(&constraints), - exclude_newer, - &client, - &retry_policy, - ) - .await - .with_context(|| { - format!("Failed to find ruff version matching default constraints: {constraints}") - })?; - debug!( - "Resolved `ruff@{constraints}` to `ruff=={}`", - resolved.version - ); - resolved - } - BinVersion::Pinned(version) => { - // Use the exact version directly without manifest lookup. - if exclude_newer.is_some() { - debug!("`--exclude-newer` is ignored for pinned version `{version}`"); + let ruff_path = if let Some(ruff_path) = ruff_path { + if show_version { + let output = Command::new(&ruff_path) + .arg("--version") + .output() + .await + .context("Failed to query Ruff version")?; + if !output.status.success() { + anyhow::bail!("Failed to query Ruff version"); } - ResolvedVersion::from_version(Binary::Ruff, version)? - } - BinVersion::Latest => { - // Fetch the latest version from the manifest - let resolved = - find_matching_version(Binary::Ruff, None, exclude_newer, &client, &retry_policy) - .await - .with_context(|| "Failed to find latest ruff version")?; - debug!("Resolved `ruff@latest` to `ruff=={}`", resolved.version); - resolved - } - BinVersion::Constraint(constraints) => { - // Find the best version matching the constraints - let resolved = find_matching_version( - Binary::Ruff, - Some(&constraints), - exclude_newer, - &client, - &retry_policy, - ) - .await - .with_context(|| format!("Failed to find ruff version matching: {constraints}"))?; - debug!( - "Resolved `ruff@{constraints}` to `ruff=={}`", - resolved.version - ); - resolved + write!( + printer.stderr(), + "{}", + String::from_utf8_lossy(&output.stdout) + )?; } - }; + ruff_path + } else { + let retry_policy = client_builder.retry_policy(); + // Python downloads are performing their own retries to catch stream errors, disable the + // default retries to avoid the middleware from performing uncontrolled retries. + let client = client_builder.retries(0).build()?; - if show_version { - writeln!(printer.stderr(), "ruff {}", resolved.version)?; - } + let reporter = BinaryDownloadReporter::single(printer); + let bin_version = version + .as_deref() + .map(BinVersion::from_str) + .transpose()? + .unwrap_or(BinVersion::Default); - let ruff_path = bin_install( - Binary::Ruff, - &resolved, - &client, - &retry_policy, - &cache, - &reporter, - ) - .await - .with_context(|| format!("Failed to install ruff {}", resolved.version))?; + let resolved = match bin_version { + BinVersion::Default => { + // Find the best version matching the default constraints + let constraints = Binary::Ruff.default_constraints(); + let resolved = find_matching_version( + Binary::Ruff, + Some(&constraints), + exclude_newer, + &client, + &retry_policy, + ) + .await + .with_context(|| { + format!( + "Failed to find ruff version matching default constraints: {constraints}" + ) + })?; + debug!( + "Resolved `ruff@{constraints}` to `ruff=={}`", + resolved.version + ); + resolved + } + BinVersion::Pinned(version) => { + // Use the exact version directly without manifest lookup. + if exclude_newer.is_some() { + debug!("`--exclude-newer` is ignored for pinned version `{version}`"); + } + ResolvedVersion::from_version(Binary::Ruff, version)? + } + BinVersion::Latest => { + // Fetch the latest version from the manifest + let resolved = find_matching_version( + Binary::Ruff, + None, + exclude_newer, + &client, + &retry_policy, + ) + .await + .with_context(|| "Failed to find latest ruff version")?; + debug!("Resolved `ruff@latest` to `ruff=={}`", resolved.version); + resolved + } + BinVersion::Constraint(constraints) => { + // Find the best version matching the constraints + let resolved = find_matching_version( + Binary::Ruff, + Some(&constraints), + exclude_newer, + &client, + &retry_policy, + ) + .await + .with_context(|| format!("Failed to find ruff version matching: {constraints}"))?; + debug!( + "Resolved `ruff@{constraints}` to `ruff=={}`", + resolved.version + ); + resolved + } + }; + + if show_version { + writeln!(printer.stderr(), "ruff {}", resolved.version)?; + } + + bin_install( + Binary::Ruff, + &resolved, + &client, + &retry_policy, + &cache, + &reporter, + ) + .await + .with_context(|| format!("Failed to install ruff {}", resolved.version))? + }; let mut command = Command::new(&ruff_path); command.current_dir(target_dir); diff --git a/crates/uv/src/lib.rs b/crates/uv/src/lib.rs index aecccacf82f..9e98111c2b9 100644 --- a/crates/uv/src/lib.rs +++ b/crates/uv/src/lib.rs @@ -2736,7 +2736,7 @@ async fn run_project( } ProjectCommand::Format(args) => { // Resolve the settings from the command-line arguments and workspace configuration. - let args = settings::FormatSettings::resolve(args, filesystem); + let args = settings::FormatSettings::resolve(args, filesystem, environment); show_settings!(args); // Initialize the cache. @@ -2744,6 +2744,7 @@ async fn run_project( Box::pin(commands::format( project_dir, + args.ruff_path, args.check, args.diff, args.extra_args, @@ -2777,6 +2778,7 @@ async fn run_project( Box::pin(commands::check( project_dir, + args.ty_path, args.lock_check, args.frozen, args.no_sync, diff --git a/crates/uv/src/settings.rs b/crates/uv/src/settings.rs index f1aea550072..574b18c9ef5 100644 --- a/crates/uv/src/settings.rs +++ b/crates/uv/src/settings.rs @@ -2916,6 +2916,7 @@ impl ExportSettings { /// The resolved settings to use for a `format` invocation. #[derive(Debug, Clone)] pub(crate) struct FormatSettings { + pub(crate) ruff_path: Option, pub(crate) check: bool, pub(crate) diff: bool, pub(crate) extra_args: Vec, @@ -2927,7 +2928,11 @@ pub(crate) struct FormatSettings { impl FormatSettings { /// Resolve the [`FormatSettings`] from the CLI and filesystem configuration. - pub(crate) fn resolve(args: FormatArgs, _filesystem: Option) -> Self { + pub(crate) fn resolve( + args: FormatArgs, + _filesystem: Option, + environment: EnvironmentOptions, + ) -> Self { let FormatArgs { check, diff, @@ -2939,6 +2944,7 @@ impl FormatSettings { } = args; Self { + ruff_path: environment.ruff_path, check, diff, extra_args, @@ -2953,6 +2959,7 @@ impl FormatSettings { /// The resolved settings to use for a `check` invocation. #[derive(Debug, Clone)] pub(crate) struct CheckSettings { + pub(crate) ty_path: Option, pub(crate) extras: ExtrasSpecification, pub(crate) groups: DependencyGroups, pub(crate) lock_check: LockCheck, @@ -3027,6 +3034,7 @@ impl CheckSettings { let malware_settings = MalwareCheckSettings::from(&environment); Self { + ty_path: environment.ty_path, extras: ExtrasSpecification::from_args( extra.unwrap_or_default(), no_extra, diff --git a/crates/uv/tests/project/check.rs b/crates/uv/tests/project/check.rs index 54761df9273..af65418918b 100644 --- a/crates/uv/tests/project/check.rs +++ b/crates/uv/tests/project/check.rs @@ -1,4 +1,5 @@ use anyhow::Result; +#[cfg(feature = "test-pypi")] use assert_cmd::assert::OutputAssertExt; use assert_fs::prelude::*; use indoc::indoc; @@ -37,6 +38,51 @@ fn check_project() -> Result<()> { Ok(()) } +#[test] +#[cfg(feature = "test-pypi")] +fn check_uses_ty_from_environment() -> Result<()> { + let context = + uv_test::test_context!("3.12").with_filter((r"ty 0\.0\.17(?: \([^)]*\))?", "ty 0.0.17")); + let tool_dir = context.root.child("tools"); + let bin_dir = context.root.child("tool-bin"); + + context + .tool_install() + .arg("ty==0.0.17") + .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) + .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) + .env(EnvVars::UV_EXCLUDE_NEWER, "2026-02-15T00:00:00Z") + .assert() + .success(); + + let ty = bin_dir.child(format!("ty{}", std::env::consts::EXE_SUFFIX)); + context.temp_dir.child("main.py").write_str("x = 1")?; + + uv_snapshot!( + context.filters(), + context + .check() + .arg("--no-project") + .arg("--ty-version") + .arg(">=999.0.0") + .arg("--verbose") + .env(EnvVars::RUST_LOG, "uv::commands::project::check::ty=debug") + .env(EnvVars::TY, ty.as_os_str()), + @" + success: true + exit_code: 0 + ----- stdout ----- + All checks passed! + + ----- stderr ----- + warning: `uv check` is experimental and may change without warning. Pass `--preview-features check-command` to disable this warning. + DEBUG Using `ty 0.0.17` + " + ); + + Ok(()) +} + #[test] fn check_passes_workspace_metadata_to_ty() -> Result<()> { let context = uv_test::test_context!("3.12"); diff --git a/crates/uv/tests/project/format.rs b/crates/uv/tests/project/format.rs index 15d5d5771f4..520df553587 100644 --- a/crates/uv/tests/project/format.rs +++ b/crates/uv/tests/project/format.rs @@ -1,8 +1,12 @@ use anyhow::Result; +#[cfg(feature = "test-pypi")] +use assert_cmd::assert::OutputAssertExt; use assert_fs::prelude::*; use indoc::indoc; use insta::assert_snapshot; +#[cfg(feature = "test-pypi")] +use uv_static::EnvVars; use uv_test::uv_snapshot; #[test] @@ -41,6 +45,50 @@ fn format_project() -> Result<()> { Ok(()) } +#[test] +#[cfg(feature = "test-pypi")] +fn format_uses_ruff_from_environment() -> Result<()> { + let context = uv_test::test_context!("3.12"); + let tool_dir = context.root.child("tools"); + let bin_dir = context.root.child("tool-bin"); + + context + .tool_install() + .arg("ruff==0.3.4") + .env(EnvVars::UV_TOOL_DIR, tool_dir.as_os_str()) + .env(EnvVars::XDG_BIN_HOME, bin_dir.as_os_str()) + .assert() + .success(); + + let main_py = context.temp_dir.child("main.py"); + main_py.write_str("x = 1")?; + let ruff = bin_dir.child(format!("ruff{}", std::env::consts::EXE_SUFFIX)); + + uv_snapshot!( + context.filters(), + context + .format() + .arg("--version") + .arg(">=999.0.0") + .arg("--show-version") + .env(EnvVars::RUFF, ruff.as_os_str()), + @" + success: true + exit_code: 0 + ----- stdout ----- + 1 file reformatted + + ----- stderr ----- + warning: `uv format` is experimental and may change without warning. Pass `--preview-features format-command` to disable this warning. + ruff 0.3.4 + " + ); + + assert_snapshot!(fs_err::read_to_string(&main_py)?, @"x = 1"); + + Ok(()) +} + #[test] fn format_missing_pyproject_toml() -> Result<()> { let context = uv_test::test_context_with_versions!(&[]);