Repository: astral-sh/uv
File: crates/uv/src/commands/project/format.rs (Rust)

Code before:
/// Run the formatter.
pub(crate) async fn format(
    project_dir: &Path,
    check: bool,
    diff: bool,
    extra_args: Vec<String>,
    version: Option<String>,
    network_settings: NetworkSettings,
    cache: Cache,
    printer: Printer,
    preview: Preview,
) -> Result<ExitStatus> {
    // Check if the format feature is in preview
    if !preview.is_enabled(PreviewFeatures::FORMAT) {
        warn_user!(
            "`uv format` is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.",
            PreviewFeatures::FORMAT
        );
    }

    let workspace_cache = WorkspaceCache::default();
    let project =
        VirtualProject::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache).await;
    let working_dir = match project {
        // If we found a project, we use the project root
        Ok(proj) => proj.root().to_owned(),
        // If there is a problem finding a project, we just use the provided directory
        // e.g. unmanaged projects
        Err(WorkspaceError::MissingPyprojectToml)
        | Err(WorkspaceError::MissingProject(_))
        | Err(WorkspaceError::NonWorkspace(_)) => project_dir.to_owned(),
        Err(err) => return Err(err.into()),
    };

    // Parse version if provided
    let version = version.as_deref().map(Version::from_str).transpose()?;

    let client = BaseClientBuilder::new()
        .retries_from_env()?
        .connectivity(network_settings.connectivity)
        .native_tls(network_settings.native_tls)
        .allow_insecure_host(network_settings.allow_insecure_host.clone())
        .build();

    // Get the path to Ruff, downloading it if necessary
    let reporter = BinaryDownloadReporter::single(printer);
    let default_version = Binary::Ruff.default_version();
    let version = version.as_ref().unwrap_or(&default_version);
    let ruff_path = bin_install(Binary::Ruff, version, &client, &cache, &reporter)
        .await
        .with_context(|| format!("Failed to install ruff {version}"))?;

Review comment (bug):
had to `.to_owned()`... If I instead do `match &project`, then the `Err(err) => return Err(err.into()),` would fail as there is no `From <&WorkspaceError> for anyhow::Error` (there exist such implementation for owned `WorkspaceError` ,but not for borrowed). Therefore we need the owned version (`match project`) and just return `proj.root()` would also have lifetime issues due to the move semantics of `match project`

Code after:
/// Run the formatter.
pub(crate) async fn format(
    project_dir: &Path,
    check: bool,
    diff: bool,
    extra_args: Vec<String>,
    version: Option<String>,
    network_settings: NetworkSettings,
    cache: Cache,
    printer: Printer,
    preview: Preview,
) -> Result<ExitStatus> {
    // Check if the format feature is in preview
    if !preview.is_enabled(PreviewFeatures::FORMAT) {
        warn_user!(
            "`uv format` is experimental and may change without warning. Pass `--preview-features {}` to disable this warning.",
            PreviewFeatures::FORMAT
        );
    }

    let workspace_cache = WorkspaceCache::default();
    let target_dir =
        match VirtualProject::discover(project_dir, &DiscoveryOptions::default(), &workspace_cache)
            .await
        {
            // If we found a project, we use the project root
            Ok(proj) => proj.root().to_owned(),
            // If there is a problem finding a project, we just use the provided directory,
            // e.g., for unmanaged projects
            Err(
                WorkspaceError::MissingPyprojectToml
                | WorkspaceError::MissingProject(_)
                | WorkspaceError::NonWorkspace(_),
            ) => project_dir.to_owned(),
            Err(err) => return Err(err.into()),
        };

    // Parse version if provided
    let version = version.as_deref().map(Version::from_str).transpose()?;

    let client = BaseClientBuilder::new()
        .retries_from_env()?
        .connectivity(network_settings.connectivity)
        .native_tls(network_settings.native_tls)
        .allow_insecure_host(network_settings.allow_insecure_host.clone())
        .build();

    // Get the path to Ruff, downloading it if necessary
    let reporter = BinaryDownloadReporter::single(printer);
    let default_version = Binary::Ruff.default_version();
    let version = version.as_ref().unwrap_or(&default_version);