From 1a5bca0b359bb0d1013479723be51adf8f65e5f6 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Tue, 17 Nov 2026 14:43:53 +1100 Subject: [PATCH 1/4] perf(staged): add the worktree while a transfer from Blox is still capturing Moving a project from a Blox workspace to this machine, each branch's local worktree was added only after the branch had been snapshotted, downloaded and landed, and the step shown as "Adding the worktree" also covered a cold capture of the new worktree's shell environment. The worktree needs only a commit to check out, and the clone already holds one nearby. Each leg now picks it before its capture starts: the head the inspection saw when the clone has it, else origin's copy of the branch, its upstream, or the base. It records the worktree in the undo list, then adds it detached at that commit, with hooks off, on a scoped thread that also starts the shell-environment capture. The snapshot, the download and the landing run on the leg's thread as before. Once the branch has landed, `git checkout ` moves the worktree onto it, which rewrites only the files that differ and fires `post-checkout` once, and the finish runs as it did. The early worktree is an optimisation with a complete fallback. With no commit to start from, an early add or switch that fails, or a guess about Git LFS (from the inspection's counts) that the snapshot contradicts, the leg clears the early worktree and adds one on the branch at the same path, as before. A capture that fails or is cancelled returns its own error; the thread is always joined first and rollback removes the recorded worktree, so no cleanup path is new. Only transfers to local take this path. The prewarmed environment was captured at the start commit, so it is dropped after the switch when the two commits differ under `bin/` or in a root-level marker file the cache keys on, and the finish recaptures. The path's cached environment is also dropped before the prewarm, since anything cached there belongs to an earlier worktree. Progress phases are unchanged. Each leg now logs its early add, switch, environment wait and finish durations and whether it fell back. Tests cover the worktree being added while the snapshot runs, a snapshot failing after the early add, a head that moves after the inspection, the early add failing, the LFS guess being wrong, the undo list naming the worktree at the first snapshotting event, the start-commit choice, the invalidation rule, and the detached add and switch firing one hook. Signed-off-by: Matt Toohey Co-Authored-By: Claude Fable 5.2 --- apps/staged/src-tauri/src/git/cli.rs | 27 ++ apps/staged/src-tauri/src/git/mod.rs | 10 +- apps/staged/src-tauri/src/git/worktree.rs | 145 +++++- .../src/project_transfer/orchestrator.rs | 94 ++-- .../orchestrator/early_worktree.rs | 448 ++++++++++++++++++ .../project_transfer/orchestrator_tests.rs | 1 + .../orchestrator_tests/early_worktree.rs | 273 +++++++++++ .../orchestrator_tests/lfs.rs | 2 +- .../src-tauri/src/project_transfer/undo.rs | 5 +- apps/staged/src-tauri/src/shell_env.rs | 1 + .../src-tauri/src/shell_env/env_root.rs | 9 + 11 files changed, 968 insertions(+), 47 deletions(-) create mode 100644 apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs create mode 100644 apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs diff --git a/apps/staged/src-tauri/src/git/cli.rs b/apps/staged/src-tauri/src/git/cli.rs index aad265ed4..8c4f4ed52 100644 --- a/apps/staged/src-tauri/src/git/cli.rs +++ b/apps/staged/src-tauri/src/git/cli.rs @@ -280,6 +280,33 @@ pub(crate) fn prewarm_shell_env(repo: &Path) { warm_shell_env(repo); } +/// Wait for the captured shell env of `repo`, starting the capture if +/// nothing has: what the first captured-env op there would wait for, as a +/// step of its own so a caller can time it apart from that op. A capture that +/// fails is that op's to report. +/// +/// A no-op under unit tests, like [`prewarm_shell_env`]. +#[cfg(not(test))] +pub(crate) fn wait_for_shell_env(repo: &Path) { + let _ = crate::session_runner::shell_env_cache().get_blocking(repo); +} + +#[cfg(test)] +pub(crate) fn wait_for_shell_env(_repo: &Path) {} + +/// Drop the captured shell env `repo` uses, or the capture in flight for +/// it, so the next captured-env op there captures afresh. For a caller that +/// changed what the capture reads after it started. +/// +/// A no-op under unit tests, like [`prewarm_shell_env`]. +#[cfg(not(test))] +pub(crate) fn invalidate_shell_env(repo: &Path) { + crate::session_runner::shell_env_cache().invalidate(repo); +} + +#[cfg(test)] +pub(crate) fn invalidate_shell_env(_repo: &Path) {} + /// Which environment to pass to the spawned git process. /// /// Also surfaces at the `state::compute_local_branch_git_state` boundary as a diff --git a/apps/staged/src-tauri/src/git/mod.rs b/apps/staged/src-tauri/src/git/mod.rs index cf556ba0d..e9bf5016c 100644 --- a/apps/staged/src-tauri/src/git/mod.rs +++ b/apps/staged/src-tauri/src/git/mod.rs @@ -18,10 +18,12 @@ mod worktree; pub use branch_config::{read_branch_config_snapshot, BranchConfigSnapshot}; pub(crate) use cli::configure_captured; +pub(crate) use cli::invalidate_shell_env; pub(crate) use cli::prewarm_shell_env; pub(crate) use cli::run as cli_run; pub(crate) use cli::run_lite_or_captured as cli_run_lite_or_captured; pub(crate) use cli::run_smart as cli_run_smart; +pub(crate) use cli::wait_for_shell_env; pub use cli::{EnvSource, GitError}; pub use commit::commit; pub use diff::{get_file_diff, get_unified_diff, list_diff_files}; @@ -59,7 +61,8 @@ pub use types::*; pub use upstream::{upstream_branch_name, upstream_branch_name_with}; pub(crate) use worktree::force_delete_branch; pub use worktree::{ - branch_exists, create_worktree, create_worktree_at_path, create_worktree_for_existing_branch, + branch_exists, create_detached_worktree_without_hooks, create_worktree, + create_worktree_at_path, create_worktree_for_existing_branch, create_worktree_for_existing_branch_at_path, create_worktree_for_existing_branch_without_lfs_smudge, create_worktree_from_pr, create_worktree_from_pr_at_path, discard_worktree_changes, fetch_origin_branch, @@ -68,6 +71,7 @@ pub use worktree::{ list_worktrees, move_worktree, parse_branch_commit_line, parse_worktree_status_paths, project_worktree_path_for, project_worktree_root_for, remote_branch_exists, remove_worktree, reset_to_commit, set_upstream_to_origin, set_upstream_to_origin_or_unset, switch_branch, - update_branch_from_pr, worktree_path_for, BranchCommitFields, CommitInfo, UpdateFromPrResult, - WorktreeChangePaths, BRANCH_COMMIT_LOG_FORMAT, + switch_detached_worktree_to_branch, update_branch_from_pr, worktree_path_for, + BranchCommitFields, CommitInfo, UpdateFromPrResult, WorktreeChangePaths, + BRANCH_COMMIT_LOG_FORMAT, }; diff --git a/apps/staged/src-tauri/src/git/worktree.rs b/apps/staged/src-tauri/src/git/worktree.rs index 6d41a8745..e9a55780e 100644 --- a/apps/staged/src-tauri/src/git/worktree.rs +++ b/apps/staged/src-tauri/src/git/worktree.rs @@ -182,12 +182,7 @@ pub fn create_worktree_for_existing_branch_without_lfs_smudge( branch_name: &str, worktree_path: &Path, ) -> Result { - add_worktree_for_existing_branch( - repo, - branch_name, - worktree_path, - &[("GIT_LFS_SKIP_SMUDGE", "1")], - ) + add_worktree_for_existing_branch(repo, branch_name, worktree_path, lfs_smudge_vars(true)) } fn add_worktree_for_existing_branch( @@ -210,6 +205,81 @@ fn add_worktree_for_existing_branch( Ok(worktree_path.to_path_buf()) } +/// Add a worktree detached at `commit`, which `repo` must already hold, +/// without firing hooks. +/// +/// For a worktree made before its branch exists: +/// [`switch_detached_worktree_to_branch`] puts it on the branch later, and +/// that checkout is the one `post-checkout` should see. `skip_lfs_smudge` +/// checks LFS files out as pointers, as +/// [`create_worktree_for_existing_branch_without_lfs_smudge`] does. +pub fn create_detached_worktree_without_hooks( + repo: &Path, + commit: &str, + worktree_path: &Path, + skip_lfs_smudge: bool, +) -> Result { + ensure_worktree_parent_exists(worktree_path)?; + ensure_worktree_absent(worktree_path)?; + + let worktree_str = worktree_path + .to_str() + .ok_or_else(|| GitError::InvalidPath(worktree_path.display().to_string()))?; + + // git -c core.hooksPath=/dev/null worktree add --detach + cli::run_with_vars( + repo, + &[ + "-c", + "core.hooksPath=/dev/null", + "worktree", + "add", + "--detach", + worktree_str, + commit, + ], + lfs_smudge_vars(skip_lfs_smudge), + )?; + + Ok(worktree_path.to_path_buf()) +} + +/// Check `branch_name` out in `worktree_path`, a clean worktree of `repo` +/// detached at some other commit: only the files that differ are rewritten. +/// Hooks fire, as they do for a worktree added on the branch. +/// +/// Runs in the worktree but with `repo`'s captured env, the one +/// [`create_worktree_for_existing_branch_at_path`] gives the hooks and +/// filters of its checkout, so it doesn't wait on a capture for the worktree. +pub fn switch_detached_worktree_to_branch( + repo: &Path, + worktree_path: &Path, + branch_name: &str, + skip_lfs_smudge: bool, +) -> Result<(), GitError> { + let worktree_str = worktree_path + .to_str() + .ok_or_else(|| GitError::InvalidPath(worktree_path.display().to_string()))?; + + // git -C checkout -- + // The second `-C` is absolute, so it replaces the `-C ` that + // `cli` puts first; `--` keeps a file of the same name out of it. + cli::run_with_vars( + repo, + &["-C", worktree_str, "checkout", branch_name, "--"], + lfs_smudge_vars(skip_lfs_smudge), + )?; + Ok(()) +} + +fn lfs_smudge_vars(skip: bool) -> &'static [(&'static str, &'static str)] { + if skip { + &[("GIT_LFS_SKIP_SMUDGE", "1")] + } else { + &[] + } +} + /// Move an existing worktree to a new path. /// /// Goes through `git worktree move` rather than `fs::rename` because a @@ -1273,6 +1343,69 @@ mod tests { let _ = std::fs::remove_dir_all(&to); } + /// The pair that builds a worktree before its branch exists: detached + /// at a commit the repo has, hooks off, then onto the branch, which is + /// the one checkout `post-checkout` sees. + #[cfg(unix)] + #[test] + fn a_detached_worktree_goes_onto_its_branch_with_one_post_checkout() { + use std::os::unix::fs::PermissionsExt; + + let repo = crate::test_utils::TempGitRepo::new(); + repo.write_file("tracked.txt", "base\n"); + // A file named as the branch: the switch must not take it for one. + repo.write_file("feature", "a file\n"); + let base = repo.commit("base"); + repo.write_file("tracked.txt", "tip\n"); + let tip = repo.commit("tip"); + + let root = crate::test_utils::TempDir::new("detached-worktree"); + let hooks = root.path().join("hooks"); + let log = root.path().join("post-checkout.log"); + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("post-checkout"); + std::fs::write( + &hook, + format!("#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n", log.display()), + ) + .unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + repo.run_git(&["config", "core.hooksPath", hooks.to_str().unwrap()]); + let worktree = root.path().join("wt"); + let on = |wt: &Path| { + cli::run(wt, &["rev-parse", "--abbrev-ref", "HEAD"]) + .unwrap() + .trim() + .to_string() + }; + + create_detached_worktree_without_hooks(repo.path(), &base, &worktree, false).unwrap(); + + assert_eq!(on(&worktree), "HEAD", "detached"); + assert_eq!( + std::fs::read_to_string(worktree.join("tracked.txt")).unwrap(), + "base\n" + ); + assert!(!log.exists(), "the detached add fired the hook"); + + repo.run_git(&["branch", "feature", &tip]); + switch_detached_worktree_to_branch(repo.path(), &worktree, "feature", false).unwrap(); + + assert_eq!(on(&worktree), "feature"); + assert_eq!( + std::fs::read_to_string(worktree.join("tracked.txt")).unwrap(), + "tip\n" + ); + assert_eq!(cli::run(&worktree, &["status", "--porcelain"]).unwrap(), ""); + assert_eq!( + std::fs::read_to_string(&log).unwrap(), + format!("{base} {tip} 1\n"), + "one branch checkout, from the start commit" + ); + // The repo's own checkout is where it was. + assert_eq!(on(repo.path()), "main"); + } + fn local_branches(repo: &crate::test_utils::TempGitRepo) -> String { repo.run_git(&["branch", "--list", "--format=%(refname:short)"]) } diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator.rs index 71b5745e2..55cb507de 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator.rs @@ -25,15 +25,22 @@ //! [`Run::for_each_leg`]). What touches shared state stays sequential: the //! inspection, starting and deleting the workspace, the database switch, //! and the unchanged check right before the source comes down. +//! +//! Within a leg the steps follow one another, but for one: coming to local, +//! the branch's worktree is added, and its shell environment captured, while +//! the capture from the workspace still runs (see [`early_worktree`]). +mod early_worktree; mod parallel; mod teardown; +#[cfg(test)] +pub(crate) use early_worktree::FailingEarlyAdds; #[cfg(test)] pub(crate) use parallel::SerialLegs; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; @@ -61,8 +68,7 @@ use super::preflight::{ use super::registry::TransferGuard; use super::scripts::{ApplyReport, IgnoredFiles, Snapshot, CLONE_SCRIPT}; use super::undo::{ - self, AddedExcludes, AddedRemote, AddedWorktree, CreatedBranch, ReplacedConfig, SourceCheckout, - Undo, + self, AddedExcludes, AddedRemote, CreatedBranch, ReplacedConfig, SourceCheckout, Undo, }; use super::TransferError; @@ -856,24 +862,45 @@ impl Run<'_> { dir: source_dir, }) })?; + // Coming to local, the worktree is added at a commit the clone + // already has while the capture runs, to be switched onto the branch + // once that has landed. + let early = match self.direction { + TransferDirection::ToLocal => { + self.guard_not_cancelled()?; + self.plan_early_worktree(leg, Path::new(&plan.dest_dir)) + } + TransferDirection::ToRemote => None, + }; // Why `on_step` stopped the carry, when it was not a cancel. let mut not_recorded = None; - let carried = carry_repo_with(source.as_ref(), dest.as_ref(), &plan, &mut |step| { - let (phase, bytes) = match step { - CarryStep::Snapshotting => (TransferPhase::Snapshotting, None), - CarryStep::Moving { bytes } => (TransferPhase::Moving, Some(bytes)), - CarryStep::Applying { .. } => (TransferPhase::Applying, None), - }; - self.emit(phase, Some(leg), None, bytes); - self.guard_not_cancelled()?; - if let (CarryStep::Applying { snapshot }, Landing::Branch) = (step, plan.landing) { - if let Err(e) = self.record_landing(&plan, snapshot) { - not_recorded = Some(e); - return Err(TransferError::Cancelled); + // The scope joins the early add before the leg goes on, whatever + // the capture came to — a panic included. + let (carried, early_add) = std::thread::scope(|scope| { + let adding = early.as_ref().map(|early| scope.spawn(move || early.add())); + let carried = carry_repo_with(source.as_ref(), dest.as_ref(), &plan, &mut |step| { + let (phase, bytes) = match step { + CarryStep::Snapshotting => (TransferPhase::Snapshotting, None), + CarryStep::Moving { bytes } => (TransferPhase::Moving, Some(bytes)), + CarryStep::Applying { .. } => (TransferPhase::Applying, None), + }; + self.emit(phase, Some(leg), None, bytes); + self.guard_not_cancelled()?; + if let (CarryStep::Applying { snapshot }, Landing::Branch) = (step, plan.landing) { + if let Err(e) = self.record_landing(&plan, snapshot) { + not_recorded = Some(e); + return Err(TransferError::Cancelled); + } } - } - Ok(()) + Ok(()) + }); + // A panic in the early add is the leg's, message intact. + let early_add = + adding.map(|adding| adding.join().unwrap_or_else(|panic| resume_unwind(panic))); + (carried, early_add) }); + // A capture that failed or was cancelled: what the early add made + // is in the undo list, for the rollback. let mut outcome = match (carried, not_recorded) { (Err(_), Some(e)) => return Err(e.into()), (carried, _) => carried?, @@ -884,24 +911,14 @@ impl Run<'_> { Some(leg), Some("Adding the worktree".to_string()), )?; - let clone = PathBuf::from(&plan.dest_dir); - let worktree = self.free_worktree_path(leg)?; - self.record(|undo| { - undo.worktrees.push(AddedWorktree { - clone: clone.clone(), - worktree: worktree.clone(), - }) - })?; - // LFS files check out as pointers, which `finish` replaces with - // the objects that came: a smudge filter would download each one - // again, and fail the checkout on any it can't. - let add_worktree = if outcome.snapshot.lfs.is_some() { - crate::git::create_worktree_for_existing_branch_without_lfs_smudge - } else { - crate::git::create_worktree_for_existing_branch_at_path - }; - add_worktree(&clone, &leg.dest_branch, &worktree) - .map_err(|e| format!("Cannot add the worktree for {}: {e}", leg.dest_branch))?; + let (worktree, mut timings) = + self.settle_worktree(leg, &plan, &outcome, early.zip(early_add))?; + // What the finish would wait for first, apart from it for the + // log. + let waiting = Instant::now(); + crate::git::wait_for_shell_env(&worktree); + timings.environment = waiting.elapsed(); + let finishing = Instant::now(); let endpoint = self.host.local_endpoint(&worktree)?; let (finished, added) = self.finish_recording_excludes( endpoint.as_ref(), @@ -909,6 +926,13 @@ impl Run<'_> { &outcome, &path_str(&worktree)?, )?; + timings.finish = finishing.elapsed(); + log::info!( + "[project_transfer] transfer {}: the worktree for {}: {}", + self.guard.transfer_id(), + leg.dest_branch, + timings.describe() + ); outcome.applied.warnings.extend(finished.warnings); outcome.applied.lfs_unavailable |= finished.lfs_unavailable; outcome.applied.ignored = outcome.applied.ignored.take().or(finished.ignored); diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs new file mode 100644 index 000000000..07fe0dd72 --- /dev/null +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs @@ -0,0 +1,448 @@ +//! A branch's local worktree, started while its capture still runs. +//! +//! Coming to local, a worktree needs nothing from the capture but the +//! commit to check out, and the clone already holds one nearby: the head +//! the inspection saw, or what the destination just fetched from origin. +//! So the leg adds the worktree detached at that commit, and starts the +//! capture of its shell environment, on a thread of its own while the +//! snapshot, the download and the landing run; once the branch has landed +//! it only switches the worktree onto it, which rewrites the files that +//! differ. +//! +//! This is an optimisation with a complete fallback. A leg with no commit +//! to start from, an early add or a switch that fails, or a guess about +//! Git LFS the snapshot contradicts, all end in the sequence without it: +//! `git worktree add ` once the branch has landed. The +//! worktree is recorded in the undo list before the thread starts and the +//! thread is joined before the leg returns, so rollback and startup recovery +//! find it as they find a worktree added late. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use super::super::carry::{CarryOutcome, CarryPlan}; +use super::super::undo::{self, AddedWorktree}; +use super::{origin_tip_names, Failure, Leg, Run}; + +#[cfg(test)] +thread_local! { + /// A test's request that early adds planned from this thread fail. + static FAIL_EARLY_ADDS_FOR_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While it lives, the early worktree adds of legs run from this thread +/// fail part way, leaving a directory git knows nothing of — for a test of +/// the fallback. The legs of a one-repository transfer, or of one under +/// [`super::SerialLegs`], run on the thread that runs the transfer. +#[cfg(test)] +pub(crate) struct FailingEarlyAdds; + +#[cfg(test)] +impl FailingEarlyAdds { + pub(crate) fn for_this_thread() -> Self { + FAIL_EARLY_ADDS_FOR_TEST.with(|f| f.set(true)); + Self + } +} + +#[cfg(test)] +impl Drop for FailingEarlyAdds { + fn drop(&mut self) { + FAIL_EARLY_ADDS_FOR_TEST.with(|f| f.set(false)); + } +} + +/// A worktree to add before its branch exists. Owns all it needs, so the +/// thread adding it borrows nothing from the leg. +pub(super) struct EarlyWorktree { + clone: PathBuf, + path: PathBuf, + /// The commit it is added at, which the clone already holds. + start: String, + /// Whether the snapshot is expected to bring LFS objects, in which case + /// LFS files check out as pointers for the finish to replace. + skip_lfs_smudge: bool, + #[cfg(test)] + fail: bool, +} + +/// How an early add went. +pub(super) struct EarlyAdd { + result: Result<(), String>, + took: Duration, +} + +impl EarlyWorktree { + /// Add the worktree, and start capturing its shell environment so the + /// finish finds it cached or waits only for the rest. Hooks stay off: + /// `post-checkout` fires once, when the worktree goes onto its branch. + pub(super) fn add(&self) -> EarlyAdd { + let started = Instant::now(); + let result = self.add_detached(); + if result.is_ok() { + // Whatever is cached for the path is from a worktree that was + // there before. + crate::git::invalidate_shell_env(&self.path); + crate::git::prewarm_shell_env(&self.path); + } + EarlyAdd { + result, + took: started.elapsed(), + } + } + + fn add_detached(&self) -> Result<(), String> { + #[cfg(test)] + if self.fail { + std::fs::create_dir_all(&self.path).map_err(|e| e.to_string())?; + std::fs::write(self.path.join("half-added"), "").map_err(|e| e.to_string())?; + return Err("injected failure".to_string()); + } + crate::git::create_detached_worktree_without_hooks( + &self.clone, + &self.start, + &self.path, + self.skip_lfs_smudge, + ) + .map(drop) + .map_err(|e| e.to_string()) + } +} + +/// How a leg's worktree came to be, for the log. +#[derive(Default)] +pub(super) struct WorktreeTimings { + /// The early add and the commit it started from. + early_add: Option<(Duration, String)>, + switch: Option, + /// The add once the branch had landed: the only one, or the fallback's. + late_add: Option, + /// Why the early worktree was discarded, when it was. + fell_back: Option, + pub(super) environment: Duration, + pub(super) finish: Duration, +} + +impl WorktreeTimings { + pub(super) fn describe(&self) -> String { + let mut parts = Vec::new(); + if let Some((took, start)) = &self.early_add { + parts.push(format!("early add at {start} {took:.1?}")); + } + if let Some(took) = self.switch { + parts.push(format!("switch {took:.1?}")); + } + if let Some(took) = self.late_add { + parts.push(format!("late add {took:.1?}")); + } + parts.push(format!("environment {:.1?}", self.environment)); + parts.push(format!("finish {:.1?}", self.finish)); + parts.push(match &self.fell_back { + Some(why) => format!("fell back ({why})"), + None => "no fallback".to_string(), + }); + parts.join(", ") + } +} + +/// The remote-tracking refs a leg's destination fetched from origin, in the +/// order an early worktree prefers them: the branch, its upstream, then +/// the base. +fn start_refs(leg: &Leg) -> Vec { + // The base comes first there. + let names = origin_tip_names(leg); + names + .iter() + .skip(1) + .chain(names.first()) + .map(|name| format!("refs/remotes/origin/{name}")) + .collect() +} + +/// The commit to add an early worktree at: `head`, the source's head as +/// the inspection saw it, when `clone` holds it (a branch pushed in full, +/// or one this machine has carried before), else the first of `refs` that +/// resolves. `None` when the clone holds none of them. +pub(super) fn start_commit(clone: &Path, head: Option<&str>, refs: &[String]) -> Option { + let commit = |rev: &str| { + // Peeling makes git read the object, so a head the clone lacks + // fails here instead of in the checkout. + let peeled = format!("{rev}^{{commit}}"); + crate::git::cli_run(clone, &["rev-parse", "--verify", "--quiet", &peeled]) + .ok() + .map(|out| out.trim().to_string()) + .filter(|id| !id.is_empty()) + }; + head.and_then(commit) + .or_else(|| refs.iter().find_map(|r| commit(r))) +} + +/// Whether a shell environment captured in a worktree at `start` may differ +/// from one captured after it moved to `head`: whether the two commits +/// differ in anything a capture at the worktree's root reads +/// ([`crate::shell_env::env_root_inputs`]). Not being able to tell counts +/// as differing, which costs one more capture. +pub(super) fn env_capture_is_stale(clone: &Path, start: &str, head: &str) -> bool { + if start == head { + return false; + } + let mut args = vec!["diff", "--name-only", "--no-renames", start, head, "--"]; + for input in crate::shell_env::env_root_inputs() { + args.push(input); + } + match crate::git::cli_run(clone, &args) { + Ok(changed) => !changed.trim().is_empty(), + Err(e) => { + log::warn!( + "[project_transfer] cannot compare {start} and {head} in {}: {e}", + clone.display() + ); + true + } + } +} + +impl Run<'_> { + /// Before the leg's capture starts: pick the commit and the path for + /// its worktree and record it, as the late add would have. `None` leaves + /// the worktree to the late add, which reports whatever stood in the + /// way here. + pub(super) fn plan_early_worktree(&self, leg: &Leg, clone: &Path) -> Option { + let branch = &leg.dest_branch; + let start = start_commit(clone, leg.row.head.as_deref(), &start_refs(leg))?; + let planned = self.free_worktree_path(leg).and_then(|path| { + self.record(|undo| { + undo.worktrees.push(AddedWorktree { + clone: clone.to_path_buf(), + worktree: path.clone(), + }) + })?; + Ok(path) + }); + let path = match planned { + Ok(path) => path, + Err(e) => { + log::warn!("[project_transfer] no early worktree for {branch}: {e}"); + return None; + } + }; + Some(EarlyWorktree { + clone: clone.to_path_buf(), + path, + start, + skip_lfs_smudge: leg.row.lfs_present + leg.row.lfs_missing > 0, + #[cfg(test)] + fail: FAIL_EARLY_ADDS_FOR_TEST.with(|f| f.get()), + }) + } + + /// Once the leg's branch has landed: put it in its worktree. The early + /// worktree is switched onto the branch; without one, or when it or the + /// switch failed, or its LFS guess was wrong, the worktree is added on + /// the branch as it always was — at the early one's path, once that is + /// cleared. + pub(super) fn settle_worktree( + &self, + leg: &Leg, + plan: &CarryPlan, + outcome: &CarryOutcome, + early: Option<(EarlyWorktree, EarlyAdd)>, + ) -> Result<(PathBuf, WorktreeTimings), Failure> { + let clone = PathBuf::from(&plan.dest_dir); + let branch = &leg.dest_branch; + // LFS files check out as pointers, which `finish` replaces with + // the objects that came: a smudge filter would download each one + // again, and fail the checkout on any it can't. + let skip_lfs_smudge = outcome.snapshot.lfs.is_some(); + let mut timings = WorktreeTimings::default(); + + let worktree = match early { + Some((early, add)) => { + timings.early_add = Some((add.took, early.start.clone())); + let added = add.result.is_ok(); + let switching = Instant::now(); + let switched = add + .result + .map_err(|e| format!("the early add failed: {e}")) + .and_then(|()| { + if early.skip_lfs_smudge == skip_lfs_smudge { + Ok(()) + } else { + Err(format!( + "it was added {} LFS objects to come, and the snapshot {}", + if early.skip_lfs_smudge { + "expecting" + } else { + "not expecting" + }, + if skip_lfs_smudge { + "brought some" + } else { + "brought none" + }, + )) + } + }) + .and_then(|()| { + crate::git::switch_detached_worktree_to_branch( + &clone, + &early.path, + branch, + skip_lfs_smudge, + ) + .map_err(|e| format!("cannot switch it to {branch}: {e}")) + }); + match switched { + Ok(()) => { + timings.switch = Some(switching.elapsed()); + if env_capture_is_stale(&clone, &early.start, &outcome.snapshot.head) { + crate::git::invalidate_shell_env(&early.path); + } + return Ok((early.path, timings)); + } + Err(why) => { + log::warn!( + "[project_transfer] transfer {}: discarding the early worktree \ + for {branch} at {}: {why}", + self.guard.transfer_id(), + early.path.display() + ); + if added { + // The capture it started runs in the directory + // about to go. + crate::git::wait_for_shell_env(&early.path); + } + undo::remove_worktree_keeping_branch(&clone, &early.path) + .map_err(|e| format!("Cannot add the worktree for {branch}: {e}"))?; + crate::git::invalidate_shell_env(&early.path); + timings.fell_back = Some(why); + early.path + } + } + } + None => { + let worktree = self.free_worktree_path(leg)?; + self.record(|undo| { + undo.worktrees.push(AddedWorktree { + clone: clone.clone(), + worktree: worktree.clone(), + }) + })?; + worktree + } + }; + + let adding = Instant::now(); + let add_worktree = if skip_lfs_smudge { + crate::git::create_worktree_for_existing_branch_without_lfs_smudge + } else { + crate::git::create_worktree_for_existing_branch_at_path + }; + add_worktree(&clone, branch, &worktree) + .map_err(|e| format!("Cannot add the worktree for {branch}: {e}"))?; + timings.late_add = Some(adding.elapsed()); + Ok((worktree, timings)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::TempGitRepo; + + fn repo_with_base() -> (TempGitRepo, String) { + let repo = TempGitRepo::new(); + repo.write_file("a.txt", "alpha\n"); + let base = repo.commit("base"); + (repo, base) + } + + fn commit_file(repo: &TempGitRepo, name: &str) -> String { + if let Some(parent) = Path::new(name).parent() { + std::fs::create_dir_all(repo.path().join(parent)).unwrap(); + } + repo.write_file(name, "content\n"); + repo.commit(name) + } + + #[test] + fn a_capture_is_stale_only_when_what_it_reads_changed() { + let (repo, base) = repo_with_base(); + assert!(!env_capture_is_stale(repo.path(), &base, &base)); + + // Source files, and a marker below the root, are not read by a + // capture at the root. + commit_file(&repo, "src/main.rs"); + commit_file(&repo, "apps/web/.nvmrc"); + let unrelated = commit_file(&repo, "sbin/tool"); + assert!(!env_capture_is_stale(repo.path(), &base, &unrelated)); + + for input in [ + "bin/activate-hermit", + "bin/hermit.hcl", + ".envrc", + ".mise/config.toml", + ] { + let before = repo.run_git(&["rev-parse", "HEAD"]).trim().to_string(); + let after = commit_file(&repo, input); + assert!( + env_capture_is_stale(repo.path(), &before, &after), + "{input}" + ); + // Whichever way the worktree moved. + assert!( + env_capture_is_stale(repo.path(), &after, &before), + "{input}" + ); + assert!(env_capture_is_stale(repo.path(), &base, &after), "{input}"); + } + } + + #[test] + fn a_capture_counts_as_stale_when_the_commits_cannot_be_compared() { + let (repo, base) = repo_with_base(); + let missing = "0123456789abcdef0123456789abcdef01234567"; + assert!(env_capture_is_stale(repo.path(), &base, missing)); + } + + #[test] + fn the_start_commit_is_the_head_when_the_clone_holds_it_else_the_first_ref_it_has() { + let (repo, base) = repo_with_base(); + let tip = commit_file(&repo, "b.txt"); + repo.run_git(&["update-ref", "refs/remotes/origin/main", &base]); + repo.run_git(&["update-ref", "refs/remotes/origin/feature", &tip]); + let refs = |names: &[&str]| -> Vec { + names + .iter() + .map(|n| format!("refs/remotes/origin/{n}")) + .collect() + }; + let missing = "0123456789abcdef0123456789abcdef01234567"; + + assert_eq!( + start_commit(repo.path(), Some(&base), &refs(&["feature", "main"])), + Some(base.clone()), + "the head, though a ref is ahead of it" + ); + assert_eq!( + start_commit(repo.path(), Some(missing), &refs(&["feature", "main"])), + Some(tip.clone()), + "a head the clone lacks" + ); + assert_eq!( + start_commit(repo.path(), None, &refs(&["gone", "main"])), + Some(base), + "a ref origin never had" + ); + assert_eq!( + start_commit(repo.path(), Some(missing), &refs(&["gone"])), + None + ); + // A tree is not something to check out. + let tree = repo + .run_git(&["rev-parse", "HEAD^{tree}"]) + .trim() + .to_string(); + assert_eq!(start_commit(repo.path(), Some(&tree), &[]), None); + } +} diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests.rs index c4e67a5ee..b1b5dd841 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests.rs @@ -41,6 +41,7 @@ use crate::store::{ }; use crate::test_utils::TempDir; +mod early_worktree; mod ignored; mod lfs; diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs new file mode 100644 index 000000000..e4ca682c8 --- /dev/null +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs @@ -0,0 +1,273 @@ +//! Coming to local, a branch's worktree is added while its capture from +//! the workspace still runs, then switched onto the branch once that has +//! landed — or, when anything about it goes wrong, discarded for a worktree +//! added the way it always was. +//! +//! A worktree that went the early way shows it in its `HEAD` reflog: one +//! added on the branch never moved from another commit. + +use std::time::{Duration, Instant}; + +use super::super::orchestrator::FailingEarlyAdds; +use super::super::tests::lfs::{lfs_installed, track_psd, POINTER_PREFIX}; +use super::super::undo::AddedWorktree; +use super::lfs::lfs_project; +use super::*; + +/// Take `f`'s one branch, `feature`, to a workspace: pushed, then a commit +/// ahead of origin, with an untracked file. Returns the pushed tip and the +/// head. +fn send_to_a_workspace(f: &Fixture) -> (String, String) { + let worktree = f.worktree(0); + write(&worktree, "pushed.txt", "pushed\n"); + let pushed = commit(&worktree, "pushed"); + git(&worktree, &["push", "-q", "-u", "origin", "feature"]); + write(&worktree, "ahead.txt", "ahead\n"); + let head = commit(&worktree, "ahead"); + write(&worktree, "notes.txt", "untracked\n"); + f.transfer(true).result.expect("to remote"); + (pushed, head) +} + +/// Where the branch's worktree goes when the project comes back. +fn worktree_path(f: &Fixture) -> PathBuf { + f.host + .local_worktree_path(&f.project.id, WIDGETS, "feature") + .unwrap() +} + +/// Hold every snapshot in the workspace until `worktree` is there (one +/// that never comes fails the wait after 20 s). Returns, per snapshot, +/// whether it was. +fn hold_the_snapshot_for(f: &Fixture, worktree: &Path) -> Arc>> { + let seen = Arc::new(Mutex::new(Vec::new())); + let (held, gitfile) = (Arc::clone(&seen), worktree.join(".git")); + f.host.on_every_script(move |side, script| { + if side != Side::Workspace || script != SNAPSHOT_SCRIPT { + return; + } + let deadline = Instant::now() + Duration::from_secs(20); + while !gitfile.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + held.lock().unwrap().push(gitfile.exists()); + }); + seen +} + +/// Every move of the worktree's `HEAD`, as its reflog words them. +fn head_moves(worktree: &Path) -> Vec { + git(worktree, &["reflog", "--format=%gs", "HEAD"]) + .lines() + .map(str::to_string) + .collect() +} + +/// Whether the worktree was added early, at `start`, and switched onto +/// `feature` from there. +fn switched_from(worktree: &Path, start: &str) -> bool { + head_moves(worktree).contains(&format!("checkout: moving from {start} to feature")) +} + +/// Whether the worktree was added on its branch, never having been +/// anywhere else. +fn added_on_its_branch(worktree: &Path) -> bool { + !head_moves(worktree) + .iter() + .any(|m| m.starts_with("checkout: ")) +} + +/// The branch's worktree, which must be on `feature` at `head`. +fn worktree_on_feature_at(f: &Fixture, head: &str) -> PathBuf { + let worktree = f.worktree(0); + assert_eq!(worktree, worktree_path(f)); + assert_eq!( + git(&worktree, &["rev-parse", "--abbrev-ref", "HEAD"]).trim(), + "feature" + ); + assert_eq!(rev(&worktree, "HEAD"), head); + assert_eq!(rev(&f.host.clone_of(WIDGETS), "refs/heads/feature"), head); + worktree +} + +/// The snapshot waits here for the worktree, so it only finishes because +/// the worktree is added beside it. The workspace's head is new to the +/// clone, so the worktree starts at what origin has of the branch. +#[test] +fn the_worktree_is_added_while_the_snapshot_runs() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let (pushed, _) = send_to_a_workspace(&f); + let checkout = f.checkout(0); + write(&checkout, "remote.txt", "made remotely\n"); + let head = commit(&checkout, "made remotely"); + write( + &checkout, + "partial.txt", + "one\ntwo\nthree\nfour\nfive\nsix\n", + ); + let expected = observe(&checkout); + let worktree = worktree_path(&f); + let seen = hold_the_snapshot_for(&f, &worktree); + + f.transfer(true).result.expect("to local"); + + assert_eq!(*seen.lock().unwrap(), vec![true], "added by the snapshot"); + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert_eq!(observe(&worktree), expected); + assert!( + switched_from(&worktree, &pushed), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(temp_refs(&worktree), ""); +} + +/// The worktree is in the undo list before it is made, which is now before +/// the snapshot: a transfer cut off anywhere after has it to remove. +#[test] +fn the_undo_list_names_the_worktree_before_the_snapshot_starts() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + send_to_a_workspace(&f); + let recorded = Mutex::new(None); + + let transfer = f.transfer_with(true, &|progress| { + if progress.phase != TransferPhase::Snapshotting || recorded.lock().unwrap().is_some() { + return; + } + let dir = f.host.root.join("transfers").join(&progress.transfer_id); + let undo = backups::read_manifest(&dir).expect("manifest").undo; + *recorded.lock().unwrap() = Some(undo.worktrees); + }); + + transfer.result.expect("to local"); + assert_eq!( + recorded.into_inner().unwrap(), + Some(vec![AddedWorktree { + clone: f.host.clone_of(WIDGETS), + worktree: worktree_path(&f), + }]) + ); +} + +/// The snapshot fails once the early worktree is there: the leg waits for +/// the add, and the rollback removes what it made. +#[test] +fn a_snapshot_that_fails_after_the_early_add_leaves_no_worktree() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + send_to_a_workspace(&f); + let clone = f.host.clone_of(WIDGETS); + let (db, before) = (f.db_state(), clone_state(&clone)); + let source = source_fingerprint(&f.checkout(0)); + let seen = hold_the_snapshot_for(&f, &worktree_path(&f)); + f.host + .arm(Fault::Script(Side::Workspace, SNAPSHOT_SCRIPT, 1)); + + let transfer = f.transfer(true); + + let err = transfer.result.unwrap_err(); + assert!(f.host.fired(), "{err}"); + assert_eq!(*seen.lock().unwrap(), vec![true], "the worktree was there"); + assert!(f.worktree_dirs().is_empty(), "{:?}", f.worktree_dirs()); + assert_eq!(clone_state(&clone), before); + assert_eq!(f.db_state(), db); + assert_eq!(source_fingerprint(&f.checkout(0)), source); + let manifest = f.manifest(&transfer.transfer_id).expect("manifest"); + assert_eq!(manifest.status, "rolledBack"); +} + +/// The early worktree starts at the head the inspection saw; a commit made +/// in the workspace after that comes with the snapshot, and the switch +/// takes the worktree to it. +#[test] +fn a_head_that_moves_after_the_inspection_still_lands_in_the_worktree() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let (_, inspected) = send_to_a_workspace(&f); + let checkout = f.checkout(0); + let moved = Arc::new(Mutex::new(None)); + let (source, late) = (checkout.clone(), Arc::clone(&moved)); + f.host.before(Side::Workspace, SNAPSHOT_SCRIPT, 1, move || { + write(&source, "late.txt", "after the inspection\n"); + write(&source, "a.txt", "alpha, later\n"); + let head = commit(&source, "late"); + *late.lock().unwrap() = Some((head, observe(&source))); + }); + + f.transfer(true).result.expect("to local"); + + let (head, expected) = moved.lock().unwrap().take().expect("the head moved"); + assert_ne!(head, inspected); + let worktree = worktree_on_feature_at(&f, &head); + assert_eq!(observe(&worktree), expected); + assert!( + switched_from(&worktree, &inspected), + "{:?}", + head_moves(&worktree) + ); +} + +/// An early add that fails part way, leaving a directory behind, costs +/// nothing but the head start: the leg clears it and adds the worktree on +/// the branch at the same path. +#[test] +fn an_early_add_that_fails_falls_back_to_adding_the_worktree_late() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let (_, head) = send_to_a_workspace(&f); + let expected = observe(&f.checkout(0)); + let failing = FailingEarlyAdds::for_this_thread(); + + let transfer = f.transfer(true); + drop(failing); + + transfer.result.expect("to local"); + // At the path that was recorded, and nowhere else. + let worktree = worktree_on_feature_at(&f, &head); + assert_eq!(f.worktree_dirs(), vec![worktree.clone()]); + assert_eq!(observe(&worktree), expected); + assert!( + added_on_its_branch(&worktree), + "{:?}", + head_moves(&worktree) + ); + assert!(!worktree.join("half-added").exists()); +} + +/// The inspection saw no LFS objects, so the early worktree was added with +/// the smudge filter on; by the snapshot the checkout has an LFS file. The +/// leg discards the early worktree and adds one the way a snapshot with LFS +/// objects needs: pointers first, for the finish to replace. +#[test] +fn a_wrong_guess_about_lfs_falls_back_to_adding_the_worktree_late() { + if !lfs_installed("a_wrong_guess_about_lfs_falls_back_to_adding_the_worktree_late") { + return; + } + let f = lfs_project(); + let (_, head) = send_to_a_workspace(&f); + assert_eq!(f.preflight().repos[0].lfs_present, 0); + let art = noise(1800, 41); + let (source, content) = (f.checkout(0), art.clone()); + let seen = hold_the_snapshot_for(&f, &worktree_path(&f)); + f.host.before(Side::Workspace, SNAPSHOT_SCRIPT, 1, move || { + track_psd(&source); + write(&source, "art/new.psd", &content); + }); + + let result = f.transfer(true).result.expect("to local"); + + assert_eq!(*seen.lock().unwrap(), vec![true], "an early worktree"); + let worktree = worktree_on_feature_at(&f, &head); + assert!( + added_on_its_branch(&worktree), + "{:?}", + head_moves(&worktree) + ); + let actual = fs::read(worktree.join("art/new.psd")).unwrap(); + assert!(!actual.starts_with(POINTER_PREFIX), "a pointer"); + assert!(actual == art, "other content"); + assert!( + !codes(&result.repos[0].warnings) + .iter() + .any(|c| c.starts_with("lfs")), + "{:?}", + result.repos[0].warnings + ); +} diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/lfs.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/lfs.rs index b386ac49c..57d33c96e 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/lfs.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/lfs.rs @@ -8,7 +8,7 @@ use super::*; /// A single-repo project whose scripts see no git config but the clones' /// own, like Blox: git-lfs installed, no LFS filter set up anywhere. -fn lfs_project() -> Fixture { +pub(super) fn lfs_project() -> Fixture { let f = Fixture::new(&[(WIDGETS, "feature")]); for (key, value) in isolated_config(&f.host.root) { f.host diff --git a/apps/staged/src-tauri/src/project_transfer/undo.rs b/apps/staged/src-tauri/src/project_transfer/undo.rs index 1452e92c6..6580b89a6 100644 --- a/apps/staged/src-tauri/src/project_transfer/undo.rs +++ b/apps/staged/src-tauri/src/project_transfer/undo.rs @@ -430,8 +430,9 @@ fn restore_branch_config( } /// Remove a worktree the transfer added, without `remove_worktree`'s branch -/// deletion: the branch is the rollback's to decide about. -fn remove_worktree_keeping_branch(clone: &Path, worktree: &Path) -> Result<(), String> { +/// deletion: the branch is the rollback's to decide about. A directory git +/// does not know as a worktree, such as an add left part way, goes too. +pub(super) fn remove_worktree_keeping_branch(clone: &Path, worktree: &Path) -> Result<(), String> { let Some(path) = worktree.to_str() else { return Err(format!("not a UTF-8 path: {}", worktree.display())); }; diff --git a/apps/staged/src-tauri/src/shell_env.rs b/apps/staged/src-tauri/src/shell_env.rs index 2d61b39c6..039cff824 100644 --- a/apps/staged/src-tauri/src/shell_env.rs +++ b/apps/staged/src-tauri/src/shell_env.rs @@ -51,6 +51,7 @@ mod leftover_group; mod capture_limit_tests; use capture_slots::{CaptureSlots, Urgency, CAPTURE_LIMIT}; +pub(crate) use env_root::env_root_inputs; use env_root::resolve_env_root; use leftover_group::{LeftoverState, Leftovers}; diff --git a/apps/staged/src-tauri/src/shell_env/env_root.rs b/apps/staged/src-tauri/src/shell_env/env_root.rs index 4131d9b38..7c37e342d 100644 --- a/apps/staged/src-tauri/src/shell_env/env_root.rs +++ b/apps/staged/src-tauri/src/shell_env/env_root.rs @@ -47,6 +47,15 @@ pub(super) const DIR_ENV_MARKERS: &[&str] = &[ ".ruby-version", ]; +/// What a capture at an env root reads from the root itself, as paths +/// relative to it: Hermit's `bin/`, whose `activate-hermit` and package +/// stubs decide what the shell gets, and the [`DIR_ENV_MARKERS`]. A root +/// whose content changes under a snapshot without touching any of these +/// still has the env that snapshot holds. +pub(crate) fn env_root_inputs() -> impl Iterator { + std::iter::once("bin").chain(DIR_ENV_MARKERS.iter().copied()) +} + /// Resolve the directory whose captured env `dir` can share: its env root. /// /// Walking up from `dir` itself, the first directory that is a Hermit root From 9f1e859f7399c9a849ae8a4b39fc90f1bbddd870 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Tue, 17 Nov 2026 15:38:30 +1100 Subject: [PATCH 2/4] fix(staged): keep an early transfer worktree safe to remove and new to hooks A transfer from Blox adds each branch's worktree while the capture still runs and starts a shell-environment capture in it. Review of that change found four things to fix. Rollback could delete the worktree while that capture's login shell was still starting inside it, since the leg joined the add but not the capture. Whatever the shell wrote could stop the removal or bring the directory back. The shell-environment cache has no way to stop a capture, so it gains `wait_out_and_invalidate`: wait for the capture in flight for a directory, never starting one, then drop what is cached. The shared removal routine calls it first, which covers rollback, startup recovery and the fallback alike, and replaces the fallback's own wait. A cancel during the prewarm now takes up to one capture longer. A capture made stale by the switch is waited out the same way instead of being dropped while it runs, so no second shell starts beside it and none is left where a later removal cannot wait for it. A `git worktree add` killed part way leaves an entry locked with the reason `initializing`. A singly forced removal refuses it, a prune keeps it, and every later add at that path fails. The removal routine now forces twice, and unlocks before pruning when that fails too. `post-checkout` fired from the switch, so it was told the start commit was the previous head, and for a fully pushed branch got the same commit twice. A hook that sets up a new worktree on seeing the null id did nothing. Hooks are now off for the switch as well, and the hook is fired once afterwards by `git hook run` with what `git worktree add ` passes: the null id, the head and `1`. A hook that fails there fails the leg, as it fails `git worktree add`, rather than falling back to an add that would fire it again. `git hook run` needs git 2.36, so a leg whose git lacks it plans no early worktree and adds late as before. One difference remains: git exports `GIT_DIR` to a hook it fires inside a linked worktree, where `git worktree add` clears it. The path with no early worktree now also drops what is cached for its path before adding, as the early path does. Tests: a gate holds the early add until the snapshot has started and the snapshot until the add has finished, so the overlap is proven rather than only the missing dependency. Hook tests record the arguments on both paths and compare them with a worktree git added itself, cover the equal-commits case, a failing hook and a git without `git hook run`. A real `git worktree add` is killed in a smudge filter to reproduce the locked entry, with and without its directory, and removal plus a re-add at the same path are checked. The shell-environment calls, no-ops under test, are now recorded per watched directory with whether the path existed, which pins the wait before the removal on rollback and on the fallback, and the wait before a recapture. The cache method is tested against a real held shell. Signed-off-by: Matt Toohey Co-Authored-By: Claude Fable 5.2 --- apps/staged/src-tauri/src/git/cli.rs | 97 +++++- apps/staged/src-tauri/src/git/mod.rs | 15 +- apps/staged/src-tauri/src/git/worktree.rs | 237 +++++++++++-- .../src/project_transfer/orchestrator.rs | 6 +- .../orchestrator/early_worktree.rs | 125 ++++--- .../orchestrator/early_worktree/seams.rs | 150 +++++++++ .../orchestrator_tests/early_worktree.rs | 316 +++++++++++++++++- .../src-tauri/src/project_transfer/undo.rs | 170 +++++++++- apps/staged/src-tauri/src/shell_env.rs | 40 +++ .../src-tauri/src/shell_env/wait_out_tests.rs | 113 +++++++ 10 files changed, 1176 insertions(+), 93 deletions(-) create mode 100644 apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree/seams.rs create mode 100644 apps/staged/src-tauri/src/shell_env/wait_out_tests.rs diff --git a/apps/staged/src-tauri/src/git/cli.rs b/apps/staged/src-tauri/src/git/cli.rs index 8c4f4ed52..c5b0d2b31 100644 --- a/apps/staged/src-tauri/src/git/cli.rs +++ b/apps/staged/src-tauri/src/git/cli.rs @@ -277,6 +277,8 @@ pub fn run_smart(repo: &Path, args: &[&str]) -> Result { /// Use this when a caller has already resolved the directory a future /// captured-env operation will need, but has no git read to run there yet. pub(crate) fn prewarm_shell_env(repo: &Path) { + #[cfg(test)] + shell_env_calls::record("prewarm", repo); warm_shell_env(repo); } @@ -292,11 +294,14 @@ pub(crate) fn wait_for_shell_env(repo: &Path) { } #[cfg(test)] -pub(crate) fn wait_for_shell_env(_repo: &Path) {} +pub(crate) fn wait_for_shell_env(repo: &Path) { + shell_env_calls::record("wait", repo); +} /// Drop the captured shell env `repo` uses, or the capture in flight for -/// it, so the next captured-env op there captures afresh. For a caller that -/// changed what the capture reads after it started. +/// it, so the next captured-env op there captures afresh. A capture in +/// flight runs on, uncounted; a caller that changed what it reads, or is +/// about to delete `repo`, wants [`wait_out_and_invalidate_shell_env`]. /// /// A no-op under unit tests, like [`prewarm_shell_env`]. #[cfg(not(test))] @@ -305,7 +310,91 @@ pub(crate) fn invalidate_shell_env(repo: &Path) { } #[cfg(test)] -pub(crate) fn invalidate_shell_env(_repo: &Path) {} +pub(crate) fn invalidate_shell_env(repo: &Path) { + shell_env_calls::record("invalidate", repo); +} + +/// [`invalidate_shell_env`] once the capture in flight for `repo`, if there +/// is one, has finished: its shell is running in `repo`, so this is for a +/// caller about to delete the directory, or to capture it again. Never +/// starts a capture. A capture can't be stopped early, so this can take as +/// long as one does (see +/// [`ShellEnvCache::wait_out_and_invalidate`](crate::shell_env::ShellEnvCache::wait_out_and_invalidate)). +/// +/// A no-op under unit tests, like [`prewarm_shell_env`]. +#[cfg(not(test))] +pub(crate) fn wait_out_and_invalidate_shell_env(repo: &Path) { + crate::session_runner::shell_env_cache().wait_out_and_invalidate(repo); +} + +#[cfg(test)] +pub(crate) fn wait_out_and_invalidate_shell_env(repo: &Path) { + shell_env_calls::record("wait out and invalidate", repo); +} + +/// What the shell-env entry points above were asked for, since they do +/// nothing under unit tests: a test that cares in what order a caller used +/// them, and whether a directory was still there when it did, watches a +/// directory of its own. +#[cfg(test)] +pub(crate) mod shell_env_calls { + use std::path::{Path, PathBuf}; + use std::sync::Mutex; + + /// One call, for a path under a watched directory. + #[derive(Debug, Clone, PartialEq, Eq)] + pub(crate) struct Call { + /// `prewarm`, `wait`, `invalidate` or `wait out and invalidate`. + pub(crate) what: &'static str, + pub(crate) path: PathBuf, + /// Whether `path` existed when the call was made. + pub(crate) existed: bool, + } + + static WATCHED: Mutex)>> = Mutex::new(Vec::new()); + + /// While it lives, calls for paths under its directory are kept, from + /// whichever thread makes them. + pub(crate) struct Watch(PathBuf); + + impl Watch { + pub(crate) fn under(dir: &Path) -> Self { + let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); + watched.push((dir.to_path_buf(), Vec::new())); + Self(dir.to_path_buf()) + } + + /// The calls so far, in order. + pub(crate) fn calls(&self) -> Vec { + let watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); + watched + .iter() + .find(|(dir, _)| *dir == self.0) + .map(|(_, calls)| calls.clone()) + .unwrap_or_default() + } + } + + impl Drop for Watch { + fn drop(&mut self) { + let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); + watched.retain(|(dir, _)| *dir != self.0); + } + } + + pub(super) fn record(what: &'static str, path: &Path) { + let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); + for (dir, calls) in watched.iter_mut() { + if path.starts_with(dir.as_path()) { + calls.push(Call { + what, + path: path.to_path_buf(), + existed: path.exists(), + }); + } + } + } +} /// Which environment to pass to the spawned git process. /// diff --git a/apps/staged/src-tauri/src/git/mod.rs b/apps/staged/src-tauri/src/git/mod.rs index e9bf5016c..4e8215b9c 100644 --- a/apps/staged/src-tauri/src/git/mod.rs +++ b/apps/staged/src-tauri/src/git/mod.rs @@ -23,7 +23,10 @@ pub(crate) use cli::prewarm_shell_env; pub(crate) use cli::run as cli_run; pub(crate) use cli::run_lite_or_captured as cli_run_lite_or_captured; pub(crate) use cli::run_smart as cli_run_smart; +#[cfg(test)] +pub(crate) use cli::shell_env_calls; pub(crate) use cli::wait_for_shell_env; +pub(crate) use cli::wait_out_and_invalidate_shell_env; pub use cli::{EnvSource, GitError}; pub use commit::commit; pub use diff::{get_file_diff, get_unified_diff, list_diff_files}; @@ -61,8 +64,8 @@ pub use types::*; pub use upstream::{upstream_branch_name, upstream_branch_name_with}; pub(crate) use worktree::force_delete_branch; pub use worktree::{ - branch_exists, create_detached_worktree_without_hooks, create_worktree, - create_worktree_at_path, create_worktree_for_existing_branch, + branch_exists, can_run_hooks_on_request, create_detached_worktree_without_hooks, + create_worktree, create_worktree_at_path, create_worktree_for_existing_branch, create_worktree_for_existing_branch_at_path, create_worktree_for_existing_branch_without_lfs_smudge, create_worktree_from_pr, create_worktree_from_pr_at_path, discard_worktree_changes, fetch_origin_branch, @@ -70,8 +73,8 @@ pub use worktree::{ get_parent_commit, has_unpushed_commits, has_upstream, list_worktree_change_paths, list_worktrees, move_worktree, parse_branch_commit_line, parse_worktree_status_paths, project_worktree_path_for, project_worktree_root_for, remote_branch_exists, remove_worktree, - reset_to_commit, set_upstream_to_origin, set_upstream_to_origin_or_unset, switch_branch, - switch_detached_worktree_to_branch, update_branch_from_pr, worktree_path_for, - BranchCommitFields, CommitInfo, UpdateFromPrResult, WorktreeChangePaths, - BRANCH_COMMIT_LOG_FORMAT, + reset_to_commit, run_post_checkout_as_for_a_new_worktree, set_upstream_to_origin, + set_upstream_to_origin_or_unset, switch_branch, switch_detached_worktree_to_branch, + update_branch_from_pr, worktree_path_for, BranchCommitFields, CommitInfo, UpdateFromPrResult, + WorktreeChangePaths, BRANCH_COMMIT_LOG_FORMAT, }; diff --git a/apps/staged/src-tauri/src/git/worktree.rs b/apps/staged/src-tauri/src/git/worktree.rs index e9a55780e..9dade16e1 100644 --- a/apps/staged/src-tauri/src/git/worktree.rs +++ b/apps/staged/src-tauri/src/git/worktree.rs @@ -210,7 +210,8 @@ fn add_worktree_for_existing_branch( /// /// For a worktree made before its branch exists: /// [`switch_detached_worktree_to_branch`] puts it on the branch later, and -/// that checkout is the one `post-checkout` should see. `skip_lfs_smudge` +/// [`run_post_checkout_as_for_a_new_worktree`] then fires the one +/// `post-checkout` a worktree added on the branch would have. `skip_lfs_smudge` /// checks LFS files out as pointers, as /// [`create_worktree_for_existing_branch_without_lfs_smudge`] does. pub fn create_detached_worktree_without_hooks( @@ -231,7 +232,7 @@ pub fn create_detached_worktree_without_hooks( repo, &[ "-c", - "core.hooksPath=/dev/null", + HOOKS_OFF, "worktree", "add", "--detach", @@ -246,7 +247,12 @@ pub fn create_detached_worktree_without_hooks( /// Check `branch_name` out in `worktree_path`, a clean worktree of `repo` /// detached at some other commit: only the files that differ are rewritten. -/// Hooks fire, as they do for a worktree added on the branch. +/// +/// Hooks stay off. The `post-checkout` this checkout would fire names the +/// commit the worktree was detached at as the previous head, where a +/// worktree added on the branch names none, so a hook that sets a new +/// worktree up on seeing that would do nothing. +/// [`run_post_checkout_as_for_a_new_worktree`] fires it instead. /// /// Runs in the worktree but with `repo`'s captured env, the one /// [`create_worktree_for_existing_branch_at_path`] gives the hooks and @@ -261,17 +267,90 @@ pub fn switch_detached_worktree_to_branch( .to_str() .ok_or_else(|| GitError::InvalidPath(worktree_path.display().to_string()))?; - // git -C checkout -- + // git -c core.hooksPath=/dev/null -C checkout -- // The second `-C` is absolute, so it replaces the `-C ` that // `cli` puts first; `--` keeps a file of the same name out of it. cli::run_with_vars( repo, - &["-C", worktree_str, "checkout", branch_name, "--"], + &[ + "-c", + HOOKS_OFF, + "-C", + worktree_str, + "checkout", + branch_name, + "--", + ], lfs_smudge_vars(skip_lfs_smudge), )?; Ok(()) } +/// Whether `repo`'s git can fire a hook on request, with `git hook run` +/// (git 2.36 and later), which [`run_post_checkout_as_for_a_new_worktree`] +/// needs. A git that cannot say counts as one that can't. +pub fn can_run_hooks_on_request(repo: &Path) -> bool { + cli::run(repo, &["--list-cmds=builtins"]).is_ok_and(|builtins| lists_hook_command(&builtins)) +} + +fn lists_hook_command(builtins: &str) -> bool { + builtins.lines().any(|command| command.trim() == "hook") +} + +/// Fire `post-checkout` in `worktree_path`, a worktree of `repo` made by +/// [`create_detached_worktree_without_hooks`] and +/// [`switch_detached_worktree_to_branch`], with the arguments `git worktree +/// add ` gives it: the null object id as the previous head, +/// the worktree's head, and `1` for a branch checkout. Hooks tell a new +/// worktree by that null id, and some do their setup only then. +/// +/// The hook is found and run by `git hook run`, so `core.hooksPath` and the +/// rest apply as they would have; check [`can_run_hooks_on_request`] before +/// building a worktree this way. It runs at the worktree's root with +/// `repo`'s captured env, and `GIT_LFS_SKIP_SMUDGE` when the checkout had +/// it, as under `git worktree add`. One difference remains: git exports +/// `GIT_DIR` to it, as it does to every hook it fires from inside a linked +/// worktree, where `git worktree add` clears it. +/// +/// No hook is success. A hook that fails is the error, as it fails `git +/// worktree add`; the worktree stays as it is. +pub fn run_post_checkout_as_for_a_new_worktree( + repo: &Path, + worktree_path: &Path, + skip_lfs_smudge: bool, +) -> Result<(), GitError> { + let worktree_str = worktree_path + .to_str() + .ok_or_else(|| GitError::InvalidPath(worktree_path.display().to_string()))?; + + let head = cli::run(repo, &["-C", worktree_str, "rev-parse", "--verify", "HEAD"])?; + let head = head.trim(); + // As long as the repo's object ids are: 40 zeros, or 64 under SHA-256. + let no_previous_head = "0".repeat(head.len()); + + // git -C hook run --ignore-missing post-checkout -- 1 + cli::run_with_vars( + repo, + &[ + "-C", + worktree_str, + "hook", + "run", + "--ignore-missing", + "post-checkout", + "--", + &no_previous_head, + head, + "1", + ], + lfs_smudge_vars(skip_lfs_smudge), + )?; + Ok(()) +} + +/// `-c` value that keeps every hook from firing. +const HOOKS_OFF: &str = "core.hooksPath=/dev/null"; + fn lfs_smudge_vars(skip: bool) -> &'static [(&'static str, &'static str)] { if skip { &[("GIT_LFS_SKIP_SMUDGE", "1")] @@ -1343,15 +1422,68 @@ mod tests { let _ = std::fs::remove_dir_all(&to); } - /// The pair that builds a worktree before its branch exists: detached - /// at a commit the repo has, hooks off, then onto the branch, which is - /// the one checkout `post-checkout` sees. + /// Point `repo` at a `post-checkout` hook that appends its three + /// arguments and the directory it ran in to a log, then runs `then`. + /// Returns the log. #[cfg(unix)] - #[test] - fn a_detached_worktree_goes_onto_its_branch_with_one_post_checkout() { + fn recording_post_checkout( + repo: &crate::test_utils::TempGitRepo, + root: &Path, + then: &str, + ) -> std::path::PathBuf { use std::os::unix::fs::PermissionsExt; + let hooks = root.join("hooks"); + let log = root.join("post-checkout.log"); + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("post-checkout"); + std::fs::write( + &hook, + format!( + "#!/bin/sh\necho \"$1 $2 $3 $(pwd -P)\" >> '{}'\n{then}\n", + log.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + repo.run_git(&["config", "core.hooksPath", hooks.to_str().unwrap()]); + log + } + + #[cfg(unix)] + fn logged(log: &Path) -> Vec { + std::fs::read_to_string(log) + .unwrap_or_default() + .lines() + .map(str::to_string) + .collect() + } + + /// Whether this machine's git has `git hook run`; says so when not. + #[cfg(unix)] + fn git_runs_hooks_on_request(repo: &Path, test: &str) -> bool { + let can = can_run_hooks_on_request(repo); + if !can { + eprintln!("skipping {test}: this git has no `git hook run`"); + } + can + } + + /// The three steps that build a worktree before its branch exists: + /// detached at a commit the repo has, onto the branch, then the hook. + /// `post-checkout` fires once, at the end, and is told what `git + /// worktree add ` tells it, which is checked here against + /// a worktree git added that way. + #[cfg(unix)] + #[test] + fn a_detached_worktree_goes_onto_its_branch_looking_new_to_post_checkout() { let repo = crate::test_utils::TempGitRepo::new(); + if !git_runs_hooks_on_request( + repo.path(), + "a_detached_worktree_goes_onto_its_branch_looking_new_to_post_checkout", + ) { + return; + } repo.write_file("tracked.txt", "base\n"); // A file named as the branch: the switch must not take it for one. repo.write_file("feature", "a file\n"); @@ -1360,17 +1492,7 @@ mod tests { let tip = repo.commit("tip"); let root = crate::test_utils::TempDir::new("detached-worktree"); - let hooks = root.path().join("hooks"); - let log = root.path().join("post-checkout.log"); - std::fs::create_dir_all(&hooks).unwrap(); - let hook = hooks.join("post-checkout"); - std::fs::write( - &hook, - format!("#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n", log.display()), - ) - .unwrap(); - std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - repo.run_git(&["config", "core.hooksPath", hooks.to_str().unwrap()]); + let log = recording_post_checkout(&repo, root.path(), ""); let worktree = root.path().join("wt"); let on = |wt: &Path| { cli::run(wt, &["rev-parse", "--abbrev-ref", "HEAD"]) @@ -1378,6 +1500,7 @@ mod tests { .trim() .to_string() }; + let real = |wt: &Path| std::fs::canonicalize(wt).unwrap().display().to_string(); create_detached_worktree_without_hooks(repo.path(), &base, &worktree, false).unwrap(); @@ -1386,7 +1509,7 @@ mod tests { std::fs::read_to_string(worktree.join("tracked.txt")).unwrap(), "base\n" ); - assert!(!log.exists(), "the detached add fired the hook"); + assert_eq!(logged(&log), [""; 0], "the detached add fired the hook"); repo.run_git(&["branch", "feature", &tip]); switch_detached_worktree_to_branch(repo.path(), &worktree, "feature", false).unwrap(); @@ -1397,15 +1520,79 @@ mod tests { "tip\n" ); assert_eq!(cli::run(&worktree, &["status", "--porcelain"]).unwrap(), ""); + assert_eq!(logged(&log), [""; 0], "the switch fired the hook"); + + run_post_checkout_as_for_a_new_worktree(repo.path(), &worktree, false).unwrap(); + + let null = "0".repeat(tip.len()); + assert_eq!( + logged(&log), + [format!("{null} {tip} 1 {}", real(&worktree))], + "once, with no previous head, in the worktree" + ); + + // What git itself tells the hook of a worktree added on a branch. + repo.run_git(&["branch", "control", &tip]); + let control = root.path().join("control"); + create_worktree_for_existing_branch_at_path(repo.path(), "control", &control).unwrap(); assert_eq!( - std::fs::read_to_string(&log).unwrap(), - format!("{base} {tip} 1\n"), - "one branch checkout, from the start commit" + logged(&log)[1..], + [format!("{null} {tip} 1 {}", real(&control))], + "git's own arguments for a new worktree" ); + // The repo's own checkout is where it was. assert_eq!(on(repo.path()), "main"); } + /// The hook failing fails the step, as it fails `git worktree add`, and + /// it has still fired just the once. No hook at all is success. + #[cfg(unix)] + #[test] + fn a_post_checkout_that_fails_is_an_error_and_none_is_not() { + let repo = crate::test_utils::TempGitRepo::new(); + if !git_runs_hooks_on_request( + repo.path(), + "a_post_checkout_that_fails_is_an_error_and_none_is_not", + ) { + return; + } + repo.write_file("tracked.txt", "base\n"); + let base = repo.commit("base"); + repo.run_git(&["branch", "feature", &base]); + let root = crate::test_utils::TempDir::new("failing-post-checkout"); + let worktree = root.path().join("wt"); + let empty = root.path().join("no-hooks"); + std::fs::create_dir_all(&empty).unwrap(); + repo.run_git(&["config", "core.hooksPath", empty.to_str().unwrap()]); + create_detached_worktree_without_hooks(repo.path(), &base, &worktree, false).unwrap(); + switch_detached_worktree_to_branch(repo.path(), &worktree, "feature", false).unwrap(); + + run_post_checkout_as_for_a_new_worktree(repo.path(), &worktree, false) + .expect("no hook to run"); + + let log = recording_post_checkout(&repo, root.path(), "echo no good >&2\nexit 3"); + let err = run_post_checkout_as_for_a_new_worktree(repo.path(), &worktree, false) + .expect_err("the hook failed"); + assert!(err.to_string().contains("no good"), "{err}"); + assert_eq!(logged(&log).len(), 1, "{:?}", logged(&log)); + assert_eq!( + cli::run(&worktree, &["rev-parse", "--abbrev-ref", "HEAD"]) + .unwrap() + .trim(), + "feature", + "the worktree is left as it was" + ); + } + + #[test] + fn a_git_without_the_hook_command_cannot_run_hooks_on_request() { + assert!(lists_hook_command("add\nhook\nworktree\n")); + assert!(!lists_hook_command("add\nhooks\nworktree\n")); + // An older git that doesn't know the option prints nothing useful. + assert!(!lists_hook_command("")); + } + fn local_branches(repo: &crate::test_utils::TempGitRepo) -> String { repo.run_git(&["branch", "--list", "--format=%(refname:short)"]) } diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator.rs index 55cb507de..a1d156b05 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator.rs @@ -35,7 +35,7 @@ mod parallel; mod teardown; #[cfg(test)] -pub(crate) use early_worktree::FailingEarlyAdds; +pub(crate) use early_worktree::{FailingEarlyAdds, GatedEarlyAdds, GitWithoutHookRun}; #[cfg(test)] pub(crate) use parallel::SerialLegs; @@ -900,7 +900,9 @@ impl Run<'_> { (carried, early_add) }); // A capture that failed or was cancelled: what the early add made - // is in the undo list, for the rollback. + // is in the undo list, for the rollback. The capture of its shell + // environment may still be running in it; the rollback waits for + // that before it removes the worktree. let mut outcome = match (carried, not_recorded) { (Err(_), Some(e)) => return Err(e.into()), (carried, _) => carried?, diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs index 07fe0dd72..2cfa1dece 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs @@ -9,13 +9,21 @@ //! it only switches the worktree onto it, which rewrites the files that //! differ. //! +//! Hooks see none of that. They are off for the add and for the switch, +//! and `post-checkout` is then fired once, by `git hook run`, with what +//! `git worktree add ` tells it: no previous head. A hook +//! that sets a new worktree up on seeing that still does. +//! //! This is an optimisation with a complete fallback. A leg with no commit -//! to start from, an early add or a switch that fails, or a guess about -//! Git LFS the snapshot contradicts, all end in the sequence without it: -//! `git worktree add ` once the branch has landed. The -//! worktree is recorded in the undo list before the thread starts and the -//! thread is joined before the leg returns, so rollback and startup recovery -//! find it as they find a worktree added late. +//! to start from, a git too old to fire a hook on request, an early add or +//! a switch that fails, or a guess about Git LFS the snapshot contradicts, +//! all end in the sequence without it: `git worktree add ` +//! once the branch has landed. The worktree is recorded in the undo list +//! before the thread starts and the thread is joined before the leg +//! returns, so rollback and startup recovery find it as they find a +//! worktree added late. The capture of its shell environment runs on past +//! that join, in the worktree, so whatever removes the worktree waits for +//! it first ([`undo::remove_worktree_keeping_branch`]). use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -25,32 +33,10 @@ use super::super::undo::{self, AddedWorktree}; use super::{origin_tip_names, Failure, Leg, Run}; #[cfg(test)] -thread_local! { - /// A test's request that early adds planned from this thread fail. - static FAIL_EARLY_ADDS_FOR_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// While it lives, the early worktree adds of legs run from this thread -/// fail part way, leaving a directory git knows nothing of — for a test of -/// the fallback. The legs of a one-repository transfer, or of one under -/// [`super::SerialLegs`], run on the thread that runs the transfer. -#[cfg(test)] -pub(crate) struct FailingEarlyAdds; - -#[cfg(test)] -impl FailingEarlyAdds { - pub(crate) fn for_this_thread() -> Self { - FAIL_EARLY_ADDS_FOR_TEST.with(|f| f.set(true)); - Self - } -} +mod seams; #[cfg(test)] -impl Drop for FailingEarlyAdds { - fn drop(&mut self) { - FAIL_EARLY_ADDS_FOR_TEST.with(|f| f.set(false)); - } -} +pub(crate) use seams::{FailingEarlyAdds, GatedEarlyAdds, GitWithoutHookRun}; /// A worktree to add before its branch exists. Owns all it needs, so the /// thread adding it borrows nothing from the leg. @@ -63,7 +49,7 @@ pub(super) struct EarlyWorktree { /// LFS files check out as pointers for the finish to replace. skip_lfs_smudge: bool, #[cfg(test)] - fail: bool, + seams: seams::Seams, } /// How an early add went. @@ -75,7 +61,7 @@ pub(super) struct EarlyAdd { impl EarlyWorktree { /// Add the worktree, and start capturing its shell environment so the /// finish finds it cached or waits only for the rest. Hooks stay off: - /// `post-checkout` fires once, when the worktree goes onto its branch. + /// `post-checkout` fires once, when the worktree is on its branch. pub(super) fn add(&self) -> EarlyAdd { let started = Instant::now(); let result = self.add_detached(); @@ -85,6 +71,10 @@ impl EarlyWorktree { crate::git::invalidate_shell_env(&self.path); crate::git::prewarm_shell_env(&self.path); } + #[cfg(test)] + if let Some(gate) = &self.seams.gate { + gate.add_finished(); + } EarlyAdd { result, took: started.elapsed(), @@ -93,7 +83,11 @@ impl EarlyWorktree { fn add_detached(&self) -> Result<(), String> { #[cfg(test)] - if self.fail { + if let Some(gate) = &self.seams.gate { + gate.hold_the_add(); + } + #[cfg(test)] + if self.seams.fail_add { std::fs::create_dir_all(&self.path).map_err(|e| e.to_string())?; std::fs::write(self.path.join("half-added"), "").map_err(|e| e.to_string())?; return Err("injected failure".to_string()); @@ -115,6 +109,8 @@ pub(super) struct WorktreeTimings { /// The early add and the commit it started from. early_add: Option<(Duration, String)>, switch: Option, + /// The `post-checkout` fired once the early worktree was on its branch. + hook: Option, /// The add once the branch had landed: the only one, or the fallback's. late_add: Option, /// Why the early worktree was discarded, when it was. @@ -132,6 +128,9 @@ impl WorktreeTimings { if let Some(took) = self.switch { parts.push(format!("switch {took:.1?}")); } + if let Some(took) = self.hook { + parts.push(format!("post-checkout {took:.1?}")); + } if let Some(took) = self.late_add { parts.push(format!("late add {took:.1?}")); } @@ -177,6 +176,16 @@ pub(super) fn start_commit(clone: &Path, head: Option<&str>, refs: &[String]) -> .or_else(|| refs.iter().find_map(|r| commit(r))) } +/// Whether `clone`'s git can fire the `post-checkout` an early worktree +/// leaves for the end ([`crate::git::can_run_hooks_on_request`]). +fn fires_hooks_on_request(clone: &Path) -> bool { + #[cfg(test)] + if seams::Seams::of_this_thread().no_hook_run { + return false; + } + crate::git::can_run_hooks_on_request(clone) +} + /// Whether a shell environment captured in a worktree at `start` may differ /// from one captured after it moved to `head`: whether the two commits /// differ in anything a capture at the worktree's root reads @@ -210,6 +219,15 @@ impl Run<'_> { pub(super) fn plan_early_worktree(&self, leg: &Leg, clone: &Path) -> Option { let branch = &leg.dest_branch; let start = start_commit(clone, leg.row.head.as_deref(), &start_refs(leg))?; + if !fires_hooks_on_request(clone) { + // Without it `post-checkout` could only fire from the switch, + // which tells it the worktree came from the start commit. + log::info!( + "[project_transfer] no early worktree for {branch}: this git has no \ + `git hook run` to fire post-checkout with" + ); + return None; + } let planned = self.free_worktree_path(leg).and_then(|path| { self.record(|undo| { undo.worktrees.push(AddedWorktree { @@ -232,15 +250,19 @@ impl Run<'_> { start, skip_lfs_smudge: leg.row.lfs_present + leg.row.lfs_missing > 0, #[cfg(test)] - fail: FAIL_EARLY_ADDS_FOR_TEST.with(|f| f.get()), + seams: seams::Seams::of_this_thread(), }) } /// Once the leg's branch has landed: put it in its worktree. The early - /// worktree is switched onto the branch; without one, or when it or the - /// switch failed, or its LFS guess was wrong, the worktree is added on - /// the branch as it always was — at the early one's path, once that is - /// cleared. + /// worktree is switched onto the branch and `post-checkout` fired as for + /// a new worktree; without one, or when it or the switch failed, or its + /// LFS guess was wrong, the worktree is added on the branch as it always + /// was — at the early one's path, once that is cleared. + /// + /// `post-checkout` fires once either way. So a hook that fails after + /// the switch fails the leg, as it fails `git worktree add`, rather + /// than falling back to an add that would fire it again. pub(super) fn settle_worktree( &self, leg: &Leg, @@ -259,7 +281,6 @@ impl Run<'_> { let worktree = match early { Some((early, add)) => { timings.early_add = Some((add.took, early.start.clone())); - let added = add.result.is_ok(); let switching = Instant::now(); let switched = add .result @@ -295,8 +316,20 @@ impl Run<'_> { match switched { Ok(()) => { timings.switch = Some(switching.elapsed()); + let firing = Instant::now(); + crate::git::run_post_checkout_as_for_a_new_worktree( + &clone, + &early.path, + skip_lfs_smudge, + ) + .map_err(|e| format!("Cannot add the worktree for {branch}: {e}"))?; + timings.hook = Some(firing.elapsed()); if env_capture_is_stale(&clone, &early.start, &outcome.snapshot.head) { - crate::git::invalidate_shell_env(&early.path); + // The capture may still be running. Dropped now + // it would run on beside the one the finish + // starts, where nothing that removes the + // worktree could wait for it. + crate::git::wait_out_and_invalidate_shell_env(&early.path); } return Ok((early.path, timings)); } @@ -307,14 +340,11 @@ impl Run<'_> { self.guard.transfer_id(), early.path.display() ); - if added { - // The capture it started runs in the directory - // about to go. - crate::git::wait_for_shell_env(&early.path); - } + // Waits out the capture the early add started, + // which runs in the directory about to go, and + // drops its result. undo::remove_worktree_keeping_branch(&clone, &early.path) .map_err(|e| format!("Cannot add the worktree for {branch}: {e}"))?; - crate::git::invalidate_shell_env(&early.path); timings.fell_back = Some(why); early.path } @@ -328,6 +358,9 @@ impl Run<'_> { worktree: worktree.clone(), }) })?; + // As the early add does: whatever is cached for the path + // is from a worktree that was there before. + crate::git::invalidate_shell_env(&worktree); worktree } }; diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree/seams.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree/seams.rs new file mode 100644 index 000000000..fc44bdd82 --- /dev/null +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree/seams.rs @@ -0,0 +1,150 @@ +//! What tests reach into an early worktree with: a failure to inject, a +//! gate that proves the add and the snapshot overlap, and a git too old to +//! fire hooks on request. +//! +//! Each is asked for on the thread that runs the transfer and picked up +//! when a leg plans its worktree. The legs of a one-repository transfer, +//! or of one under [`super::super::SerialLegs`], run on that thread. + +use std::cell::RefCell; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +thread_local! { + static SEAMS: RefCell = RefCell::new(Seams::default()); +} + +/// What the early worktrees planned from a thread are to do differently. +#[derive(Clone, Default)] +pub(super) struct Seams { + pub(super) fail_add: bool, + pub(super) no_hook_run: bool, + pub(super) gate: Option>, +} + +impl Seams { + pub(super) fn of_this_thread() -> Self { + SEAMS.with(|seams| seams.borrow().clone()) + } + + fn change(change: impl FnOnce(&mut Seams)) { + SEAMS.with(|seams| change(&mut seams.borrow_mut())); + } +} + +/// While it lives, the early worktree adds of legs run from this thread +/// fail part way, leaving a directory git knows nothing of — for a test of +/// the fallback. +pub(crate) struct FailingEarlyAdds; + +impl FailingEarlyAdds { + pub(crate) fn for_this_thread() -> Self { + Seams::change(|seams| seams.fail_add = true); + Self + } +} + +impl Drop for FailingEarlyAdds { + fn drop(&mut self) { + Seams::change(|seams| seams.fail_add = false); + } +} + +/// While it lives, legs run from this thread find a git that cannot fire a +/// hook on request (one before 2.36), so they plan no early worktree. +pub(crate) struct GitWithoutHookRun; + +impl GitWithoutHookRun { + pub(crate) fn for_this_thread() -> Self { + Seams::change(|seams| seams.no_hook_run = true); + Self + } +} + +impl Drop for GitWithoutHookRun { + fn drop(&mut self) { + Seams::change(|seams| seams.no_hook_run = false); + } +} + +/// While it lives, the early worktree adds of legs run from this thread +/// wait at its [`EarlyAddGate`]. +pub(crate) struct GatedEarlyAdds(Arc); + +impl GatedEarlyAdds { + pub(crate) fn for_this_thread() -> Self { + let gate = Arc::new(EarlyAddGate::default()); + Seams::change(|seams| seams.gate = Some(Arc::clone(&gate))); + Self(gate) + } + + pub(crate) fn gate(&self) -> Arc { + Arc::clone(&self.0) + } +} + +impl Drop for GatedEarlyAdds { + fn drop(&mut self) { + Seams::change(|seams| seams.gate = None); + } +} + +/// Holds an early add until the leg's snapshot has started, and that +/// snapshot until the add has finished, so a test can tell the two ran at +/// once: an add made before the capture starts never sees the snapshot +/// start, and one made after it never finishes inside it. Either wait gives +/// up after [`EarlyAddGate::PATIENCE`] and says so. +#[derive(Default)] +pub(crate) struct EarlyAddGate { + state: Mutex, + changed: Condvar, +} + +#[derive(Default)] +struct GateState { + snapshot_started: bool, + /// Whether the snapshot had started when the add went ahead, once it + /// has. + add_began_in_the_snapshot: Option, + add_finished: bool, +} + +impl EarlyAddGate { + const PATIENCE: Duration = Duration::from_secs(20); + + /// For the test's script hook, at the start of the snapshot: let the + /// add go, and hold the snapshot until the add has finished. Returns + /// whether it did. + pub(crate) fn snapshot_started(&self) -> bool { + let mut state = self.state.lock().unwrap(); + state.snapshot_started = true; + self.changed.notify_all(); + let (state, _) = self + .changed + .wait_timeout_while(state, Self::PATIENCE, |state| !state.add_finished) + .unwrap(); + state.add_finished + } + + /// Whether the snapshot had started when the add went ahead; `None` if + /// no add came to the gate. + pub(crate) fn add_began_in_the_snapshot(&self) -> Option { + self.state.lock().unwrap().add_began_in_the_snapshot + } + + /// The add, before it does anything: wait for the snapshot to start. + pub(super) fn hold_the_add(&self) { + let state = self.state.lock().unwrap(); + let (mut state, _) = self + .changed + .wait_timeout_while(state, Self::PATIENCE, |state| !state.snapshot_started) + .unwrap(); + state.add_began_in_the_snapshot = Some(state.snapshot_started); + } + + /// The add, with the worktree made and its capture started. + pub(super) fn add_finished(&self) { + self.state.lock().unwrap().add_finished = true; + self.changed.notify_all(); + } +} diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs index e4ca682c8..b077a1e34 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs @@ -5,14 +5,19 @@ //! //! A worktree that went the early way shows it in its `HEAD` reflog: one //! added on the branch never moved from another commit. +//! +//! The shell-environment calls do nothing under test, so what these tests +//! see of them is which were made for the worktree, in what order, and +//! whether the worktree was there at the time. use std::time::{Duration, Instant}; -use super::super::orchestrator::FailingEarlyAdds; +use super::super::orchestrator::{FailingEarlyAdds, GatedEarlyAdds, GitWithoutHookRun}; use super::super::tests::lfs::{lfs_installed, track_psd, POINTER_PREFIX}; use super::super::undo::AddedWorktree; use super::lfs::lfs_project; use super::*; +use crate::git::shell_env_calls::Watch; /// Take `f`'s one branch, `feature`, to a workspace: pushed, then a commit /// ahead of origin, with an untracked file. Returns the pushed tip and the @@ -55,6 +60,80 @@ fn hold_the_snapshot_for(f: &Fixture, worktree: &Path) -> Arc>> seen } +/// Make the early add and the snapshot wait for each other (see +/// [`super::super::orchestrator::GatedEarlyAdds`]). Returns, per snapshot, +/// whether the add finished while it was held. +fn gate_the_early_add(f: &Fixture) -> (GatedEarlyAdds, Arc>>) { + let gated = GatedEarlyAdds::for_this_thread(); + let finished = Arc::new(Mutex::new(Vec::new())); + let (gate, seen) = (gated.gate(), Arc::clone(&finished)); + f.host.on_every_script(move |side, script| { + if side == Side::Workspace && script == SNAPSHOT_SCRIPT { + let finished = gate.snapshot_started(); + seen.lock().unwrap().push(finished); + } + }); + (gated, finished) +} + +/// Give the clone a `post-checkout` hook that logs its three arguments and +/// then runs `then`. Returns the log. +fn record_post_checkout(f: &Fixture, then: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + + let hooks = f.host.root.join("hooks"); + let log = f.host.root.join("post-checkout.log"); + fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("post-checkout"); + fs::write( + &hook, + format!( + "#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n{then}\n", + log.display() + ), + ) + .unwrap(); + fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap(); + git( + &f.host.clone_of(WIDGETS), + &["config", "core.hooksPath", path(&hooks)], + ); + log +} + +fn lines(log: &Path) -> Vec { + fs::read_to_string(log) + .unwrap_or_default() + .lines() + .map(str::to_string) + .collect() +} + +/// What `post-checkout` is told of a worktree new on a branch at `head`. +fn new_worktree_at(head: &str) -> String { + format!("{} {head} 1", "0".repeat(head.len())) +} + +/// The shell-environment calls made for `worktree`, in order, each with +/// whether the worktree existed then. +fn shell_env_calls(watch: &Watch, worktree: &Path) -> Vec<(&'static str, bool)> { + watch + .calls() + .into_iter() + .filter(|call| call.path == worktree) + .map(|call| (call.what, call.existed)) + .collect() +} + +/// A commit made in the workspace's checkout, which the clone has never +/// seen: the early worktree starts at what origin has, and the switch has +/// files to rewrite. `file` is one the commit adds. +fn commit_in_the_workspace(f: &Fixture, file: &str) -> String { + let checkout = f.checkout(0); + write(&checkout, file, "made remotely\n"); + commit(&checkout, "made remotely") +} + /// Every move of the worktree's `HEAD`, as its reflog words them. fn head_moves(worktree: &Path) -> Vec { git(worktree, &["reflog", "--format=%gs", "HEAD"]) @@ -90,16 +169,19 @@ fn worktree_on_feature_at(f: &Fixture, head: &str) -> PathBuf { worktree } -/// The snapshot waits here for the worktree, so it only finishes because -/// the worktree is added beside it. The workspace's head is new to the +/// The add and the snapshot wait for each other: the add does nothing +/// until the snapshot has started, and the snapshot goes no further until +/// the add is done. So the transfer only gets through with the add running +/// inside the snapshot, on a thread of its own: an add made before the +/// capture would never see the snapshot start, and one made after it would +/// not finish while the snapshot waits. The workspace's head is new to the /// clone, so the worktree starts at what origin has of the branch. #[test] fn the_worktree_is_added_while_the_snapshot_runs() { let f = Fixture::new(&[(WIDGETS, "feature")]); let (pushed, _) = send_to_a_workspace(&f); let checkout = f.checkout(0); - write(&checkout, "remote.txt", "made remotely\n"); - let head = commit(&checkout, "made remotely"); + let head = commit_in_the_workspace(&f, "remote.txt"); write( &checkout, "partial.txt", @@ -107,11 +189,21 @@ fn the_worktree_is_added_while_the_snapshot_runs() { ); let expected = observe(&checkout); let worktree = worktree_path(&f); - let seen = hold_the_snapshot_for(&f, &worktree); + let watch = Watch::under(&f.host.root); + let (gated, finished_in_the_snapshot) = gate_the_early_add(&f); f.transfer(true).result.expect("to local"); - assert_eq!(*seen.lock().unwrap(), vec![true], "added by the snapshot"); + assert_eq!( + gated.gate().add_began_in_the_snapshot(), + Some(true), + "the add did not wait for the snapshot to start" + ); + assert_eq!( + *finished_in_the_snapshot.lock().unwrap(), + vec![true], + "the add did not finish while the snapshot was held" + ); assert_eq!(worktree_on_feature_at(&f, &head), worktree); assert_eq!(observe(&worktree), expected); assert!( @@ -120,6 +212,196 @@ fn the_worktree_is_added_while_the_snapshot_runs() { head_moves(&worktree) ); assert_eq!(temp_refs(&worktree), ""); + // The capture started by the add is the one the finish waits for: + // nothing between the two commits changes what a capture reads. + assert_eq!( + shell_env_calls(&watch, &worktree), + [("invalidate", true), ("prewarm", true), ("wait", true)] + ); +} + +/// `post-checkout` hears of the early worktree once, after it is on its +/// branch, and is told what git tells it of a worktree added on a branch: +/// no previous head. Neither the detached add nor the switch from the start +/// commit reaches it. +#[test] +fn post_checkout_fires_once_for_an_early_worktree_as_for_a_new_one() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { + eprintln!("skipping: this git has no `git hook run`"); + return; + } + let (pushed, _) = send_to_a_workspace(&f); + let head = commit_in_the_workspace(&f, "remote.txt"); + let log = record_post_checkout(&f, ""); + + f.transfer(true).result.expect("to local"); + + let worktree = worktree_on_feature_at(&f, &head); + assert!( + switched_from(&worktree, &pushed), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(lines(&log), [new_worktree_at(&head)]); +} + +/// The commonest case: the clone already holds the head, so the worktree +/// is added at it and the switch moves no file. The hook is still told the +/// worktree is new, not that it went from the head to the head. +#[test] +fn post_checkout_sees_a_new_worktree_when_the_start_commit_is_the_head() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { + eprintln!("skipping: this git has no `git hook run`"); + return; + } + let (_, head) = send_to_a_workspace(&f); + let log = record_post_checkout(&f, ""); + + f.transfer(true).result.expect("to local"); + + let worktree = worktree_on_feature_at(&f, &head); + assert!( + switched_from(&worktree, &head), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(lines(&log), [new_worktree_at(&head)]); +} + +/// A git that cannot fire a hook on request gets no early worktree: the +/// worktree is added on the branch once that has landed, and git fires the +/// hook itself, the same once and with the same arguments. +#[test] +fn a_git_that_cannot_fire_hooks_on_request_adds_the_worktree_late() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + send_to_a_workspace(&f); + let head = commit_in_the_workspace(&f, "remote.txt"); + let expected = observe(&f.checkout(0)); + let log = record_post_checkout(&f, ""); + let watch = Watch::under(&f.host.root); + let old_git = GitWithoutHookRun::for_this_thread(); + + let transfer = f.transfer(true); + drop(old_git); + + transfer.result.expect("to local"); + let worktree = worktree_on_feature_at(&f, &head); + assert_eq!(observe(&worktree), expected); + assert!( + added_on_its_branch(&worktree), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(lines(&log), [new_worktree_at(&head)]); + // What is cached for the path is dropped before the worktree is there, + // as on the early path, and nothing is started ahead of the finish. + assert_eq!( + shell_env_calls(&watch, &worktree), + [("invalidate", false), ("wait", true)] + ); +} + +/// A `post-checkout` that fails fails the transfer, as it does when it +/// fails `git worktree add`. It is not taken for a reason to fall back, +/// which would fire it a second time. +#[test] +fn a_post_checkout_that_fails_fails_the_transfer_having_fired_once() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { + eprintln!("skipping: this git has no `git hook run`"); + return; + } + send_to_a_workspace(&f); + let head = commit_in_the_workspace(&f, "remote.txt"); + let source = source_fingerprint(&f.checkout(0)); + let log = record_post_checkout(&f, "echo no good >&2\nexit 1"); + + let transfer = f.transfer(true); + + let err = transfer.result.unwrap_err(); + assert!(err.contains("Cannot add the worktree for feature"), "{err}"); + assert!(err.contains("no good"), "{err}"); + assert_eq!(lines(&log), [new_worktree_at(&head)]); + assert!(f.worktree_dirs().is_empty(), "{:?}", f.worktree_dirs()); + assert_eq!(source_fingerprint(&f.checkout(0)), source); + let manifest = f.manifest(&transfer.transfer_id).expect("manifest"); + assert_eq!(manifest.status, "rolledBack"); +} + +/// The capture the early add started ran at the start commit. When the +/// branch's head differs from it in something a capture reads, that capture +/// is waited out and dropped before the finish asks for a new one, so two +/// are never running in the worktree and none is left untracked. +#[test] +fn a_stale_capture_is_waited_out_before_the_finish_captures_again() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let (pushed, _) = send_to_a_workspace(&f); + let head = commit_in_the_workspace(&f, ".nvmrc"); + let watch = Watch::under(&f.host.root); + + f.transfer(true).result.expect("to local"); + + let worktree = worktree_on_feature_at(&f, &head); + assert!( + switched_from(&worktree, &pushed), + "{:?}", + head_moves(&worktree) + ); + assert_eq!( + shell_env_calls(&watch, &worktree), + [ + ("invalidate", true), + ("prewarm", true), + ("wait out and invalidate", true), + ("wait", true) + ] + ); +} + +/// A switch that fails after the early add went well: an untracked file +/// turned up in the worktree where the branch has one. The leg falls back, +/// and the capture the early add started is waited out while the worktree +/// is still there, before it is removed and added again on the branch. +#[test] +fn a_switch_that_fails_waits_out_the_capture_before_the_worktree_is_replaced() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + send_to_a_workspace(&f); + let head = commit_in_the_workspace(&f, "remote.txt"); + let expected = observe(&f.checkout(0)); + let worktree = worktree_path(&f); + let watch = Watch::under(&f.host.root); + let gated = GatedEarlyAdds::for_this_thread(); + let (gate, early) = (gated.gate(), worktree.clone()); + f.host.on_every_script(move |side, script| { + if side == Side::Workspace && script == SNAPSHOT_SCRIPT { + assert!(gate.snapshot_started(), "no early worktree"); + write(&early, "remote.txt", "in the way\n"); + write(&early, "scratch.txt", "left by something else\n"); + } + }); + + f.transfer(true).result.expect("to local"); + + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert_eq!(f.worktree_dirs(), vec![worktree.clone()]); + assert!( + added_on_its_branch(&worktree), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(observe(&worktree), expected); + assert!(!worktree.join("scratch.txt").exists()); + assert_eq!( + shell_env_calls(&watch, &worktree), + [ + ("invalidate", true), + ("prewarm", true), + ("wait out and invalidate", true), + ("wait", true) + ] + ); } /// The worktree is in the undo list before it is made, which is now before @@ -150,7 +432,9 @@ fn the_undo_list_names_the_worktree_before_the_snapshot_starts() { } /// The snapshot fails once the early worktree is there: the leg waits for -/// the add, and the rollback removes what it made. +/// the add, and the rollback removes what it made. The capture the add +/// started in the worktree is waited out first, while the worktree is +/// still there, and nothing asks for another. #[test] fn a_snapshot_that_fails_after_the_early_add_leaves_no_worktree() { let f = Fixture::new(&[(WIDGETS, "feature")]); @@ -158,6 +442,7 @@ fn a_snapshot_that_fails_after_the_early_add_leaves_no_worktree() { let clone = f.host.clone_of(WIDGETS); let (db, before) = (f.db_state(), clone_state(&clone)); let source = source_fingerprint(&f.checkout(0)); + let watch = Watch::under(&f.host.root); let seen = hold_the_snapshot_for(&f, &worktree_path(&f)); f.host .arm(Fault::Script(Side::Workspace, SNAPSHOT_SCRIPT, 1)); @@ -168,6 +453,14 @@ fn a_snapshot_that_fails_after_the_early_add_leaves_no_worktree() { assert!(f.host.fired(), "{err}"); assert_eq!(*seen.lock().unwrap(), vec![true], "the worktree was there"); assert!(f.worktree_dirs().is_empty(), "{:?}", f.worktree_dirs()); + assert_eq!( + shell_env_calls(&watch, &worktree_path(&f)), + [ + ("invalidate", true), + ("prewarm", true), + ("wait out and invalidate", true) + ] + ); assert_eq!(clone_state(&clone), before); assert_eq!(f.db_state(), db); assert_eq!(source_fingerprint(&f.checkout(0)), source); @@ -213,6 +506,7 @@ fn an_early_add_that_fails_falls_back_to_adding_the_worktree_late() { let f = Fixture::new(&[(WIDGETS, "feature")]); let (_, head) = send_to_a_workspace(&f); let expected = observe(&f.checkout(0)); + let watch = Watch::under(&f.host.root); let failing = FailingEarlyAdds::for_this_thread(); let transfer = f.transfer(true); @@ -229,6 +523,12 @@ fn an_early_add_that_fails_falls_back_to_adding_the_worktree_late() { head_moves(&worktree) ); assert!(!worktree.join("half-added").exists()); + // No capture was started in what the add left, so the removal had + // nothing to wait for; it still asks, with the directory there. + assert_eq!( + shell_env_calls(&watch, &worktree), + [("wait out and invalidate", true), ("wait", true)] + ); } /// The inspection saw no LFS objects, so the early worktree was added with diff --git a/apps/staged/src-tauri/src/project_transfer/undo.rs b/apps/staged/src-tauri/src/project_transfer/undo.rs index 6580b89a6..9803ec9ec 100644 --- a/apps/staged/src-tauri/src/project_transfer/undo.rs +++ b/apps/staged/src-tauri/src/project_transfer/undo.rs @@ -431,12 +431,26 @@ fn restore_branch_config( /// Remove a worktree the transfer added, without `remove_worktree`'s branch /// deletion: the branch is the rollback's to decide about. A directory git -/// does not know as a worktree, such as an add left part way, goes too. +/// does not know as a worktree, such as an add that failed part way, goes +/// too, and so does what a `git worktree add` killed part way leaves: an +/// entry git keeps locked, with the reason `initializing`, which a plain +/// removal refuses, a prune skips, and a later add at the path trips over. +/// +/// A worktree added early has had a capture of its shell environment +/// started in it (see `orchestrator::early_worktree`). That capture's shell +/// may still be starting there, and whatever it writes would stop the +/// removal or bring the directory back after it, so the capture is waited +/// out first and its result dropped. Nothing can stop it sooner. pub(super) fn remove_worktree_keeping_branch(clone: &Path, worktree: &Path) -> Result<(), String> { let Some(path) = worktree.to_str() else { return Err(format!("not a UTF-8 path: {}", worktree.display())); }; - if crate::git::cli_run(clone, &["worktree", "remove", "--force", path]).is_ok() { + crate::git::wait_out_and_invalidate_shell_env(worktree); + // Forced twice: once past what the worktree holds, once past a lock. + // The only lock a worktree the transfer has just added can carry is + // the one git holds for the length of the add. + let forced = ["worktree", "remove", "--force", "--force", path]; + if crate::git::cli_run(clone, &forced).is_ok() { return Ok(()); } let removed = if worktree.exists() { @@ -444,6 +458,8 @@ pub(super) fn remove_worktree_keeping_branch(clone: &Path, worktree: &Path) -> R } else { Ok(()) }; + // A prune leaves a locked entry be, whatever became of its directory. + let _ = crate::git::cli_run(clone, &["worktree", "unlock", path]); let _ = crate::git::cli_run(clone, &["worktree", "prune"]); removed } @@ -551,4 +567,154 @@ mod tests { remove_added_excludes(&made).unwrap(); assert_eq!(std::fs::read_to_string(&exclude).unwrap(), "later\n"); } + + /// Start `git worktree add` for `worktree` in `repo`, whose `held.bin` + /// has a smudge filter that never finishes, and kill it outright once + /// the checkout has reached that file: what is left is a directory + /// with some of the files and an entry git still holds locked. + #[cfg(unix)] + fn kill_an_add_part_way(repo: &crate::test_utils::TempGitRepo, worktree: &Path) { + use std::os::unix::process::CommandExt; + use std::time::{Duration, Instant}; + + let reached = repo.path().join(".git/reached-the-filter"); + // Nothing is forked once the marker is there, so the kill below + // has no process still being made to miss. + let smudge = format!("sh -c ': > \"{}\"; exec sleep 600'", reached.display()); + repo.run_git(&["config", "filter.held.smudge", &smudge]); + let mut add = std::process::Command::new("git"); + add.arg("-c") + .arg("core.hooksPath=/dev/null") + .arg("-C") + .arg(repo.path()) + .args(["worktree", "add", "--detach"]) + .arg(worktree) + .arg("HEAD") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + // A group of its own, so the kill takes the checkout git runs + // and the filter under it as well. + .process_group(0); + crate::git::strip_git_env(&mut add); + let mut add = add.spawn().unwrap(); + let group = -libc::pid_t::try_from(add.id()).unwrap(); + + let deadline = Instant::now() + Duration::from_secs(60); + while !reached.exists() { + assert!( + Instant::now() < deadline, + "the add never reached the filter" + ); + std::thread::sleep(Duration::from_millis(10)); + } + // SAFETY: `kill` has no memory-safety preconditions, and the group + // is this test's own, alive at least in the filter's `sleep`. + unsafe { libc::kill(group, libc::SIGKILL) }; + add.wait().unwrap(); + // Until the group is gone, so nothing of it is still writing. + // SAFETY: as above. + while unsafe { libc::kill(group, libc::SIGKILL) } == 0 { + assert!(Instant::now() < deadline, "the add's processes outlived it"); + std::thread::sleep(Duration::from_millis(10)); + } + repo.run_git(&["config", "--unset", "filter.held.smudge"]); + std::fs::remove_file(&reached).unwrap(); + } + + /// A repo with a commit whose `held.bin` goes through the `held` + /// filter. Returns it with a root for worktrees. + #[cfg(unix)] + fn repo_with_a_filtered_file() -> (crate::test_utils::TempGitRepo, crate::test_utils::TempDir) { + let repo = crate::test_utils::TempGitRepo::new(); + repo.write_file(".gitattributes", "held.bin filter=held\n"); + repo.write_file("a.txt", "alpha\n"); + repo.write_file("held.bin", "held\n"); + repo.commit("base"); + (repo, crate::test_utils::TempDir::new("killed-add")) + } + + /// The lock git holds on a worktree for the length of its add. + #[cfg(unix)] + fn lock_reason(repo: &crate::test_utils::TempGitRepo, name: &str) -> Option { + let locked = repo.path().join(".git/worktrees").join(name).join("locked"); + std::fs::read_to_string(locked) + .ok() + .map(|reason| reason.trim().to_string()) + } + + #[cfg(unix)] + fn add_detached(repo: &crate::test_utils::TempGitRepo, worktree: &Path) -> Result<(), String> { + crate::git::create_detached_worktree_without_hooks(repo.path(), "HEAD", worktree, false) + .map(drop) + .map_err(|e| e.to_string()) + } + + #[cfg(unix)] + #[test] + fn removes_what_a_killed_add_left_so_the_path_can_be_added_again() { + let (repo, root) = repo_with_a_filtered_file(); + let worktree = root.path().join("wt"); + kill_an_add_part_way(&repo, &worktree); + let path = worktree.to_str().unwrap(); + + // The state: part of a checkout, and a lock a plain removal and a + // new add both stop at. + assert!(worktree.join("a.txt").exists()); + assert!(!worktree.join("held.bin").exists()); + assert_eq!(lock_reason(&repo, "wt").as_deref(), Some("initializing")); + let refused = repo + .try_run_git(&["worktree", "remove", "--force", path]) + .expect_err("git removed a locked worktree"); + assert!(refused.contains("locked"), "{refused}"); + assert!(worktree.exists()); + + remove_worktree_keeping_branch(repo.path(), &worktree).unwrap(); + + assert!(!worktree.exists()); + assert_eq!(lock_reason(&repo, "wt"), None); + assert!(!repo.path().join(".git/worktrees/wt").exists()); + add_detached(&repo, &worktree).expect("a worktree at the same path"); + assert_eq!( + std::fs::read_to_string(worktree.join("held.bin")).unwrap(), + "held\n" + ); + } + + /// What a build without the fix left of a killed add: it deleted the + /// directory and pruned, which keeps the locked entry, and every later + /// add at that path failed on it. + #[cfg(unix)] + #[test] + fn clears_a_locked_entry_whose_directory_is_already_gone() { + let (repo, root) = repo_with_a_filtered_file(); + let worktree = root.path().join("wt"); + kill_an_add_part_way(&repo, &worktree); + std::fs::remove_dir_all(&worktree).unwrap(); + repo.run_git(&["worktree", "prune"]); + assert_eq!(lock_reason(&repo, "wt").as_deref(), Some("initializing")); + let refused = add_detached(&repo, &worktree).expect_err("git added over a locked entry"); + assert!(refused.contains("locked"), "{refused}"); + + remove_worktree_keeping_branch(repo.path(), &worktree).unwrap(); + + assert_eq!(lock_reason(&repo, "wt"), None); + add_detached(&repo, &worktree).expect("a worktree at the same path"); + } + + /// A directory git never heard of, and a path with nothing at it, are + /// removed without complaint, as before. + #[test] + fn removes_a_directory_git_does_not_know_and_tolerates_none() { + let repo = crate::test_utils::TempGitRepo::new(); + repo.write_file("a.txt", "alpha\n"); + repo.commit("base"); + let root = crate::test_utils::TempDir::new("stray-worktree"); + let stray = root.path().join("stray"); + std::fs::create_dir_all(stray.join("nested")).unwrap(); + std::fs::write(stray.join("nested/file"), "").unwrap(); + + remove_worktree_keeping_branch(repo.path(), &stray).unwrap(); + assert!(!stray.exists()); + remove_worktree_keeping_branch(repo.path(), &stray).unwrap(); + } } diff --git a/apps/staged/src-tauri/src/shell_env.rs b/apps/staged/src-tauri/src/shell_env.rs index 039cff824..02c6b8b7e 100644 --- a/apps/staged/src-tauri/src/shell_env.rs +++ b/apps/staged/src-tauri/src/shell_env.rs @@ -49,6 +49,8 @@ mod leftover_group; #[cfg(all(test, unix))] mod capture_limit_tests; +#[cfg(all(test, unix))] +mod wait_out_tests; use capture_slots::{CaptureSlots, Urgency, CAPTURE_LIMIT}; pub(crate) use env_root::env_root_inputs; @@ -1343,6 +1345,44 @@ impl ShellEnvCache { self.inner.lock().unwrap().remove(&key); } + /// [`invalidate`] for a caller about to delete `working_dir`, or one that + /// must not have two captures of it running: first wait for the capture + /// in flight for its env root, if there is one, since that capture's + /// shell is running in the directory. It never starts a capture. + /// + /// A capture can't be stopped early (it "never belongs to a caller"; see + /// the module docs), so this waits it out: for at most its queue time + /// plus [`SHELL_CAPTURE_TIMEOUT`], and as a waiter without a bound, which + /// moves a queued capture ahead of prewarms. What a shell killed at that + /// timeout started may still be running afterwards, until + /// [`LEFTOVER_GROUP_TIMEOUT`]; this doesn't wait for that. Nor can it + /// see a capture whose entry [`invalidate`] dropped while it ran. + /// + /// [`invalidate`]: ShellEnvCache::invalidate + pub fn wait_out_and_invalidate(&self, working_dir: &Path) { + let key = self.env_key(working_dir); + loop { + let promise = { + let mut map = self.inner.lock().unwrap(); + match map.get(&key) { + Some(CachedEntry::InFlight(handle)) => Arc::clone(&handle.promise), + _ => { + // Dropped under the lock that found nothing in + // flight, so no capture starts in between. + map.remove(&key); + break; + } + } + }; + // The capture replaces its `InFlight` entry before it wakes + // its waiters, so the next look finds its result, or a capture + // someone has started since. + let _waiter = promise.register_unbounded_waiter(&self.slots); + let _ = promise.wait_blocking(); + } + self.env_keys.lock().unwrap().remove(working_dir); + } + /// Drop all cached snapshots and resolved env roots. pub fn invalidate_all(&self) { self.env_keys.lock().unwrap().clear(); diff --git a/apps/staged/src-tauri/src/shell_env/wait_out_tests.rs b/apps/staged/src-tauri/src/shell_env/wait_out_tests.rs new file mode 100644 index 000000000..d3200143f --- /dev/null +++ b/apps/staged/src-tauri/src/shell_env/wait_out_tests.rs @@ -0,0 +1,113 @@ +//! [`ShellEnvCache::wait_out_and_invalidate`]: what a caller about to delete +//! a directory uses so no capture's shell is still running in it. + +use super::*; +use crate::test_utils::{wait_for_file_sh, write_fake_shell}; +use std::sync::mpsc; + +/// Fake `$SHELL` that logs `started`, waits for `log/release`, runs the +/// capture's script, and logs `exited` as the last thing it does. +fn held_shell(log: &Path) -> tempfile::TempPath { + let log = single_quote(&log.to_string_lossy()); + write_fake_shell(&format!( + "#!/bin/sh\n\ + PATH=/usr/bin:/bin\n\ + export PATH\n\ + echo started >> {log}/events\n\ + {wait}\n\ + /bin/sh -s\n\ + echo exited >> {log}/events\n", + wait = wait_for_file_sh(&format!("{log}/release")), + )) +} + +fn events(log: &Path) -> Vec { + std::fs::read_to_string(log.join("events")) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() +} + +fn wait_for_events(log: &Path, count: usize) { + let deadline = Instant::now() + Duration::from_secs(30); + while events(log).len() < count { + assert!(Instant::now() < deadline, "{:?}", events(log)); + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn cache_with(shell: &Path, home: &Path) -> Arc { + Arc::new( + ShellEnvCache::with_shell_and_ttl(shell.to_path_buf(), Duration::from_secs(3600)) + .with_home(home), + ) +} + +/// The shell of a capture in flight is running in the directory, so the +/// call returns only once it has exited, and leaves nothing cached. It +/// waits for that capture rather than starting one of its own. +#[test] +fn waits_for_the_capture_in_flight_then_drops_its_result() { + let scratch = tempfile::tempdir().expect("tempdir"); + let shell = held_shell(scratch.path()); + let cache = cache_with(&shell, scratch.path()); + let dir = tempfile::tempdir_in(scratch.path()).expect("tempdir"); + + cache.prewarm(dir.path()); + wait_for_events(scratch.path(), 1); + + let (done, waited) = mpsc::channel(); + let (waiting, path) = (Arc::clone(&cache), dir.path().to_path_buf()); + let waiter = std::thread::spawn(move || { + waiting.wait_out_and_invalidate(&path); + let _ = done.send(()); + }); + assert!( + waited.recv_timeout(Duration::from_millis(300)).is_err(), + "returned while the shell was still running" + ); + assert_eq!(events(scratch.path()), ["started"]); + + std::fs::write(scratch.path().join("release"), "").unwrap(); + waited + .recv_timeout(Duration::from_secs(30)) + .expect("the capture finished"); + waiter.join().unwrap(); + + assert_eq!( + events(scratch.path()), + ["started", "exited"], + "one shell, gone by the time the wait ended" + ); + assert!( + cache.inner.lock().unwrap().get(dir.path()).is_none(), + "the capture's result stayed cached" + ); +} + +/// With nothing in flight there is nothing to wait for, and nothing is +/// started: a capture would put a shell in the directory about to go. +#[test] +fn starts_no_capture_where_none_is_in_flight() { + let scratch = tempfile::tempdir().expect("tempdir"); + std::fs::write(scratch.path().join("release"), "").unwrap(); + let shell = held_shell(scratch.path()); + let cache = cache_with(&shell, scratch.path()); + let dir = tempfile::tempdir_in(scratch.path()).expect("tempdir"); + + cache.wait_out_and_invalidate(dir.path()); + assert_eq!(events(scratch.path()), Vec::::new()); + + // A snapshot already cached is dropped, as `invalidate` drops it. + cache.get_blocking(dir.path()).expect("capture"); + assert_eq!(events(scratch.path()), ["started", "exited"]); + cache.wait_out_and_invalidate(dir.path()); + assert_eq!(events(scratch.path()), ["started", "exited"]); + assert!(cache.inner.lock().unwrap().get(dir.path()).is_none()); + + // And a directory that is already gone is no trouble. + let gone = dir.path().join("gone"); + cache.wait_out_and_invalidate(&gone); + assert_eq!(events(scratch.path()).len(), 2); +} From 7fb171c7fed2275ce4c7a45acfc81cc59e651cb5 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Tue, 17 Nov 2026 16:44:28 +1100 Subject: [PATCH 3/4] fix(staged): capture a transferred worktree's environment after post-checkout A transfer from Blox adds each branch's worktree early and starts a shell-environment capture in it, then fires `post-checkout` once the worktree is on its branch. Review of that found the capture ran before the hook. A hook that sets a new worktree up, by allowing its `.envrc`, trusting a tool-versions file or writing either, did so after the capture's shell had started, and the finish then used that capture, which stays cached for up to an hour. A worktree added late is first captured after `git worktree add` has fired the hook. The hook also ran beside the capture's login shell in the same directory. Once the worktree is on its branch, the leg now asks which `post-checkout` hooks git would run there. When one would, it waits out the early capture and drops it before firing the hook, so no shell of that capture is in the directory while the hook works and the finish captures after it: the order the late path has. A repo with no such hook keeps the capture. The check that the two commits differ in what a capture reads shares that one wait, now before the hook instead of after it. `git::post_checkout_hooks_for_worktree` answers the question the way `git hook run` will: the hook directory's file from `git rev-parse --git-path`, which follows `core.hooksPath` from the worktree, counted when it is there and executable, and git's own `git hook list` where it has one, which is where git also runs hooks named in config. What it cannot tell counts as a hook. One hook is exempt: the `post-checkout` that `git lfs install` writes, so Git LFS repos keep the head start. `git lfs post-checkout` only sets the write flag of lockable files. The hook is recognised by its three lines: `#!/bin/sh`, the guard that reports a missing `git-lfs` and exits 2, and `git lfs post-checkout "$@"`. Git LFS has reworded the report several times, so its text is free as long as it stays one double-quoted string with nothing the shell would run. Anything added or changed, or a second hook from config beside it, makes it any other hook. A hook manager that owns the machine's `core.hooksPath` and installs a `post-checkout` for every repo counts as a hook, since what it goes on to run cannot be known. Repos under one lose the head start on the environment unless they set a hook directory of their own. The doc comment on `run_post_checkout_as_for_a_new_worktree` named `GIT_DIR` as the one difference from a late add. It now states the second: a relative `core.hooksPath` is resolved from the new worktree, so the branch's copy of the hook runs where `git -C worktree add` runs the main checkout's, and a branch without that directory fires no hook, silently. The behaviour is unchanged. Each leg's log line says when the early capture was dropped, how long the wait took and why. Tests: with a hook, the capture is waited out and dropped while the hook has not yet run, and the finish's wait comes after it; firing the hook first fails that test. With an empty hook directory, with a hook git would ignore for not being executable, and with the stock Git LFS hook, the capture is kept. The detection is tested against a real linked worktree for each case, a relative `core.hooksPath` whose directory only one branch has, a hook named in config, the four texts Git LFS has shipped, edited copies of the stock hook, and what `git lfs install` writes on the machine running the tests. The shell-environment recorder can note whether a file existed at each call, which is how the hook is placed among them. Tests that look at those calls give the clone its own hook directory, so a machine-wide one does not decide them. Signed-off-by: Matt Toohey Co-Authored-By: Claude Fable 5.2 --- apps/staged/src-tauri/src/git/cli.rs | 42 ++- apps/staged/src-tauri/src/git/mod.rs | 4 + .../src-tauri/src/git/post_checkout_hook.rs | 169 ++++++++++ .../src/git/post_checkout_hook/tests.rs | 289 ++++++++++++++++++ apps/staged/src-tauri/src/git/worktree.rs | 27 +- .../orchestrator/early_worktree.rs | 74 ++++- .../orchestrator_tests/early_worktree.rs | 195 +++++++++++- 7 files changed, 761 insertions(+), 39 deletions(-) create mode 100644 apps/staged/src-tauri/src/git/post_checkout_hook.rs create mode 100644 apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs diff --git a/apps/staged/src-tauri/src/git/cli.rs b/apps/staged/src-tauri/src/git/cli.rs index c5b0d2b31..9a6e7a7ac 100644 --- a/apps/staged/src-tauri/src/git/cli.rs +++ b/apps/staged/src-tauri/src/git/cli.rs @@ -349,9 +349,18 @@ pub(crate) mod shell_env_calls { pub(crate) path: PathBuf, /// Whether `path` existed when the call was made. pub(crate) existed: bool, + /// Whether the file the watch was told to note + /// ([`Watch::noting`]) existed then; `false` with none to note. + pub(crate) noted: bool, } - static WATCHED: Mutex)>> = Mutex::new(Vec::new()); + struct Watched { + dir: PathBuf, + note: Option, + calls: Vec, + } + + static WATCHED: Mutex> = Mutex::new(Vec::new()); /// While it lives, calls for paths under its directory are kept, from /// whichever thread makes them. @@ -360,17 +369,33 @@ pub(crate) mod shell_env_calls { impl Watch { pub(crate) fn under(dir: &Path) -> Self { let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); - watched.push((dir.to_path_buf(), Vec::new())); + watched.push(Watched { + dir: dir.to_path_buf(), + note: None, + calls: Vec::new(), + }); Self(dir.to_path_buf()) } + /// Also keep, per call, whether `file` existed when it was made: + /// a file something else writes when it runs places that run + /// among the calls. + pub(crate) fn noting(self, file: &Path) -> Self { + let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(entry) = watched.iter_mut().find(|entry| entry.dir == self.0) { + entry.note = Some(file.to_path_buf()); + } + drop(watched); + self + } + /// The calls so far, in order. pub(crate) fn calls(&self) -> Vec { let watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); watched .iter() - .find(|(dir, _)| *dir == self.0) - .map(|(_, calls)| calls.clone()) + .find(|entry| entry.dir == self.0) + .map(|entry| entry.calls.clone()) .unwrap_or_default() } } @@ -378,18 +403,19 @@ pub(crate) mod shell_env_calls { impl Drop for Watch { fn drop(&mut self) { let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); - watched.retain(|(dir, _)| *dir != self.0); + watched.retain(|entry| entry.dir != self.0); } } pub(super) fn record(what: &'static str, path: &Path) { let mut watched = WATCHED.lock().unwrap_or_else(|e| e.into_inner()); - for (dir, calls) in watched.iter_mut() { - if path.starts_with(dir.as_path()) { - calls.push(Call { + for entry in watched.iter_mut() { + if path.starts_with(entry.dir.as_path()) { + entry.calls.push(Call { what, path: path.to_path_buf(), existed: path.exists(), + noted: entry.note.as_deref().is_some_and(Path::exists), }); } } diff --git a/apps/staged/src-tauri/src/git/mod.rs b/apps/staged/src-tauri/src/git/mod.rs index 4e8215b9c..ad666696e 100644 --- a/apps/staged/src-tauri/src/git/mod.rs +++ b/apps/staged/src-tauri/src/git/mod.rs @@ -6,6 +6,7 @@ mod diff; mod env; mod files; pub mod github; +mod post_checkout_hook; mod rebase; mod refs; mod state; @@ -45,6 +46,9 @@ pub use github::{ CreatePrResult, FailedCheck, GitHubAuthStatus, GitHubCommentResult, GitHubRepo, HeadBranchPr, Issue, PrListState, PrStatus, PullRequest, }; +#[cfg(test)] +pub(crate) use post_checkout_hook::STOCK_GIT_LFS_POST_CHECKOUT; +pub use post_checkout_hook::{post_checkout_hooks_for_worktree, PostCheckoutHooks}; pub use rebase::{rebase_preserving_merge_edits_command, HAND_EDIT_COMMIT_SUBJECT_PREFIX}; pub use refs::{ branch_name_without_origin, detect_default_branch, detect_default_branch_from_remote, diff --git a/apps/staged/src-tauri/src/git/post_checkout_hook.rs b/apps/staged/src-tauri/src/git/post_checkout_hook.rs new file mode 100644 index 000000000..fa2210377 --- /dev/null +++ b/apps/staged/src-tauri/src/git/post_checkout_hook.rs @@ -0,0 +1,169 @@ +//! Which `post-checkout` hooks git would fire in a worktree, for a caller +//! that has something to settle before they run. +//! +//! A hook can do anything: allow a `.envrc`, trust a tool-versions file, +//! write either. The one exception told apart here is the hook `git lfs +//! install` writes, which is common and is known to do none of that. + +use std::path::Path; + +use super::cli; + +/// What `git hook run post-checkout` would run in a worktree. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PostCheckoutHooks { + /// Nothing. + None, + /// Only the hook `git lfs install` writes, unedited. `git lfs + /// post-checkout` sets the write flag of lockable files and nothing + /// else, so it changes nothing a shell reads on starting in the + /// worktree. + GitLfsOnly, + /// Something else, which may do anything. Also the answer when git + /// could not be asked. + Other, +} + +/// The `post-checkout` hooks `git -C hook run` would run +/// for `worktree_path`, a worktree of `repo`, as +/// [`run_post_checkout_as_for_a_new_worktree`] is about to. +/// +/// Git is asked for the hook directory's file, which follows +/// `core.hooksPath` as the run does (a relative one from the worktree), and +/// for its own list of hooks where it has one (`git hook list`, which +/// came with the hooks git runs from config). The file counts when git +/// would run it: there and executable. +/// +/// [`run_post_checkout_as_for_a_new_worktree`]: super::run_post_checkout_as_for_a_new_worktree +pub fn post_checkout_hooks_for_worktree(repo: &Path, worktree_path: &Path) -> PostCheckoutHooks { + let Some(worktree_str) = worktree_path.to_str() else { + return PostCheckoutHooks::Other; + }; + + // git -C rev-parse --git-path hooks/post-checkout + let git_path = [ + "-C", + worktree_str, + "rev-parse", + "--git-path", + "hooks/post-checkout", + ]; + let in_hooks_dir = match cli::run(repo, &git_path) { + // Relative to the worktree when it is relative. + Ok(path) => HookFile::at(&worktree_path.join(path.trim_end_matches(['\n', '\r']))), + Err(e) => { + log::warn!( + "[git] cannot find the post-checkout hook of {}: {e}", + worktree_path.display() + ); + return PostCheckoutHooks::Other; + } + }; + + // git -C hook list -z post-checkout + // One name per hook it would run, or would but for being disabled. It + // fails when there are none, and on a git that has no list, which has + // no hooks but the file either. + let listed = cli::run( + repo, + &["-C", worktree_str, "hook", "list", "-z", "post-checkout"], + ) + .ok() + .map(|names| names.split('\0').filter(|name| !name.is_empty()).count()); + + classify(in_hooks_dir, listed) +} + +/// `listed` is how many hooks git listed, `None` when it listed none or +/// has no list. Whatever does not add up is [`PostCheckoutHooks::Other`]. +fn classify(in_hooks_dir: HookFile, listed: Option) -> PostCheckoutHooks { + match (in_hooks_dir, listed) { + (HookFile::Absent, None | Some(0)) => PostCheckoutHooks::None, + // Listed alone, the file is the one hook there is. + (HookFile::StockGitLfs, None | Some(1)) => PostCheckoutHooks::GitLfsOnly, + _ => PostCheckoutHooks::Other, + } +} + +/// The `post-checkout` file of a hook directory. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HookFile { + /// Not there, or not executable, which git ignores. + Absent, + StockGitLfs, + Other, +} + +impl HookFile { + fn at(path: &Path) -> Self { + let runnable = + std::fs::metadata(path).is_ok_and(|file| file.is_file() && executable(&file)); + if !runnable { + return Self::Absent; + } + match std::fs::read_to_string(path) { + Ok(script) if is_stock_git_lfs_post_checkout(&script) => Self::StockGitLfs, + _ => Self::Other, + } + } +} + +/// Whether anyone may execute the file. Git asks whether it may itself, so +/// this errs towards a hook being there. +#[cfg(unix)] +fn executable(file: &std::fs::Metadata) -> bool { + use std::os::unix::fs::PermissionsExt; + + file.permissions().mode() & 0o111 != 0 +} + +#[cfg(not(unix))] +fn executable(_file: &std::fs::Metadata) -> bool { + true +} + +/// Whether `script` is the `post-checkout` hook `git lfs install` writes, +/// with nothing added: a `#!/bin/sh` line, a line that reports a missing +/// `git-lfs` and exits, and `git lfs post-checkout "$@"`. +/// +/// Git LFS has reworded the report several times, so its text is free, but +/// only as far as it stays one double-quoted string the shell runs nothing +/// from. A hook this doesn't know is not the stock one. +fn is_stock_git_lfs_post_checkout(script: &str) -> bool { + let lines: Vec<&str> = script.lines().collect(); + let [shebang, guard, run] = lines[..] else { + return false; + }; + shebang == "#!/bin/sh" + && reports_missing_git_lfs_and_exits(guard) + && run == r#"git lfs post-checkout "$@""# +} + +fn reports_missing_git_lfs_and_exits(line: &str) -> bool { + let report = line + .strip_prefix("command -v git-lfs >/dev/null 2>&1 || { ") + .and_then(|rest| rest.strip_suffix(r#""; exit 2; }"#)); + let message = report.and_then(|report| { + // What Git LFS writes now, and what it wrote before. + report + .strip_prefix(r#"printf >&2 "\n%s\n\n" ""#) + .or_else(|| report.strip_prefix(r#"echo >&2 ""#)) + }); + // Inside double quotes only these end the string or run something, and + // a backslash last would keep the closing quote from closing it. + message.is_some_and(|message| !message.contains(['"', '$', '`']) && !message.ends_with('\\')) +} + +/// The hook Git LFS 3.8.1 installs, for tests elsewhere that need a +/// worktree to have it. +#[cfg(test)] +pub(crate) const STOCK_GIT_LFS_POST_CHECKOUT: &str = concat!( + "#!/bin/sh\n", + r#"command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }"#, + "\n", + r#"git lfs post-checkout "$@""#, + "\n", +); + +#[cfg(test)] +mod tests; diff --git a/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs b/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs new file mode 100644 index 000000000..0132ec5d0 --- /dev/null +++ b/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs @@ -0,0 +1,289 @@ +//! Every repo here names its own `core.hooksPath`, so a hook directory set +//! for the whole machine (a hook manager's, say) is not what gets found. + +use std::path::{Path, PathBuf}; + +use super::*; +use crate::test_utils::{TempDir, TempGitRepo}; + +/// The stock hook as Git LFS wrote it before it took to `printf`, oldest +/// last. +const EARLIER_STOCK_HOOKS: [&str; 3] = [ + concat!( + "#!/bin/sh\n", + r#"command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks').\n"; exit 2; }"#, + "\n", + r#"git lfs post-checkout "$@""#, + ), + concat!( + "#!/bin/sh\n", + r#"command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting '.git/hooks/post-checkout'.\n"; exit 2; }"#, + "\n", + r#"git lfs post-checkout "$@""#, + ), + concat!( + "#!/bin/sh\n", + r#"command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/post-checkout.\n"; exit 2; }"#, + "\n", + r#"git lfs post-checkout "$@""#, + ), +]; + +/// A repo with one commit, its hook directory an empty one under `root`, +/// and a linked worktree at that commit. Returns the hook directory and +/// the worktree. +fn repo_with_worktree(root: &Path) -> (TempGitRepo, PathBuf, PathBuf) { + let repo = TempGitRepo::new(); + repo.write_file("tracked.txt", "base\n"); + let base = repo.commit("base"); + let hooks = root.join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + repo.run_git(&["config", "core.hooksPath", hooks.to_str().unwrap()]); + let worktree = root.join("wt"); + super::super::create_detached_worktree_without_hooks(repo.path(), &base, &worktree, false) + .unwrap(); + (repo, hooks, worktree) +} + +#[cfg(unix)] +fn write_hook(hooks: &Path, script: &str, mode: u32) { + use std::os::unix::fs::PermissionsExt; + + std::fs::create_dir_all(hooks).unwrap(); + let hook = hooks.join("post-checkout"); + std::fs::write(&hook, script).unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(mode)).unwrap(); +} + +/// Whether this machine's git lists hooks, and so runs the ones config +/// names: it lists the one in `hooks`. +#[cfg(unix)] +fn git_lists_hooks(repo: &Path, hooks: &Path) -> bool { + write_hook(hooks, "#!/bin/sh\n", 0o755); + let lists = cli::run(repo, &["hook", "list", "-z", "post-checkout"]).is_ok(); + std::fs::remove_file(hooks.join("post-checkout")).unwrap(); + lists +} + +fn git_lfs_installed(test: &str) -> bool { + let installed = std::process::Command::new("git") + .args(["lfs", "version"]) + .output() + .is_ok_and(|out| out.status.success()); + if !installed { + eprintln!("skipping {test}: git-lfs is not installed"); + } + installed +} + +#[test] +fn only_a_file_with_nothing_else_listed_counts_as_none_or_as_git_lfs() { + use HookFile::{Absent, Other, StockGitLfs}; + + // A git with no list, or one that listed nothing: the file decides. + assert_eq!(classify(Absent, None), PostCheckoutHooks::None); + assert_eq!(classify(StockGitLfs, None), PostCheckoutHooks::GitLfsOnly); + assert_eq!(classify(Other, None), PostCheckoutHooks::Other); + + // The file is what git listed. + assert_eq!( + classify(StockGitLfs, Some(1)), + PostCheckoutHooks::GitLfsOnly + ); + assert_eq!(classify(Other, Some(1)), PostCheckoutHooks::Other); + + // A hook that config names, alone or beside the file. + assert_eq!(classify(Absent, Some(1)), PostCheckoutHooks::Other); + assert_eq!(classify(StockGitLfs, Some(2)), PostCheckoutHooks::Other); + assert_eq!(classify(Absent, Some(2)), PostCheckoutHooks::Other); + + // A list and a file that disagree. + assert_eq!(classify(Absent, Some(0)), PostCheckoutHooks::None); + assert_eq!(classify(StockGitLfs, Some(0)), PostCheckoutHooks::Other); +} + +#[test] +fn the_hook_git_lfs_installs_is_told_by_its_three_lines() { + assert!(is_stock_git_lfs_post_checkout(STOCK_GIT_LFS_POST_CHECKOUT)); + for earlier in EARLIER_STOCK_HOOKS { + assert!(is_stock_git_lfs_post_checkout(earlier), "{earlier}"); + } + // Reworded again, as it has been before. + assert!(is_stock_git_lfs_post_checkout(concat!( + "#!/bin/sh\n", + r#"command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "Git LFS is missing; see 'core.hookspath'."; exit 2; }"#, + "\n", + r#"git lfs post-checkout "$@""#, + "\n", + ))); +} + +#[test] +fn a_git_lfs_hook_with_anything_added_or_changed_is_not_the_stock_one() { + let stock = STOCK_GIT_LFS_POST_CHECKOUT; + let guard = stock.lines().nth(1).unwrap(); + let with_guard = |guard: &str| format!("#!/bin/sh\n{guard}\ngit lfs post-checkout \"$@\"\n"); + assert!(is_stock_git_lfs_post_checkout(&with_guard(guard))); + + let edited = [ + // A line more, wherever it goes. + format!("{stock}direnv allow\n"), + stock.replacen("#!/bin/sh\n", "#!/bin/sh\ndirenv allow\n", 1), + format!("{stock}\n"), + // Another shell, another command, another hook's command. + stock.replacen("#!/bin/sh", "#!/bin/bash", 1), + stock.replacen( + "git lfs post-checkout \"$@\"", + "git lfs post-checkout \"$@\"; direnv allow", + 1, + ), + stock.replacen("git lfs post-checkout", "git lfs post-merge", 1), + stock.replacen( + "git lfs post-checkout \"$@\"", + "git lfs post-checkout \"$@\" && mise trust", + 1, + ), + // A report that runs something, or stops being one string. + with_guard(&guard.replacen("This repository", "$(direnv allow) This repository", 1)), + with_guard(&guard.replacen("This repository", "`direnv allow` This repository", 1)), + with_guard(&guard.replacen( + "This repository", + "\"; direnv allow; echo \"This repository", + 1, + )), + with_guard(&guard.replacen("'.git/hooks').\"", "'.git/hooks').\\\"", 1)), + // A guard that goes on to something else, or doesn't exit. + with_guard(&guard.replacen("exit 2; }", "exit 2; }; direnv allow", 1)), + with_guard(&guard.replacen("exit 2; }", "direnv allow; }", 1)), + with_guard(&guard.replacen("command -v git-lfs", "direnv allow; command -v git-lfs", 1)), + with_guard(&guard.replacen("printf >&2", "direnv allow; printf >&2", 1)), + // Nothing at all, and a hook of another kind. + String::new(), + "#!/bin/sh\nexec lefthook run post-checkout \"$@\"\n".to_string(), + ]; + for script in edited { + assert!(!is_stock_git_lfs_post_checkout(&script), "{script}"); + } +} + +/// A hook directory with no `post-checkout`, or one git would ignore for +/// not being executable, has no hook; any other file is one that may do +/// anything, and the stock Git LFS hook is told apart from those. +#[cfg(unix)] +#[test] +fn the_hook_directory_file_is_none_other_or_git_lfs() { + let root = TempDir::new("post-checkout-hooks"); + let (repo, hooks, worktree) = repo_with_worktree(root.path()); + let found = || post_checkout_hooks_for_worktree(repo.path(), &worktree); + + assert_eq!(found(), PostCheckoutHooks::None, "an empty hook directory"); + + write_hook(&hooks, "#!/bin/sh\ndirenv allow\n", 0o644); + assert_eq!(found(), PostCheckoutHooks::None, "not executable"); + + write_hook(&hooks, "#!/bin/sh\ndirenv allow\n", 0o755); + assert_eq!(found(), PostCheckoutHooks::Other); + + write_hook(&hooks, STOCK_GIT_LFS_POST_CHECKOUT, 0o755); + assert_eq!(found(), PostCheckoutHooks::GitLfsOnly); + + write_hook(&hooks, STOCK_GIT_LFS_POST_CHECKOUT, 0o644); + assert_eq!( + found(), + PostCheckoutHooks::None, + "stock, but not executable" + ); + + write_hook( + &hooks, + &format!("{STOCK_GIT_LFS_POST_CHECKOUT}mise trust\n"), + 0o755, + ); + assert_eq!( + found(), + PostCheckoutHooks::Other, + "stock, with a line added" + ); +} + +/// What `git lfs install` writes on this machine is recognised, whichever +/// Git LFS that is: a rewording this fails on needs teaching to +/// [`is_stock_git_lfs_post_checkout`], which until then costs such repos +/// only the head start. +#[cfg(unix)] +#[test] +fn the_hook_this_machines_git_lfs_installs_is_recognised() { + if !git_lfs_installed("the_hook_this_machines_git_lfs_installs_is_recognised") { + return; + } + let root = TempDir::new("post-checkout-lfs"); + let (repo, hooks, worktree) = repo_with_worktree(root.path()); + + // Not through `repo.run_git`, which turns the hook directory off. + cli::run(repo.path(), &["lfs", "install", "--local"]).expect("git lfs install"); + + let installed = std::fs::read_to_string(hooks.join("post-checkout")).expect("the hook"); + assert_eq!( + post_checkout_hooks_for_worktree(repo.path(), &worktree), + PostCheckoutHooks::GitLfsOnly, + "{installed}" + ); +} + +/// A relative `core.hooksPath` is looked up from the worktree, as `git +/// hook run` there does: the hook is the branch's copy, and a branch +/// without the directory has none, whatever the repo's main checkout has. +#[cfg(unix)] +#[test] +fn a_relative_hooks_path_is_the_worktrees_own() { + let root = TempDir::new("post-checkout-relative"); + let (repo, _, without) = repo_with_worktree(root.path()); + repo.run_git(&["config", "core.hooksPath", ".githooks"]); + write_hook( + &repo.path().join(".githooks"), + "#!/bin/sh\ndirenv allow\n", + 0o755, + ); + let with_hooks = repo.commit("hooks"); + let with = root.path().join("with"); + super::super::create_detached_worktree_without_hooks(repo.path(), &with_hooks, &with, false) + .unwrap(); + + assert_eq!( + post_checkout_hooks_for_worktree(repo.path(), &with), + PostCheckoutHooks::Other + ); + assert_eq!( + post_checkout_hooks_for_worktree(repo.path(), &without), + PostCheckoutHooks::None, + "the main checkout's copy is not this worktree's" + ); +} + +/// A git that runs hooks named in config lists them, and one of those is a +/// hook that may do anything, with the stock Git LFS file or without it. +#[cfg(unix)] +#[test] +fn a_hook_named_in_config_is_another_hook() { + let root = TempDir::new("post-checkout-config"); + let (repo, hooks, worktree) = repo_with_worktree(root.path()); + if !git_lists_hooks(repo.path(), &hooks) { + eprintln!( + "skipping a_hook_named_in_config_is_another_hook: this git has no `git hook list`" + ); + return; + } + let found = || post_checkout_hooks_for_worktree(repo.path(), &worktree); + assert_eq!(found(), PostCheckoutHooks::None); + + repo.run_git(&["config", "hook.setup.event", "post-checkout"]); + repo.run_git(&["config", "hook.setup.command", "direnv allow"]); + assert_eq!(found(), PostCheckoutHooks::Other, "config's hook alone"); + + write_hook(&hooks, STOCK_GIT_LFS_POST_CHECKOUT, 0o755); + assert_eq!(found(), PostCheckoutHooks::Other, "beside the stock file"); + + // Another event's hook is not this one's. + repo.run_git(&["config", "hook.setup.event", "post-merge"]); + assert_eq!(found(), PostCheckoutHooks::GitLfsOnly); +} diff --git a/apps/staged/src-tauri/src/git/worktree.rs b/apps/staged/src-tauri/src/git/worktree.rs index 9dade16e1..6df1c82f0 100644 --- a/apps/staged/src-tauri/src/git/worktree.rs +++ b/apps/staged/src-tauri/src/git/worktree.rs @@ -304,16 +304,29 @@ fn lists_hook_command(builtins: &str) -> bool { /// the worktree's head, and `1` for a branch checkout. Hooks tell a new /// worktree by that null id, and some do their setup only then. /// -/// The hook is found and run by `git hook run`, so `core.hooksPath` and the -/// rest apply as they would have; check [`can_run_hooks_on_request`] before +/// The hook is found and run by `git hook run`, so `core.hooksPath` and +/// hooks named in config apply; check [`can_run_hooks_on_request`] before /// building a worktree this way. It runs at the worktree's root with /// `repo`'s captured env, and `GIT_LFS_SKIP_SMUDGE` when the checkout had -/// it, as under `git worktree add`. One difference remains: git exports -/// `GIT_DIR` to it, as it does to every hook it fires from inside a linked -/// worktree, where `git worktree add` clears it. +/// it, as under `git worktree add`. /// -/// No hook is success. A hook that fails is the error, as it fails `git -/// worktree add`; the worktree stays as it is. +/// Two differences from `git worktree add ` remain: +/// +/// - Git exports `GIT_DIR` to the hook, as it does to every hook it fires +/// from inside a linked worktree, where `git worktree add` clears it. +/// - A relative `core.hooksPath`, `.githooks` say, is resolved from where +/// git runs. `git -C worktree add` takes the hook from `repo`'s +/// main checkout, whatever that has checked out; this takes it from the +/// new worktree, so it is the branch's copy that runs. A branch without +/// that directory has no hook here, and none fires, silently, where the +/// add would have fired the main checkout's. Every later checkout in the +/// worktree finds its hook the way this does. An absolute path, and the +/// default hook directory, are the same from both. +/// +/// [`post_checkout_hooks_for_worktree`](super::post_checkout_hooks_for_worktree) +/// tells what this is about to run. No hook is success. A hook that fails +/// is the error, as it fails `git worktree add`; the worktree stays as it +/// is. pub fn run_post_checkout_as_for_a_new_worktree( repo: &Path, worktree_path: &Path, diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs index 2cfa1dece..d5acea744 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs @@ -14,6 +14,16 @@ //! `git worktree add ` tells it: no previous head. A hook //! that sets a new worktree up on seeing that still does. //! +//! Such a hook may change what a shell picks up in the worktree: allow its +//! `.envrc`, trust or write a tool-versions file. A worktree added late is +//! first captured after the hook, inside `git worktree add`, has run. So +//! when a hook is about to run here, the capture the early add started is +//! waited out and dropped before it does, and the finish captures after +//! it; the hook never runs beside that capture's shell. A repo with no +//! `post-checkout` hook keeps the head start, as does one whose only hook +//! is the one `git lfs install` writes +//! ([`crate::git::PostCheckoutHooks`]). +//! //! This is an optimisation with a complete fallback. A leg with no commit //! to start from, a git too old to fire a hook on request, an early add or //! a switch that fails, or a guess about Git LFS the snapshot contradicts, @@ -31,6 +41,7 @@ use std::time::{Duration, Instant}; use super::super::carry::{CarryOutcome, CarryPlan}; use super::super::undo::{self, AddedWorktree}; use super::{origin_tip_names, Failure, Leg, Run}; +use crate::git::PostCheckoutHooks; #[cfg(test)] mod seams; @@ -61,7 +72,9 @@ pub(super) struct EarlyAdd { impl EarlyWorktree { /// Add the worktree, and start capturing its shell environment so the /// finish finds it cached or waits only for the rest. Hooks stay off: - /// `post-checkout` fires once, when the worktree is on its branch. + /// `post-checkout` fires once, when the worktree is on its branch, and + /// this capture is kept only if that changes nothing it read + /// ([`early_capture_unusable`]). pub(super) fn add(&self) -> EarlyAdd { let started = Instant::now(); let result = self.add_detached(); @@ -109,6 +122,9 @@ pub(super) struct WorktreeTimings { /// The early add and the commit it started from. early_add: Option<(Duration, String)>, switch: Option, + /// The wait for the capture the early add started, when it could not + /// serve the finish, and why it could not. + early_capture_dropped: Option<(Duration, &'static str)>, /// The `post-checkout` fired once the early worktree was on its branch. hook: Option, /// The add once the branch had landed: the only one, or the fallback's. @@ -128,6 +144,9 @@ impl WorktreeTimings { if let Some(took) = self.switch { parts.push(format!("switch {took:.1?}")); } + if let Some((took, why)) = self.early_capture_dropped { + parts.push(format!("early environment dropped {took:.1?} ({why})")); + } if let Some(took) = self.hook { parts.push(format!("post-checkout {took:.1?}")); } @@ -211,6 +230,28 @@ pub(super) fn env_capture_is_stale(clone: &Path, start: &str, head: &str) -> boo } } +/// Why the shell environment captured in `worktree` since its early add at +/// `start` can't serve the finish, now that it is on its branch at `head` +/// and `post-checkout` is about to fire; `None` when it can. +/// +/// A hook comes first: one that may change what a shell picks up there +/// ([`PostCheckoutHooks::Other`]) must run before the capture the finish +/// uses, as it does when `git worktree add` fires it, and not beside the +/// shell of an earlier one. Without such a hook, the capture is as good as +/// one made now unless the two commits differ in what it reads +/// ([`env_capture_is_stale`]). +fn early_capture_unusable( + clone: &Path, + worktree: &Path, + start: &str, + head: &str, +) -> Option<&'static str> { + if crate::git::post_checkout_hooks_for_worktree(clone, worktree) == PostCheckoutHooks::Other { + return Some("a post-checkout hook runs first"); + } + env_capture_is_stale(clone, start, head).then_some("captured at another commit") +} + impl Run<'_> { /// Before the leg's capture starts: pick the commit and the path for /// its worktree and record it, as the late add would have. `None` leaves @@ -256,9 +297,12 @@ impl Run<'_> { /// Once the leg's branch has landed: put it in its worktree. The early /// worktree is switched onto the branch and `post-checkout` fired as for - /// a new worktree; without one, or when it or the switch failed, or its - /// LFS guess was wrong, the worktree is added on the branch as it always - /// was — at the early one's path, once that is cleared. + /// a new worktree, once the capture the early add started is out of the + /// way when the hook or the switch leaves it unusable + /// ([`early_capture_unusable`]). Without an early worktree, or when it + /// or the switch failed, or its LFS guess was wrong, the worktree is + /// added on the branch as it always was — at the early one's path, once + /// that is cleared. /// /// `post-checkout` fires once either way. So a hook that fails after /// the switch fails the leg, as it fails `git worktree add`, rather @@ -316,6 +360,21 @@ impl Run<'_> { match switched { Ok(()) => { timings.switch = Some(switching.elapsed()); + if let Some(why) = early_capture_unusable( + &clone, + &early.path, + &early.start, + &outcome.snapshot.head, + ) { + // The capture may still be running. It is + // waited out, not just dropped: its shell would + // run on beside the hook, and beside the capture + // the finish starts, where nothing that removes + // the worktree could wait for it. + let waiting = Instant::now(); + crate::git::wait_out_and_invalidate_shell_env(&early.path); + timings.early_capture_dropped = Some((waiting.elapsed(), why)); + } let firing = Instant::now(); crate::git::run_post_checkout_as_for_a_new_worktree( &clone, @@ -324,13 +383,6 @@ impl Run<'_> { ) .map_err(|e| format!("Cannot add the worktree for {branch}: {e}"))?; timings.hook = Some(firing.elapsed()); - if env_capture_is_stale(&clone, &early.start, &outcome.snapshot.head) { - // The capture may still be running. Dropped now - // it would run on beside the one the finish - // starts, where nothing that removes the - // worktree could wait for it. - crate::git::wait_out_and_invalidate_shell_env(&early.path); - } return Ok((early.path, timings)); } Err(why) => { diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs index b077a1e34..c70fdf176 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs @@ -9,6 +9,11 @@ //! The shell-environment calls do nothing under test, so what these tests //! see of them is which were made for the worktree, in what order, and //! whether the worktree was there at the time. +//! +//! Whether the capture the early add starts is kept depends on the +//! `post-checkout` hooks git finds, and a machine may have a hook directory +//! of its own for every repo. A test that looks at those calls therefore +//! gives the clone its own: a hook, or an empty directory. use std::time::{Duration, Instant}; @@ -79,26 +84,42 @@ fn gate_the_early_add(f: &Fixture) -> (GatedEarlyAdds, Arc>>) { /// Give the clone a `post-checkout` hook that logs its three arguments and /// then runs `then`. Returns the log. fn record_post_checkout(f: &Fixture, then: &str) -> PathBuf { + let log = f.host.root.join("post-checkout.log"); + install_post_checkout( + f, + &format!( + "#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n{then}\n", + log.display() + ), + ); + log +} + +/// Give the clone a hook directory holding only a `post-checkout` with +/// this content. +fn install_post_checkout(f: &Fixture, script: &str) { use std::os::unix::fs::PermissionsExt; let hooks = f.host.root.join("hooks"); - let log = f.host.root.join("post-checkout.log"); fs::create_dir_all(&hooks).unwrap(); let hook = hooks.join("post-checkout"); - fs::write( - &hook, - format!( - "#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n{then}\n", - log.display() - ), - ) - .unwrap(); + fs::write(&hook, script).unwrap(); fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap(); git( &f.host.clone_of(WIDGETS), &["config", "core.hooksPath", path(&hooks)], ); - log +} + +/// Give the clone an empty hook directory: no hook of its own, and none of +/// the machine's. +fn without_hooks(f: &Fixture) { + let hooks = f.host.root.join("no-hooks"); + fs::create_dir_all(&hooks).unwrap(); + git( + &f.host.clone_of(WIDGETS), + &["config", "core.hooksPath", path(&hooks)], + ); } fn lines(log: &Path) -> Vec { @@ -125,6 +146,17 @@ fn shell_env_calls(watch: &Watch, worktree: &Path) -> Vec<(&'static str, bool)> .collect() } +/// The shell-environment calls made for `worktree`, in order, each with +/// whether the file `watch` notes was there by then. +fn shell_env_calls_noting(watch: &Watch, worktree: &Path) -> Vec<(&'static str, bool)> { + watch + .calls() + .into_iter() + .filter(|call| call.path == worktree) + .map(|call| (call.what, call.noted)) + .collect() +} + /// A commit made in the workspace's checkout, which the clone has never /// seen: the early worktree starts at what origin has, and the switch has /// files to rewrite. `file` is one the commit adds. @@ -176,10 +208,14 @@ fn worktree_on_feature_at(f: &Fixture, head: &str) -> PathBuf { /// capture would never see the snapshot start, and one made after it would /// not finish while the snapshot waits. The workspace's head is new to the /// clone, so the worktree starts at what origin has of the branch. +/// +/// The clone has no `post-checkout` hook, so the capture the add started +/// is the one the finish uses. #[test] fn the_worktree_is_added_while_the_snapshot_runs() { let f = Fixture::new(&[(WIDGETS, "feature")]); let (pushed, _) = send_to_a_workspace(&f); + without_hooks(&f); let checkout = f.checkout(0); let head = commit_in_the_workspace(&f, "remote.txt"); write( @@ -212,8 +248,9 @@ fn the_worktree_is_added_while_the_snapshot_runs() { head_moves(&worktree) ); assert_eq!(temp_refs(&worktree), ""); - // The capture started by the add is the one the finish waits for: - // nothing between the two commits changes what a capture reads. + // The capture started by the add is the one the finish waits for: no + // hook runs, and nothing between the two commits changes what a + // capture reads. assert_eq!( shell_env_calls(&watch, &worktree), [("invalidate", true), ("prewarm", true), ("wait", true)] @@ -270,6 +307,136 @@ fn post_checkout_sees_a_new_worktree_when_the_start_commit_is_the_head() { assert_eq!(lines(&log), [new_worktree_at(&head)]); } +/// A `post-checkout` hook may change what a shell picks up in the worktree, +/// and the capture the early add started ran before it. So that capture is +/// waited out and dropped before the hook fires, and the finish captures +/// after it: the order a worktree added late has, with no shell of an +/// earlier capture in the directory while the hook works. The clone holds +/// the head, so the two commits are the same and the hook is the only +/// reason. +#[test] +fn a_post_checkout_hook_runs_after_the_early_capture_and_before_the_finishs() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { + eprintln!("skipping: this git has no `git hook run`"); + return; + } + let (_, head) = send_to_a_workspace(&f); + let log = record_post_checkout(&f, ""); + let worktree = worktree_path(&f); + let watch = Watch::under(&f.host.root).noting(&log); + + f.transfer(true).result.expect("to local"); + + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert!( + switched_from(&worktree, &head), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(lines(&log), [new_worktree_at(&head)]); + assert_eq!( + shell_env_calls(&watch, &worktree), + [ + ("invalidate", true), + ("prewarm", true), + ("wait out and invalidate", true), + ("wait", true) + ] + ); + // Each call with whether the hook had run by then. + assert_eq!( + shell_env_calls_noting(&watch, &worktree), + [ + ("invalidate", false), + ("prewarm", false), + ("wait out and invalidate", false), + ("wait", true) + ] + ); +} + +/// A clone with no `post-checkout` hook keeps the capture the early add +/// started, in the commonest case too: the clone holds the head, the switch +/// moves no file, and nothing fires. +#[test] +fn without_a_post_checkout_hook_the_early_capture_serves_the_finish() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let (_, head) = send_to_a_workspace(&f); + without_hooks(&f); + let worktree = worktree_path(&f); + let watch = Watch::under(&f.host.root); + + f.transfer(true).result.expect("to local"); + + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert!( + switched_from(&worktree, &head), + "{:?}", + head_moves(&worktree) + ); + assert_eq!( + shell_env_calls(&watch, &worktree), + [("invalidate", true), ("prewarm", true), ("wait", true)] + ); +} + +/// A hook that is there but not executable is one git ignores, so it +/// costs nothing either. +#[test] +fn a_post_checkout_git_would_ignore_keeps_the_early_capture() { + use std::os::unix::fs::PermissionsExt; + + let f = Fixture::new(&[(WIDGETS, "feature")]); + let (_, head) = send_to_a_workspace(&f); + let log = record_post_checkout(&f, ""); + let hook = f.host.root.join("hooks").join("post-checkout"); + fs::set_permissions(&hook, fs::Permissions::from_mode(0o644)).unwrap(); + let worktree = worktree_path(&f); + let watch = Watch::under(&f.host.root); + + f.transfer(true).result.expect("to local"); + + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert_eq!(lines(&log), [""; 0], "the hook ran"); + assert_eq!( + shell_env_calls(&watch, &worktree), + [("invalidate", true), ("prewarm", true), ("wait", true)] + ); +} + +/// The hook `git lfs install` writes only sets the write flag of lockable +/// files, so a clone whose one hook is that keeps the capture the early +/// add started, and the hook still fires. +#[test] +fn the_stock_git_lfs_post_checkout_keeps_the_early_capture() { + if !lfs_installed("the_stock_git_lfs_post_checkout_keeps_the_early_capture") { + return; + } + let f = Fixture::new(&[(WIDGETS, "feature")]); + if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { + eprintln!("skipping: this git has no `git hook run`"); + return; + } + let (_, head) = send_to_a_workspace(&f); + install_post_checkout(&f, crate::git::STOCK_GIT_LFS_POST_CHECKOUT); + let worktree = worktree_path(&f); + let watch = Watch::under(&f.host.root); + + f.transfer(true).result.expect("to local"); + + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert!( + switched_from(&worktree, &head), + "{:?}", + head_moves(&worktree) + ); + assert_eq!( + shell_env_calls(&watch, &worktree), + [("invalidate", true), ("prewarm", true), ("wait", true)] + ); +} + /// A git that cannot fire a hook on request gets no early worktree: the /// worktree is added on the branch once that has landed, and git fires the /// hook itself, the same once and with the same arguments. @@ -333,11 +500,13 @@ fn a_post_checkout_that_fails_fails_the_transfer_having_fired_once() { /// The capture the early add started ran at the start commit. When the /// branch's head differs from it in something a capture reads, that capture /// is waited out and dropped before the finish asks for a new one, so two -/// are never running in the worktree and none is left untracked. +/// are never running in the worktree and none is left untracked. No hook +/// is needed for that. #[test] fn a_stale_capture_is_waited_out_before_the_finish_captures_again() { let f = Fixture::new(&[(WIDGETS, "feature")]); let (pushed, _) = send_to_a_workspace(&f); + without_hooks(&f); let head = commit_in_the_workspace(&f, ".nvmrc"); let watch = Watch::under(&f.host.root); From 5c6e7df3a9c51b1259f5b7a3f61336f91909530c Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Tue, 17 Nov 2026 17:29:14 +1100 Subject: [PATCH 4/4] fix(staged): add a transferred worktree late when config names a post-checkout hook A transfer from Blox adds each branch's worktree early with the hook directory turned off, switches it onto the branch the same way, then fires `post-checkout` once with `git hook run`. Review of that found one defect and two things to tighten. `core.hooksPath=/dev/null` only turns the hook directory off. Git 2.54 and later also run hooks that config names (`hook..event` with `hook..command`), wherever the hook directory points. Such a `post-checkout` fired at the detached add, told of the start commit, again at the switch, told the worktree came from there, and a third time on request. A leg now asks the clone's effective config, with `git config --get-regexp` over the `hook..event` keys, before it plans an early worktree. When any of them is `post-checkout` it plans none and adds the worktree once the branch has landed, as before this branch, so git fires the hook once with the null id. An event counts even if a later empty value or `hook..enabled` takes it back, and on a git too old to run it. The check that decides whether the early capture of the shell environment must be dropped read `git hook list` and took any failure for "no hooks named in config": no hooks, a git without the subcommand, a config git could not parse, and a child that never ran all looked the same. It now uses the same config query, which every git answers. Only exit 1 with nothing printed is "none". Any other exit, a killed child, or a git that cannot be spawned counts as a hook, so the capture is dropped. `cli::run_output` returns the exit status with the captured environment, as `run_lite_output` does with the inherited one. A hook that may do anything was only looked for once the worktree was on its branch, so the early add always started a capture that such a hook then cost: a login shell, one of the four capture slots, and a wait before the hook. `git::post_checkout_hooks_to_come` now answers from the clone before the add. The default hook directory and an absolute `core.hooksPath` are the same from every worktree, so a hook there is already known, and the early add then starts no capture. The worktree is still added early. A relative `core.hooksPath` makes the hook the branch's own file, so that case alone is still decided once the worktree is on its branch, with the wait-out as before. The check on the branch stays in every case, and still waits out whatever capture is in flight before a hook fires. Each leg's log line says when no early capture was started. The clone's config is read as its main checkout reads it. A conditional include that only the new worktree matches is not seen before the add. Tests no longer depend on the machine's git config. A test-only guard, `OwnConfigOnly`, keyed by directory like the shell-environment recorder, makes the git that `git::cli` runs for repos under it read no global or system config. The early-worktree tests and the hook-detection tests hold one, so a hook manager's `core.hooksPath` or a hook named in the user's config no longer decides them, and the default hook directory is exercised. The per-test empty hook directory is gone. Tests: a clone with a config-named hook that logs every invocation gets its worktree added on the branch, starts nothing early, and logs one line with the null id; with the plan check removed that test fails. A hook in an absolute hook directory keeps the early add, starts no capture, and runs before the finish's. A hook committed on the branch under a relative `core.hooksPath` keeps the earlier order: prewarm, wait-out, hook, capture. The detection is tested from the worktree and from the clone for the default directory, an absolute one, a relative one and a config-named hook, and the two must agree where the directory is shared. The exit-status reading is tested over "none", other events, a taken-back event, exits 128, 129 and 3, an exit 1 with a complaint or with output, and a killed child. A repo whose config git cannot parse, and a path that is no repo, count as having a hook. Signed-off-by: Matt Toohey Co-Authored-By: Claude Fable 5.2 --- apps/staged/src-tauri/src/git/cli.rs | 61 ++++- apps/staged/src-tauri/src/git/mod.rs | 7 +- .../src-tauri/src/git/post_checkout_hook.rs | 238 ++++++++++++---- .../src/git/post_checkout_hook/tests.rs | 258 ++++++++++++++---- apps/staged/src-tauri/src/git/worktree.rs | 13 +- .../orchestrator/early_worktree.rs | 104 +++++-- .../orchestrator_tests/early_worktree.rs | 189 ++++++++++++- 7 files changed, 710 insertions(+), 160 deletions(-) diff --git a/apps/staged/src-tauri/src/git/cli.rs b/apps/staged/src-tauri/src/git/cli.rs index 9a6e7a7ac..7cf998588 100644 --- a/apps/staged/src-tauri/src/git/cli.rs +++ b/apps/staged/src-tauri/src/git/cli.rs @@ -233,7 +233,19 @@ pub struct GitOutput { /// [`GitOutput`] for the caller to interpret. A git that cannot be spawned, a /// path that is not a repository, and non-UTF-8 stdout are still errors. pub fn run_lite_output(repo: &Path, args: &[&str]) -> Result { - let output = spawn_git(repo, args, EnvSource::Lite)?; + output_with_env(repo, args, EnvSource::Lite) +} + +/// [`run`] without the success check, as [`run_lite_output`] is to +/// [`run_lite`]: for a question whose answer is in the exit status and +/// depends on which git answers and with what config, so it is asked with +/// the env the commands it is about will run with. +pub fn run_output(repo: &Path, args: &[&str]) -> Result { + output_with_env(repo, args, EnvSource::Captured) +} + +fn output_with_env(repo: &Path, args: &[&str], source: EnvSource) -> Result { + let output = spawn_git(repo, args, source)?; let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); if !output.status.success() && stderr.contains("not a git repository") { return Err(GitError::NotARepo(repo.display().to_string())); @@ -422,6 +434,50 @@ pub(crate) mod shell_env_calls { } } +/// Keeps the machine's git config out of a test. The git this module runs +/// reads the user's and the system's config like any other, so a test of +/// something that config decides (which hooks fire, say, on a machine whose +/// hook manager owns `core.hooksPath`) would pass or fail by where it ran. +#[cfg(test)] +pub(crate) mod own_config_only { + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::sync::Mutex; + + static DIRS: Mutex> = Mutex::new(Vec::new()); + + /// While it lives, the git this module runs for a repo under its + /// directory, from whichever thread, reads no config but the repo's + /// own. Git a test runs itself is not touched. + pub(crate) struct OwnConfigOnly(PathBuf); + + impl OwnConfigOnly { + pub(crate) fn under(dir: &Path) -> Self { + let mut dirs = DIRS.lock().unwrap_or_else(|e| e.into_inner()); + dirs.push(dir.to_path_buf()); + Self(dir.to_path_buf()) + } + } + + impl Drop for OwnConfigOnly { + fn drop(&mut self) { + let mut dirs = DIRS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = dirs.iter().position(|dir| *dir == self.0) { + dirs.remove(at); + } + } + } + + pub(super) fn apply(command: &mut Command, repo: &Path) { + let dirs = DIRS.lock().unwrap_or_else(|e| e.into_inner()); + if dirs.iter().any(|dir| repo.starts_with(dir)) { + command + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_NOSYSTEM", "1"); + } + } +} + /// Which environment to pass to the spawned git process. /// /// Also surfaces at the `state::compute_local_branch_git_state` boundary as a @@ -696,8 +752,9 @@ fn apply_env(command: &mut Command, repo: &Path, source: EnvSource) -> AppliedEn } #[cfg(test)] -fn apply_env(command: &mut Command, _repo: &Path, _source: EnvSource) -> AppliedEnv { +fn apply_env(command: &mut Command, repo: &Path, _source: EnvSource) -> AppliedEnv { strip_git_env(command); + own_config_only::apply(command, repo); pin_c_locale(command); AppliedEnv::Lite } diff --git a/apps/staged/src-tauri/src/git/mod.rs b/apps/staged/src-tauri/src/git/mod.rs index ad666696e..2fdd674fc 100644 --- a/apps/staged/src-tauri/src/git/mod.rs +++ b/apps/staged/src-tauri/src/git/mod.rs @@ -20,6 +20,8 @@ mod worktree; pub use branch_config::{read_branch_config_snapshot, BranchConfigSnapshot}; pub(crate) use cli::configure_captured; pub(crate) use cli::invalidate_shell_env; +#[cfg(test)] +pub(crate) use cli::own_config_only::OwnConfigOnly; pub(crate) use cli::prewarm_shell_env; pub(crate) use cli::run as cli_run; pub(crate) use cli::run_lite_or_captured as cli_run_lite_or_captured; @@ -48,7 +50,10 @@ pub use github::{ }; #[cfg(test)] pub(crate) use post_checkout_hook::STOCK_GIT_LFS_POST_CHECKOUT; -pub use post_checkout_hook::{post_checkout_hooks_for_worktree, PostCheckoutHooks}; +pub use post_checkout_hook::{ + post_checkout_hooks_for_worktree, post_checkout_hooks_to_come, PostCheckoutHooks, + PostCheckoutHooksToCome, +}; pub use rebase::{rebase_preserving_merge_edits_command, HAND_EDIT_COMMIT_SUBJECT_PREFIX}; pub use refs::{ branch_name_without_origin, detect_default_branch, detect_default_branch_from_remote, diff --git a/apps/staged/src-tauri/src/git/post_checkout_hook.rs b/apps/staged/src-tauri/src/git/post_checkout_hook.rs index fa2210377..b4e12be65 100644 --- a/apps/staged/src-tauri/src/git/post_checkout_hook.rs +++ b/apps/staged/src-tauri/src/git/post_checkout_hook.rs @@ -1,13 +1,21 @@ //! Which `post-checkout` hooks git would fire in a worktree, for a caller -//! that has something to settle before they run. +//! that has something to settle before they run, or that means to keep +//! them quiet through a checkout of its own. //! //! A hook can do anything: allow a `.envrc`, trust a tool-versions file, //! write either. The one exception told apart here is the hook `git lfs //! install` writes, which is common and is known to do none of that. +//! +//! Git finds hooks in two places: the hook directory's file, and, from +//! git 2.54, config (`hook..event` with `hook..command`). Both +//! are read here from what decides them, the file and the config, so the +//! answer needs no `git hook list`, which gits before 2.54 lack. Whatever +//! cannot be told for certain counts as a hook. -use std::path::Path; +use std::path::{Path, PathBuf}; -use super::cli; +use super::branch_config::parse_config_entries_z; +use super::cli::{self, GitOutput}; /// What `git hook run post-checkout` would run in a worktree. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -20,91 +28,205 @@ pub enum PostCheckoutHooks { /// worktree. GitLfsOnly, /// Something else, which may do anything. Also the answer when git - /// could not be asked. + /// could not be asked, or what it said could not be read. Other, } +/// What a repo can tell of the `post-checkout` hooks of a worktree it has +/// yet to add. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PostCheckoutHooksToCome { + /// Its config names one, or could not be read. Git runs such a hook + /// wherever `core.hooksPath` points, so + /// [`create_detached_worktree_without_hooks`] and + /// [`switch_detached_worktree_to_branch`] would each fire it. + /// + /// [`create_detached_worktree_without_hooks`]: super::create_detached_worktree_without_hooks + /// [`switch_detached_worktree_to_branch`]: super::switch_detached_worktree_to_branch + NamedInConfig, + /// Config names none, and the hook directory is the same from every + /// worktree (the default one, or an absolute `core.hooksPath`): this + /// is what the worktree will have. + Known(PostCheckoutHooks), + /// Config names none, and `core.hooksPath` is relative, so the hook is + /// the one in the worktree's own files: its branch decides, and + /// [`post_checkout_hooks_for_worktree`] tells once it is checked out. + OfTheBranch, +} + /// The `post-checkout` hooks `git -C hook run` would run /// for `worktree_path`, a worktree of `repo`, as /// [`run_post_checkout_as_for_a_new_worktree`] is about to. /// /// Git is asked for the hook directory's file, which follows /// `core.hooksPath` as the run does (a relative one from the worktree), and -/// for its own list of hooks where it has one (`git hook list`, which -/// came with the hooks git runs from config). The file counts when git -/// would run it: there and executable. +/// for the hooks its config names there. The file counts when git would +/// run it: there and executable. A hook config names counts whether or not +/// this git runs such hooks, or config goes on to disable it. /// /// [`run_post_checkout_as_for_a_new_worktree`]: super::run_post_checkout_as_for_a_new_worktree pub fn post_checkout_hooks_for_worktree(repo: &Path, worktree_path: &Path) -> PostCheckoutHooks { let Some(worktree_str) = worktree_path.to_str() else { return PostCheckoutHooks::Other; }; + if config_names_post_checkout_hook(repo, &["-C", worktree_str]) { + return PostCheckoutHooks::Other; + } + hook_file_git_finds(repo, worktree_path, &["-C", worktree_str]) + .map_or(PostCheckoutHooks::Other, |file| hook_file_at(&file)) +} + +/// What `repo` can tell of the `post-checkout` hooks of a worktree before +/// adding it: enough to plan around all but a relative `core.hooksPath`. +/// +/// Config is read as `repo`'s main checkout reads it. A conditional +/// include that only the worktree will match (`includeIf "onbranch:…"`) +/// is not seen here; [`post_checkout_hooks_for_worktree`] sees it once the +/// worktree is there. +pub fn post_checkout_hooks_to_come(repo: &Path) -> PostCheckoutHooksToCome { + if config_names_post_checkout_hook(repo, &[]) { + return PostCheckoutHooksToCome::NamedInConfig; + } + + // git config -z --type=path --get core.hooksPath + // As git reads it: the last value, with a leading `~` expanded. + let hooks_path = ["config", "-z", "--type=path", "--get", "core.hooksPath"]; + let hooks_dir = match cli::run_output(repo, &hooks_path) { + Ok(output) => hooks_dir_to_come(&output), + Err(e) => Err(e.to_string()), + }; + let file = match hooks_dir { + Ok(HooksDirToCome::Default) => hook_file_git_finds(repo, repo, &[]), + Ok(HooksDirToCome::At(dir)) => Some(dir.join("post-checkout")), + Ok(HooksDirToCome::OfTheBranch) => return PostCheckoutHooksToCome::OfTheBranch, + Err(why) => { + log::warn!( + "[git] cannot read core.hooksPath of {}: {why}", + repo.display() + ); + None + } + }; + PostCheckoutHooksToCome::Known( + file.map_or(PostCheckoutHooks::Other, |file| hook_file_at(&file)), + ) +} + +/// Where a worktree yet to be added will look for its hooks. +#[derive(Debug, PartialEq, Eq)] +enum HooksDirToCome { + /// The repo's own hook directory: `core.hooksPath` is not set. + Default, + /// An absolute `core.hooksPath`. + At(PathBuf), + /// A relative one, resolved from the worktree's root. + OfTheBranch, +} - // git -C rev-parse --git-path hooks/post-checkout - let git_path = [ - "-C", - worktree_str, - "rev-parse", - "--git-path", - "hooks/post-checkout", - ]; - let in_hooks_dir = match cli::run(repo, &git_path) { - // Relative to the worktree when it is relative. - Ok(path) => HookFile::at(&worktree_path.join(path.trim_end_matches(['\n', '\r']))), +/// Read a finished `git config -z --type=path --get core.hooksPath`. Exit +/// 1 with nothing said is git's "not set"; any other failure is not an +/// answer. +fn hooks_dir_to_come(output: &GitOutput) -> Result { + if nothing_matched(output) { + return Ok(HooksDirToCome::Default); + } + if !output.success { + return Err(describe_failure(output)); + } + let value = output.stdout.strip_suffix('\0').unwrap_or(&output.stdout); + let dir = Path::new(value); + Ok(if dir.is_absolute() { + HooksDirToCome::At(dir.to_path_buf()) + } else { + HooksDirToCome::OfTheBranch + }) +} + +/// The hook directory's `post-checkout` as git finds it with `at` (`-C +/// `, or nothing for `repo` itself), a relative answer being relative +/// to `dir`. `None` when git cannot say. +fn hook_file_git_finds(repo: &Path, dir: &Path, at: &[&str]) -> Option { + // git [-C ] rev-parse --git-path hooks/post-checkout + let mut args = at.to_vec(); + args.extend(["rev-parse", "--git-path", "hooks/post-checkout"]); + match cli::run(repo, &args) { + Ok(path) => Some(dir.join(path.trim_end_matches(['\n', '\r']))), Err(e) => { log::warn!( "[git] cannot find the post-checkout hook of {}: {e}", - worktree_path.display() + dir.display() ); - return PostCheckoutHooks::Other; + None } - }; + } +} - // git -C hook list -z post-checkout - // One name per hook it would run, or would but for being disabled. It - // fails when there are none, and on a git that has no list, which has - // no hooks but the file either. - let listed = cli::run( - repo, - &["-C", worktree_str, "hook", "list", "-z", "post-checkout"], - ) - .ok() - .map(|names| names.split('\0').filter(|name| !name.is_empty()).count()); +/// Every `hook..event` in config. +const HOOK_EVENTS: &str = r"^hook\..*\.event$"; - classify(in_hooks_dir, listed) +/// Whether the config git reads with `at` (`-C `, or nothing for +/// `repo` itself) names a `post-checkout` hook. Not being able to tell +/// counts as naming one. +fn config_names_post_checkout_hook(repo: &Path, at: &[&str]) -> bool { + // git [-C ] config -z --get-regexp '^hook\..*\.event$' + let mut args = at.to_vec(); + args.extend(["config", "-z", "--get-regexp", HOOK_EVENTS]); + let named = match cli::run_output(repo, &args) { + Ok(output) => events_name_post_checkout(&output), + Err(e) => Err(e.to_string()), + }; + named.unwrap_or_else(|why| { + log::warn!( + "[git] cannot read the hooks config names for {}: {why}", + repo.display() + ); + true + }) } -/// `listed` is how many hooks git listed, `None` when it listed none or -/// has no list. Whatever does not add up is [`PostCheckoutHooks::Other`]. -fn classify(in_hooks_dir: HookFile, listed: Option) -> PostCheckoutHooks { - match (in_hooks_dir, listed) { - (HookFile::Absent, None | Some(0)) => PostCheckoutHooks::None, - // Listed alone, the file is the one hook there is. - (HookFile::StockGitLfs, None | Some(1)) => PostCheckoutHooks::GitLfsOnly, - _ => PostCheckoutHooks::Other, +/// Read a finished `git config -z --get-regexp` over [`HOOK_EVENTS`]: +/// whether any hook is given the `post-checkout` event. One that is counts +/// even if a later empty value, or `hook..enabled`, takes it back. +/// Exit 1 with nothing said is git's "no key matched"; any other failure, +/// a child that was killed included, is not an answer. +fn events_name_post_checkout(output: &GitOutput) -> Result { + if nothing_matched(output) { + return Ok(false); } + if !output.success { + return Err(describe_failure(output)); + } + Ok(parse_config_entries_z(&output.stdout) + .iter() + .any(|(_, event)| event.as_deref() == Some("post-checkout"))) } -/// The `post-checkout` file of a hook directory. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum HookFile { - /// Not there, or not executable, which git ignores. - Absent, - StockGitLfs, - Other, +/// Whether a `git config` query ended the way it does when nothing is set: +/// exit 1, with no output and no complaint. +fn nothing_matched(output: &GitOutput) -> bool { + output.code == Some(1) && output.stdout.is_empty() && output.stderr.trim().is_empty() } -impl HookFile { - fn at(path: &Path) -> Self { - let runnable = - std::fs::metadata(path).is_ok_and(|file| file.is_file() && executable(&file)); - if !runnable { - return Self::Absent; - } - match std::fs::read_to_string(path) { - Ok(script) if is_stock_git_lfs_post_checkout(&script) => Self::StockGitLfs, - _ => Self::Other, - } +fn describe_failure(output: &GitOutput) -> String { + let stderr = output.stderr.trim(); + match (stderr.is_empty(), output.code) { + (false, _) => stderr.to_string(), + (true, Some(code)) => format!("git config exited with status {code}"), + (true, None) => "git config was killed by a signal".to_string(), + } +} + +/// What the hook directory's `post-checkout` at `path` is, when config +/// names no hook and it is the one there can be: nothing when it is not +/// there or not executable, which git ignores. +fn hook_file_at(path: &Path) -> PostCheckoutHooks { + let runnable = std::fs::metadata(path).is_ok_and(|file| file.is_file() && executable(&file)); + if !runnable { + return PostCheckoutHooks::None; + } + match std::fs::read_to_string(path) { + Ok(script) if is_stock_git_lfs_post_checkout(&script) => PostCheckoutHooks::GitLfsOnly, + _ => PostCheckoutHooks::Other, } } diff --git a/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs b/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs index 0132ec5d0..6ebb09748 100644 --- a/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs +++ b/apps/staged/src-tauri/src/git/post_checkout_hook/tests.rs @@ -1,8 +1,10 @@ -//! Every repo here names its own `core.hooksPath`, so a hook directory set -//! for the whole machine (a hook manager's, say) is not what gets found. +//! The git asked here reads no config but each repo's own +//! ([`OwnConfigOnly`]), so a hook directory or a hook the machine's config +//! sets (a hook manager's, say) is not what gets found. use std::path::{Path, PathBuf}; +use super::super::cli::own_config_only::OwnConfigOnly; use super::*; use crate::test_utils::{TempDir, TempGitRepo}; @@ -29,20 +31,19 @@ const EARLIER_STOCK_HOOKS: [&str; 3] = [ ), ]; -/// A repo with one commit, its hook directory an empty one under `root`, -/// and a linked worktree at that commit. Returns the hook directory and -/// the worktree. -fn repo_with_worktree(root: &Path) -> (TempGitRepo, PathBuf, PathBuf) { +/// A repo with one commit and a linked worktree at that commit under +/// `root`, asked about with no config but its own. Returns its hook +/// directory, the default one, and the worktree. +fn repo_with_worktree(root: &Path) -> (TempGitRepo, PathBuf, PathBuf, OwnConfigOnly) { let repo = TempGitRepo::new(); + let own_config = OwnConfigOnly::under(repo.path()); repo.write_file("tracked.txt", "base\n"); let base = repo.commit("base"); - let hooks = root.join("hooks"); - std::fs::create_dir_all(&hooks).unwrap(); - repo.run_git(&["config", "core.hooksPath", hooks.to_str().unwrap()]); + let hooks = repo.path().join(".git").join("hooks"); let worktree = root.join("wt"); super::super::create_detached_worktree_without_hooks(repo.path(), &base, &worktree, false) .unwrap(); - (repo, hooks, worktree) + (repo, hooks, worktree, own_config) } #[cfg(unix)] @@ -55,16 +56,6 @@ fn write_hook(hooks: &Path, script: &str, mode: u32) { std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(mode)).unwrap(); } -/// Whether this machine's git lists hooks, and so runs the ones config -/// names: it lists the one in `hooks`. -#[cfg(unix)] -fn git_lists_hooks(repo: &Path, hooks: &Path) -> bool { - write_hook(hooks, "#!/bin/sh\n", 0o755); - let lists = cli::run(repo, &["hook", "list", "-z", "post-checkout"]).is_ok(); - std::fs::remove_file(hooks.join("post-checkout")).unwrap(); - lists -} - fn git_lfs_installed(test: &str) -> bool { let installed = std::process::Command::new("git") .args(["lfs", "version"]) @@ -76,30 +67,130 @@ fn git_lfs_installed(test: &str) -> bool { installed } +/// A `git config` query that ended with `code` (`None`: killed), having +/// printed these. +fn finished(code: Option, stdout: &str, stderr: &str) -> GitOutput { + GitOutput { + success: code == Some(0), + code, + stdout: stdout.to_string(), + stderr: stderr.to_string(), + } +} + +/// What does not answer the question, whichever it was: a config git +/// cannot read, a usage error, an exit 1 that came with a complaint or +/// with output, a child that was killed. +const NO_ANSWER: [(Option, &str, &str); 6] = [ + ( + Some(128), + "", + "fatal: bad config line 3 in file .git/config\n", + ), + (Some(129), "", "usage: git config []\n"), + (Some(3), "", ""), + (Some(1), "", "warning: something else is wrong\n"), + (Some(1), "hook.setup.event\npost-merge\0", ""), + (None, "", ""), +]; + +#[test] +fn config_names_no_hook_only_when_git_says_so() { + let named = |stdout: &str| events_name_post_checkout(&finished(Some(0), stdout, "")); + + // No `hook..event` at all: exit 1, and nothing said. + assert_eq!( + events_name_post_checkout(&finished(Some(1), "", "")), + Ok(false) + ); + // Hooks, for other events. + assert_eq!( + named("hook.lint.event\npre-commit\0hook.lint.event\npre-push\0"), + Ok(false) + ); + assert_eq!( + named("hook.lint.event\npre-commit\0hook.setup.event\npost-checkout\0"), + Ok(true) + ); + // Taken back by an empty value, it still counts. + assert_eq!( + named("hook.setup.event\npost-checkout\0hook.setup.event\n\0"), + Ok(true) + ); + // The event, not a name or a value that only contains it. + assert_eq!( + named("hook.post-checkout-setup.event\npost-checkout-setup\0"), + Ok(false) + ); + + for (code, stdout, stderr) in NO_ANSWER { + let unreadable = events_name_post_checkout(&finished(code, stdout, stderr)); + assert!(unreadable.is_err(), "{code:?} {stdout:?} {stderr:?}"); + } +} + #[test] -fn only_a_file_with_nothing_else_listed_counts_as_none_or_as_git_lfs() { - use HookFile::{Absent, Other, StockGitLfs}; +fn the_hook_directory_to_come_is_the_default_an_absolute_one_or_the_branchs() { + let read = |stdout: &str| hooks_dir_to_come(&finished(Some(0), stdout, "")); - // A git with no list, or one that listed nothing: the file decides. - assert_eq!(classify(Absent, None), PostCheckoutHooks::None); - assert_eq!(classify(StockGitLfs, None), PostCheckoutHooks::GitLfsOnly); - assert_eq!(classify(Other, None), PostCheckoutHooks::Other); + assert_eq!( + hooks_dir_to_come(&finished(Some(1), "", "")), + Ok(HooksDirToCome::Default) + ); + assert_eq!( + read("/opt/hook-manager/hooks\0"), + Ok(HooksDirToCome::At(PathBuf::from("/opt/hook-manager/hooks"))) + ); + assert_eq!(read(".githooks\0"), Ok(HooksDirToCome::OfTheBranch)); + assert_eq!(read("tools/hooks\0"), Ok(HooksDirToCome::OfTheBranch)); + // Set to nothing: left for the worktree to tell. + assert_eq!(read("\0"), Ok(HooksDirToCome::OfTheBranch)); + + for (code, stdout, stderr) in NO_ANSWER { + let unreadable = hooks_dir_to_come(&finished(code, stdout, stderr)); + assert!(unreadable.is_err(), "{code:?} {stdout:?} {stderr:?}"); + } +} - // The file is what git listed. +/// A repo whose config git cannot read answers neither question, and that +/// counts as a hook: one that may do anything in a worktree it has, and +/// one nothing would keep quiet in a worktree it is yet to add. +#[test] +fn a_repo_that_cannot_be_asked_counts_as_having_a_hook() { + let root = TempDir::new("post-checkout-unreadable"); + let (repo, _, worktree, _own_config) = repo_with_worktree(root.path()); + assert_eq!( + post_checkout_hooks_for_worktree(repo.path(), &worktree), + PostCheckoutHooks::None + ); assert_eq!( - classify(StockGitLfs, Some(1)), - PostCheckoutHooks::GitLfsOnly + post_checkout_hooks_to_come(repo.path()), + PostCheckoutHooksToCome::Known(PostCheckoutHooks::None) ); - assert_eq!(classify(Other, Some(1)), PostCheckoutHooks::Other); - // A hook that config names, alone or beside the file. - assert_eq!(classify(Absent, Some(1)), PostCheckoutHooks::Other); - assert_eq!(classify(StockGitLfs, Some(2)), PostCheckoutHooks::Other); - assert_eq!(classify(Absent, Some(2)), PostCheckoutHooks::Other); + let config = repo.path().join(".git").join("config"); + let mut broken = std::fs::read_to_string(&config).unwrap(); + broken.push_str("[hook \"setup\n"); + std::fs::write(&config, broken).unwrap(); - // A list and a file that disagree. - assert_eq!(classify(Absent, Some(0)), PostCheckoutHooks::None); - assert_eq!(classify(StockGitLfs, Some(0)), PostCheckoutHooks::Other); + assert_eq!( + post_checkout_hooks_for_worktree(repo.path(), &worktree), + PostCheckoutHooks::Other + ); + assert_eq!( + post_checkout_hooks_to_come(repo.path()), + PostCheckoutHooksToCome::NamedInConfig + ); + // As does a place that is no repo at all. + let nowhere = root.path().join("nowhere"); + assert_eq!( + post_checkout_hooks_for_worktree(&nowhere, &worktree), + PostCheckoutHooks::Other + ); + assert_eq!( + post_checkout_hooks_to_come(&nowhere), + PostCheckoutHooksToCome::NamedInConfig + ); } #[test] @@ -166,17 +257,31 @@ fn a_git_lfs_hook_with_anything_added_or_changed_is_not_the_stock_one() { } } +/// Asked of the worktree, and of the repo before it adds one: with the +/// hook directory the same from both, the two must agree. +#[cfg(unix)] +fn found_from_both(repo: &Path, worktree: &Path) -> PostCheckoutHooks { + let found = post_checkout_hooks_for_worktree(repo, worktree); + assert_eq!( + post_checkout_hooks_to_come(repo), + PostCheckoutHooksToCome::Known(found) + ); + found +} + /// A hook directory with no `post-checkout`, or one git would ignore for /// not being executable, has no hook; any other file is one that may do -/// anything, and the stock Git LFS hook is told apart from those. +/// anything, and the stock Git LFS hook is told apart from those. The +/// directory is the repo's default one, which a worktree shares, so the +/// repo can tell the same before it adds the worktree. #[cfg(unix)] #[test] fn the_hook_directory_file_is_none_other_or_git_lfs() { let root = TempDir::new("post-checkout-hooks"); - let (repo, hooks, worktree) = repo_with_worktree(root.path()); - let found = || post_checkout_hooks_for_worktree(repo.path(), &worktree); + let (repo, hooks, worktree, _own_config) = repo_with_worktree(root.path()); + let found = || found_from_both(repo.path(), &worktree); - assert_eq!(found(), PostCheckoutHooks::None, "an empty hook directory"); + assert_eq!(found(), PostCheckoutHooks::None, "no hook but the samples"); write_hook(&hooks, "#!/bin/sh\ndirenv allow\n", 0o644); assert_eq!(found(), PostCheckoutHooks::None, "not executable"); @@ -206,6 +311,30 @@ fn the_hook_directory_file_is_none_other_or_git_lfs() { ); } +/// An absolute `core.hooksPath`, a hook manager's say, takes the place of +/// the default directory for the repo and its worktrees alike, so the repo +/// can tell what a worktree will have there too. +#[cfg(unix)] +#[test] +fn an_absolute_hooks_path_is_the_same_from_the_repo_and_its_worktrees() { + let root = TempDir::new("post-checkout-absolute"); + let (repo, default_hooks, worktree, _own_config) = repo_with_worktree(root.path()); + let found = || found_from_both(repo.path(), &worktree); + let hooks = root.path().join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + repo.run_git(&["config", "core.hooksPath", hooks.to_str().unwrap()]); + // No longer where git looks. + write_hook(&default_hooks, "#!/bin/sh\ndirenv allow\n", 0o755); + + assert_eq!(found(), PostCheckoutHooks::None, "an empty hook directory"); + + write_hook(&hooks, STOCK_GIT_LFS_POST_CHECKOUT, 0o755); + assert_eq!(found(), PostCheckoutHooks::GitLfsOnly); + + write_hook(&hooks, "#!/bin/sh\nexec hook-manager \"$@\"\n", 0o755); + assert_eq!(found(), PostCheckoutHooks::Other); +} + /// What `git lfs install` writes on this machine is recognised, whichever /// Git LFS that is: a rewording this fails on needs teaching to /// [`is_stock_git_lfs_post_checkout`], which until then costs such repos @@ -217,7 +346,7 @@ fn the_hook_this_machines_git_lfs_installs_is_recognised() { return; } let root = TempDir::new("post-checkout-lfs"); - let (repo, hooks, worktree) = repo_with_worktree(root.path()); + let (repo, hooks, worktree, _own_config) = repo_with_worktree(root.path()); // Not through `repo.run_git`, which turns the hook directory off. cli::run(repo.path(), &["lfs", "install", "--local"]).expect("git lfs install"); @@ -228,16 +357,21 @@ fn the_hook_this_machines_git_lfs_installs_is_recognised() { PostCheckoutHooks::GitLfsOnly, "{installed}" ); + assert_eq!( + post_checkout_hooks_to_come(repo.path()), + PostCheckoutHooksToCome::Known(PostCheckoutHooks::GitLfsOnly) + ); } /// A relative `core.hooksPath` is looked up from the worktree, as `git /// hook run` there does: the hook is the branch's copy, and a branch /// without the directory has none, whatever the repo's main checkout has. +/// So the repo cannot tell what a worktree yet to be added will have. #[cfg(unix)] #[test] fn a_relative_hooks_path_is_the_worktrees_own() { let root = TempDir::new("post-checkout-relative"); - let (repo, _, without) = repo_with_worktree(root.path()); + let (repo, _, without, _own_config) = repo_with_worktree(root.path()); repo.run_git(&["config", "core.hooksPath", ".githooks"]); write_hook( &repo.path().join(".githooks"), @@ -258,32 +392,46 @@ fn a_relative_hooks_path_is_the_worktrees_own() { PostCheckoutHooks::None, "the main checkout's copy is not this worktree's" ); + assert_eq!( + post_checkout_hooks_to_come(repo.path()), + PostCheckoutHooksToCome::OfTheBranch + ); } -/// A git that runs hooks named in config lists them, and one of those is a -/// hook that may do anything, with the stock Git LFS file or without it. +/// A hook that config names is one that may do anything, with the stock +/// Git LFS file or without it, and one the repo knows of before it adds a +/// worktree. That is read from config, so it is the answer on a git too +/// old to run such a hook as well. #[cfg(unix)] #[test] fn a_hook_named_in_config_is_another_hook() { let root = TempDir::new("post-checkout-config"); - let (repo, hooks, worktree) = repo_with_worktree(root.path()); - if !git_lists_hooks(repo.path(), &hooks) { - eprintln!( - "skipping a_hook_named_in_config_is_another_hook: this git has no `git hook list`" - ); - return; - } + let (repo, hooks, worktree, _own_config) = repo_with_worktree(root.path()); let found = || post_checkout_hooks_for_worktree(repo.path(), &worktree); + let to_come = || post_checkout_hooks_to_come(repo.path()); assert_eq!(found(), PostCheckoutHooks::None); - repo.run_git(&["config", "hook.setup.event", "post-checkout"]); + // Another event's hook is not this one's. + repo.run_git(&["config", "hook.setup.event", "post-merge"]); repo.run_git(&["config", "hook.setup.command", "direnv allow"]); + assert_eq!(found(), PostCheckoutHooks::None); + assert_eq!( + to_come(), + PostCheckoutHooksToCome::Known(PostCheckoutHooks::None) + ); + + repo.run_git(&["config", "--add", "hook.setup.event", "post-checkout"]); assert_eq!(found(), PostCheckoutHooks::Other, "config's hook alone"); + assert_eq!(to_come(), PostCheckoutHooksToCome::NamedInConfig); write_hook(&hooks, STOCK_GIT_LFS_POST_CHECKOUT, 0o755); assert_eq!(found(), PostCheckoutHooks::Other, "beside the stock file"); + assert_eq!(to_come(), PostCheckoutHooksToCome::NamedInConfig); - // Another event's hook is not this one's. - repo.run_git(&["config", "hook.setup.event", "post-merge"]); + repo.run_git(&["config", "--unset-all", "hook.setup.event"]); assert_eq!(found(), PostCheckoutHooks::GitLfsOnly); + assert_eq!( + to_come(), + PostCheckoutHooksToCome::Known(PostCheckoutHooks::GitLfsOnly) + ); } diff --git a/apps/staged/src-tauri/src/git/worktree.rs b/apps/staged/src-tauri/src/git/worktree.rs index 6df1c82f0..036776c71 100644 --- a/apps/staged/src-tauri/src/git/worktree.rs +++ b/apps/staged/src-tauri/src/git/worktree.rs @@ -206,7 +206,10 @@ fn add_worktree_for_existing_branch( } /// Add a worktree detached at `commit`, which `repo` must already hold, -/// without firing hooks. +/// without firing the hook directory's hooks. A hook that config names +/// fires all the same ([`HOOKS_OFF`]): a caller first checks that +/// [`post_checkout_hooks_to_come`](super::post_checkout_hooks_to_come) is +/// not [`NamedInConfig`](super::PostCheckoutHooksToCome::NamedInConfig). /// /// For a worktree made before its branch exists: /// [`switch_detached_worktree_to_branch`] puts it on the branch later, and @@ -248,7 +251,9 @@ pub fn create_detached_worktree_without_hooks( /// Check `branch_name` out in `worktree_path`, a clean worktree of `repo` /// detached at some other commit: only the files that differ are rewritten. /// -/// Hooks stay off. The `post-checkout` this checkout would fire names the +/// The hook directory's hooks stay off, as for +/// [`create_detached_worktree_without_hooks`] and with the same exception. +/// The `post-checkout` this checkout would fire names the /// commit the worktree was detached at as the previous head, where a /// worktree added on the branch names none, so a hook that sets a new /// worktree up on seeing that would do nothing. @@ -361,7 +366,9 @@ pub fn run_post_checkout_as_for_a_new_worktree( Ok(()) } -/// `-c` value that keeps every hook from firing. +/// `-c` value that keeps the hook directory's hooks from firing. It is no +/// use against a hook that config names (`hook..event`, git 2.54 and +/// later), which git runs wherever the hook directory is. const HOOKS_OFF: &str = "core.hooksPath=/dev/null"; fn lfs_smudge_vars(skip: bool) -> &'static [(&'static str, &'static str)] { diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs index d5acea744..469d4183b 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator/early_worktree.rs @@ -9,31 +9,39 @@ //! it only switches the worktree onto it, which rewrites the files that //! differ. //! -//! Hooks see none of that. They are off for the add and for the switch, -//! and `post-checkout` is then fired once, by `git hook run`, with what -//! `git worktree add ` tells it: no previous head. A hook -//! that sets a new worktree up on seeing that still does. +//! Hooks see none of that. The hook directory is off for the add and for +//! the switch, and `post-checkout` is then fired once, by `git hook run`, +//! with what `git worktree add ` tells it: no previous +//! head. A hook that sets a new worktree up on seeing that still does. +//! Turning the hook directory off does not quiet a hook that config names +//! (`hook..event`), which the add and the switch would each fire, so +//! a clone whose config names a `post-checkout` hook gets no early +//! worktree. //! -//! Such a hook may change what a shell picks up in the worktree: allow its +//! A hook may change what a shell picks up in the worktree: allow its //! `.envrc`, trust or write a tool-versions file. A worktree added late is //! first captured after the hook, inside `git worktree add`, has run. So -//! when a hook is about to run here, the capture the early add started is -//! waited out and dropped before it does, and the finish captures after -//! it; the hook never runs beside that capture's shell. A repo with no -//! `post-checkout` hook keeps the head start, as does one whose only hook -//! is the one `git lfs install` writes -//! ([`crate::git::PostCheckoutHooks`]). +//! the capture of the early worktree's environment is only started when no +//! such hook is known to be coming, which the clone can tell before the +//! add unless its `core.hooksPath` is relative and the hook is the +//! branch's own ([`crate::git::PostCheckoutHooksToCome`]). When a hook +//! turns out to be about to run all the same, the capture is waited out +//! and dropped before it does, and the finish captures after it; the hook +//! never runs beside that capture's shell. A repo with no `post-checkout` +//! hook keeps the head start, as does one whose only hook is the one `git +//! lfs install` writes ([`crate::git::PostCheckoutHooks`]). //! //! This is an optimisation with a complete fallback. A leg with no commit -//! to start from, a git too old to fire a hook on request, an early add or -//! a switch that fails, or a guess about Git LFS the snapshot contradicts, -//! all end in the sequence without it: `git worktree add ` -//! once the branch has landed. The worktree is recorded in the undo list -//! before the thread starts and the thread is joined before the leg -//! returns, so rollback and startup recovery find it as they find a -//! worktree added late. The capture of its shell environment runs on past -//! that join, in the worktree, so whatever removes the worktree waits for -//! it first ([`undo::remove_worktree_keeping_branch`]). +//! to start from, a git too old to fire a hook on request, a hook named in +//! config, an early add or a switch that fails, or a guess about Git LFS +//! the snapshot contradicts, all end in the sequence without it: `git +//! worktree add ` once the branch has landed. The worktree +//! is recorded in the undo list before the thread starts and the thread is +//! joined before the leg returns, so rollback and startup recovery find it +//! as they find a worktree added late. The capture of its shell +//! environment runs on past that join, in the worktree, so whatever +//! removes the worktree waits for it first +//! ([`undo::remove_worktree_keeping_branch`]). use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -41,7 +49,7 @@ use std::time::{Duration, Instant}; use super::super::carry::{CarryOutcome, CarryPlan}; use super::super::undo::{self, AddedWorktree}; use super::{origin_tip_names, Failure, Leg, Run}; -use crate::git::PostCheckoutHooks; +use crate::git::{PostCheckoutHooks, PostCheckoutHooksToCome}; #[cfg(test)] mod seams; @@ -59,6 +67,11 @@ pub(super) struct EarlyWorktree { /// Whether the snapshot is expected to bring LFS objects, in which case /// LFS files check out as pointers for the finish to replace. skip_lfs_smudge: bool, + /// Whether to start capturing its shell environment once it is added. + /// Not when a `post-checkout` hook that may change it is already known + /// to be coming: the capture could only be dropped before the hook + /// ran, having held a login shell and the hook up for nothing. + prewarm: bool, #[cfg(test)] seams: seams::Seams, } @@ -70,8 +83,9 @@ pub(super) struct EarlyAdd { } impl EarlyWorktree { - /// Add the worktree, and start capturing its shell environment so the - /// finish finds it cached or waits only for the rest. Hooks stay off: + /// Add the worktree and, unless a hook is known to be coming that + /// would cost it, start capturing its shell environment so the finish + /// finds it cached or waits only for the rest. Hooks stay off: /// `post-checkout` fires once, when the worktree is on its branch, and /// this capture is kept only if that changes nothing it read /// ([`early_capture_unusable`]). @@ -82,7 +96,9 @@ impl EarlyWorktree { // Whatever is cached for the path is from a worktree that was // there before. crate::git::invalidate_shell_env(&self.path); - crate::git::prewarm_shell_env(&self.path); + if self.prewarm { + crate::git::prewarm_shell_env(&self.path); + } } #[cfg(test)] if let Some(gate) = &self.seams.gate { @@ -122,6 +138,9 @@ pub(super) struct WorktreeTimings { /// The early add and the commit it started from. early_add: Option<(Duration, String)>, switch: Option, + /// Whether the early add started no capture, a hook being known to be + /// coming. + no_early_capture: bool, /// The wait for the capture the early add started, when it could not /// serve the finish, and why it could not. early_capture_dropped: Option<(Duration, &'static str)>, @@ -144,6 +163,9 @@ impl WorktreeTimings { if let Some(took) = self.switch { parts.push(format!("switch {took:.1?}")); } + if self.no_early_capture { + parts.push("no early environment (a post-checkout hook is coming)".to_string()); + } if let Some((took, why)) = self.early_capture_dropped { parts.push(format!("early environment dropped {took:.1?} ({why})")); } @@ -257,6 +279,15 @@ impl Run<'_> { /// its worktree and record it, as the late add would have. `None` leaves /// the worktree to the late add, which reports whatever stood in the /// way here. + /// + /// What the clone can tell of the worktree's `post-checkout` hooks + /// ([`crate::git::post_checkout_hooks_to_come`]) decides two things. A + /// hook its config names would fire at the early add and again at the + /// switch, each time told of the wrong commits, before it is fired on + /// request: such a clone gets no early worktree, and the late add + /// fires the hook once. A hook already known to be one that may do + /// anything leaves the early worktree without a capture of its + /// environment, which that hook would cost it. pub(super) fn plan_early_worktree(&self, leg: &Leg, clone: &Path) -> Option { let branch = &leg.dest_branch; let start = start_commit(clone, leg.row.head.as_deref(), &start_refs(leg))?; @@ -269,6 +300,21 @@ impl Run<'_> { ); return None; } + let prewarm = match crate::git::post_checkout_hooks_to_come(clone) { + PostCheckoutHooksToCome::NamedInConfig => { + log::info!( + "[project_transfer] no early worktree for {branch}: the config of {} \ + names a post-checkout hook, which nothing keeps from firing at the \ + early add and the switch", + clone.display() + ); + return None; + } + PostCheckoutHooksToCome::Known(PostCheckoutHooks::Other) => false, + // A relative `core.hooksPath` is the branch's to decide, once + // the worktree is on it. + PostCheckoutHooksToCome::Known(_) | PostCheckoutHooksToCome::OfTheBranch => true, + }; let planned = self.free_worktree_path(leg).and_then(|path| { self.record(|undo| { undo.worktrees.push(AddedWorktree { @@ -290,6 +336,7 @@ impl Run<'_> { path, start, skip_lfs_smudge: leg.row.lfs_present + leg.row.lfs_missing > 0, + prewarm, #[cfg(test)] seams: seams::Seams::of_this_thread(), }) @@ -360,6 +407,7 @@ impl Run<'_> { match switched { Ok(()) => { timings.switch = Some(switching.elapsed()); + timings.no_early_capture = !early.prewarm; if let Some(why) = early_capture_unusable( &clone, &early.path, @@ -370,10 +418,14 @@ impl Run<'_> { // waited out, not just dropped: its shell would // run on beside the hook, and beside the capture // the finish starts, where nothing that removes - // the worktree could wait for it. + // the worktree could wait for it. An add that + // started none asks all the same, at the cost + // of nothing, for one something else started. let waiting = Instant::now(); crate::git::wait_out_and_invalidate_shell_env(&early.path); - timings.early_capture_dropped = Some((waiting.elapsed(), why)); + if early.prewarm { + timings.early_capture_dropped = Some((waiting.elapsed(), why)); + } } let firing = Instant::now(); crate::git::run_post_checkout_as_for_a_new_worktree( diff --git a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs index c70fdf176..1fb295b94 100644 --- a/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs +++ b/apps/staged/src-tauri/src/project_transfer/orchestrator_tests/early_worktree.rs @@ -10,10 +10,12 @@ //! see of them is which were made for the worktree, in what order, and //! whether the worktree was there at the time. //! -//! Whether the capture the early add starts is kept depends on the -//! `post-checkout` hooks git finds, and a machine may have a hook directory -//! of its own for every repo. A test that looks at those calls therefore -//! gives the clone its own: a hook, or an empty directory. +//! Whether a leg gets an early worktree, and whether the capture its add +//! starts is kept, depend on the `post-checkout` hooks git finds, and a +//! machine may have a hook directory of its own for every repo, or name a +//! hook in its config. So the git each transfer here runs reads no config +//! but the repos' own ([`own_config_only`]): a clone has the hooks a test +//! gives it, and otherwise the default hook directory with none in it. use std::time::{Duration, Instant}; @@ -23,6 +25,13 @@ use super::super::undo::AddedWorktree; use super::lfs::lfs_project; use super::*; use crate::git::shell_env_calls::Watch; +use crate::git::OwnConfigOnly; + +/// Keep the machine's git config out of the git `f`'s transfers run, +/// while what this returns lives. +fn own_config_only(f: &Fixture) -> OwnConfigOnly { + OwnConfigOnly::under(&f.host.root) +} /// Take `f`'s one branch, `feature`, to a workspace: pushed, then a commit /// ahead of origin, with an untracked file. Returns the pushed tip and the @@ -111,15 +120,60 @@ fn install_post_checkout(f: &Fixture, script: &str) { ); } -/// Give the clone an empty hook directory: no hook of its own, and none of -/// the machine's. -fn without_hooks(f: &Fixture) { - let hooks = f.host.root.join("no-hooks"); +/// Put a `post-checkout` hook that logs its three arguments among the +/// files of the branch's worktree, in `.githooks`, for the next commit +/// there to take, and have the clone look for its hooks in that +/// directory of whichever worktree git runs in. Returns the log. +fn record_post_checkout_from_the_branch(f: &Fixture) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + + let log = f.host.root.join("post-checkout.log"); + let hooks = f.worktree(0).join(".githooks"); fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("post-checkout"); + fs::write( + &hook, + format!("#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n", log.display()), + ) + .unwrap(); + fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap(); git( &f.host.clone_of(WIDGETS), - &["config", "core.hooksPath", path(&hooks)], + &["config", "core.hooksPath", ".githooks"], ); + log +} + +/// Name a `post-checkout` hook in the clone's config, one that logs its +/// three arguments each time git runs it. Returns the log, and whether +/// this git runs hooks that config names at all (git 2.54 and later). +fn record_post_checkout_named_in_config(f: &Fixture) -> (PathBuf, bool) { + use std::os::unix::fs::PermissionsExt; + + let clone = f.host.clone_of(WIDGETS); + let log = f.host.root.join("post-checkout.log"); + let script = f.host.root.join("record-post-checkout.sh"); + fs::write( + &script, + format!("#!/bin/sh\necho \"$1 $2 $3\" >> '{}'\n", log.display()), + ) + .unwrap(); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + git(&clone, &["config", "hook.record.event", "post-checkout"]); + git( + &clone, + &[ + "config", + "hook.record.command", + &format!("'{}'", path(&script)), + ], + ); + + // Asked of the git the transfer will run, the way it will run it. + let probe = ["hook", "run", "post-checkout", "--", "a", "probe", "run"]; + let runs = crate::git::cli_run(&clone, &probe).is_ok() && lines(&log) == ["a probe run"]; + let _ = fs::remove_file(&log); + (log, runs) } fn lines(log: &Path) -> Vec { @@ -214,8 +268,8 @@ fn worktree_on_feature_at(f: &Fixture, head: &str) -> PathBuf { #[test] fn the_worktree_is_added_while_the_snapshot_runs() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); let (pushed, _) = send_to_a_workspace(&f); - without_hooks(&f); let checkout = f.checkout(0); let head = commit_in_the_workspace(&f, "remote.txt"); write( @@ -264,6 +318,7 @@ fn the_worktree_is_added_while_the_snapshot_runs() { #[test] fn post_checkout_fires_once_for_an_early_worktree_as_for_a_new_one() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { eprintln!("skipping: this git has no `git hook run`"); return; @@ -289,6 +344,7 @@ fn post_checkout_fires_once_for_an_early_worktree_as_for_a_new_one() { #[test] fn post_checkout_sees_a_new_worktree_when_the_start_commit_is_the_head() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { eprintln!("skipping: this git has no `git hook run`"); return; @@ -308,21 +364,71 @@ fn post_checkout_sees_a_new_worktree_when_the_start_commit_is_the_head() { } /// A `post-checkout` hook may change what a shell picks up in the worktree, -/// and the capture the early add started ran before it. So that capture is +/// so a capture made before it runs is no use to the finish. The clone's +/// hook directory is an absolute one, the same from every worktree, so the +/// hook is known before the add: the worktree is still added early, but no +/// capture is started in it, and the finish's is the first, after the +/// hook. The leg still asks for any capture to be waited out before the +/// hook fires, and finds none. +#[test] +fn a_post_checkout_hook_known_before_the_add_starts_no_early_capture() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); + if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { + eprintln!("skipping: this git has no `git hook run`"); + return; + } + let (_, head) = send_to_a_workspace(&f); + let log = record_post_checkout(&f, ""); + let worktree = worktree_path(&f); + let watch = Watch::under(&f.host.root).noting(&log); + + f.transfer(true).result.expect("to local"); + + assert_eq!(worktree_on_feature_at(&f, &head), worktree); + assert!( + switched_from(&worktree, &head), + "{:?}", + head_moves(&worktree) + ); + assert_eq!(lines(&log), [new_worktree_at(&head)]); + assert_eq!( + shell_env_calls(&watch, &worktree), + [ + ("invalidate", true), + ("wait out and invalidate", true), + ("wait", true) + ] + ); + // Each call with whether the hook had run by then. + assert_eq!( + shell_env_calls_noting(&watch, &worktree), + [ + ("invalidate", false), + ("wait out and invalidate", false), + ("wait", true) + ] + ); +} + +/// A relative `core.hooksPath` makes the hook the branch's own file, which +/// the clone cannot know of before the worktree is on its branch, so the +/// early add starts its capture. Once the hook is found, that capture is /// waited out and dropped before the hook fires, and the finish captures /// after it: the order a worktree added late has, with no shell of an /// earlier capture in the directory while the hook works. The clone holds /// the head, so the two commits are the same and the hook is the only /// reason. #[test] -fn a_post_checkout_hook_runs_after_the_early_capture_and_before_the_finishs() { +fn a_branchs_own_post_checkout_hook_runs_after_the_early_capture_and_before_the_finishs() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { eprintln!("skipping: this git has no `git hook run`"); return; } + let log = record_post_checkout_from_the_branch(&f); let (_, head) = send_to_a_workspace(&f); - let log = record_post_checkout(&f, ""); let worktree = worktree_path(&f); let watch = Watch::under(&f.host.root).noting(&log); @@ -356,14 +462,57 @@ fn a_post_checkout_hook_runs_after_the_early_capture_and_before_the_finishs() { ); } +/// Turning the hook directory off, as the early add and the switch do, +/// does not quiet a `post-checkout` hook that config names: git would run +/// it at the add, told of the start commit, at the switch, told the +/// worktree came from there, and a third time on request. So a clone whose +/// config names one gets no early worktree. The worktree is added on the +/// branch once that has landed, and the hook hears of it once, as new. +/// +/// The workspace's head is new to the clone, so an early worktree would +/// have started at another commit and had files to switch. +#[test] +fn a_post_checkout_hook_named_in_config_fires_once_for_a_worktree_added_late() { + let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); + send_to_a_workspace(&f); + let head = commit_in_the_workspace(&f, "remote.txt"); + let expected = observe(&f.checkout(0)); + let (log, git_runs_it) = record_post_checkout_named_in_config(&f); + let watch = Watch::under(&f.host.root); + + f.transfer(true).result.expect("to local"); + + let worktree = worktree_on_feature_at(&f, &head); + assert_eq!(observe(&worktree), expected); + assert!( + added_on_its_branch(&worktree), + "{:?}", + head_moves(&worktree) + ); + // Nothing was started ahead of the finish, in a worktree that was not + // there yet. + assert_eq!( + shell_env_calls(&watch, &worktree), + [("invalidate", false), ("wait", true)] + ); + if git_runs_it { + assert_eq!(lines(&log), [new_worktree_at(&head)]); + } else { + // The plan is made from config, whatever this git does with it. + eprintln!("this git runs no hooks named in config: only the late add was checked"); + assert_eq!(lines(&log), [""; 0]); + } +} + /// A clone with no `post-checkout` hook keeps the capture the early add /// started, in the commonest case too: the clone holds the head, the switch /// moves no file, and nothing fires. #[test] fn without_a_post_checkout_hook_the_early_capture_serves_the_finish() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); let (_, head) = send_to_a_workspace(&f); - without_hooks(&f); let worktree = worktree_path(&f); let watch = Watch::under(&f.host.root); @@ -388,6 +537,7 @@ fn a_post_checkout_git_would_ignore_keeps_the_early_capture() { use std::os::unix::fs::PermissionsExt; let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); let (_, head) = send_to_a_workspace(&f); let log = record_post_checkout(&f, ""); let hook = f.host.root.join("hooks").join("post-checkout"); @@ -414,6 +564,7 @@ fn the_stock_git_lfs_post_checkout_keeps_the_early_capture() { return; } let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { eprintln!("skipping: this git has no `git hook run`"); return; @@ -443,6 +594,7 @@ fn the_stock_git_lfs_post_checkout_keeps_the_early_capture() { #[test] fn a_git_that_cannot_fire_hooks_on_request_adds_the_worktree_late() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); send_to_a_workspace(&f); let head = commit_in_the_workspace(&f, "remote.txt"); let expected = observe(&f.checkout(0)); @@ -476,6 +628,7 @@ fn a_git_that_cannot_fire_hooks_on_request_adds_the_worktree_late() { #[test] fn a_post_checkout_that_fails_fails_the_transfer_having_fired_once() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); if !crate::git::can_run_hooks_on_request(&f.host.clone_of(WIDGETS)) { eprintln!("skipping: this git has no `git hook run`"); return; @@ -505,8 +658,8 @@ fn a_post_checkout_that_fails_fails_the_transfer_having_fired_once() { #[test] fn a_stale_capture_is_waited_out_before_the_finish_captures_again() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); let (pushed, _) = send_to_a_workspace(&f); - without_hooks(&f); let head = commit_in_the_workspace(&f, ".nvmrc"); let watch = Watch::under(&f.host.root); @@ -536,6 +689,7 @@ fn a_stale_capture_is_waited_out_before_the_finish_captures_again() { #[test] fn a_switch_that_fails_waits_out_the_capture_before_the_worktree_is_replaced() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); send_to_a_workspace(&f); let head = commit_in_the_workspace(&f, "remote.txt"); let expected = observe(&f.checkout(0)); @@ -578,6 +732,7 @@ fn a_switch_that_fails_waits_out_the_capture_before_the_worktree_is_replaced() { #[test] fn the_undo_list_names_the_worktree_before_the_snapshot_starts() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); send_to_a_workspace(&f); let recorded = Mutex::new(None); @@ -607,6 +762,7 @@ fn the_undo_list_names_the_worktree_before_the_snapshot_starts() { #[test] fn a_snapshot_that_fails_after_the_early_add_leaves_no_worktree() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); send_to_a_workspace(&f); let clone = f.host.clone_of(WIDGETS); let (db, before) = (f.db_state(), clone_state(&clone)); @@ -643,6 +799,7 @@ fn a_snapshot_that_fails_after_the_early_add_leaves_no_worktree() { #[test] fn a_head_that_moves_after_the_inspection_still_lands_in_the_worktree() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); let (_, inspected) = send_to_a_workspace(&f); let checkout = f.checkout(0); let moved = Arc::new(Mutex::new(None)); @@ -673,6 +830,7 @@ fn a_head_that_moves_after_the_inspection_still_lands_in_the_worktree() { #[test] fn an_early_add_that_fails_falls_back_to_adding_the_worktree_late() { let f = Fixture::new(&[(WIDGETS, "feature")]); + let _own_config = own_config_only(&f); let (_, head) = send_to_a_workspace(&f); let expected = observe(&f.checkout(0)); let watch = Watch::under(&f.host.root); @@ -710,6 +868,7 @@ fn a_wrong_guess_about_lfs_falls_back_to_adding_the_worktree_late() { return; } let f = lfs_project(); + let _own_config = own_config_only(&f); let (_, head) = send_to_a_workspace(&f); assert_eq!(f.preflight().repos[0].lfs_present, 0); let art = noise(1800, 41);