diff --git a/src/git.rs b/src/git.rs index c88f567..d956e8a 100644 --- a/src/git.rs +++ b/src/git.rs @@ -538,15 +538,25 @@ pub async fn config(dir: &Path, key: &str) -> Result, GitError> { } } -/// The directory Git runs this repository's hooks from. Linked worktrees -/// share it. +/// This repository's own hooks directory, where `hooks install` writes scripts. +/// Linked worktrees share the common Git directory. Unlike `--git-path hooks`, +/// this does not follow `core.hooksPath` into another tool's directory. pub async fn hooks_dir(dir: &Path) -> Result { - line_in( + let output = git_in( dir, - &["rev-parse", "--path-format=absolute", "--git-path", "hooks"], + None, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], ) - .await - .map(PathBuf::from) + .await?; + Ok(common_dir_from_output(&output).join("hooks")) +} + +fn common_dir_from_output(output: &[u8]) -> PathBuf { + // Git adds a line ending; a space at the end of the path is still part of + // the directory name and must not be removed with `trim()`. + let path = output.strip_suffix(b"\n").unwrap_or(&output); + let path = path.strip_suffix(b"\r").unwrap_or(path); + PathBuf::from(String::from_utf8_lossy(path).into_owned()) } /// The full repository path of the remote. @@ -637,6 +647,12 @@ pub fn full_name(url: &str) -> Option { mod tests { use super::*; + #[test] + fn git_common_dir_keeps_trailing_spaces() { + assert_eq!(common_dir_from_output(b"repo \n"), PathBuf::from("repo ")); + assert_eq!(common_dir_from_output(b"repo \r\n"), PathBuf::from("repo ")); + } + #[test] fn reads_owner_and_name_from_remote_urls() { for url in [ diff --git a/src/hooks.rs b/src/hooks.rs index 7d5550a..b1c37f9 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -167,12 +167,40 @@ pub(crate) async fn manage(args: HooksArgs) -> anyhow::Result<()> { return Ok(()); } let dir = git::hooks_dir(here).await?; + if hooks_dir_is_external(&dir).await? { + for hook in selection.hooks() { + say(&format!( + "{} resolves outside this repository's Git directory, so nothing was written. Add this line to its {} hook by hand: {}", + dir.display(), + hook.name(), + hook.line() + )); + } + return Ok(()); + } for hook in selection.hooks() { install(&dir, hook).await?; } } HooksAction::Uninstall(selection) => { let dir = git::hooks_dir(here).await?; + if let Some(path) = git::config(here, "core.hooksPath").await? { + for hook in selection.hooks() { + say(&format!( + "core.hooksPath is {}, so remove this line from its {} hook by hand if you added it: {}", + one_line(&path), + hook.name(), + hook.line() + )); + } + } + if hooks_dir_is_external(&dir).await? { + say(&format!( + "{} resolves outside this repository's Git directory, so its hooks were left unchanged. Remove Proofline hooks there by hand if you own that directory.", + dir.display() + )); + return Ok(()); + } for hook in selection.hooks() { uninstall(&dir, hook).await?; } @@ -181,6 +209,16 @@ pub(crate) async fn manage(args: HooksArgs) -> anyhow::Result<()> { Ok(()) } +async fn hooks_dir_is_external(dir: &Path) -> anyhow::Result { + let common_dir = dir.parent().context("Git hooks directory has no parent")?; + let common_dir = tokio::fs::canonicalize(common_dir).await?; + match tokio::fs::canonicalize(dir).await { + Ok(resolved) => Ok(!resolved.starts_with(common_dir)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.into()), + } +} + async fn install(dir: &Path, hook: Hook) -> anyhow::Result<()> { let path = dir.join(hook.name()); let script = hook.script(); diff --git a/tests/hooks.rs b/tests/hooks.rs index ca3f94a..9cf7391 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -370,6 +370,111 @@ async fn install_writes_only_its_own_scripts_and_uninstall_removes_only_them() { assert_eq!(read(&checkout.hook("pre-commit")), None); } +#[tokio::test] +async fn uninstall_keeps_hooks_path_owned_by_another_tool() { + let checkout = Checkout::new().await; + let unused = "http://127.0.0.1:9"; + let install = checkout.proofline(unused, &["hooks", "install"], "").await; + assert!(install.status.success(), "{}", stderr(&install)); + + let shared = checkout.root().join(".husky"); + tokio::fs::create_dir_all(&shared).await.unwrap(); + let copied_script = read(&checkout.hook("pre-commit")).unwrap(); + tokio::fs::write(shared.join("pre-commit"), &copied_script) + .await + .unwrap(); + checkout.git(&["config", "core.hooksPath", ".husky"]).await; + + let uninstall = checkout + .proofline(unused, &["hooks", "uninstall"], "") + .await; + assert!(uninstall.status.success(), "{}", stderr(&uninstall)); + assert_eq!(read(&checkout.hook("pre-commit")), None); + assert_eq!(read(&checkout.hook("pre-push")), None); + assert_eq!( + read(&shared.join("pre-commit")).as_deref(), + Some(copied_script.as_str()) + ); + assert!(stderr(&uninstall).contains("remove this line from its pre-commit hook by hand")); +} + +#[tokio::test] +async fn uninstall_from_linked_worktree_removes_shared_git_hooks() { + let checkout = Checkout::new().await; + let install = checkout + .proofline("http://127.0.0.1:9", &["hooks", "install"], "") + .await; + assert!(install.status.success(), "{}", stderr(&install)); + + let linked = checkout.temporary.path().join("linked"); + checkout + .git(&[ + "worktree", + "add", + "-q", + "-b", + "linked", + linked.to_str().unwrap(), + ]) + .await; + let mut command = Command::new(env!("CARGO_BIN_EXE_proofline")); + command.args(["hooks", "uninstall"]); + checkout.environment(&mut command); + let uninstall = command.current_dir(&linked).output().await.unwrap(); + + assert!(uninstall.status.success(), "{}", stderr(&uninstall)); + assert_eq!(read(&checkout.hook("pre-commit")), None); + assert_eq!(read(&checkout.hook("pre-push")), None); +} + +#[cfg(unix)] +#[tokio::test] +async fn install_does_not_follow_symlinked_git_hooks_directory() { + let checkout = Checkout::new().await; + let hooks = checkout.root().join(".git/hooks"); + let original = checkout.temporary.path().join("original-hooks"); + let shared = checkout.temporary.path().join("shared-hooks"); + tokio::fs::rename(&hooks, &original).await.unwrap(); + tokio::fs::create_dir_all(&shared).await.unwrap(); + std::os::unix::fs::symlink(&shared, &hooks).unwrap(); + + let install = checkout + .proofline("http://127.0.0.1:9", &["hooks", "install"], "") + .await; + assert!(install.status.success(), "{}", stderr(&install)); + assert_eq!(read(&shared.join("pre-commit")), None); + assert_eq!(read(&shared.join("pre-push")), None); + assert!(stderr(&install).contains("nothing was written")); +} + +#[cfg(unix)] +#[tokio::test] +async fn uninstall_does_not_follow_symlinked_git_hooks_directory() { + for custom_path in [false, true] { + let checkout = Checkout::new().await; + let install = checkout + .proofline("http://127.0.0.1:9", &["hooks", "install"], "") + .await; + assert!(install.status.success(), "{}", stderr(&install)); + + let shared = checkout.temporary.path().join("shared-hooks"); + let hooks = checkout.root().join(".git/hooks"); + tokio::fs::rename(&hooks, &shared).await.unwrap(); + std::os::unix::fs::symlink(&shared, &hooks).unwrap(); + if custom_path { + checkout.git(&["config", "core.hooksPath", ".husky"]).await; + } + + let uninstall = checkout + .proofline("http://127.0.0.1:9", &["hooks", "uninstall"], "") + .await; + assert!(uninstall.status.success(), "{}", stderr(&uninstall)); + assert!(read(&shared.join("pre-commit")).is_some()); + assert!(read(&shared.join("pre-push")).is_some()); + assert!(stderr(&uninstall).contains("resolves outside this repository's Git directory")); + } +} + #[tokio::test] async fn the_exit_policy_blocks_only_on_request_and_never_reads_a_gap_as_clean() { let checkout = Checkout::new().await;