From 9ad5bad82e5ea8a69fe49d6e22b06fcb4c04ceeb Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Tue, 24 Nov 2026 13:25:08 +0800 Subject: [PATCH] fix(vcs): refresh status after git commands run outside the IDE in subfolder projects, worktrees and submodules (#5555) The project file watcher only reports Git metadata in the .git folders it sees: the project root's and nested repositories'. When the project is a subfolder of its repository, a linked worktree, a mapped repository elsewhere, or a submodule (.git/modules/), a commit, checkout or reset in a terminal wrote nothing the watcher reported, so file statuses stayed stale until something else triggered a refresh. Watch HEAD, index, packed-refs and refs/** of those git directories, follow repository changes, and emit VcsChanged for them (ignoring the IDE's own index writes). --- crates/ide-host/src/project.rs | 111 ++++++++++++- crates/ide-vcs/src/lib.rs | 2 + crates/ide-vcs/src/metadata_watch.rs | 224 +++++++++++++++++++++++++++ 3 files changed, 333 insertions(+), 4 deletions(-) create mode 100644 crates/ide-vcs/src/metadata_watch.rs diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index fc0a99267..ad7e75e30 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -76,6 +76,8 @@ pub struct Project { /// watchers for (a virtualenv elsewhere, a path dependency). lsp_watchers: Mutex>, pub(crate) _scratch_watcher: Option, + /// Git metadata of repositories whose git directory lies outside the project folder. + pub(crate) git_metadata: Option>, /// Picks up data sources edited on disk outside the Database tool window. _db_sources_watch: Option, /// A LightEdit window's loose files ([`Host::open_light`]): global settings only, @@ -385,6 +387,10 @@ impl Host { for repo in repos.read().all() { repo.set_execution_allowed(trusted.load(Ordering::Acquire)); } + let git_metadata = git_metadata_watch(&root, &sink); + if let Some(watch) = &git_metadata { + watch.set_repos(repos.read().all(), &root); + } // Shared handle: `unwatched_reason` is a live query on the watcher, // filled after `start` returns so the on-change callback can reach it. let watcher_weak = Arc::new(std::sync::OnceLock::>::new()); @@ -398,6 +404,7 @@ impl Host { let kotlin_bridge = kotlin_bridge.clone(); let phpstan = phpstan.clone(); let repos = repos.clone(); + let git_metadata = git_metadata.clone(); let settings = settings.clone(); let index = index.clone(); let documents = documents.clone(); @@ -521,6 +528,7 @@ impl Host { scan_repositories( &root, &repos, + git_metadata.as_deref(), &settings, &sink, &build_cache, @@ -611,11 +619,11 @@ impl Host { mark("watcher"); { let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone()); - let build_cache = build_cache.clone(); + let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone()); let trusted = trusted.load(Ordering::Acquire); - std::thread::Builder::new() - .name("openidea-vcs-roots".into()) - .spawn(move || scan_repositories(&root, &repos, &settings, &sink, &build_cache, trusted))?; + std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || { + scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted) + })?; } mark("git"); tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis()); @@ -664,6 +672,7 @@ impl Host { content_watchers: Mutex::new(content_watchers), lsp_watchers: Mutex::new(Vec::new()), _scratch_watcher: scratch_watcher, + git_metadata, _db_sources_watch: db_sources_watch, files_events_active, light: false, @@ -911,6 +920,7 @@ impl Host { content_watchers: Mutex::new(Vec::new()), lsp_watchers: Mutex::new(Vec::new()), _scratch_watcher: None, + git_metadata: None, _db_sources_watch: None, files_events_active: Arc::new(AtomicBool::new(false)), light: true, @@ -1014,6 +1024,7 @@ fn light_watcher( fn scan_repositories( root: &Path, repos: &RwLock, + git_metadata: Option<&ide_vcs::MetadataWatch>, settings: &SettingsStore, sink: &SharedSink, build_cache: &Path, @@ -1022,6 +1033,9 @@ fn scan_repositories( match discover_repositories(root, settings, build_cache, trusted) { Ok(found) => { if found.roots() != repos.read().roots() { + if let Some(watch) = git_metadata { + watch.set_repos(found.all(), root); + } *repos.write() = found; sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() }); } @@ -1075,6 +1089,7 @@ impl Project { scan_repositories( &self.root, &self.repos, + self.git_metadata.as_deref(), &self.settings, &self.sink, &self.build_cache_dir(), @@ -2329,6 +2344,20 @@ mod maven_linkage_tests { } } +/// Commits, checkouts and resets made outside the IDE in a git directory the project +/// watcher doesn't see (the project is a subfolder of its repository, or a linked worktree). +fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option> { + let (root, sink) = (root.to_path_buf(), sink.clone()); + ide_vcs::MetadataWatch::new(move |paths| { + if paths.iter().any(|p| vcs_path_changed(p)) { + sink.emit(IdeEvent::VcsChanged { root: root.clone().into() }); + } + }) + .map(Arc::new) + .map_err(|e| tracing::warn!("{}", e.message)) + .ok() +} + fn vcs_path_changed(path: &Path) -> bool { !path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path) } @@ -2613,3 +2642,77 @@ mod content_roots_tests { assert_eq!(members[&root], ["/dist", "/target"]); } } + +#[cfg(test)] +mod external_git_metadata_tests { + use crate::{Host, HostConfig}; + use ide_core::{IdeEvent, SharedSink}; + use parking_lot::Mutex; + use std::path::Path; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + fn git(dir: &Path, args: &[&str]) { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false"]) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + } + + /// A commit made in a terminal refreshes the project's VCS state when the project folder + /// is the repository root, a subfolder of it, or a linked worktree, and for a submodule. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn external_commits_refresh_vcs_wherever_the_git_dir_lives() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let main = base.join("main"); + std::fs::create_dir_all(main.join("sub")).unwrap(); + git(&main, &["init", "-q", "-b", "main"]); + git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]); + git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]); + let lib = base.join("lib"); + std::fs::create_dir(&lib).unwrap(); + git(&lib, &["init", "-q", "-b", "main"]); + git(&lib, &["commit", "-q", "--allow-empty", "-m", "init"]); + let sup = base.join("super"); + std::fs::create_dir(&sup).unwrap(); + git(&sup, &["init", "-q", "-b", "main"]); + git(&sup, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", lib.to_str().unwrap(), "lib"]); + git(&sup, &["commit", "-q", "-m", "submodule"]); + let seen = Arc::new(Mutex::new(0usize)); + let counted = seen.clone(); + let sink: SharedSink = Arc::new(move |e: IdeEvent| { + if matches!(e, IdeEvent::VcsChanged { .. }) { + *counted.lock() += 1; + } + }); + let host = Host::new(HostConfig { + sink_for: Box::new(move |_| sink.clone()), + local_data_dir: base.join("local"), + ..HostConfig::for_test(&base) + }); + let cases = [ + (main.clone(), main.clone()), + (main.join("sub"), main.join("sub")), + (base.join("wt"), base.join("wt")), + (sup.clone(), sup.join("lib")), + ]; + for (project, repo) in cases { + host.open_project("main", &project).unwrap(); + std::thread::sleep(Duration::from_millis(1500)); + *seen.lock() = 0; + std::fs::write(repo.join("a.txt"), repo.to_string_lossy().as_bytes()).unwrap(); + git(&repo, &["add", "a.txt"]); + git(&repo, &["commit", "-q", "-m", "change"]); + let deadline = Instant::now() + Duration::from_secs(10); + while *seen.lock() == 0 && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(*seen.lock() > 0, "no VcsChanged for a commit in {}", repo.display()); + host.close_project("main"); + } + } +} diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 3c365bc3f..49631ca40 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -933,6 +933,8 @@ mod ignore; mod index_writes; mod log_index; mod manage; +mod metadata_watch; +pub use metadata_watch::MetadataWatch; mod ops; mod patch; mod preserve; diff --git a/crates/ide-vcs/src/metadata_watch.rs b/crates/ide-vcs/src/metadata_watch.rs new file mode 100644 index 000000000..54473f5f9 --- /dev/null +++ b/crates/ide-vcs/src/metadata_watch.rs @@ -0,0 +1,224 @@ +use crate::Repo; +use ide_core::{IdeError, IdeResult}; +use notify::{RecommendedWatcher, RecursiveMode, Watcher}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::{Duration, Instant}; + +const QUIET: Duration = Duration::from_millis(100); +const MAX_WAIT: Duration = Duration::from_secs(1); + +/// Watches the Git metadata (`HEAD`, `index`, `packed-refs`, `refs/**`) of repositories whose +/// git directories lie outside the project's own file watcher: a project opened in a +/// subfolder of its repository, a linked worktree, a mapped repository elsewhere. Commits, +/// checkouts and resets run in a terminal then reach the IDE like those below the project. +pub struct MetadataWatch { + watcher: Mutex, + /// Watched directory → whether only its top-level metadata files count (`false`: a + /// recursively watched `refs` directory, where every non-lock file counts). + dirs: Arc>>, +} + +impl MetadataWatch { + /// `changed` receives the metadata files that changed, coalesced over short bursts. + pub fn new(changed: impl Fn(Vec) + Send + 'static) -> IdeResult { + let dirs = Arc::new(Mutex::new(BTreeMap::::new())); + let (tx, rx) = mpsc::channel::(); + let watched = dirs.clone(); + let watcher = notify::recommended_watcher(move |event: notify::Result| { + let Ok(event) = event else { return }; + if event.kind.is_access() { + return; + } + let dirs = watched.lock().unwrap_or_else(|e| e.into_inner()); + for path in event.paths.iter().filter(|p| is_metadata(&dirs, p)) { + let _ = tx.send(path.clone()); + } + }) + .map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?; + std::thread::Builder::new() + .name("openidea-git-metadata".into()) + .spawn(move || { + while let Ok(first) = rx.recv() { + let deadline = Instant::now() + MAX_WAIT; + let mut paths = BTreeSet::from([first]); + while Instant::now() < deadline + && let Ok(path) = rx.recv_timeout(QUIET) + { + paths.insert(path); + } + changed(paths.into_iter().collect()); + } + }) + .map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?; + Ok(Self { watcher: Mutex::new(watcher), dirs }) + } + + /// Watches the metadata of `repos` that the project watcher of `covered` doesn't report: + /// git directories outside it, and submodule git directories (`.git/modules/…`) inside it. + pub fn set_repos(&self, repos: &[Arc], covered: &Path) { + let covered = dunce::canonicalize(covered).unwrap_or_else(|_| covered.to_path_buf()); + let mut wanted = BTreeMap::new(); + for repo in repos { + let Ok([git_dir, common_dir]) = repo.metadata_dirs() else { continue }; + for (dir, top_level) in [(git_dir, true), (common_dir.clone(), true), (common_dir.join("refs"), false)] { + if let Ok(dir) = dunce::canonicalize(&dir) + && !watched_by_project(&covered, &dir) + { + wanted.insert(dir, top_level); + } + } + } + let mut watcher = self.watcher.lock().unwrap_or_else(|e| e.into_inner()); + let mut dirs = self.dirs.lock().unwrap_or_else(|e| e.into_inner()); + for dir in dirs.keys().filter(|d| !wanted.contains_key(*d)) { + let _ = watcher.unwatch(dir); + } + wanted.retain(|dir, top_level| { + if dirs.contains_key(dir) { + return true; + } + let mode = if *top_level { RecursiveMode::NonRecursive } else { RecursiveMode::Recursive }; + watcher.watch(dir, mode).map_err(|e| tracing::debug!("Git metadata watcher {}: {e}", dir.display())).is_ok() + }); + *dirs = wanted; + } + + pub fn watched_dirs(&self) -> Vec { + self.dirs.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect() + } +} + +fn watched_by_project(root: &Path, dir: &Path) -> bool { + dir.strip_prefix(root) + .is_ok_and(|rel| !rel.components().skip_while(|c| c.as_os_str() != ".git").any(|c| c.as_os_str() == "modules")) +} + +fn is_metadata(dirs: &BTreeMap, path: &Path) -> bool { + if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".lock")) { + return false; + } + dirs.iter().any(|(dir, top_level)| match path.strip_prefix(dir) { + Ok(rest) if *top_level => rest.to_str().is_some_and(|r| matches!(r, "HEAD" | "index" | "packed-refs")), + Ok(rest) => !rest.as_os_str().is_empty(), + Err(_) => false, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn git(dir: &Path, args: &[&str]) { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false"]) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + } + + fn wait_for(seen: &Mutex>, pred: impl Fn(&[PathBuf]) -> bool) -> bool { + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if pred(&seen.lock().unwrap()) { + return true; + } + std::thread::sleep(Duration::from_millis(50)); + } + false + } + + #[test] + fn metadata_files_count_and_locks_and_objects_do_not() { + let dirs = BTreeMap::from([(PathBuf::from("/r/.git"), true), (PathBuf::from("/r/.git/refs"), false)]); + for (path, expected) in [ + ("/r/.git/HEAD", true), + ("/r/.git/index", true), + ("/r/.git/packed-refs", true), + ("/r/.git/refs/heads/main", true), + ("/r/.git/refs/heads/feature/x", true), + ("/r/.git/index.lock", false), + ("/r/.git/refs/heads/main.lock", false), + ("/r/.git/objects/aa/bb", false), + ("/r/.git/logs/HEAD", false), + ("/r/.git/COMMIT_EDITMSG", false), + ("/r/src/HEAD", false), + ] { + assert_eq!(is_metadata(&dirs, Path::new(path)), expected, "{path}"); + } + } + + /// The project folder is a subfolder of its repository, or a linked worktree: a commit made + /// in a terminal writes only outside it, and still surfaces. + #[test] + fn external_commits_surface_for_projects_outside_their_git_dir() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let main = base.join("main"); + std::fs::create_dir_all(main.join("sub")).unwrap(); + git(&main, &["init", "-q", "-b", "main"]); + git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]); + git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]); + for project in [main.join("sub"), base.join("wt")] { + let repo = Arc::new(Repo::discover(&project).unwrap().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let watch = { + let seen = seen.clone(); + MetadataWatch::new(move |paths| seen.lock().unwrap().extend(paths)).unwrap() + }; + watch.set_repos(std::slice::from_ref(&repo), &project); + assert!(!watch.watched_dirs().is_empty(), "{}", project.display()); + std::thread::sleep(Duration::from_millis(300)); + std::fs::write(project.join("a.txt"), project.to_string_lossy().as_bytes()).unwrap(); + git(&project, &["add", "a.txt"]); + git(&project, &["commit", "-q", "-m", "change"]); + assert!( + wait_for(&seen, |p| p.iter().any(|p| p.starts_with(repo.metadata_dirs().unwrap()[1].join("refs")))), + "{}: {:?}", + project.display(), + seen.lock().unwrap() + ); + assert!( + wait_for(&seen, |p| p.iter().any(|p| p.ends_with("index"))), + "{}: {:?}", + project.display(), + seen.lock().unwrap() + ); + } + } + + #[test] + fn the_project_watcher_reports_its_git_dirs_but_not_submodule_ones() { + let root = Path::new("/p"); + for (dir, expected) in [ + ("/p/.git", true), + ("/p/.git/refs", true), + ("/p/.git/worktrees/wt", true), + ("/p/nested/.git", true), + ("/p/.git/modules/lib", false), + ("/p/.git/modules/lib/refs", false), + ("/p/.git/modules/a/modules/b", false), + ("/elsewhere/.git", false), + ] { + assert_eq!(watched_by_project(root, Path::new(dir)), expected, "{dir}"); + } + } + + #[test] + fn metadata_below_the_covered_folder_is_left_to_the_project_watcher() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + git(&root, &["init", "-q"]); + let repo = Arc::new(Repo::discover(&root).unwrap().unwrap()); + let watch = MetadataWatch::new(|_| {}).unwrap(); + watch.set_repos(std::slice::from_ref(&repo), &root); + assert!(watch.watched_dirs().is_empty()); + watch.set_repos(std::slice::from_ref(&repo), &root.join("elsewhere")); + assert_eq!(watch.watched_dirs().len(), 2, "{:?}", watch.watched_dirs()); + watch.set_repos(&[], &root); + assert!(watch.watched_dirs().is_empty()); + } +}