дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
fix(editor): refresh open files not covered by project watchers (#8054)
* fix(editor): refresh open files not covered by project watchers * fix(editor): guard idle unwatched sync wakeups and isolate focus-sync tests
Цей коміт міститься в:
1 джерело
63f20ce5cc
коміт
587d964e42
6 files changed
+271
-9
No files matched your search
@@ -15,6 +15,13 @@ struct Fixture {
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let f = Self::with_background_sync();
|
||||
// Keep background unwatched-file polling out of focus-sync tests so they exercise `doc_sync_from_disk` directly.
|
||||
f.project.stop_unwatched_document_sync();
|
||||
f
|
||||
}
|
||||
|
||||
fn with_background_sync() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
@@ -169,6 +176,88 @@ async fn outside_project_document_reloads() {
|
||||
assert_eq!(f.project.documents.snapshot(original.id).unwrap().text, "outside changed externally\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn open_external_document_reloads_without_window_focus() {
|
||||
let f = Fixture::with_background_sync();
|
||||
let original = f.open(&f.outside).await;
|
||||
std::fs::write(&f.outside, "newly materialized source\n").unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
if loaded.text == "newly materialized source\n" {
|
||||
assert!(!loaded.dirty);
|
||||
assert!(loaded.version > original.version);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("open external file should refresh while the IDE is still focused");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn open_generated_document_reloads_without_window_focus() {
|
||||
let f = Fixture::with_background_sync();
|
||||
let generated = f.project.root.join("target/generated-sources/OwnersApi.java");
|
||||
std::fs::create_dir_all(generated.parent().unwrap()).unwrap();
|
||||
std::fs::write(&generated, "interface OwnersApi { void listOwners(String lastName); }\n").unwrap();
|
||||
let original = f.open(&generated).await;
|
||||
let rewritten = "interface OwnersApi { void listOwners(String lastName, String city); }\n";
|
||||
std::fs::write(&generated, rewritten).unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
let loaded = f.project.documents.snapshot(original.id).unwrap();
|
||||
if loaded.text == rewritten {
|
||||
assert!(!loaded.dirty);
|
||||
assert!(loaded.version > original.version);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("an open generated source should refresh while the IDE is still focused");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn dirty_unwatched_documents_keep_edits_on_background_sync() {
|
||||
let f = Fixture::with_background_sync();
|
||||
let mut dirty = Vec::new();
|
||||
for path in [&f.outside, &f.path] {
|
||||
let original = f.open(path).await;
|
||||
doc_edit(
|
||||
&f.host,
|
||||
"main",
|
||||
original.id,
|
||||
original.version,
|
||||
ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "local ".into() }] },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
std::fs::write(path, "external replacement\n").unwrap();
|
||||
dirty.push((original.id, format!("local {}", original.text)));
|
||||
}
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
let events = f.document_events();
|
||||
if dirty.iter().all(|(id, _)| {
|
||||
events.iter().any(|event| matches!(event, IdeEvent::DocDiskConflict { doc, .. } if doc == id))
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("background sync should report both conflicts");
|
||||
for (id, expected) in dirty {
|
||||
let loaded = f.project.documents.snapshot(id).unwrap();
|
||||
assert_eq!(loaded.text, expected);
|
||||
assert!(loaded.dirty);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn setting_defaults_on_and_disabled_sync_keeps_buffer() {
|
||||
let f = Fixture::new();
|
||||
@@ -226,6 +315,7 @@ async fn synchronization_only_changes_the_calling_windows_documents() {
|
||||
let other_root = f.outside.parent().unwrap().join("other-project");
|
||||
std::fs::create_dir(&other_root).unwrap();
|
||||
let other = f.host.open_project("other", &other_root).unwrap();
|
||||
other.stop_unwatched_document_sync();
|
||||
let other_doc = doc_open(&f.host, "other", f.outside.clone()).await.unwrap();
|
||||
std::fs::write(&f.outside, "external change in shared file\n").unwrap();
|
||||
f.sync().await;
|
||||
|
||||
@@ -26,6 +26,8 @@ pub struct Project {
|
||||
pub(crate) files_events_active: Arc<AtomicBool>,
|
||||
/// Cancelled synchronously when this project incarnation begins closing.
|
||||
pub(crate) closed: CancellationToken,
|
||||
/// Stops the background unwatched-document sync loop; cancelled with `closed`.
|
||||
unwatched_sync: CancellationToken,
|
||||
pub root: PathBuf,
|
||||
/// Window-scoped event sink, for commands that emit project events.
|
||||
pub sink: SharedSink,
|
||||
@@ -892,10 +894,12 @@ impl Host {
|
||||
let plugin_diagnostics =
|
||||
crate::plugins::diagnostics::Diagnostics::new(sink.clone(), self.runtime.clone(), &documents, &root);
|
||||
documents.add_observer(plugin_diagnostics.clone());
|
||||
let closed = CancellationToken::new();
|
||||
let project = Arc::new(Project {
|
||||
plugin_diagnostics,
|
||||
trusted,
|
||||
closed: CancellationToken::new(),
|
||||
unwatched_sync: closed.child_token(),
|
||||
closed,
|
||||
flutter: ide_flutter::FlutterDaemon::new(
|
||||
root.clone(),
|
||||
sink.clone(),
|
||||
@@ -1013,6 +1017,7 @@ impl Host {
|
||||
}
|
||||
});
|
||||
}
|
||||
project.start_unwatched_document_sync(&self.runtime);
|
||||
project.lsp.prewarm_java_configuration();
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.start(&self.runtime);
|
||||
@@ -1313,10 +1318,12 @@ impl Host {
|
||||
let plugin_diagnostics =
|
||||
crate::plugins::diagnostics::Diagnostics::new(sink.clone(), self.runtime.clone(), &documents, &dir);
|
||||
documents.add_observer(plugin_diagnostics.clone());
|
||||
let closed = CancellationToken::new();
|
||||
let project = Arc::new(Project {
|
||||
plugin_diagnostics,
|
||||
trusted: Arc::new(AtomicBool::new(false)),
|
||||
closed: CancellationToken::new(),
|
||||
unwatched_sync: closed.child_token(),
|
||||
closed,
|
||||
flutter: ide_flutter::FlutterDaemon::new(
|
||||
dir.clone(),
|
||||
sink.clone(),
|
||||
@@ -1392,6 +1399,63 @@ impl Project {
|
||||
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
|
||||
}
|
||||
|
||||
fn is_covered_by_watchers(&self, path: &Path) -> bool {
|
||||
self.watcher.covers_file(path)
|
||||
|| self.content_watchers.lock().iter().any(|(_, w)| w.covers_file(path))
|
||||
|| self._scratch_watcher.as_ref().is_some_and(|w| w.covers_file(path))
|
||||
}
|
||||
|
||||
fn is_covered_by_watchers_nonblocking(&self, path: &Path) -> bool {
|
||||
self.watcher.covers_file(path)
|
||||
|| self.content_watchers.try_lock().is_some_and(|w| w.iter().any(|(_, w)| w.covers_file(path)))
|
||||
|| self._scratch_watcher.as_ref().is_some_and(|w| w.covers_file(path))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn stop_unwatched_document_sync(&self) {
|
||||
self.unwatched_sync.cancel();
|
||||
}
|
||||
|
||||
/// The project watcher cannot see every open file (for example, dependency sources
|
||||
/// outside its roots or generated sources in excluded build folders). Check only
|
||||
/// those open documents on a blocking worker, rather than scanning those directories.
|
||||
fn start_unwatched_document_sync(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
|
||||
let project = Arc::downgrade(self);
|
||||
let stop = self.unwatched_sync.clone();
|
||||
runtime.spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = stop.cancelled() => break,
|
||||
_ = tokio::time::sleep(Duration::from_secs(1)) => {}
|
||||
}
|
||||
let Some(project_arc) = project.upgrade() else { break };
|
||||
if stop.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
if !project_arc
|
||||
.documents
|
||||
.has_unwatched_documents(|path| project_arc.is_covered_by_watchers_nonblocking(path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let stop_blocking = stop.clone();
|
||||
if tokio::task::spawn_blocking(move || {
|
||||
if stop_blocking.is_cancelled() {
|
||||
return false;
|
||||
}
|
||||
project_arc.documents.sync_unwatched_from_disk(|path| project_arc.is_covered_by_watchers(path));
|
||||
true
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
!= Some(true)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
pub fn watch_light_dir(&self, dir: &Path) {
|
||||
if !self.light {
|
||||
|
||||
@@ -170,6 +170,18 @@ impl Watcher {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// Whether an ordinary file can produce a change in this watcher's batch
|
||||
/// (including the ignored-file bucket). Excluded files and paths outside
|
||||
/// a flat watch need a different source of notifications.
|
||||
pub fn covers_file(&self, path: &Path) -> bool {
|
||||
let Ok(rel) = path.strip_prefix(&self.root) else { return false };
|
||||
!rel.as_os_str().is_empty()
|
||||
&& (self.inner.state.mode != WatchMode::Flat || path.parent() == Some(self.root.as_path()))
|
||||
&& EventFilter::git_internal(rel).is_none()
|
||||
&& !crate::encoding::is_atomic_temp(path)
|
||||
&& !self.excludes.read().is_excluded(rel)
|
||||
}
|
||||
|
||||
/// Repository enclosing the watched root, if any.
|
||||
pub fn repo_root(&self) -> Option<&Path> {
|
||||
self.rules.repo_root()
|
||||
@@ -1861,6 +1873,27 @@ mod tests {
|
||||
b.iter().flat_map(|b| b.created.iter().chain(&b.modified).chain(&b.removed).cloned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_coverage_tracks_exclusions_and_watch_mode() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let sink: SharedSink = Arc::new(|_e: IdeEvent| {});
|
||||
let watcher =
|
||||
Watcher::start_with(&root, vec!["target".into()], sink.clone(), Box::new(|_| {}), WatchMode::Recursive)
|
||||
.unwrap();
|
||||
assert!(watcher.covers_file(&root.join("src/main.rs")));
|
||||
assert!(!watcher.covers_file(&root.join("target/generated-sources/Api.java")));
|
||||
assert!(!watcher.covers_file(&root.with_extension("outside")));
|
||||
assert!(!watcher.covers_file(&root.join(".git/HEAD")));
|
||||
watcher.set_excludes(&["dist".into()]);
|
||||
assert!(watcher.covers_file(&root.join("target/generated-sources/Api.java")));
|
||||
assert!(!watcher.covers_file(&root.join("dist/generated.ts")));
|
||||
|
||||
let flat = Watcher::start_with(&root, Vec::new(), sink, Box::new(|_| {}), WatchMode::Flat).unwrap();
|
||||
assert!(flat.covers_file(&root.join("file.txt")));
|
||||
assert!(!flat.covers_file(&root.join("src/file.txt")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_directory_mode_skips_excluded_dirs_and_follows_new_ones() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -151,6 +151,8 @@ struct RegEntry {
|
||||
slot: Slot,
|
||||
refs: u32,
|
||||
keys: Vec<PathBuf>,
|
||||
/// Disk path eligible for external sync (`None` for virtual, untitled, binary or archive buffers).
|
||||
syncable_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -707,7 +709,8 @@ impl Documents {
|
||||
for k in &keys {
|
||||
reg.by_key.insert(k.clone(), id);
|
||||
}
|
||||
reg.docs.insert(id, RegEntry { slot: slot.clone(), refs: 1, keys });
|
||||
let syncable_path = (!loaded.binary && !in_archive).then(|| path.to_path_buf());
|
||||
reg.docs.insert(id, RegEntry { slot: slot.clone(), refs: 1, keys, syncable_path });
|
||||
id
|
||||
};
|
||||
let info = match ipc_text {
|
||||
@@ -780,7 +783,7 @@ impl Documents {
|
||||
}
|
||||
let id = DocId::next();
|
||||
reg.by_key.insert(key.clone(), id);
|
||||
reg.docs.insert(id, RegEntry { slot: slot.clone(), refs: 1, keys: vec![key] });
|
||||
reg.docs.insert(id, RegEntry { slot: slot.clone(), refs: 1, keys: vec![key], syncable_path: None });
|
||||
id
|
||||
};
|
||||
let info = Self::info(id, &st);
|
||||
@@ -844,7 +847,7 @@ impl Documents {
|
||||
}
|
||||
let id = DocId::next();
|
||||
reg.by_key.insert(key.clone(), id);
|
||||
reg.docs.insert(id, RegEntry { slot: slot.clone(), refs: 1, keys: vec![key] });
|
||||
reg.docs.insert(id, RegEntry { slot: slot.clone(), refs: 1, keys: vec![key], syncable_path: None });
|
||||
id
|
||||
};
|
||||
let info = Self::info(id, &st);
|
||||
@@ -1218,6 +1221,7 @@ impl Documents {
|
||||
}
|
||||
if let Some(entry) = reg.docs.get_mut(&doc) {
|
||||
entry.keys = keys;
|
||||
entry.syncable_path = (!ide_vfs::is_archive_path(&target)).then(|| target.clone());
|
||||
}
|
||||
}
|
||||
let old_path = std::mem::replace(&mut st.path, target.clone());
|
||||
@@ -1633,17 +1637,34 @@ impl Documents {
|
||||
/// Re-checks open file buffers, including files outside the watched roots.
|
||||
/// Call from a blocking worker; unchanged files only need their metadata.
|
||||
pub fn sync_from_disk(&self) {
|
||||
self.sync_open_documents(false);
|
||||
self.sync_open_documents(false, |_| true);
|
||||
}
|
||||
|
||||
/// Refreshes clean buffers after an IDE operation rewrites files. Such an
|
||||
/// operation can preserve both file length and the timestamp's millisecond.
|
||||
/// The open document's selected codec is retained.
|
||||
pub fn sync_after_disk_change(&self) {
|
||||
self.sync_open_documents(true);
|
||||
self.sync_open_documents(true, |_| true);
|
||||
}
|
||||
|
||||
fn sync_open_documents(&self, force_clean: bool) {
|
||||
/// Whether any open disk-backed text document is outside `is_watched`.
|
||||
/// In-memory check only: locks the registry, never individual document slots or disk.
|
||||
pub fn has_unwatched_documents(&self, is_watched: impl Fn(&Path) -> bool) -> bool {
|
||||
self.registry
|
||||
.lock()
|
||||
.docs
|
||||
.values()
|
||||
.filter_map(|entry| entry.syncable_path.as_deref())
|
||||
.any(|path| !is_watched(path))
|
||||
}
|
||||
|
||||
/// Checks only open files not covered by a document watcher, for example
|
||||
/// dependency sources or generated files in excluded build folders.
|
||||
pub fn sync_unwatched_from_disk(&self, is_watched: impl Fn(&Path) -> bool) {
|
||||
self.sync_open_documents(false, |path| !is_watched(path));
|
||||
}
|
||||
|
||||
fn sync_open_documents(&self, force_clean: bool, include: impl Fn(&Path) -> bool) {
|
||||
let slots: Vec<Slot> = self.registry.lock().docs.values().map(|e| e.slot.clone()).collect();
|
||||
let paths: Vec<PathBuf> = slots
|
||||
.iter()
|
||||
@@ -1652,6 +1673,7 @@ impl Documents {
|
||||
(!st.closed && st.uri.is_none() && !st.binary && !ide_vfs::is_archive_path(&st.path))
|
||||
.then(|| st.path.clone())
|
||||
})
|
||||
.filter(|path| include(path))
|
||||
.collect();
|
||||
self.reload_from_disk(&paths, force_clean, true);
|
||||
}
|
||||
|
||||
@@ -665,7 +665,9 @@ impl Documents {
|
||||
for key in &keys {
|
||||
registry.by_key.insert(key.clone(), *id);
|
||||
}
|
||||
registry.docs.insert(*id, RegEntry { slot: Arc::new(Mutex::new(state)), refs: 1, keys });
|
||||
let syncable_path = (state.uri.is_none() && !state.binary && !ide_vfs::is_archive_path(&state.path))
|
||||
.then(|| state.path.clone());
|
||||
registry.docs.insert(*id, RegEntry { slot: Arc::new(Mutex::new(state)), refs: 1, keys, syncable_path });
|
||||
}
|
||||
let files = edit
|
||||
.files
|
||||
|
||||
@@ -56,6 +56,57 @@ fn fixture() -> Fixture {
|
||||
Fixture { _tmp: tmp, root, docs, events, rec }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwatched_sync_leaves_covered_documents_to_the_watcher() {
|
||||
let f = fixture();
|
||||
let watched = f.root.join("watched.txt");
|
||||
let unwatched = f.root.join("unwatched.txt");
|
||||
for path in [&watched, &unwatched] {
|
||||
fs::write(path, "original\n").unwrap();
|
||||
}
|
||||
let watched_doc = f.docs.open(&watched).unwrap();
|
||||
let unwatched_doc = f.docs.open(&unwatched).unwrap();
|
||||
for path in [&watched, &unwatched] {
|
||||
fs::write(path, "rewritten source\n").unwrap();
|
||||
}
|
||||
|
||||
f.docs.sync_unwatched_from_disk(|path| path == watched);
|
||||
|
||||
assert_eq!(f.docs.snapshot(watched_doc.id).unwrap().version, watched_doc.version);
|
||||
assert_eq!(f.docs.snapshot(unwatched_doc.id).unwrap().text, "rewritten source\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_unwatched_documents_tracks_open_disk_buffers() {
|
||||
let f = fixture();
|
||||
let watched = f.root.join("watched.txt");
|
||||
let unwatched = f.root.join("unwatched.txt");
|
||||
let binary = f.root.join("blob.bin");
|
||||
fs::write(&watched, "a\n").unwrap();
|
||||
fs::write(&unwatched, "b\n").unwrap();
|
||||
fs::write(&binary, b"\0\0binary").unwrap();
|
||||
let is_watched = |path: &Path| path == watched;
|
||||
|
||||
assert!(!f.docs.has_unwatched_documents(is_watched));
|
||||
|
||||
let _virtual_doc =
|
||||
f.docs.open_virtual("test://virtual", LanguageId::plain_text(), "v", "utf-8", false, false).unwrap();
|
||||
let untitled = f.docs.open_untitled(None).unwrap();
|
||||
let _binary_doc = f.docs.open(&binary).unwrap();
|
||||
let _watched_doc = f.docs.open(&watched).unwrap();
|
||||
assert!(!f.docs.has_unwatched_documents(is_watched));
|
||||
|
||||
let unwatched_doc = f.docs.open(&unwatched).unwrap();
|
||||
assert!(f.docs.has_unwatched_documents(is_watched));
|
||||
|
||||
f.docs.close(unwatched_doc.id);
|
||||
assert!(!f.docs.has_unwatched_documents(is_watched));
|
||||
|
||||
let saved_outside = f.root.join("saved-unwatched.txt");
|
||||
f.docs.save_as(untitled.id, &saved_outside).unwrap();
|
||||
assert!(f.docs.has_unwatched_documents(is_watched));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_disk_changes_preserve_the_open_documents_encoding() {
|
||||
let f = fixture();
|
||||
|
||||
Reference in new issue
Заблокувати користувача