дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 06:42:54 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f2869643b7 | ||
|
|
06fab1b237 | ||
|
|
b95f87e645 | ||
|
|
36f2855253 |
No files matched your search
@@ -5,8 +5,10 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
|
||||
build_dirs(root).into_iter().next()
|
||||
}
|
||||
|
||||
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
|
||||
/// ask for the builds many times while a project opens; on a network share each walk is
|
||||
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
|
||||
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
|
||||
|
||||
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
|
||||
|
||||
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
|
||||
fn build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
|
||||
ide_core::project_roots::discover(root, &markers)
|
||||
let dirs = ide_core::project_roots::discover(root, &markers);
|
||||
let now = Instant::now();
|
||||
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
|
||||
map.insert(root.to_path_buf(), (now, dirs.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
|
||||
match cached {
|
||||
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
|
||||
_ => build_dirs(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
|
||||
/// (after a build or settings script appeared, changed or was removed there).
|
||||
pub fn forget_build_dirs(root: &Path) {
|
||||
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
|
||||
}
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
/// Linked build identities without reading their scripts, as of now (a sync, a build).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, build_dirs)
|
||||
}
|
||||
|
||||
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
|
||||
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, cached_build_dirs)
|
||||
}
|
||||
|
||||
fn linked_dirs_from(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
discover: fn(&Path) -> Vec<PathBuf>,
|
||||
) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn discovered_builds_are_reused_until_forgotten() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::create_dir_all(root.join("a")).unwrap();
|
||||
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
std::fs::create_dir_all(root.join("b")).unwrap();
|
||||
std::fs::write(root.join("b/build.gradle"), "").unwrap();
|
||||
// A walk per call is thousands of round trips on a network share.
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
super::forget_build_dirs(&root.join("b"));
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
|
||||
// A sync sees a new build at once, and so does every later lookup.
|
||||
std::fs::create_dir_all(root.join("c")).unwrap();
|
||||
std::fs::write(root.join("c/build.gradle"), "").unwrap();
|
||||
let all = vec![root.join("a"), root.join("b"), root.join("c")];
|
||||
assert_eq!(super::build_dirs(root), all);
|
||||
assert_eq!(super::cached_build_dirs(root), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_linkage_discovers_all_shallow_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<PathBuf> {
|
||||
let builds = gradle::linked_dirs(root, settings);
|
||||
let builds = gradle::linked_dirs_cached(root, settings);
|
||||
let dirs: Vec<String> = builds
|
||||
.iter()
|
||||
.flat_map(|dir| {
|
||||
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
let reported = gradle::linked_dirs_cached(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -19,6 +19,7 @@ pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod network_path;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Whether a path is on a network file system, where every stat is a round trip to a server.
|
||||
|
||||
use std::path::{Component, Path, Prefix};
|
||||
|
||||
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
|
||||
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
|
||||
pub fn is_network_path(path: &Path) -> bool {
|
||||
match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
|
||||
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_remote_drive(letter: u8) -> bool {
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
/// `DRIVE_REMOTE` (WindowsProgramming).
|
||||
const DRIVE_REMOTE: u32 = 4;
|
||||
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
|
||||
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
|
||||
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_remote_drive(_letter: u8) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_network_path;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn unc_paths_are_on_the_network() {
|
||||
if cfg!(windows) {
|
||||
assert!(is_network_path(Path::new(r"\\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
|
||||
}
|
||||
assert!(!is_network_path(Path::new("relative/path")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_directory_is_not() {
|
||||
let dir = std::env::temp_dir();
|
||||
assert!(!is_network_path(&dir), "{}", dir.display());
|
||||
}
|
||||
}
|
||||
@@ -158,24 +158,28 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<
|
||||
// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
|
||||
let project = host.project(window);
|
||||
host.blocking(move || {
|
||||
let excludes = project
|
||||
.map(|p| {
|
||||
// An attached project's folders follow its own exclusions.
|
||||
let root = p.root_of(&path);
|
||||
let globs = p.exclude_globs_in(&root);
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// root patterns (`/build`) when the project is a repo subfolder.
|
||||
let repo = root.ancestors().find(|d| d.join(".git").exists());
|
||||
match repo.and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
None => globs,
|
||||
let Ok(p) = project else { return ide_vfs::read_dir(&path, &[]) };
|
||||
// An attached project's folders follow its own exclusions.
|
||||
let root = p.root_of(&path);
|
||||
let globs = p.exclude_globs_in(&root);
|
||||
// `read_dir` matches relative to the enclosing repository: re-anchor
|
||||
// root patterns (`/build`) when the project is a repo subfolder. The
|
||||
// watcher already found the project folder's repository; on a network
|
||||
// share each `.git` probe up the tree is a round trip.
|
||||
let repo = if root == p.root && p.watcher.root() == p.root {
|
||||
p.watcher.repo_root().map(Path::to_path_buf)
|
||||
} else {
|
||||
root.ancestors().find(|d| d.join(".git").exists()).map(Path::to_path_buf)
|
||||
};
|
||||
let excludes =
|
||||
match repo.as_deref().and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
|
||||
Some(rel) => {
|
||||
let rel = rel.to_string_lossy().replace('\\', "/");
|
||||
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ide_vfs::read_dir(&path, &excludes)
|
||||
None => globs,
|
||||
};
|
||||
p.watcher.read_dir(&path, &excludes)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -149,7 +149,8 @@ pub fn settings_set(
|
||||
|
||||
/// Effective source / test / resource / excluded roots of the window's project:
|
||||
/// auto-detected from build files, overridden by Settings › Project Structure.
|
||||
#[command(trust = always)]
|
||||
/// Off the UI thread: Gradle source roots may walk the project for builds, slow on a share.
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
pub fn project_roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots> {
|
||||
Ok(host.project(window)?.roots())
|
||||
}
|
||||
|
||||
@@ -141,6 +141,8 @@ impl Host {
|
||||
self.environment.direnv_opened(&root, &sink);
|
||||
}
|
||||
let settings = SettingsStore::load(&self.config_dir, Some(&root));
|
||||
// Builds may have changed while no watcher was looking.
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
|
||||
let member_excludes: MemberExcludes = Arc::new(RwLock::new(member_excludes(&settings, &root)));
|
||||
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read(), &member_excludes.read());
|
||||
@@ -505,6 +507,7 @@ impl Host {
|
||||
// Build files / conventional folders changed: re-detect roots.
|
||||
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
|
||||
if touched.into_iter().any(ide_workspace::roots::affects_roots) {
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
let fresh = ide_workspace::roots::detect(&root);
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`) leave the index too.
|
||||
|
||||
@@ -182,7 +182,9 @@ impl Shared {
|
||||
let snapshot_started = Instant::now();
|
||||
let fast = self.try_fast_start();
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
if let Err(reason) = fast {
|
||||
if fast.is_err() && self.is_cancelled() {
|
||||
// Closing: the stat loops stopped early, and a fallback walk would only stall the close.
|
||||
} else if let Err(reason) = fast {
|
||||
let snapshot_guard = SystemTime::now();
|
||||
let walk_started = Instant::now();
|
||||
let found = self.walk_roots(None);
|
||||
@@ -276,13 +278,24 @@ impl Shared {
|
||||
}
|
||||
let root = filter.root();
|
||||
let validation_started = Instant::now();
|
||||
for i in 0..snapshot.dirs_len() {
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") };
|
||||
if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) {
|
||||
return Err("directory changed");
|
||||
}
|
||||
// In parallel: on a network share each stat is a round trip.
|
||||
let cancelled = &self.cancelled;
|
||||
let dirs_valid = INDEX_POOL.install(|| {
|
||||
(0..snapshot.dirs_len()).into_par_iter().all(|i| {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
return false;
|
||||
}
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
std::fs::symlink_metadata(&path)
|
||||
.is_ok_and(|meta| meta.is_dir() && mtime_of(&meta) == snapshot.dir_mtime(i))
|
||||
})
|
||||
});
|
||||
if self.is_cancelled() {
|
||||
return Err("cancelled");
|
||||
}
|
||||
if !dirs_valid {
|
||||
return Err("directory changed");
|
||||
}
|
||||
let external = crate::store::external_ignore_candidates(root);
|
||||
let saved_external: Vec<&str> = (0..snapshot.ignore_len())
|
||||
@@ -309,28 +322,56 @@ impl Shared {
|
||||
}
|
||||
let validation_elapsed = validation_started.elapsed();
|
||||
let build_started = Instant::now();
|
||||
let entries: Vec<Option<(FileEntry, Vec<StoredSymbol>)>> = INDEX_POOL.install(|| {
|
||||
(0..snapshot.len())
|
||||
.into_par_iter()
|
||||
.map(|i| {
|
||||
let path = root.join(snapshot.rel(i));
|
||||
let meta = std::fs::symlink_metadata(&path).ok()?;
|
||||
if !meta.is_file() || mtime_of(&meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i) {
|
||||
// Files are checked against their folder's listing, one per folder: on Windows the
|
||||
// listing carries each entry's metadata, so a share costs a round trip per folder
|
||||
// instead of one per file. Elsewhere `DirEntry::metadata` is the same `lstat`.
|
||||
let mut by_dir: HashMap<&str, Vec<usize>> = HashMap::new();
|
||||
for i in 0..snapshot.len() {
|
||||
let rel = snapshot.rel(i);
|
||||
if !safe_rel(rel) {
|
||||
return Err("file changed");
|
||||
}
|
||||
let dir = rel.rfind('/').map_or("", |at| &rel[..at]);
|
||||
by_dir.entry(dir).or_default().push(i);
|
||||
}
|
||||
let by_dir: Vec<(&str, Vec<usize>)> = by_dir.into_iter().collect();
|
||||
let entries: Option<Vec<Vec<Indexed>>> = INDEX_POOL.install(|| {
|
||||
by_dir
|
||||
.par_iter()
|
||||
.map(|(dir, files)| {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
Some(snapshot.entry(i, root))
|
||||
let path = if dir.is_empty() { root.to_owned() } else { root.join(dir) };
|
||||
let listed: HashMap<std::ffi::OsString, std::fs::Metadata> = std::fs::read_dir(&path)
|
||||
.ok()?
|
||||
.filter_map(|e| {
|
||||
let e = e.ok()?;
|
||||
Some((e.file_name(), e.metadata().ok()?))
|
||||
})
|
||||
.collect();
|
||||
files
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let rel = snapshot.rel(i);
|
||||
let name = rel.rfind('/').map_or(rel, |at| &rel[at + 1..]);
|
||||
let meta = listed.get(std::ffi::OsStr::new(name))?;
|
||||
if !meta.is_file() || mtime_of(meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(snapshot.entry(i, root))
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let built = build_started.elapsed();
|
||||
if entries.iter().any(Option::is_none) {
|
||||
return Err("file changed");
|
||||
}
|
||||
let validated = entries;
|
||||
let mut entries = Vec::with_capacity(validated.len());
|
||||
for entry in validated {
|
||||
entries.push(entry.expect("validated above"));
|
||||
if self.is_cancelled() {
|
||||
return Err("cancelled");
|
||||
}
|
||||
let Some(entries) = entries else { return Err("file changed") };
|
||||
let entries: Vec<(FileEntry, Vec<StoredSymbol>)> = entries.into_iter().flatten().collect();
|
||||
let dirs: Vec<(Box<str>, PathBuf, u32)> = (0..snapshot.dirs_len())
|
||||
.filter_map(|i| {
|
||||
let rel = snapshot.dir(i);
|
||||
@@ -1108,6 +1149,9 @@ impl Shared {
|
||||
|
||||
type ContentHash = [u8; 32];
|
||||
|
||||
/// A file validated on a warm start, with its stored symbols.
|
||||
type Indexed = (FileEntry, Vec<StoredSymbol>);
|
||||
|
||||
/// `Some(prev_hash)` when `f` is missing or stale in `d` (`None` inner hash when
|
||||
/// the file must be parsed fresh); `None` when `d` is already current for `f`.
|
||||
fn prev_hash_if_stale(d: &IndexData, f: &Found) -> Option<Option<ContentHash>> {
|
||||
@@ -1438,6 +1482,32 @@ mod metric_tests {
|
||||
assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_start_checks_files_against_their_folder_listing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(root.join("src/deep")).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
std::fs::write(root.join("src/lib.rs"), "pub fn a() {}\n").unwrap();
|
||||
std::fs::write(root.join("src/deep/b.rs"), "pub fn b() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
let open = || {
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
index
|
||||
};
|
||||
open().scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let index = open();
|
||||
assert_eq!(index.try_fast_start(), Ok(()));
|
||||
assert_eq!(index.data.read().file_count, 3);
|
||||
// Same folder mtime, a different size: only the listing's metadata can tell.
|
||||
let dir_mtime = std::fs::metadata(root.join("src/deep")).unwrap().modified().unwrap();
|
||||
std::fs::write(root.join("src/deep/b.rs"), "pub fn b() { /* longer */ }\n").unwrap();
|
||||
std::fs::File::open(root.join("src/deep")).and_then(|f| f.set_modified(dir_mtime)).ok();
|
||||
assert_eq!(open().try_fast_start(), Err("file changed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopened_cache_counts_metadata_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1533,7 +1603,8 @@ mod metric_tests {
|
||||
index.run(true);
|
||||
});
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
// The project is closing: its validation stops instead of statting the rest of a tree.
|
||||
assert_eq!(index.data.read().file_count, 0);
|
||||
assert_eq!(count.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -157,8 +157,32 @@ impl DiskSpelling {
|
||||
|
||||
type Entries = (BTreeMap<String, Entry>, HashSet<String>);
|
||||
|
||||
/// Stat checks for a work tree on a network share: mtime and size only.
|
||||
///
|
||||
/// A share's index is usually written by git on the server too, whose inode, owner and change
|
||||
/// time never match what Windows reports for the same file (inode 0, creation time). Every
|
||||
/// tracked file would then fail the stat check and be read in full to compare its content,
|
||||
/// over the network, on each status; and the index written back would fail the same way for
|
||||
/// git on the server.
|
||||
const NETWORK_STAT_CONFIG: [(&str, &str); 2] = [("core.checkStat", "minimal"), ("core.trustCTime", "false")];
|
||||
|
||||
fn on_network(r: &Repo) -> bool {
|
||||
ide_core::network_path::is_network_path(r.root())
|
||||
}
|
||||
|
||||
fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
let repo = r.gix()?;
|
||||
let mut repo = r.gix()?;
|
||||
if on_network(r) {
|
||||
use gix::config::tree::{Core, Key};
|
||||
let mut config = repo.config_snapshot_mut();
|
||||
let keys: [&'static dyn Key; 2] = [&Core::CHECK_STAT, &Core::TRUST_C_TIME];
|
||||
for (key, (_, value)) in keys.into_iter().zip(NETWORK_STAT_CONFIG) {
|
||||
if let Err(e) = config.set_value(key, value) {
|
||||
tracing::debug!("{}: {e}", key.logical_name());
|
||||
}
|
||||
}
|
||||
config.commit().map_err(gx)?;
|
||||
}
|
||||
let mut map: BTreeMap<String, Entry> = BTreeMap::new();
|
||||
let mut conflicts: HashSet<String> = HashSet::new();
|
||||
|
||||
@@ -273,12 +297,22 @@ fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
|
||||
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
|
||||
}
|
||||
|
||||
/// `-c` options for [`NETWORK_STAT_CONFIG`] when the work tree is on a network share.
|
||||
fn network_args(r: &Repo) -> Vec<String> {
|
||||
if !on_network(r) {
|
||||
return Vec::new();
|
||||
}
|
||||
NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect()
|
||||
}
|
||||
|
||||
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
|
||||
/// In Restricted Mode git compares content without the repository's clean/process
|
||||
/// filters and doesn't ask submodules for their own status (which runs their config).
|
||||
fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?;
|
||||
let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect();
|
||||
let network = network_args(r);
|
||||
args.extend(network.iter().map(String::as_str));
|
||||
args.extend(["status", "--porcelain=v2", "-z", "--untracked-files=all"]);
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
@@ -292,6 +326,8 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeResult<Entries> {
|
||||
let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?;
|
||||
let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect();
|
||||
let network = network_args(r);
|
||||
args.extend(network.iter().map(String::as_str));
|
||||
args.extend(["--literal-pathspecs", "status", "--porcelain=v2", "-z", "--untracked-files=all"]);
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
|
||||
@@ -124,6 +124,16 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering {
|
||||
///
|
||||
/// Inside an archive (`<archive>!/<entry>`, or the archive file itself) lists its entries.
|
||||
pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
|
||||
read_dir_with(dir, excludes, None)
|
||||
}
|
||||
|
||||
/// [`read_dir`] matching `.gitignore` / `.ignore` with `shared` rules (a watcher's, kept current by its
|
||||
/// events) instead of rules looked up afresh: on a network share each lookup is several round trips.
|
||||
pub(crate) fn read_dir_with(
|
||||
dir: &Path,
|
||||
excludes: &[String],
|
||||
shared: Option<&rules::GitignoreStack>,
|
||||
) -> IdeResult<Vec<FileEntry>> {
|
||||
if let Some((archive, entry)) = split_archive_path(dir) {
|
||||
return read_archive_dir(&archive, &entry);
|
||||
}
|
||||
@@ -133,27 +143,37 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
|
||||
if !fs::metadata(dir)?.is_dir() {
|
||||
return Err(IdeError::invalid(format!("{} is not a directory", dir.display())));
|
||||
}
|
||||
let gitignore = rules::GitignoreStack::cached(dir);
|
||||
let fresh;
|
||||
let gitignore = match shared {
|
||||
Some(shared) => shared,
|
||||
None => {
|
||||
fresh = rules::GitignoreStack::cached(dir);
|
||||
&fresh
|
||||
}
|
||||
};
|
||||
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
|
||||
let excludes = ExcludeMatcher::new(excludes);
|
||||
|
||||
let paths: Vec<PathBuf> = fs::read_dir(dir)?
|
||||
let listed: Vec<fs::DirEntry> = fs::read_dir(dir)?
|
||||
.filter_map(|entry| match entry {
|
||||
Ok(e) => Some(e.path()),
|
||||
Ok(e) => Some(e),
|
||||
Err(e) => {
|
||||
tracing::debug!("read_dir {}: {e}", dir.display());
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// One stat per entry dominates a large folder (and every stat is a round trip on a network
|
||||
// share): stat in parallel; small folders stay on this thread.
|
||||
let mut entries: Vec<(bool, FileEntry)> = paths
|
||||
// On Windows `DirEntry::metadata` comes with the listing (FindNextFileW) at no further
|
||||
// cost; a separate stat per entry was one network round trip each on an SMB share.
|
||||
// Elsewhere it is one `lstat` per entry: stat in parallel; small folders stay on this thread.
|
||||
let mut entries: Vec<(bool, FileEntry)> = listed
|
||||
.into_par_iter()
|
||||
.with_min_len(256)
|
||||
.filter_map(|path| {
|
||||
.filter_map(|entry| {
|
||||
let path = entry.path();
|
||||
let name = path.file_name()?.to_string_lossy().into_owned();
|
||||
let lmeta = fs::symlink_metadata(&path).ok()?;
|
||||
// Does not follow symlinks, like `symlink_metadata`.
|
||||
let lmeta = entry.metadata().ok()?;
|
||||
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
|
||||
match fs::metadata(&path) {
|
||||
Ok(m) => {
|
||||
|
||||
@@ -58,6 +58,7 @@ type Emit = Arc<dyn Fn(&FsBatch) + Send + Sync>;
|
||||
/// `on_change` (used by the index) with the same batch. Stops when dropped;
|
||||
/// no callback runs after `drop` returns.
|
||||
pub struct Watcher {
|
||||
root: PathBuf,
|
||||
inner: Inner,
|
||||
excludes: SharedExcludes,
|
||||
rules: Arc<GitignoreStack>,
|
||||
@@ -116,7 +117,7 @@ impl Watcher {
|
||||
(Self::start_polling(&root, filter, emit, mode)?, Some(e.message))
|
||||
}
|
||||
};
|
||||
Ok(Self { inner, excludes: shared, rules, polling })
|
||||
Ok(Self { root, inner, excludes: shared, rules, polling })
|
||||
}
|
||||
|
||||
/// Why changes are polled for instead of reported by the OS; `None` when they are.
|
||||
@@ -144,6 +145,24 @@ impl Watcher {
|
||||
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(Path::new("/")));
|
||||
}
|
||||
|
||||
/// The watched directory (canonical).
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// Repository enclosing the watched root, if any.
|
||||
pub fn repo_root(&self) -> Option<&Path> {
|
||||
self.rules.repo_root()
|
||||
}
|
||||
|
||||
/// [`crate::read_dir`] reusing this watcher's ignore rules for directories below its root.
|
||||
/// They are invalidated by the watcher's own events, so expanding folder after folder does not
|
||||
/// look for `.git` and re-read every `.gitignore` up to the repository root each time.
|
||||
pub fn read_dir(&self, dir: &Path, excludes: &[String]) -> IdeResult<Vec<crate::FileEntry>> {
|
||||
let shared = dir.starts_with(&self.root).then_some(&*self.rules);
|
||||
crate::read_dir_with(dir, excludes, shared)
|
||||
}
|
||||
|
||||
/// Number of OS-level watches (1 in recursive and flat mode).
|
||||
pub fn watch_count(&self) -> usize {
|
||||
self.inner.state.watched.lock().len()
|
||||
@@ -2224,7 +2243,7 @@ mod tests {
|
||||
let (excludes, rules) = (filter.excludes.clone(), filter.gitignore.clone());
|
||||
let emit: Emit = Arc::new(move |b: &FsBatch| batches.lock().push(b.clone()));
|
||||
let inner = Watcher::start_polling(root, filter, emit, WatchMode::default()).unwrap();
|
||||
Watcher { inner, excludes, rules, polling: Some("cannot start file watcher".into()) }
|
||||
Watcher { root: root.to_path_buf(), inner, excludes, rules, polling: Some("cannot start file watcher".into()) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2311,7 +2330,7 @@ mod tests {
|
||||
notify::Config::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let watcher = Watcher { inner, excludes, rules, polling: None };
|
||||
let watcher = Watcher { root: root.clone(), inner, excludes, rules, polling: None };
|
||||
assert!(watcher.polling().is_none(), "the OS watcher did start");
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while watcher.unwatched_reason().is_none() && Instant::now() < deadline {
|
||||
|
||||
@@ -311,6 +311,45 @@ fn wait_for(events: &Mutex<Vec<FsBatch>>, pred: impl Fn(&[FsBatch]) -> bool) ->
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watcher_read_dir_reuses_its_ignore_rules() {
|
||||
let (_t, r) = root();
|
||||
write(&r.join(".git/HEAD"), "ref: refs/heads/main\n");
|
||||
write(&r.join(".gitignore"), "*.log\n");
|
||||
write(&r.join("sub/a.log"), "x");
|
||||
write(&r.join("sub/b.txt"), "x");
|
||||
let sink: SharedSink = Arc::new(|_| {});
|
||||
let watcher = Watcher::start(&r, vec![], sink, Box::new(|_| {})).unwrap();
|
||||
assert_eq!(watcher.root(), r);
|
||||
assert_eq!(watcher.repo_root(), Some(r.as_path()));
|
||||
let ignored = |entries: Vec<FileEntry>| -> BTreeSet<String> {
|
||||
entries.into_iter().filter(|e| e.ignored).map(|e| e.name).collect()
|
||||
};
|
||||
let listed = watcher.read_dir(&r.join("sub"), &[]).unwrap();
|
||||
assert_eq!(ignored(listed.clone()), BTreeSet::from(["a.log".to_string()]));
|
||||
let plain = read_dir(&r.join("sub"), &[]).unwrap();
|
||||
assert_eq!(
|
||||
listed.iter().map(|e| (&e.name, e.kind, e.size, e.ignored)).collect::<Vec<_>>(),
|
||||
plain.iter().map(|e| (&e.name, e.kind, e.size, e.ignored)).collect::<Vec<_>>(),
|
||||
);
|
||||
// The watcher's events keep the shared rules current.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
write(&r.join(".gitignore"), "*.txt\n");
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let now = ignored(watcher.read_dir(&r.join("sub"), &[]).unwrap());
|
||||
if now == BTreeSet::from(["b.txt".to_string()]) {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "still ignored: {now:?}");
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
// Outside the watched folder: rules of its own.
|
||||
let (_o, other) = root();
|
||||
write(&other.join("x.log"), "x");
|
||||
assert!(watcher.read_dir(&other, &[]).unwrap().iter().all(|e| !e.ignored));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watcher_reports_changes() {
|
||||
let (_t, r) = root();
|
||||
|
||||
@@ -18,6 +18,30 @@ pub const PYTHON_FILES: &[&str] = &["pyproject.toml", "setup.py", "setup.cfg", "
|
||||
const SKIP_DIRS: &[&str] =
|
||||
&["node_modules", "target", "build", "dist", "out", "venv", "__pycache__", "vendor", "bower_components"];
|
||||
|
||||
/// Skipped folders that are never a virtual environment: not probed for its markers.
|
||||
const NEVER_ENV_DIRS: &[&str] = &[
|
||||
".git",
|
||||
".hg",
|
||||
".svn",
|
||||
".jj",
|
||||
".idea",
|
||||
".vscode",
|
||||
".gradle",
|
||||
".mvn",
|
||||
".github",
|
||||
".cache",
|
||||
".next",
|
||||
".nuxt",
|
||||
"node_modules",
|
||||
"target",
|
||||
"build",
|
||||
"dist",
|
||||
"out",
|
||||
"__pycache__",
|
||||
"vendor",
|
||||
"bower_components",
|
||||
];
|
||||
|
||||
/// A Python virtual environment (`python -m venv`, virtualenv, uv) or conda environment,
|
||||
/// whatever it is named: its packages are dependencies, not modules of the project.
|
||||
/// Returns the file that marks it.
|
||||
@@ -99,7 +123,34 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
|
||||
break;
|
||||
}
|
||||
let dir = if rel.is_empty() { root.to_path_buf() } else { root.join(&rel) };
|
||||
if crate::unity::is_project(&dir) {
|
||||
// The listing alone decides which markers to probe: on a network share every
|
||||
// probe is a round trip, and most folders have none of them.
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
let mut dirs: Vec<String> = Vec::new();
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() => dirs.push(name.clone()),
|
||||
Ok(t) if t.is_file() => files.push(name.clone()),
|
||||
_ => {}
|
||||
}
|
||||
names.push(name);
|
||||
}
|
||||
let named = |n: &str| names.iter().any(|x| x == n);
|
||||
// A virtual environment is excluded, not searched (its packages ship build files).
|
||||
if !rel.is_empty()
|
||||
&& (named("pyvenv.cfg") || named("conda-meta"))
|
||||
&& let Some(marker) = virtual_env_marker(&dir)
|
||||
{
|
||||
if !out.iter().any(|r| r.path == rel) {
|
||||
let from = join(&rel, marker);
|
||||
out.push(SourceFolder { path: rel, kind: RootKind::Excluded, detected_from: Some(from) });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if named("Assets") && named("ProjectSettings") && crate::unity::is_project(&dir) {
|
||||
for (name, kind) in
|
||||
[("Assets", RootKind::Source), ("Packages", RootKind::Source), ("ProjectSettings", RootKind::Resources)]
|
||||
{
|
||||
@@ -122,17 +173,6 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
|
||||
// Assets and PackageCache may contain arbitrary build files; they aren't nested modules.
|
||||
continue;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
let mut dirs: Vec<String> = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() => dirs.push(name),
|
||||
Ok(t) if t.is_file() => files.push(name),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
dirs.sort();
|
||||
let before = out.len();
|
||||
module_roots(root, &rel, &files, &mut out);
|
||||
@@ -146,18 +186,19 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
|
||||
if found.iter().any(|f| *f == child || f.is_empty() && name == "src") {
|
||||
continue;
|
||||
}
|
||||
if let Some(marker) = virtual_env_marker(&root.join(&child)) {
|
||||
if !out.iter().any(|r| r.path == child) {
|
||||
// Skipping discovery is not an exclusion: marked hidden/conventional
|
||||
// environments (`.venv`, `venv`) still need an explicit root for index and
|
||||
// watcher filtering. Folders searched below are checked once listed.
|
||||
if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
|
||||
if !NEVER_ENV_DIRS.contains(&name.as_str())
|
||||
&& let Some(marker) = virtual_env_marker(&root.join(&child))
|
||||
&& !out.iter().any(|r| r.path == child)
|
||||
{
|
||||
let from = join(&child, marker);
|
||||
out.push(SourceFolder { path: child, kind: RootKind::Excluded, detected_from: Some(from) });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Skipping discovery is not an exclusion: marked hidden/conventional
|
||||
// environments still need an explicit root for index and watcher filtering.
|
||||
if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
queue.push_back((child, depth + 1));
|
||||
}
|
||||
}
|
||||
@@ -601,6 +642,12 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_project_folder_itself_is_not_an_excluded_environment() {
|
||||
let dir = tree(&["pyvenv.cfg", "requirements.txt", "pkg/pyvenv.cfg", "pkg/lib/setup.py"]);
|
||||
assert_eq!(summary(&detect(dir.path())), vec!["[email protected]", "pkg=Excluded@pkg/pyvenv.cfg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_environment_detection_preserves_source_roots_and_user_overrides() {
|
||||
let dir = tree(&["Cargo.toml", "src/pyvenv.cfg", ".venv/pyvenv.cfg", ".conda/conda-meta/history"]);
|
||||
|
||||
@@ -387,6 +387,13 @@ pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
|
||||
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
|
||||
}
|
||||
|
||||
// Off the IPC thread: Gradle source roots may walk the project for builds, slow on a network share.
|
||||
pub(crate) fn project_roots(window: Window) -> IdeResult<ide_workspace::ProjectRoots> {
|
||||
let state = window.state::<AppState>();
|
||||
state.note_ipc();
|
||||
ide_host::ops::project::project_roots(&state.host, window.label())
|
||||
}
|
||||
|
||||
// Off the IPC thread: each member's `for_project().layer(Project)` re-parses both settings layers
|
||||
// and validates the merge against the whole `Settings` type, which a debug build's stack-heavy
|
||||
// recursion can overflow from the WebView2 callback (see the `settings_set` note above).
|
||||
|
||||
@@ -42,7 +42,7 @@ use std::sync::LazyLock;
|
||||
// Desktop bodies of project-host commands (`#[command(desktop_body = …)]`), which their derived
|
||||
// adapters call.
|
||||
use app::{
|
||||
close_project, open_project, project_current, project_trust_remove_location, project_trust_set,
|
||||
close_project, open_project, project_current, project_roots, project_trust_remove_location, project_trust_set,
|
||||
project_workspace_member_set, project_workspace_members, settings_get, settings_removed_theme, settings_set,
|
||||
};
|
||||
use doc::doc_edit;
|
||||
|
||||
Reference in new issue
Заблокувати користувача