Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(remove): recheck cleanliness after stopping the fsmonitor daemon (#4456)
Maximilian Roos3ec0bf71a1e5
diff --git a/src/git/remove.rs b/src/git/remove.rsindex 242f4fce3..e044da6e6 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -35,7 +35,8 @@//! the graceful `git fsmonitor--daemon stop` IPC request, then verifies the//! daemon is actually gone and force-kills it by PID if it has wedged.//! Without this, a daemon that has stopped answering its socket leaks-//! forever once its worktree is removed.+//! forever once its worktree is removed. With fsmonitor configured, the+//! clean check then reruns without it, catching writes during shutdown.//! 3. **Fast-path trash staging.** The worktree directory is renamed into//! `<git-common-dir>/wt/trash/<name>-<timestamp>/`. Same-filesystem renames//! are instant metadata operations, so the user's workspace clears@@ -54,20 +55,19 @@//! - [`ForceDelete`](BranchDeletionMode::ForceDelete): run `branch -D`//! without the integration check.//!-//! # The dirty-worktree gate follows git+//! # The dirty-worktree gate//!-//! Under `core.fsmonitor` the daemon answers step 1's `git status`, so a-//! daemon returning a stale clean answer would let removal delete uncommitted-//! work. That is git's own line, not a gap in `wt`: `git worktree remove`-//! refuses a dirty worktree off the same daemon-served status, and on detected-//! event loss the builtin daemon forces a client rescan or exits. A stale-//! clean answer therefore requires an *undetected* loss, which lies to the-//! user's own `git status` in that worktree just as readily.+//! Under `core.fsmonitor` the daemon answers step 1's `git status`, as it+//! answers `git worktree remove`'s. That first gate refuses a dirty worktree+//! cheaply and leaves its daemon running.//!-//! Matching git is the decision. Scoping `-c core.fsmonitor=` to that one call-//! would make `wt` stricter than the command it replaces, and would restore-//! the full re-stat the ordering above avoids — the dominant per-removal cost-//! at rust-lang/rust scale. (`--no-optional-locks` is not that knob: it+//! Stopping the daemon is `wt`'s own step, not git's, and it opens a window+//! git's gate never has: writes during the shutdown. So with fsmonitor+//! configured the gate runs again after the stop, rescanning without the+//! daemon, and that rescan is what a clean removal passes. It costs one full+//! re-stat per removal where fsmonitor is configured, and also catches a+//! stale clean answer from the daemon, which makes `wt` stricter there than+//! `git worktree remove`. (`--no-optional-locks` cannot replace the rescan: it//! governs index-lock acquisition, and git still queries the daemon under it.)//!//! # Example@@ -431,12 +431,11 @@ pub fn remove_worktree_with_cleanup(////// # Why this order///-/// The gate runs **before** the daemon stop because the fsmonitor daemon-/// serves its `git status`; stopping first would force a full re-stat, the-/// dominant per-removal cost on a large repo. That the gate therefore trusts-/// the daemon is a deliberate match to `git worktree remove`, whose own gate-/// trusts it identically — see "The dirty-worktree gate follows git" in the-/// [module-level docs](self) for why that is the decision and not a gap.+/// The gate runs **before** the daemon stop so a dirty worktree is refused off+/// the daemon's cheap answer, with its daemon left running. With fsmonitor+/// configured it runs once more after the stop, rescanning, to catch writes+/// during the shutdown — see "The dirty-worktree gate" in the+/// [module-level docs](self).////// The daemon stop runs **before** the rename because on Windows the daemon/// holds a handle on the worktree that would fail it, and git's graceful stop@@ -521,7 +520,14 @@ pub fn stage_worktree_removal(worktree.ensure_clean("remove worktree", branch, true)?;}- stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));+ stop_fsmonitor_daemon(&worktree);++ // The daemon answered the gate above, and a write can land while it shuts+ // down. Recheck without it; with fsmonitor configured, a plain status+ // would start a new daemon in the worktree about to go.+ if !force_worktree && repo.is_builtin_fsmonitor_enabled() {+ worktree.ensure_clean_without_fsmonitor("remove worktree", branch, true)?;+ }Ok(rename_into_trash(repo, worktree_path, &git_dir))}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex a9711290d..f32b1bd39 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -111,6 +111,26 @@ fn temporary_path_exclusion(worktree_root: &Path, temporary_path: &Path) -> Opti.map(|relative| format!(":(top,exclude,literal){}", relative.to_slash_lossy()))}+/// Refuse `action` when `dirty_files` (status porcelain lines) is non-empty.+fn require_no_dirty_files(+ dirty_files: Vec<String>,+ action: &str,+ branch: Option<&str>,+ force_hint: bool,+) -> anyhow::Result<()> {+ if !dirty_files.is_empty() {+ return Err(GitError::UncommittedChanges {+ action: Some(action.into()),+ branch: branch.map(String::from),+ force_hint,+ dirty_files,+ }+ .into());+ }++ Ok(())+}+/// Parse `git submodule status` output and detect whether any submodule is initialized.////// Status lines start with a one-character state marker:@@ -625,12 +645,19 @@ impl<'a> WorkingTree<'a> {/// [`GitError::UncommittedChanges`] in [`Self::ensure_clean`]. The same/// caveats as [`Self::is_dirty`] apply (skip-worktree files are invisible).pub fn dirty_files(&self) -> anyhow::Result<Vec<String>> {- let stdout = self.run_command(&[+ self.dirty_files_with(&[])+ }++ /// [`Self::dirty_files`] with `git -c` overrides ahead of `status`.+ fn dirty_files_with(&self, config: &[&str]) -> anyhow::Result<Vec<String>> {+ let mut args = config.to_vec();+ args.extend(["status","--porcelain","--untracked-files=normal","--ignore-submodules=none",- ])?;+ ]);+ let stdout = self.run_command(&args)?;Ok(stdout.lines().map(str::to_owned).collect())}@@ -953,18 +980,19 @@ impl<'a> WorkingTree<'a> {branch: Option<&str>,force_hint: bool,) -> anyhow::Result<()> {- let dirty_files = self.dirty_files()?;- if !dirty_files.is_empty() {- return Err(GitError::UncommittedChanges {- action: Some(action.into()),- branch: branch.map(String::from),- force_hint,- dirty_files,- }- .into());- }+ require_no_dirty_files(self.dirty_files()?, action, branch, force_hint)+ }- Ok(())+ /// [`Self::ensure_clean`] with fsmonitor disabled, for a worktree whose+ /// daemon was just stopped: a full rescan, and no daemon restarted.+ pub fn ensure_clean_without_fsmonitor(+ &self,+ action: &str,+ branch: Option<&str>,+ force_hint: bool,+ ) -> anyhow::Result<()> {+ let dirty_files = self.dirty_files_with(&["-c", "core.fsmonitor=false"])?;+ require_no_dirty_files(dirty_files, action, branch, force_hint)}/// Get line diff statistics for working tree changes (unstaged + staged).diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex d225c096b..7afdd69af 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -6216,6 +6216,53 @@ fn test_force_remove_interrupted_status_preserves_worktrees(assert!(!stderr.contains("Removing later-worktree"));}+/// With fsmonitor configured, a file written while the daemon shuts down is+/// refused by a rescan after the stop. The shim stands in for the daemon and+/// keeps every other Git command from starting a real one.+#[cfg(unix)]+#[rstest]+fn test_remove_keeps_work_created_during_fsmonitor_stop(mut repo: TestRepo) {+ use std::os::unix::fs::PermissionsExt;++ repo.run_git(&["config", "core.fsmonitor", "true"]);+ let worktree = repo.add_worktree("late-work");++ let bin_dir = repo.home_path().join("shutdown-git");+ fs::create_dir(&bin_dir).unwrap();+ let real_git = which::which("git").unwrap();+ let real_git = shell_escape::unix::escape(real_git.to_string_lossy());+ fs::write(+ bin_dir.join("git"),+ format!(+ r#"#!/bin/sh+case "$1" in+ fsmonitor--daemon) [ "$2" = stop ] && printf 'late work' > late.txt; exit 0 ;;+ config) exec {real_git} "$@" ;;+esac+exec {real_git} -c core.fsmonitor=false "$@"+"#+ ),+ )+ .unwrap();+ fs::set_permissions(bin_dir.join("git"), fs::Permissions::from_mode(0o755)).unwrap();+ let mut paths: Vec<_> = std::env::split_paths(&std::env::var_os("PATH").unwrap()).collect();+ paths.insert(0, bin_dir);++ let output = repo+ .wt_command()+ .args(["remove", "late-work", "--foreground", "--yes"])+ .env("PATH", std::env::join_paths(paths).unwrap())+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(!output.status.success(), "{stderr}");+ assert!(stderr.contains("has uncommitted changes"), "{stderr}");+ assert_eq!(+ fs::read_to_string(worktree.join("late.txt")).unwrap(),+ "late work"+ );+}+/// The child uses the invoking checkout's target and retains a moved tip,/// even when the replacement commit is integrated into that target.#[test]