From a0f987235b5458883c6ee6c1b78167f2fd3a7e7d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 22 Feb 2026 09:50:15 +0000 Subject: [PATCH 1/6] Initial plan From daeef1eae79cd48f92cd08ae9371130b219eebe4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 22 Feb 2026 09:58:37 +0000 Subject: [PATCH 2/6] Fix rust cli git dependency install for multi-bin repos Co-authored-by: j178 <10510431+j178@users.noreply.github.com> --- crates/prek/src/languages/rust/rust.rs | 40 ++++++++++++++++++++------ 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/prek/src/languages/rust/rust.rs b/crates/prek/src/languages/rust/rust.rs index 345e0c5d6..c62354aa1 100644 --- a/crates/prek/src/languages/rust/rust.rs +++ b/crates/prek/src/languages/rust/rust.rs @@ -32,7 +32,7 @@ fn format_cargo_dependency(dep: &str) -> String { } } -fn format_cargo_cli_dependency(dep: &str) -> Vec<&str> { +fn format_cargo_cli_dependency<'a>(dep: &'a str, git_bin: Option<&'a str>) -> Vec<&'a str> { let is_url = dep.starts_with("http://") || dep.starts_with("https://"); let (package, version) = if is_url && dep.matches(':').count() == 1 { (dep, "") // We have a url without version @@ -46,6 +46,9 @@ fn format_cargo_cli_dependency(dep: &str) -> Vec<&str> { if !version.is_empty() { args.extend(["--tag", version]); } + if let Some(bin) = git_bin { + args.extend(["--bin", bin]); + } } else { args.push(package); if !version.is_empty() { @@ -393,11 +396,16 @@ impl LanguageImpl for Rust { } // Install CLI dependencies + let hook_entry = hook.entry.split()?; + let hook_bin = hook_entry + .first() + .map(String::as_str) + .context("Rust hook entry must contain executable name")?; for cli_dep in cli_deps { let mut cmd = Cmd::new(&cargo, "install cli dep"); cmd.args(["install", "--bins", "--root"]) .arg(&info.env_path) - .args(format_cargo_cli_dependency(cli_dep)) + .args(format_cargo_cli_dependency(cli_dep, Some(hook_bin))) .arg("--locked"); cmd.env(EnvVars::PATH, &new_path) .env(EnvVars::CARGO_HOME, &cargo_home) @@ -787,22 +795,38 @@ edition = "2021" #[test] fn test_format_cargo_cli_dependency() { - assert_eq!(format_cargo_cli_dependency("typos-cli"), ["typos-cli"]); assert_eq!( - format_cargo_cli_dependency("typos-cli:1.0"), + format_cargo_cli_dependency("typos-cli", Some("typos-cli")), + ["typos-cli"] + ); + assert_eq!( + format_cargo_cli_dependency("typos-cli:1.0", Some("typos-cli")), ["typos-cli", "--version", "1.0"] ); assert_eq!( - format_cargo_cli_dependency("https://github.com/fish-shell/fish-shell"), - ["--git", "https://github.com/fish-shell/fish-shell"] + format_cargo_cli_dependency( + "https://github.com/fish-shell/fish-shell", + Some("fish_indent") + ), + [ + "--git", + "https://github.com/fish-shell/fish-shell", + "--bin", + "fish_indent" + ] ); assert_eq!( - format_cargo_cli_dependency("https://github.com/fish-shell/fish-shell:4.0"), + format_cargo_cli_dependency( + "https://github.com/fish-shell/fish-shell:4.0", + Some("fish_indent") + ), [ "--git", "https://github.com/fish-shell/fish-shell", "--tag", - "4.0" + "4.0", + "--bin", + "fish_indent" ] ); } From c77127fe6334d11a57901dff751bebe61ebb2f95 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 27 Feb 2026 15:11:28 +0000 Subject: [PATCH 3/6] Use package name for rust git cli dependencies Co-authored-by: j178 <10510431+j178@users.noreply.github.com> --- crates/prek/src/languages/rust/rust.rs | 75 +++++++++++++++++++------- 1 file changed, 57 insertions(+), 18 deletions(-) diff --git a/crates/prek/src/languages/rust/rust.rs b/crates/prek/src/languages/rust/rust.rs index c62354aa1..e6caa19c0 100644 --- a/crates/prek/src/languages/rust/rust.rs +++ b/crates/prek/src/languages/rust/rust.rs @@ -12,6 +12,7 @@ use prek_consts::prepend_paths; use tracing::debug; use crate::cli::reporter::{HookInstallReporter, HookRunReporter}; +use crate::git::clone_repo; use crate::hook::{Hook, InstallInfo, InstalledHook}; use crate::languages::LanguageImpl; use crate::languages::rust::RustRequest; @@ -32,7 +33,7 @@ fn format_cargo_dependency(dep: &str) -> String { } } -fn format_cargo_cli_dependency<'a>(dep: &'a str, git_bin: Option<&'a str>) -> Vec<&'a str> { +fn format_cargo_cli_dependency(dep: &str, git_package: Option<&str>) -> Vec { let is_url = dep.starts_with("http://") || dep.starts_with("https://"); let (package, version) = if is_url && dep.matches(':').count() == 1 { (dep, "") // We have a url without version @@ -42,22 +43,61 @@ fn format_cargo_cli_dependency<'a>(dep: &'a str, git_bin: Option<&'a str>) -> Ve let mut args = Vec::new(); if is_url { - args.extend(["--git", package]); + args.push("--git".to_string()); + args.push(package.to_string()); if !version.is_empty() { - args.extend(["--tag", version]); + args.push("--tag".to_string()); + args.push(version.to_string()); } - if let Some(bin) = git_bin { - args.extend(["--bin", bin]); + if let Some(package) = git_package { + args.push(package.to_string()); } } else { - args.push(package); + args.push(package.to_string()); if !version.is_empty() { - args.extend(["--version", version]); + args.push("--version".to_string()); + args.push(version.to_string()); } } args } +async fn find_git_package_name( + dep: &str, + binary_name: &str, + cargo: &Path, + cargo_home: &Path, + new_path: &OsStr, +) -> anyhow::Result> { + let is_url = dep.starts_with("http://") || dep.starts_with("https://"); + if !is_url { + return Ok(None); + } + + let (repo, rev) = if dep.matches(':').count() == 1 { + (dep, "HEAD") + } else { + dep.rsplit_once(':').unwrap_or((dep, "HEAD")) + }; + + let temp = tempfile::tempdir()?; + clone_repo(repo, rev, temp.path()) + .await + .with_context(|| format!("Failed to clone `{repo}` at `{rev}`"))?; + + let (_, package_name, _) = find_package_dir( + temp.path(), + binary_name, + Some(cargo), + Some(cargo_home), + Some(new_path), + ) + .await? + .with_context(|| format!("Binary `{binary_name}` not found in `{repo}`"))?; + + Ok(Some(package_name)) +} + /// Find the package directory that produces the given binary. /// Returns (`package_dir`, `package_name`, `is_workspace`). async fn find_package_dir( @@ -402,10 +442,15 @@ impl LanguageImpl for Rust { .map(String::as_str) .context("Rust hook entry must contain executable name")?; for cli_dep in cli_deps { + let package_name = + find_git_package_name(cli_dep, hook_bin, &cargo, &cargo_home, &new_path).await?; let mut cmd = Cmd::new(&cargo, "install cli dep"); cmd.args(["install", "--bins", "--root"]) .arg(&info.env_path) - .args(format_cargo_cli_dependency(cli_dep, Some(hook_bin))) + .args(format_cargo_cli_dependency( + cli_dep, + package_name.as_deref(), + )) .arg("--locked"); cmd.env(EnvVars::PATH, &new_path) .env(EnvVars::CARGO_HOME, &cargo_home) @@ -806,27 +851,21 @@ edition = "2021" assert_eq!( format_cargo_cli_dependency( "https://github.com/fish-shell/fish-shell", - Some("fish_indent") + Some("fish") ), - [ - "--git", - "https://github.com/fish-shell/fish-shell", - "--bin", - "fish_indent" - ] + ["--git", "https://github.com/fish-shell/fish-shell", "fish"] ); assert_eq!( format_cargo_cli_dependency( "https://github.com/fish-shell/fish-shell:4.0", - Some("fish_indent") + Some("fish") ), [ "--git", "https://github.com/fish-shell/fish-shell", "--tag", "4.0", - "--bin", - "fish_indent" + "fish" ] ); } From 78aaaae52e799b56707d78f63e49367eccb32acd Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 27 Feb 2026 15:17:28 +0000 Subject: [PATCH 4/6] Resolve rust git cli deps using package lookup Co-authored-by: j178 <10510431+j178@users.noreply.github.com> --- crates/prek/src/languages/rust/rust.rs | 67 +++++++++++++++++++------- 1 file changed, 49 insertions(+), 18 deletions(-) diff --git a/crates/prek/src/languages/rust/rust.rs b/crates/prek/src/languages/rust/rust.rs index e6caa19c0..107d8a497 100644 --- a/crates/prek/src/languages/rust/rust.rs +++ b/crates/prek/src/languages/rust/rust.rs @@ -33,19 +33,24 @@ fn format_cargo_dependency(dep: &str) -> String { } } -fn format_cargo_cli_dependency(dep: &str, git_package: Option<&str>) -> Vec { +fn parse_cargo_cli_dependency(dep: &str) -> (&str, Option<&str>, bool) { let is_url = dep.starts_with("http://") || dep.starts_with("https://"); let (package, version) = if is_url && dep.matches(':').count() == 1 { - (dep, "") // We have a url without version + (dep, "") } else { dep.rsplit_once(':').unwrap_or((dep, "")) }; + (package, (!version.is_empty()).then_some(version), is_url) +} + +fn format_cargo_cli_dependency(dep: &str, git_package: Option<&str>) -> Vec { + let (package, version, is_url) = parse_cargo_cli_dependency(dep); let mut args = Vec::new(); if is_url { args.push("--git".to_string()); args.push(package.to_string()); - if !version.is_empty() { + if let Some(version) = version { args.push("--tag".to_string()); args.push(version.to_string()); } @@ -54,7 +59,7 @@ fn format_cargo_cli_dependency(dep: &str, git_package: Option<&str>) -> Vec anyhow::Result> { - let is_url = dep.starts_with("http://") || dep.starts_with("https://"); + let (repo, rev, is_url) = parse_cargo_cli_dependency(dep); if !is_url { return Ok(None); } - - let (repo, rev) = if dep.matches(':').count() == 1 { - (dep, "HEAD") - } else { - dep.rsplit_once(':').unwrap_or((dep, "HEAD")) - }; + let rev = rev.unwrap_or("HEAD"); let temp = tempfile::tempdir()?; clone_repo(repo, rev, temp.path()) @@ -93,7 +93,7 @@ async fn find_git_package_name( Some(new_path), ) .await? - .with_context(|| format!("Binary `{binary_name}` not found in `{repo}`"))?; + .with_context(|| format!("Failed to locate package for binary `{binary_name}` in `{repo}`"))?; Ok(Some(package_name)) } @@ -838,21 +838,38 @@ edition = "2021" assert_eq!(format_cargo_dependency("tokio:1.0.0"), "tokio@1.0.0"); } + #[test] + fn test_parse_cargo_cli_dependency() { + assert_eq!( + parse_cargo_cli_dependency("https://github.com/fish-shell/fish-shell"), + ("https://github.com/fish-shell/fish-shell", None, true) + ); + assert_eq!( + parse_cargo_cli_dependency("https://github.com/fish-shell/fish-shell:4.0"), + ( + "https://github.com/fish-shell/fish-shell", + Some("4.0"), + true + ) + ); + assert_eq!( + parse_cargo_cli_dependency("typos-cli:1.0"), + ("typos-cli", Some("1.0"), false) + ); + } + #[test] fn test_format_cargo_cli_dependency() { assert_eq!( - format_cargo_cli_dependency("typos-cli", Some("typos-cli")), + format_cargo_cli_dependency("typos-cli", None), ["typos-cli"] ); assert_eq!( - format_cargo_cli_dependency("typos-cli:1.0", Some("typos-cli")), + format_cargo_cli_dependency("typos-cli:1.0", None), ["typos-cli", "--version", "1.0"] ); assert_eq!( - format_cargo_cli_dependency( - "https://github.com/fish-shell/fish-shell", - Some("fish") - ), + format_cargo_cli_dependency("https://github.com/fish-shell/fish-shell", Some("fish")), ["--git", "https://github.com/fish-shell/fish-shell", "fish"] ); assert_eq!( @@ -869,4 +886,18 @@ edition = "2021" ] ); } + + #[tokio::test] + async fn test_find_git_package_name_non_url() { + let result = find_git_package_name( + "typos-cli", + "typos-cli", + Path::new("cargo"), + Path::new(""), + OsStr::new(""), + ) + .await + .unwrap(); + assert!(result.is_none()); + } } From 49ae466d83a9774d72899da3641c38e41363c62c Mon Sep 17 00:00:00 2001 From: Jo <10510431+j178@users.noreply.github.com> Date: Fri, 6 Mar 2026 19:10:03 +0800 Subject: [PATCH 5/6] Reimplement --- crates/prek/src/languages/rust/rust.rs | 335 +++++++++++++++++-------- 1 file changed, 224 insertions(+), 111 deletions(-) diff --git a/crates/prek/src/languages/rust/rust.rs b/crates/prek/src/languages/rust/rust.rs index 107d8a497..b7367f6d2 100644 --- a/crates/prek/src/languages/rust/rust.rs +++ b/crates/prek/src/languages/rust/rust.rs @@ -3,6 +3,7 @@ use std::ffi::OsStr; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::process::Stdio; +use std::str::FromStr; use std::sync::Arc; use anyhow::Context; @@ -12,7 +13,6 @@ use prek_consts::prepend_paths; use tracing::debug; use crate::cli::reporter::{HookInstallReporter, HookRunReporter}; -use crate::git::clone_repo; use crate::hook::{Hook, InstallInfo, InstalledHook}; use crate::languages::LanguageImpl; use crate::languages::rust::RustRequest; @@ -33,69 +33,139 @@ fn format_cargo_dependency(dep: &str) -> String { } } -fn parse_cargo_cli_dependency(dep: &str) -> (&str, Option<&str>, bool) { - let is_url = dep.starts_with("http://") || dep.starts_with("https://"); - let (package, version) = if is_url && dep.matches(':').count() == 1 { - (dep, "") - } else { - dep.rsplit_once(':').unwrap_or((dep, "")) - }; - (package, (!version.is_empty()).then_some(version), is_url) +#[derive(Debug, Eq, PartialEq)] +enum CargoCliDependency { + Crate { + name: String, + version: Option, + }, + Git { + url: String, + tag: Option, + }, } -fn format_cargo_cli_dependency(dep: &str, git_package: Option<&str>) -> Vec { - let (package, version, is_url) = parse_cargo_cli_dependency(dep); +impl FromStr for CargoCliDependency { + type Err = anyhow::Error; - let mut args = Vec::new(); - if is_url { - args.push("--git".to_string()); - args.push(package.to_string()); - if let Some(version) = version { - args.push("--tag".to_string()); - args.push(version.to_string()); - } - if let Some(package) = git_package { - args.push(package.to_string()); - } - } else { - args.push(package.to_string()); - if let Some(version) = version { - args.push("--version".to_string()); - args.push(version.to_string()); + fn from_str(s: &str) -> Result { + let is_url = s.starts_with("http://") || s.starts_with("https://"); + let (package, version) = if is_url && s.matches(':').count() == 1 { + (s, None) + } else { + if let Some((pkg, ver)) = s.rsplit_once(':') { + (pkg, Some(ver)) + } else { + (s, None) + } + }; + + Ok(if is_url { + CargoCliDependency::Git { + url: package.to_string(), + tag: version.map(ToString::to_string), + } + } else { + CargoCliDependency::Crate { + name: package.to_string(), + version: version.map(ToString::to_string), + } + }) + } +} + +impl CargoCliDependency { + fn to_cargo_args(&self, cargo_package: Option<&str>) -> Vec { + let mut args = Vec::new(); + match self { + CargoCliDependency::Crate { name, version } => { + args.push(name.clone()); + if let Some(version) = version { + args.push("--version".to_string()); + args.push(version.clone()); + } + } + CargoCliDependency::Git { + url: repo, + tag: rev, + } => { + args.push("--git".to_string()); + args.push(repo.clone()); + if let Some(rev) = rev { + args.push("--tag".to_string()); + args.push(rev.clone()); + } + if let Some(cargo_package) = cargo_package { + args.push(cargo_package.to_string()); + } + } } + + args } - args } -async fn find_git_package_name( - dep: &str, +fn git_repo_name(url: &str) -> &str { + url.rsplit('/') + .next() + .unwrap_or(url) + .trim_end_matches(".git") +} + +async fn find_package_name_in_git_checkouts( + dep: &CargoCliDependency, binary_name: &str, cargo: &Path, cargo_home: &Path, new_path: &OsStr, ) -> anyhow::Result> { - let (repo, rev, is_url) = parse_cargo_cli_dependency(dep); - if !is_url { + let CargoCliDependency::Git { url, .. } = dep else { + return Ok(None); + }; + + let cache_root = cargo_home.join("git/checkouts"); + if !cache_root.exists() { return Ok(None); } - let rev = rev.unwrap_or("HEAD"); - let temp = tempfile::tempdir()?; - clone_repo(repo, rev, temp.path()) - .await - .with_context(|| format!("Failed to clone `{repo}` at `{rev}`"))?; + let repo_name = git_repo_name(url); + let mut checkout_dirs = fs_err::tokio::read_dir(cache_root).await?; + while let Some(checkout_dir) = checkout_dirs.next_entry().await? { + if !checkout_dir.file_type().await?.is_dir() { + continue; + } - let (_, package_name, _) = find_package_dir( - temp.path(), - binary_name, - Some(cargo), - Some(cargo_home), - Some(new_path), - ) - .await? - .with_context(|| format!("Failed to locate package for binary `{binary_name}` in `{repo}`"))?; + let checkout_dir_name = checkout_dir.file_name(); + let checkout_dir_name = checkout_dir_name.to_string_lossy(); + if !checkout_dir_name.starts_with(repo_name) { + continue; + } - Ok(Some(package_name)) + let mut rev_dirs = fs_err::tokio::read_dir(checkout_dir.path()).await?; + while let Some(rev_dir) = rev_dirs.next_entry().await? { + if !rev_dir.file_type().await?.is_dir() { + continue; + } + + let rev_path = rev_dir.path(); + if let Some((_, package_name, _)) = find_package_dir( + &rev_path, + binary_name, + Some(cargo), + Some(cargo_home), + Some(new_path), + ) + .await? + { + debug!( + "Found package `{package_name}` for binary `{binary_name}` in cargo git cache for `{url}`" + ); + return Ok(Some(package_name)); + } + } + } + + Ok(None) } /// Find the package directory that produces the given binary. @@ -212,7 +282,7 @@ async fn copy_binaries(release_dir: &Path, dest_bin_dir: &Path) -> anyhow::Resul } async fn install_local_project( - hook: &Hook, + hook_binary: &str, repo_path: &Path, info: &InstallInfo, lib_deps: &[&String], @@ -220,14 +290,10 @@ async fn install_local_project( cargo_home: &Path, new_path: &OsStr, ) -> anyhow::Result<()> { - // Get the binary name from the hook entry - let entry_parts = hook.entry.split()?; - let binary_name = &entry_parts[0]; - // Find the specific package directory for this hook's binary let (package_dir, package_name, is_workspace) = match find_package_dir( repo_path, - binary_name, + hook_binary, Some(cargo), Some(cargo_home), Some(new_path), @@ -241,7 +307,7 @@ async fn install_local_project( debug!( "Found package `{}` for binary `{}` in repo `{}` at `{}`", package_name, - binary_name, + hook_binary, repo_path.display(), package_dir.display(), ); @@ -250,7 +316,7 @@ async fn install_local_project( Ok(None) => { debug!( "Binary `{}` not found in cargo metadata for repo `{}`, falling back to repo root", - binary_name, + hook_binary, repo_path.display(), ); (repo_path.to_path_buf(), String::new(), false) @@ -354,6 +420,65 @@ async fn install_local_project( Ok(()) } +async fn install_cli_dependency( + cli_dep: &str, + hook_bin: &str, + info: &InstallInfo, + cargo: &Path, + cargo_home: &Path, + new_path: &OsStr, +) -> anyhow::Result<()> { + let dep = CargoCliDependency::from_str(cli_dep)?; + + let mut cmd = Cmd::new(cargo, "install cli dep"); + cmd.args(["install", "--bins", "--root"]) + .arg(&info.env_path) + .args(dep.to_cargo_args(None)) + .arg("--locked"); + + cmd.env(EnvVars::PATH, new_path) + .env(EnvVars::CARGO_HOME, cargo_home) + .remove_git_envs() + .check(false); + + let output = cmd.output().await?; + if output.status.success() { + return Ok(()); + } + + let stderr = String::from_utf8_lossy(&output.stderr); + if !matches!(&dep, CargoCliDependency::Git { .. }) + || !stderr.contains("multiple packages with binaries found") + { + cmd.check_output(&output)?; + } + + debug!( + "Failed to install CLI dependency `{cli_dep}`. Try resolving package name from cargo git checkouts", + ); + let package_name = + find_package_name_in_git_checkouts(&dep, hook_bin, cargo, cargo_home, new_path).await?; + let package_name = package_name.with_context(|| { + format!( + "Failed to resolve package for binary `{hook_bin}` from cargo git checkouts for `{cli_dep}`" + ) + })?; + + let mut cmd = Cmd::new(cargo, "install cli dep (retry with package)"); + cmd.args(["install", "--bins", "--root"]) + .arg(&info.env_path) + .args(dep.to_cargo_args(Some(&package_name))) + .arg("--locked"); + cmd.env(EnvVars::PATH, new_path) + .env(EnvVars::CARGO_HOME, cargo_home) + .remove_git_envs() + .check(true) + .output() + .await?; + + Ok(()) +} + #[derive(Debug, Copy, Clone)] pub(crate) struct Rust; @@ -421,10 +546,14 @@ impl LanguageImpl for Rust { } }); + // Use the hook entry as the binary name to find the package, this could be improved by allowing an explicit binary name in the hook config. + let hook_entry = hook.entry.split()?; + let hook_bin = &hook_entry[0]; + // Install library dependencies and local project if let Some(repo) = hook.repo_path() { install_local_project( - &hook, + hook_bin, repo, &info, &lib_deps, @@ -436,27 +565,8 @@ impl LanguageImpl for Rust { } // Install CLI dependencies - let hook_entry = hook.entry.split()?; - let hook_bin = hook_entry - .first() - .map(String::as_str) - .context("Rust hook entry must contain executable name")?; for cli_dep in cli_deps { - let package_name = - find_git_package_name(cli_dep, hook_bin, &cargo, &cargo_home, &new_path).await?; - let mut cmd = Cmd::new(&cargo, "install cli dep"); - cmd.args(["install", "--bins", "--root"]) - .arg(&info.env_path) - .args(format_cargo_cli_dependency( - cli_dep, - package_name.as_deref(), - )) - .arg("--locked"); - cmd.env(EnvVars::PATH, &new_path) - .env(EnvVars::CARGO_HOME, &cargo_home) - .remove_git_envs() - .check(true) - .output() + install_cli_dependency(cli_dep, hook_bin, &info, &cargo, &cargo_home, &new_path) .await?; } @@ -841,42 +951,46 @@ edition = "2021" #[test] fn test_parse_cargo_cli_dependency() { assert_eq!( - parse_cargo_cli_dependency("https://github.com/fish-shell/fish-shell"), - ("https://github.com/fish-shell/fish-shell", None, true) + CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell").unwrap(), + CargoCliDependency::Git { + url: "https://github.com/fish-shell/fish-shell".to_string(), + tag: None + } ); assert_eq!( - parse_cargo_cli_dependency("https://github.com/fish-shell/fish-shell:4.0"), - ( - "https://github.com/fish-shell/fish-shell", - Some("4.0"), - true - ) + CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell:4.0").unwrap(), + CargoCliDependency::Git { + url: "https://github.com/fish-shell/fish-shell".to_string(), + tag: Some("4.0".to_string()) + } ); assert_eq!( - parse_cargo_cli_dependency("typos-cli:1.0"), - ("typos-cli", Some("1.0"), false) + CargoCliDependency::from_str("typos-cli:1.0").unwrap(), + CargoCliDependency::Crate { + name: "typos-cli".to_string(), + version: Some("1.0".to_string()) + } ); } #[test] fn test_format_cargo_cli_dependency() { + let dep = CargoCliDependency::from_str("typos-cli").unwrap(); + assert_eq!(dep.to_cargo_args(None), ["typos-cli"]); + + let dep = CargoCliDependency::from_str("typos-cli:1.0").unwrap(); + assert_eq!(dep.to_cargo_args(None), ["typos-cli", "--version", "1.0"]); + + let dep = CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell").unwrap(); assert_eq!( - format_cargo_cli_dependency("typos-cli", None), - ["typos-cli"] - ); - assert_eq!( - format_cargo_cli_dependency("typos-cli:1.0", None), - ["typos-cli", "--version", "1.0"] - ); - assert_eq!( - format_cargo_cli_dependency("https://github.com/fish-shell/fish-shell", Some("fish")), + dep.to_cargo_args(Some("fish")), ["--git", "https://github.com/fish-shell/fish-shell", "fish"] ); + + let dep = + CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell:4.0").unwrap(); assert_eq!( - format_cargo_cli_dependency( - "https://github.com/fish-shell/fish-shell:4.0", - Some("fish") - ), + dep.to_cargo_args(Some("fish")), [ "--git", "https://github.com/fish-shell/fish-shell", @@ -887,17 +1001,16 @@ edition = "2021" ); } - #[tokio::test] - async fn test_find_git_package_name_non_url() { - let result = find_git_package_name( - "typos-cli", - "typos-cli", - Path::new("cargo"), - Path::new(""), - OsStr::new(""), - ) - .await - .unwrap(); - assert!(result.is_none()); + #[test] + fn test_git_repo_name() { + assert_eq!( + git_repo_name("https://github.com/fish-shell/fish-shell"), + "fish-shell" + ); + assert_eq!( + git_repo_name("https://github.com/fish-shell/fish-shell.git"), + "fish-shell" + ); + assert_eq!(git_repo_name("fish-shell"), "fish-shell"); } } From 782d9d5d11e30b61ec9a164776ab4abeb7281ca9 Mon Sep 17 00:00:00 2001 From: Jo <10510431+j178@users.noreply.github.com> Date: Fri, 6 Mar 2026 20:22:27 +0800 Subject: [PATCH 6/6] Add optional `package` segement --- crates/prek/src/languages/rust/rust.rs | 336 ++++++++++++------------- docs/languages.md | 12 +- 2 files changed, 166 insertions(+), 182 deletions(-) diff --git a/crates/prek/src/languages/rust/rust.rs b/crates/prek/src/languages/rust/rust.rs index b7367f6d2..ea6e4395b 100644 --- a/crates/prek/src/languages/rust/rust.rs +++ b/crates/prek/src/languages/rust/rust.rs @@ -6,7 +6,7 @@ use std::process::Stdio; use std::str::FromStr; use std::sync::Arc; -use anyhow::Context; +use anyhow::{Context, bail}; use itertools::{Either, Itertools}; use prek_consts::env_vars::EnvVars; use prek_consts::prepend_paths; @@ -42,6 +42,7 @@ enum CargoCliDependency { Git { url: String, tag: Option, + package: Option, }, } @@ -50,53 +51,74 @@ impl FromStr for CargoCliDependency { fn from_str(s: &str) -> Result { let is_url = s.starts_with("http://") || s.starts_with("https://"); - let (package, version) = if is_url && s.matches(':').count() == 1 { - (s, None) + if is_url { + let scheme_end = s + .find("://") + .map(|idx| idx + 3) + .ok_or_else(|| anyhow::anyhow!("Invalid git URL `{s}`"))?; + let rest = &s[scheme_end..]; + + let parts: Vec<&str> = rest.rsplitn(3, ':').collect(); + let (url_without_scheme, tag, package) = match parts.as_slice() { + [url] => (*url, None, None), + [tag, url] => { + if tag.is_empty() { + bail!( + "Git CLI dependency `{s}` contains an empty tag; use `cli:`, `cli::`, or `cli:::`" + ); + } + (*url, Some(*tag), None) + } + [package, tag, url] => { + if package.is_empty() { + bail!( + "Git CLI dependency `{s}` must specify a non-empty package when using `cli:::`" + ); + } + let tag = if tag.is_empty() { None } else { Some(*tag) }; + (*url, tag, Some(*package)) + } + _ => unreachable!(), + }; + + let url = format!("{}{}", &s[..scheme_end], url_without_scheme); + Ok(CargoCliDependency::Git { + url, + tag: tag.map(ToString::to_string), + package: package.map(ToString::to_string), + }) } else { - if let Some((pkg, ver)) = s.rsplit_once(':') { - (pkg, Some(ver)) + let (name, version) = if let Some((pkg, ver)) = s.rsplit_once(':') { + (pkg.to_string(), Some(ver.to_string())) } else { - (s, None) - } - }; + (s.to_string(), None) + }; - Ok(if is_url { - CargoCliDependency::Git { - url: package.to_string(), - tag: version.map(ToString::to_string), - } - } else { - CargoCliDependency::Crate { - name: package.to_string(), - version: version.map(ToString::to_string), - } - }) + Ok(CargoCliDependency::Crate { name, version }) + } } } impl CargoCliDependency { - fn to_cargo_args(&self, cargo_package: Option<&str>) -> Vec { - let mut args = Vec::new(); + fn to_cargo_args(&self) -> Vec<&str> { + let mut args: Vec<&str> = Vec::with_capacity(2); match self { CargoCliDependency::Crate { name, version } => { - args.push(name.clone()); + args.push(name); if let Some(version) = version { - args.push("--version".to_string()); - args.push(version.clone()); + args.push("--version"); + args.push(version); } } - CargoCliDependency::Git { - url: repo, - tag: rev, - } => { - args.push("--git".to_string()); - args.push(repo.clone()); - if let Some(rev) = rev { - args.push("--tag".to_string()); - args.push(rev.clone()); + CargoCliDependency::Git { url, tag, package } => { + args.push("--git"); + args.push(url); + if let Some(tag) = tag { + args.push("--tag"); + args.push(tag); } - if let Some(cargo_package) = cargo_package { - args.push(cargo_package.to_string()); + if let Some(package) = package { + args.push(package); } } } @@ -105,69 +127,6 @@ impl CargoCliDependency { } } -fn git_repo_name(url: &str) -> &str { - url.rsplit('/') - .next() - .unwrap_or(url) - .trim_end_matches(".git") -} - -async fn find_package_name_in_git_checkouts( - dep: &CargoCliDependency, - binary_name: &str, - cargo: &Path, - cargo_home: &Path, - new_path: &OsStr, -) -> anyhow::Result> { - let CargoCliDependency::Git { url, .. } = dep else { - return Ok(None); - }; - - let cache_root = cargo_home.join("git/checkouts"); - if !cache_root.exists() { - return Ok(None); - } - - let repo_name = git_repo_name(url); - let mut checkout_dirs = fs_err::tokio::read_dir(cache_root).await?; - while let Some(checkout_dir) = checkout_dirs.next_entry().await? { - if !checkout_dir.file_type().await?.is_dir() { - continue; - } - - let checkout_dir_name = checkout_dir.file_name(); - let checkout_dir_name = checkout_dir_name.to_string_lossy(); - if !checkout_dir_name.starts_with(repo_name) { - continue; - } - - let mut rev_dirs = fs_err::tokio::read_dir(checkout_dir.path()).await?; - while let Some(rev_dir) = rev_dirs.next_entry().await? { - if !rev_dir.file_type().await?.is_dir() { - continue; - } - - let rev_path = rev_dir.path(); - if let Some((_, package_name, _)) = find_package_dir( - &rev_path, - binary_name, - Some(cargo), - Some(cargo_home), - Some(new_path), - ) - .await? - { - debug!( - "Found package `{package_name}` for binary `{binary_name}` in cargo git cache for `{url}`" - ); - return Ok(Some(package_name)); - } - } - } - - Ok(None) -} - /// Find the package directory that produces the given binary. /// Returns (`package_dir`, `package_name`, `is_workspace`). async fn find_package_dir( @@ -422,7 +381,6 @@ async fn install_local_project( async fn install_cli_dependency( cli_dep: &str, - hook_bin: &str, info: &InstallInfo, cargo: &Path, cargo_home: &Path, @@ -433,42 +391,9 @@ async fn install_cli_dependency( let mut cmd = Cmd::new(cargo, "install cli dep"); cmd.args(["install", "--bins", "--root"]) .arg(&info.env_path) - .args(dep.to_cargo_args(None)) + .args(dep.to_cargo_args()) .arg("--locked"); - cmd.env(EnvVars::PATH, new_path) - .env(EnvVars::CARGO_HOME, cargo_home) - .remove_git_envs() - .check(false); - - let output = cmd.output().await?; - if output.status.success() { - return Ok(()); - } - - let stderr = String::from_utf8_lossy(&output.stderr); - if !matches!(&dep, CargoCliDependency::Git { .. }) - || !stderr.contains("multiple packages with binaries found") - { - cmd.check_output(&output)?; - } - - debug!( - "Failed to install CLI dependency `{cli_dep}`. Try resolving package name from cargo git checkouts", - ); - let package_name = - find_package_name_in_git_checkouts(&dep, hook_bin, cargo, cargo_home, new_path).await?; - let package_name = package_name.with_context(|| { - format!( - "Failed to resolve package for binary `{hook_bin}` from cargo git checkouts for `{cli_dep}`" - ) - })?; - - let mut cmd = Cmd::new(cargo, "install cli dep (retry with package)"); - cmd.args(["install", "--bins", "--root"]) - .arg(&info.env_path) - .args(dep.to_cargo_args(Some(&package_name))) - .arg("--locked"); cmd.env(EnvVars::PATH, new_path) .env(EnvVars::CARGO_HOME, cargo_home) .remove_git_envs() @@ -566,8 +491,7 @@ impl LanguageImpl for Rust { // Install CLI dependencies for cli_dep in cli_deps { - install_cli_dependency(cli_dep, hook_bin, &info, &cargo, &cargo_home, &new_path) - .await?; + install_cli_dependency(cli_dep, &info, &cargo, &cargo_home, &new_path).await?; } info.persist_env_path(); @@ -949,19 +873,12 @@ edition = "2021" } #[test] - fn test_parse_cargo_cli_dependency() { - assert_eq!( - CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell").unwrap(), - CargoCliDependency::Git { - url: "https://github.com/fish-shell/fish-shell".to_string(), - tag: None - } - ); + fn test_parse_cargo_cli_dependency_crate_forms() { assert_eq!( - CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell:4.0").unwrap(), - CargoCliDependency::Git { - url: "https://github.com/fish-shell/fish-shell".to_string(), - tag: Some("4.0".to_string()) + CargoCliDependency::from_str("typos-cli").unwrap(), + CargoCliDependency::Crate { + name: "typos-cli".to_string(), + version: None, } ); assert_eq!( @@ -974,43 +891,100 @@ edition = "2021" } #[test] - fn test_format_cargo_cli_dependency() { - let dep = CargoCliDependency::from_str("typos-cli").unwrap(); - assert_eq!(dep.to_cargo_args(None), ["typos-cli"]); - - let dep = CargoCliDependency::from_str("typos-cli:1.0").unwrap(); - assert_eq!(dep.to_cargo_args(None), ["typos-cli", "--version", "1.0"]); - - let dep = CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell").unwrap(); - assert_eq!( - dep.to_cargo_args(Some("fish")), - ["--git", "https://github.com/fish-shell/fish-shell", "fish"] - ); - - let dep = - CargoCliDependency::from_str("https://github.com/fish-shell/fish-shell:4.0").unwrap(); - assert_eq!( - dep.to_cargo_args(Some("fish")), - [ - "--git", + fn test_parse_cargo_cli_dependency_git_valid_forms() { + let cases = [ + ( "https://github.com/fish-shell/fish-shell", - "--tag", - "4.0", - "fish" - ] - ); + CargoCliDependency::Git { + url: "https://github.com/fish-shell/fish-shell".to_string(), + tag: None, + package: None, + }, + ), + ( + "https://github.com/fish-shell/fish-shell:v4.5.0", + CargoCliDependency::Git { + url: "https://github.com/fish-shell/fish-shell".to_string(), + tag: Some("v4.5.0".to_string()), + package: None, + }, + ), + ( + "https://github.com/fish-shell/fish-shell::fish", + CargoCliDependency::Git { + url: "https://github.com/fish-shell/fish-shell".to_string(), + tag: None, + package: Some("fish".to_string()), + }, + ), + ( + "https://github.com/fish-shell/fish-shell:v4.5.0:fish", + CargoCliDependency::Git { + url: "https://github.com/fish-shell/fish-shell".to_string(), + tag: Some("v4.5.0".to_string()), + package: Some("fish".to_string()), + }, + ), + ]; + + for (input, expected) in cases { + assert_eq!(CargoCliDependency::from_str(input).unwrap(), expected); + } } #[test] - fn test_git_repo_name() { - assert_eq!( - git_repo_name("https://github.com/fish-shell/fish-shell"), - "fish-shell" - ); - assert_eq!( - git_repo_name("https://github.com/fish-shell/fish-shell.git"), - "fish-shell" - ); - assert_eq!(git_repo_name("fish-shell"), "fish-shell"); + fn test_parse_cargo_cli_dependency_git_invalid_forms() { + let invalid_cases = [ + "https://github.com/fish-shell/fish-shell:", + "https://github.com/fish-shell/fish-shell:v4.5.0:", + "https://github.com/fish-shell/fish-shell::", + ]; + + for input in invalid_cases { + assert!( + CargoCliDependency::from_str(input).is_err(), + "input: {input}" + ); + } + } + + #[test] + fn test_format_cargo_cli_dependency() { + let cases = [ + ("typos-cli", vec!["typos-cli"]), + ("typos-cli:1.0", vec!["typos-cli", "--version", "1.0"]), + ( + "https://github.com/fish-shell/fish-shell", + vec!["--git", "https://github.com/fish-shell/fish-shell"], + ), + ( + "https://github.com/fish-shell/fish-shell:v4.5.0", + vec![ + "--git", + "https://github.com/fish-shell/fish-shell", + "--tag", + "v4.5.0", + ], + ), + ( + "https://github.com/fish-shell/fish-shell::fish", + vec!["--git", "https://github.com/fish-shell/fish-shell", "fish"], + ), + ( + "https://github.com/fish-shell/fish-shell:v4.5.0:fish", + vec![ + "--git", + "https://github.com/fish-shell/fish-shell", + "--tag", + "v4.5.0", + "fish", + ], + ), + ]; + + for (input, expected) in cases { + let dep = CargoCliDependency::from_str(input).unwrap(); + assert_eq!(dep.to_cargo_args(), expected, "input: {input}"); + } } } diff --git a/docs/languages.md b/docs/languages.md index a51e7237c..9159989fe 100644 --- a/docs/languages.md +++ b/docs/languages.md @@ -345,7 +345,17 @@ Supported formats: - prek supports installing packages from virtual workspaces. See [#1180](https://github.com/j178/prek/pull/1180). - `additional_dependencies` supports: - Library dependencies using `name` or `name:version` (applied via `cargo add`). - - CLI dependencies using `cli:`. These can be crates.io packages (`cli:rg:13.0.0`) or git URLs (`cli:https://github.com/BurntSushi/ripgrep:13.0.0`). + - CLI dependencies using `cli:`. + - crates.io form: `cli:` or `cli::` (for example `cli:rg:13.0.0`). + - git form (required base + optional trailing segments): `cli:[:[:]]`. + - trailing optional segments can be omitted entirely: + - `cli:https://github.com/fish-shell/fish-shell` + - `cli:https://github.com/fish-shell/fish-shell:v4.5.0` + - intermediate optional segments may be empty when a later segment is provided: + - `cli:https://github.com/fish-shell/fish-shell::fish` (no tag, explicit package) + - full form: + - `cli:https://github.com/fish-shell/fish-shell:v4.5.0:fish` + - empty package is invalid (for example `...:v4.5.0:` or `...::`). ### swift