Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(vcs): add shared and local Git ignore actions (#255)

Walter Wang8568a70a0513
diff --git a/Cargo.lock b/Cargo.lock
index 8683066ad..78ad6c372 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4516,6 +4516,7 @@ dependencies = [
"dunce",
"gix",
"ide-core",
+ "ignore",
"libc",
"regex-lite",
"serde",
@@ -4533,6 +4534,7 @@ dependencies = [
"chardetng",
"dunce",
"encoding_rs",
+ "gix",
"globset",
"ide-core",
"ignore",
diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs
index 05af0d646..6140487d1 100644
--- a/crates/ide-host/src/ops/vcs/commands.rs
+++ b/crates/ide-host/src/ops/vcs/commands.rs
@@ -242,6 +242,33 @@ pub async fn vcs_stage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeRes
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
}
+/// Project-host operation (also registered with the remote dispatcher).
+pub async fn vcs_add_to_ignore(
+ host: &Host,
+ window: &str,
+ paths: Vec<PathBuf>,
+ destination: IgnoreDestination,
+) -> IdeResult<()> {
+ let project = host.project(window)?;
+ blocking(move || {
+ for path in &paths {
+ if path == &project.root || !path.starts_with(&project.root) {
+ return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
+ }
+ }
+ apply_git_executable(&project.settings.effective());
+ let result = ide_vcs::add_to_ignore(&paths, destination);
+ // Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
+ project.watcher.reload_ignore_rules();
+ for (_, watcher) in project.content_watchers.lock().iter() {
+ watcher.reload_ignore_rules();
+ }
+ project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() });
+ result.map(|_| ())
+ })
+ .await
+}
+
pub async fn vcs_unstage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
@@ -800,6 +827,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_branches", |c| async move { vcs_branches(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_stashes", |c| async move { vcs_stashes(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_stage", |c| async move { vcs_stage(&c.host, &c.window, c.arg("paths")?).await });
+ d.add("vcs_add_to_ignore", |c| async move {
+ vcs_add_to_ignore(&c.host, &c.window, c.arg("paths")?, c.arg("destination")?).await
+ });
d.add("vcs_unstage", |c| async move { vcs_unstage(&c.host, &c.window, c.arg("paths")?).await });
d.add("vcs_stage_patch", |c| async move { vcs_stage_patch(&c.host, &c.window, c.arg("patch")?).await });
d.add("vcs_discard", |c| async move { vcs_discard(&c.host, &c.window, c.arg("paths")?).await });
diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/rpc.rs
index dbc92d0df..3e195abfc 100644
--- a/crates/ide-host/tests/rpc.rs
+++ b/crates/ide-host/tests/rpc.rs
@@ -108,6 +108,26 @@ async fn serves_projects_files_documents_search_and_runs() {
invoke(&peer, "vcs_init", json!({ "dir": project })).await.unwrap();
until("git repository", || project.join(".git").is_dir()).await;
+ // Real project-host ignore writes travel through the remote command dispatcher.
+ assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
+ let ignore_root = dunce::canonicalize(&project).unwrap();
+ for (name, destination) in [("shared.tmp", "gitignore"), ("private.tmp", "localExclude")] {
+ let path = ignore_root.join(name);
+ std::fs::write(&path, "temporary").unwrap();
+ invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [path], "destination": destination })).await.unwrap();
+ let entries = invoke(&peer, "fs_read_dir", json!({ "path": ignore_root })).await.unwrap();
+ let entry = entries.as_array().unwrap().iter().find(|e| e["name"] == name).unwrap();
+ assert_eq!(entry["ignored"], true);
+ assert_eq!(entry["excluded"], false);
+ }
+ assert!(std::fs::read_to_string(project.join(".gitignore")).unwrap().contains("/shared.tmp"));
+ assert!(std::fs::read_to_string(project.join(".git/info/exclude")).unwrap().contains("/private.tmp"));
+ let outside = tmp.path().join("outside.tmp");
+ std::fs::write(&outside, "keep").unwrap();
+ assert!(
+ invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [outside], "destination": "gitignore" })).await.is_err()
+ );
+
// Unknown commands and bad arguments come back as IdeErrors.
let e = invoke(&peer, "window_minimize", json!({})).await.unwrap_err();
assert!(e.message.contains("not available remotely"), "{e:?}");
diff --git a/crates/ide-vcs/Cargo.toml b/crates/ide-vcs/Cargo.toml
index 588237df2..169063a40 100644
--- a/crates/ide-vcs/Cargo.toml
+++ b/crates/ide-vcs/Cargo.toml
@@ -8,11 +8,13 @@ license.workspace = true
[dependencies]
dunce.workspace = true
ide-core.workspace = true
+ignore.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
gix = { workspace = true, features = ["sha1", "status", "blob-diff", "revision", "index", "dirwalk", "parallel"] }
tracing.workspace = true
+tempfile.workspace = true
which = "8"
regex-lite = "0.1"
diff --git a/crates/ide-vcs/src/ignore.rs b/crates/ide-vcs/src/ignore.rs
new file mode 100644
index 000000000..1634c27cf
--- /dev/null
+++ b/crates/ide-vcs/src/ignore.rs
@@ -0,0 +1,318 @@
+//! Literal ignore rules for Project view's Git › Add to .gitignore.
+use crate::{Repo, cli};
+use ide_core::{IdeError, IdeResult};
+use serde::{Deserialize, Serialize};
+use specta::Type;
+use std::collections::{BTreeMap, HashSet};
+use std::fs;
+use std::io::{Read, Write};
+use std::path::{Component, Path, PathBuf};
+
+#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub enum IgnoreDestination {
+ Gitignore,
+ LocalExclude,
+}
+
+struct IgnoreRule {
+ pattern: String,
+ relative: PathBuf,
+ directory: bool,
+}
+
+/// Validate the whole selection before writing. Each destination is replaced atomically;
+/// a failure in a later repository may leave earlier destinations updated (safe to retry).
+/// Never modifies the index or a selected file.
+pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeResult<Vec<PathBuf>> {
+ let mut edits: BTreeMap<PathBuf, Vec<IgnoreRule>> = BTreeMap::new();
+ let mut verify = Vec::new();
+ for path in paths {
+ // Validate before filesystem access: APFS cannot even stat invalid UTF-8 names.
+ path.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
+ if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
+ return Err(IdeError::invalid("Select an absolute path without '..'"));
+ }
+ no_symlinks(path)?;
+ let meta = fs::symlink_metadata(path)?;
+ if !meta.is_file() && !meta.is_dir() {
+ return Err(IdeError::invalid("Only regular files and directories can be ignored"));
+ }
+ // A selected nested repository directory is an entry of its enclosing repository.
+ let start = path.parent().ok_or_else(|| IdeError::invalid("Cannot ignore a filesystem root"))?;
+ let repo = Repo::discover(start)?.ok_or_else(|| IdeError::invalid("Selection is not in a Git repository"))?;
+ let rel =
+ path.strip_prefix(repo.root()).map_err(|_| IdeError::invalid("Selection is outside its repository"))?;
+ let literal = pattern(rel, meta.is_dir())?;
+ if rel.components().any(|c| c.as_os_str() == ".git") {
+ return Err(IdeError::invalid("Git administration files cannot be ignored"));
+ }
+ let rel_str = rel.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
+ let tracked = cli::run(repo.root(), &["--literal-pathspecs", "ls-files", "-z", "--", rel_str], None)?;
+ if !tracked.stdout.is_empty() {
+ return Err(IdeError::invalid(format!(
+ "{} contains tracked files. Ignore rules only affect unversioned files; no files were untracked.",
+ path.display()
+ )));
+ }
+ // check-ignore rejects --literal-pathspecs; a ./ prefix prevents pathspec
+ // magic in valid filenames such as :(top)private from being interpreted.
+ let literal_query = format!("./{rel_str}");
+ let ignored = cli::run_raw(repo.root(), &["check-ignore", "-q", "--", &literal_query], None)?;
+ match ignored.code {
+ Some(0) => continue,
+ Some(1) => {}
+ _ => return Err(IdeError::invalid(ignored.stdout_str() + &String::from_utf8_lossy(&ignored.stderr))),
+ }
+ verify.push((repo.root().to_path_buf(), rel_str.to_owned()));
+ let (file, rule, base) = match destination {
+ IgnoreDestination::LocalExclude => {
+ let output = cli::run(
+ repo.root(),
+ &["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"],
+ None,
+ )?;
+ // Strip only Git's output terminator; spaces are valid in the path.
+ let raw = output.stdout_str();
+ let file = crate::repo::absolute(Path::new(
+ raw.strip_suffix("\r\n").or_else(|| raw.strip_suffix('\n')).unwrap_or(&raw),
+ ))?;
+ let common = crate::repo::absolute(repo.gix()?.common_dir())?;
+ if file != common.join("info/exclude") {
+ return Err(IdeError::invalid("Git returned an unexpected exclude path"));
+ }
+ (file, literal, repo.root())
+ }
+ IgnoreDestination::Gitignore => {
+ let base = start
+ .ancestors()
+ .take_while(|p| p.starts_with(repo.root()))
+ .find(|p| p.join(".gitignore").symlink_metadata().is_ok())
+ .unwrap_or(repo.root());
+ (base.join(".gitignore"), pattern(path.strip_prefix(base).unwrap(), meta.is_dir())?, base)
+ }
+ };
+ no_symlinks(file.parent().unwrap())?;
+ validate_file(&file)?;
+ edits.entry(file).or_default().push(IgnoreRule {
+ pattern: rule,
+ relative: path.strip_prefix(base).unwrap().to_path_buf(),
+ directory: meta.is_dir(),
+ });
+ }
+ let mut changed = Vec::new();
+ for (file, rules) in edits {
+ append(&file, &rules).map_err(|e| {
+ IdeError::new(
+ e.kind,
+ format!(
+ "Could not update {}: {}. Earlier destinations may have succeeded; refresh and retry.",
+ file.display(),
+ e.message
+ ),
+ )
+ })?;
+ changed.push(file);
+ }
+ for (root, rel) in verify {
+ if cli::run_raw(&root, &["check-ignore", "-q", "--", &format!("./{rel}")], None)?.code != Some(0) {
+ return Err(IdeError::invalid(format!(
+ "Rule saved, but {rel} is still visible to Git. A higher-priority .gitignore rule may override it; edit that file and retry."
+ )));
+ }
+ }
+ Ok(changed)
+}
+
+fn pattern(path: &Path, directory: bool) -> IdeResult<String> {
+ let mut rule = String::from("/");
+ for (i, part) in path.components().enumerate() {
+ let Component::Normal(part) = part else { return Err(IdeError::invalid("Unsafe ignore path")) };
+ let part = part.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
+ if part.contains(['\n', '\r', '\0']) {
+ return Err(IdeError::invalid(
+ "Paths containing a newline or NUL cannot be represented safely in an ignore file",
+ ));
+ }
+ if i > 0 {
+ rule.push('/');
+ }
+ for ch in part.chars() {
+ if matches!(ch, '\\' | '*' | '?' | '[' | ']' | '#' | '!' | ' ') {
+ rule.push('\\');
+ }
+ rule.push(ch);
+ }
+ }
+ if rule == "/" {
+ return Err(IdeError::invalid("Cannot ignore a repository root"));
+ }
+ if directory {
+ rule.push('/');
+ }
+ Ok(rule)
+}
+
+/// Refuse symlinked ancestors too: writing through them could affect another repository.
+fn no_symlinks(path: &Path) -> IdeResult<()> {
+ for part in path.ancestors() {
+ match fs::symlink_metadata(part) {
+ Ok(m) if m.file_type().is_symlink() => {
+ return Err(IdeError::invalid(format!("Refusing symlink path: {}", part.display())));
+ }
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(e.into()),
+ }
+ }
+ Ok(())
+}
+
+fn validate_file(file: &Path) -> IdeResult<()> {
+ match fs::symlink_metadata(file) {
+ Ok(m) if !m.is_file() || m.file_type().is_symlink() => {
+ Err(IdeError::invalid("Ignore destination must be a regular file, not a symlink"))
+ }
+ Ok(m) if m.permissions().readonly() => {
+ Err(IdeError::invalid(format!("{} is read-only; make it writable and retry", file.display())))
+ }
+ Ok(_) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e.into()),
+ }
+}
+
+#[derive(PartialEq, Eq)]
+struct Snapshot {
+ bytes: Vec<u8>,
+ modified: Option<std::time::SystemTime>,
+ permissions: fs::Permissions,
+}
+
+fn snapshot(file: &Path) -> IdeResult<Option<Snapshot>> {
+ validate_file(file)?;
+ let mut options = fs::OpenOptions::new();
+ options.read(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.custom_flags(libc::O_NOFOLLOW);
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ // Open the reparse point itself rather than following a last-component link.
+ options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
+ }
+ match options.open(file) {
+ Ok(mut handle) => {
+ let metadata = handle.metadata()?;
+ if !metadata.is_file() || metadata.file_type().is_symlink() {
+ return Err(IdeError::invalid("Ignore destination must be a regular file"));
+ }
+ let mut bytes = Vec::new();
+ handle.read_to_end(&mut bytes)?;
+ Ok(Some(Snapshot { bytes, modified: metadata.modified().ok(), permissions: metadata.permissions() }))
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(e.into()),
+ }
+}
+
+fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
+ no_symlinks(file.parent().unwrap())?;
+ fs::create_dir_all(file.parent().unwrap())?;
+ // Conventional sibling lock: create_new never follows a preexisting symlink.
+ let lock_path = file.with_file_name(format!("{}.lock", file.file_name().unwrap().to_string_lossy()));
+ let lock = fs::OpenOptions::new().write(true).create_new(true).open(&lock_path);
+ // Keep lock cleanup scoped to successfully acquired locks only.
+ let _lock = Lock {
+ file: lock.map_err(|_| {
+ IdeError::invalid(format!("{} is locked or not writable; close other writers and retry", file.display()))
+ })?,
+ path: lock_path,
+ };
+ let before = snapshot(file)?;
+ let bytes = before.as_ref().map(|s| s.bytes.as_slice()).unwrap_or_default();
+ let text =
+ std::str::from_utf8(bytes).map_err(|_| IdeError::invalid("Ignore file is not UTF-8; edit it manually"))?;
+ if text.contains('\0') {
+ return Err(IdeError::invalid("Ignore file contains NUL; edit it manually"));
+ }
+ let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
+ // Identical text earlier in the file may have been overridden by a later
+ // negation. Deduplicate only rules that this file still applies to the path.
+ let mut builder = ignore::gitignore::GitignoreBuilder::new("");
+ for (index, line) in text.lines().enumerate() {
+ let line = if index == 0 { line.trim_start_matches('\u{feff}') } else { line };
+ if let Err(error) = builder.add_line(None, line) {
+ tracing::debug!("{}: {error}", file.display());
+ }
+ }
+ let existing = builder.build().map_err(|e| IdeError::invalid(format!("Cannot parse ignore rules: {e}")))?;
+ let mut requested = HashSet::new();
+ let mut updated = bytes.to_vec();
+ for rule in rules {
+ if !requested.insert(rule.pattern.as_str())
+ || existing.matched_path_or_any_parents(&rule.relative, rule.directory).is_ignore()
+ {
+ continue;
+ }
+ if !updated.is_empty() && !updated.ends_with(b"\n") {
+ updated.extend_from_slice(newline.as_bytes());
+ }
+ updated.extend_from_slice(rule.pattern.as_bytes());
+ updated.extend_from_slice(newline.as_bytes());
+ }
+ if updated == bytes {
+ return Ok(());
+ }
+ let mut temp = tempfile::NamedTempFile::new_in(file.parent().unwrap())?;
+ let permissions = match fs::metadata(file) {
+ Ok(meta) => meta.permissions(),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => _lock.file.metadata()?.permissions(),
+ Err(e) => return Err(e.into()),
+ };
+ temp.as_file().set_permissions(permissions)?;
+ temp.write_all(&updated)?;
+ temp.as_file().sync_all()?;
+ replace_if_unchanged(file, before, temp)
+}
+
+fn replace_if_unchanged(file: &Path, before: Option<Snapshot>, temp: tempfile::NamedTempFile) -> IdeResult<()> {
+ no_symlinks(file.parent().unwrap())?;
+ if snapshot(file)? != before {
+ return Err(IdeError::invalid("Ignore file changed while preparing the update; retry"));
+ }
+ temp.persist(file).map_err(|e| IdeError::from(e.error))?;
+ Ok(())
+}
+
+struct Lock {
+ file: fs::File,
+ path: PathBuf,
+}
+impl Drop for Lock {
+ fn drop(&mut self) {
+ let _ = &self.file;
+ let _ = fs::remove_file(&self.path);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn concurrent_writer_is_detected_without_overwriting_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = dunce::canonicalize(tmp.path()).unwrap();
+ let file = root.join(".gitignore");
+ fs::write(&file, "before\n").unwrap();
+ let before = snapshot(&file).unwrap();
+ let mut temp = tempfile::NamedTempFile::new_in(&root).unwrap();
+ temp.write_all(b"before\n/new\n").unwrap();
+ fs::write(&file, "external writer\n").unwrap();
+ assert!(replace_if_unchanged(&file, before, temp).unwrap_err().message.contains("changed"));
+ assert_eq!(fs::read_to_string(file).unwrap(), "external writer\n");
+ }
+}
diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs
index 246f8d855..ceb0735c9 100644
--- a/crates/ide-vcs/src/lib.rs
+++ b/crates/ide-vcs/src/lib.rs
@@ -441,6 +441,7 @@ pub mod changelists;
mod cli;
mod diff;
mod history;
+mod ignore;
mod manage;
mod ops;
mod patch;
@@ -454,6 +455,7 @@ mod write;
pub use cli::{detected_git_executable, git_version, set_askpass_env, set_git_executable};
pub use diff::build_partial_patch;
+pub use ignore::{IgnoreDestination, add_to_ignore};
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
pub use remotes::Remote;
pub use roots::Repos;
diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs
index 17aeb67a8..0e5ddece8 100644
--- a/crates/ide-vcs/src/repo.rs
+++ b/crates/ide-vcs/src/repo.rs
@@ -50,7 +50,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache), ignored: Default::default() }))
}
-fn absolute(p: &Path) -> IdeResult<PathBuf> {
+pub(crate) fn absolute(p: &Path) -> IdeResult<PathBuf> {
let p = if p.is_absolute() { p.to_path_buf() } else { std::env::current_dir()?.join(p) };
// Lexically clean `.`/`..` without resolving symlinks, keeping the caller's spelling.
let mut out = PathBuf::new();
diff --git a/crates/ide-vcs/tests/ignore.rs b/crates/ide-vcs/tests/ignore.rs
new file mode 100644
index 000000000..1291974f4
--- /dev/null
+++ b/crates/ide-vcs/tests/ignore.rs
@@ -0,0 +1,311 @@
+//! Runtime tests against real temporary repositories and the Git executable.
+use ide_vcs::{IgnoreDestination::*, add_to_ignore};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+fn git(root: &Path, args: &[&str]) -> String {
+ let output = Command::new("git")
+ .current_dir(root)
+ .args(args)
+ .env_remove("GIT_DIR")
+ .env_remove("GIT_WORK_TREE")
+ .env_remove("GIT_INDEX_FILE")
+ .env("GIT_CONFIG_NOSYSTEM", "1")
+ .env("GIT_CONFIG_GLOBAL", if cfg!(windows) { "NUL" } else { "/dev/null" })
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
+ String::from_utf8(output.stdout).unwrap()
+}
+struct Fixture {
+ _tmp: tempfile::TempDir,
+ root: PathBuf,
+}
+impl Fixture {
+ fn new() -> Self {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = dunce::canonicalize(tmp.path()).unwrap().join("repo");
+ std::fs::create_dir(&root).unwrap();
+ git(&root, &["init", "-q"]);
+ git(&root, &["config", "core.excludesFile", if cfg!(windows) { "NUL" } else { "/dev/null" }]);
+ Self { _tmp: tmp, root }
+ }
+ fn file(&self, name: &str) -> PathBuf {
+ let path = self.root.join(name);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, "data\n").unwrap();
+ path
+ }
+ fn ignored(&self, rel: &str) {
+ assert!(!git(&self.root, &["check-ignore", "--", &format!("./{rel}")]).is_empty());
+ assert!(
+ git(&self.root, &["--literal-pathspecs", "status", "--porcelain", "--untracked-files=all", "--", rel])
+ .is_empty()
+ );
+ }
+}
+
+#[test]
+fn shared_literals_multiselect_and_directory_are_anchored() {
+ let fx = Fixture::new();
+ let mut names = vec!["has space", "#hash", "!bang", "[ab].txt", "-dash", "中文.txt"];
+ // Win32 filenames cannot contain wildcard characters or end in a space.
+ if cfg!(unix) {
+ names.extend(["has space ", "[ab]*?.txt", ":(top)literal", ":!literal", ":(glob)*"]);
+ }
+ let mut paths: Vec<_> = names.iter().map(|n| fx.file(n)).collect();
+ fx.file("literal");
+ fx.file("cache/a.txt");
+ fx.file("other/cache/a.txt");
+ paths.push(fx.root.join("cache"));
+ for name in &names {
+ fx.file(&format!("other/{name}"));
+ }
+ add_to_ignore(&paths, Gitignore).unwrap();
+ for name in &names {
+ fx.ignored(name);
+ }
+ fx.ignored("cache/a.txt");
+ let status = git(&fx.root, &["status", "--porcelain", "--untracked-files=all"]);
+ assert!(status.contains("other/cache/a.txt"));
+ assert!(status.contains("other/!bang"));
+ assert!(status.lines().any(|line| line == "?? literal"));
+ let text = std::fs::read_to_string(fx.root.join(".gitignore")).unwrap();
+ assert!(text.contains("/cache/\n"));
+ assert!(text.contains("/\\[ab\\].txt\n"));
+ if cfg!(unix) {
+ assert!(text.contains("/\\[ab\\]\\*\\?.txt\n"));
+ }
+}
+
+#[test]
+fn local_exclude_is_local_preserves_comments_crlf_and_deduplicates() {
+ let fx = Fixture::new();
+ let path = fx.file("private.txt");
+ let exclude = fx.root.join(".git/info/exclude");
+ std::fs::write(&exclude, "# keep this\r\n/other\r\n# no final newline").unwrap();
+ add_to_ignore(&[path.clone(), path.clone()], LocalExclude).unwrap();
+ let once = std::fs::read(&exclude).unwrap();
+ assert_eq!(
+ String::from_utf8(once.clone()).unwrap(),
+ "# keep this\r\n/other\r\n# no final newline\r\n/private.txt\r\n"
+ );
+ add_to_ignore(&[path], LocalExclude).unwrap();
+ assert_eq!(std::fs::read(&exclude).unwrap(), once);
+ fx.ignored("private.txt");
+ assert!(git(&fx.root, &["status", "--porcelain"]).is_empty());
+ assert!(!fx.root.join(".gitignore").exists());
+}
+
+#[test]
+fn nearest_existing_ignore_and_nested_repositories_use_correct_bases() {
+ let fx = Fixture::new();
+ let a = fx.file("pkg/deep/a.txt");
+ std::fs::write(fx.root.join("pkg/.gitignore"), "# nested\n").unwrap();
+ add_to_ignore(&[a], Gitignore).unwrap();
+ fx.ignored("pkg/deep/a.txt");
+ assert_eq!(std::fs::read_to_string(fx.root.join("pkg/.gitignore")).unwrap(), "# nested\n/deep/a.txt\n");
+ assert!(!fx.root.join(".gitignore").exists());
+ let b = fx.file("nested/b.txt");
+ git(&fx.root.join("nested"), &["init", "-q"]);
+ add_to_ignore(&[b], Gitignore).unwrap();
+ assert_eq!(std::fs::read_to_string(fx.root.join("nested/.gitignore")).unwrap(), "/b.txt\n");
+ assert!(!fx.root.join(".gitignore").exists());
+}
+
+#[test]
+fn tracked_files_and_directories_fail_before_any_write() {
+ let fx = Fixture::new();
+ let tracked = fx.file("dir/tracked");
+ let new = fx.file("new");
+ git(&fx.root, &["add", "dir/tracked"]);
+ for path in [tracked, fx.root.join("dir")] {
+ let error = add_to_ignore(&[new.clone(), path], Gitignore).unwrap_err();
+ assert!(error.message.contains("tracked files"));
+ assert!(!fx.root.join(".gitignore").exists());
+ }
+ assert!(git(&fx.root, &["diff", "--cached", "--name-only"]).contains("dir/tracked"));
+}
+
+#[test]
+fn worktree_and_submodule_git_files_resolve_common_exclude() {
+ let fx = Fixture::new();
+ fx.file("initial");
+ git(&fx.root, &["add", "initial"]);
+ git(
+ &fx.root,
+ &[
+ "-c",
+ "user.name=Test",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "-qm",
+ "initial",
+ ],
+ );
+ let worktree = fx.root.parent().unwrap().join("linked");
+ git(&fx.root, &["worktree", "add", "-qb", "linked", worktree.to_str().unwrap()]);
+ let p = worktree.join("private");
+ std::fs::write(&p, "x").unwrap();
+ add_to_ignore(&[p], LocalExclude).unwrap();
+ assert!(std::fs::read_to_string(fx.root.join(".git/info/exclude")).unwrap().contains("/private\n"));
+ assert_eq!(git(&worktree, &["check-ignore", "private"]), "private\n");
+ assert!(git(&worktree, &["status", "--porcelain"]).is_empty());
+ // A real gitfile layout like a submodule, with metadata outside its worktree.
+ let sub = fx.root.join("sub");
+ std::fs::create_dir(&sub).unwrap();
+ let metadata = fx.root.join(".git/modules/sub");
+ std::fs::create_dir_all(metadata.parent().unwrap()).unwrap();
+ git(&sub, &["init", "-q", "--separate-git-dir", metadata.to_str().unwrap()]);
+ std::fs::write(sub.join("tracked"), "x").unwrap();
+ git(&sub, &["add", "tracked"]);
+ git(
+ &sub,
+ &[
+ "-c",
+ "user.name=Test",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "-qm",
+ "submodule initial",
+ ],
+ );
+ let commit = git(&sub, &["rev-parse", "HEAD"]);
+ std::fs::write(
+ fx.root.join(".gitmodules"),
+ "[submodule \"sub\"]\n\tpath = sub\n\turl = https://example.invalid/sub.git\n",
+ )
+ .unwrap();
+ git(&fx.root, &["update-index", "--add", "--cacheinfo", "160000", commit.trim(), "sub"]);
+ assert!(add_to_ignore(std::slice::from_ref(&sub), LocalExclude).unwrap_err().message.contains("tracked files"));
+ std::fs::write(sub.join("private"), "x").unwrap();
+ add_to_ignore(&[sub.join("private")], LocalExclude).unwrap();
+ assert!(std::fs::read_to_string(metadata.join("info/exclude")).unwrap().contains("/private\n"));
+ assert_eq!(git(&sub, &["check-ignore", "private"]), "private\n");
+}
+
+#[test]
+fn lock_failure_invalid_destination_and_traversal_preserve_data() {
+ let fx = Fixture::new();
+ let path = fx.file("new");
+ let file = fx.root.join(".gitignore");
+ std::fs::write(&file, "# original\n").unwrap();
+ std::fs::write(fx.root.join(".gitignore.lock"), "another writer").unwrap();
+ assert!(add_to_ignore(std::slice::from_ref(&path), Gitignore).unwrap_err().message.contains("locked"));
+ assert_eq!(std::fs::read_to_string(&file).unwrap(), "# original\n");
+ assert_eq!(std::fs::read_to_string(fx.root.join(".gitignore.lock")).unwrap(), "another writer");
+ assert!(add_to_ignore(&[fx.root.join("dir/../new")], Gitignore).is_err());
+ std::fs::remove_file(fx.root.join(".gitignore.lock")).unwrap();
+ std::fs::write(&file, b"# invalid\xff").unwrap();
+ assert!(add_to_ignore(&[path], Gitignore).is_err());
+ assert_eq!(std::fs::read(file).unwrap(), b"# invalid\xff");
+ assert!(!fx.root.join(".gitignore.lock").exists());
+}
+
+#[cfg(unix)]
+#[test]
+fn backslash_is_literal_newlines_and_symlinks_are_rejected() {
+ use std::os::unix::fs::symlink;
+ let fx = Fixture::new();
+ let backslash = fx.file("back\\slash");
+ add_to_ignore(&[backslash], Gitignore).unwrap();
+ fx.ignored("back\\slash");
+ let original = std::fs::read(fx.root.join(".gitignore")).unwrap();
+ for name in ["line\nname", "line\rname"] {
+ let path = fx.file(name);
+ assert!(add_to_ignore(&[path], Gitignore).is_err());
+ }
+ let outside = fx.root.parent().unwrap().join("outside");
+ std::fs::write(&outside, "safe").unwrap();
+ std::fs::remove_file(fx.root.join(".gitignore")).unwrap();
+ symlink(&outside, fx.root.join(".gitignore")).unwrap();
+ assert!(add_to_ignore(&[fx.file("new")], Gitignore).is_err());
+ assert_eq!(std::fs::read_to_string(&outside).unwrap(), "safe");
+ std::fs::remove_file(fx.root.join(".gitignore")).unwrap();
+ std::fs::write(fx.root.join(".gitignore"), &original).unwrap();
+ symlink(fx.root.parent().unwrap(), fx.root.join("link")).unwrap();
+ assert!(add_to_ignore(&[fx.root.join("link/outside")], LocalExclude).is_err());
+ assert_eq!(std::fs::read(fx.root.join(".gitignore")).unwrap(), original);
+}
+
+#[test]
+fn overridden_local_rule_is_not_duplicated_and_explains_precedence() {
+ let fx = Fixture::new();
+ let path = fx.file("private");
+ std::fs::write(fx.root.join(".gitignore"), "!/private\n").unwrap();
+ let error = add_to_ignore(std::slice::from_ref(&path), LocalExclude).unwrap_err();
+ assert!(error.message.contains("higher-priority"));
+ let exclude = fx.root.join(".git/info/exclude");
+ let once = std::fs::read(&exclude).unwrap();
+ assert!(add_to_ignore(&[path], LocalExclude).is_err());
+ assert_eq!(std::fs::read(exclude).unwrap(), once);
+}
+
+#[test]
+fn readonly_and_nonfile_destinations_remain_untouched() {
+ let fx = Fixture::new();
+ let path = fx.file("new");
+ let file = fx.root.join(".gitignore");
+ std::fs::create_dir(&file).unwrap();
+ assert!(add_to_ignore(std::slice::from_ref(&path), Gitignore).is_err());
+ std::fs::remove_dir(&file).unwrap();
+ std::fs::write(&file, "# original\n").unwrap();
+ let original = std::fs::metadata(&file).unwrap().permissions();
+ let mut permissions = original.clone();
+ permissions.set_readonly(true);
+ std::fs::set_permissions(&file, permissions).unwrap();
+ let result = add_to_ignore(&[path], Gitignore);
+ std::fs::set_permissions(&file, original).unwrap();
+ assert!(result.unwrap_err().message.contains("read-only"));
+ assert_eq!(std::fs::read_to_string(file).unwrap(), "# original\n");
+}
+
+#[test]
+fn existing_bytes_are_preserved_for_newline_and_bom_variants() {
+ for original in [b"# comment".as_slice(), b"unrelated\\", b"\xef\xbb\xbf# BOM\r\n", b"# LF\n", b""] {
+ let fx = Fixture::new();
+ let path = fx.file("new");
+ let file = fx.root.join(".gitignore");
+ std::fs::write(&file, original).unwrap();
+ add_to_ignore(&[path], Gitignore).unwrap();
+ assert!(std::fs::read(file).unwrap().starts_with(original));
+ fx.ignored("new");
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn non_utf8_paths_are_rejected_without_creating_ignore_files() {
+ use std::os::unix::ffi::OsStringExt;
+ let fx = Fixture::new();
+ let path = fx.root.join(std::ffi::OsString::from_vec(b"invalid\xff".to_vec()));
+ // APFS rejects creation of this filename; the request must fail clearly before I/O.
+ assert!(add_to_ignore(&[path], Gitignore).unwrap_err().message.contains("UTF-8"));
+ assert!(!fx.root.join(".gitignore").exists());
+}
+
+#[test]
+fn later_negations_allow_reignoring_shared_and_local_paths_without_batch_duplicates() {
+ for destination in [Gitignore, LocalExclude] {
+ let fx = Fixture::new();
+ let path = fx.file("private");
+ let file = match destination {
+ Gitignore => fx.root.join(".gitignore"),
+ LocalExclude => fx.root.join(".git/info/exclude"),
+ };
+ std::fs::write(&file, "/private\n!/private\n").unwrap();
+ assert!(git(&fx.root, &["status", "--porcelain", "--untracked-files=all"]).contains("private"));
+ add_to_ignore(&[path.clone(), path.clone()], destination).unwrap();
+ assert_eq!(std::fs::read_to_string(&file).unwrap(), "/private\n!/private\n/private\n");
+ fx.ignored("private");
+ let once = std::fs::read(&file).unwrap();
+ add_to_ignore(&[path], destination).unwrap();
+ assert_eq!(std::fs::read(file).unwrap(), once);
+ }
+}
diff --git a/crates/ide-vfs/Cargo.toml b/crates/ide-vfs/Cargo.toml
index bec96e84a..d99de38fa 100644
--- a/crates/ide-vfs/Cargo.toml
+++ b/crates/ide-vfs/Cargo.toml
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
dunce.workspace = true
+gix = { workspace = true, features = ["sha1"] }
ide-core.workspace = true
serde.workspace = true
specta.workspace = true
diff --git a/crates/ide-vfs/src/rules.rs b/crates/ide-vfs/src/rules.rs
index bee7aaf97..b118b15bf 100644
--- a/crates/ide-vfs/src/rules.rs
+++ b/crates/ide-vfs/src/rules.rs
@@ -80,20 +80,24 @@ pub(crate) struct GitignoreStack {
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
repo_level: RwLock<Vec<Gitignore>>,
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
+ nested: Mutex<HashMap<PathBuf, Option<Arc<GitignoreStack>>>>,
}
impl GitignoreStack {
pub fn new(near: &Path) -> Self {
let repo_root = find_repo_root(near);
let repo_level = RwLock::new(Self::load_repo_level(repo_root.as_deref()));
- Self { repo_root, repo_level, cache: Mutex::default() }
+ Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
}
fn load_repo_level(repo_root: Option<&Path>) -> Vec<Gitignore> {
let mut repo_level = Vec::new();
if let Some(root) = repo_root {
let mut builder = GitignoreBuilder::new(root);
- let exclude = root.join(".git").join("info").join("exclude");
+ let exclude = gix::discover(root)
+ .ok()
+ .map(|r| r.common_dir().join("info/exclude"))
+ .unwrap_or_else(|| root.join(".git/info/exclude"));
if exclude.is_file() {
builder.add(exclude);
}
@@ -115,11 +119,13 @@ impl GitignoreStack {
/// Re-reads `.git/info/exclude` and the global excludes file.
pub fn reload_repo_level(&self) {
+ self.nested.lock().clear();
*self.repo_level.write() = Self::load_repo_level(self.repo_root.as_deref());
}
/// Forgets the cached rules of `dir` and every directory below it.
pub fn invalidate_tree(&self, dir: &Path) {
+ self.nested.lock().clear();
let mut cache = self.cache.lock();
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
@@ -133,6 +139,7 @@ impl GitignoreStack {
/// Forgets the cached rules of `dir` (after its `.gitignore` changed).
pub fn invalidate(&self, dir: &Path) {
+ self.nested.lock().clear();
self.cache.lock().remove(dir);
}
@@ -169,6 +176,23 @@ impl GitignoreStack {
/// Whether `path` (absolute) is ignored. `is_dir` refers to `path` itself.
pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
+ // A project's watcher can span independent nested repositories. Their local
+ // excludes and ignore ancestry must stop at their own repository boundary.
+ if let Some(parent) = path.parent() {
+ let nested = self
+ .nested
+ .lock()
+ .entry(parent.to_path_buf())
+ .or_insert_with(|| {
+ find_repo_root(parent)
+ .filter(|root| self.repo_root.as_ref() != Some(root))
+ .map(|_| Arc::new(Self::new(parent)))
+ })
+ .clone();
+ if let Some(nested) = nested {
+ return nested.is_ignored(path, is_dir);
+ }
+ }
if self.repo_root.as_deref() == Some(path) {
return false;
}
diff --git a/crates/ide-vfs/src/watch.rs b/crates/ide-vfs/src/watch.rs
index f009ead3a..909703274 100644
--- a/crates/ide-vfs/src/watch.rs
+++ b/crates/ide-vfs/src/watch.rs
@@ -50,6 +50,7 @@ type OnChange = Box<dyn Fn(&FsBatch) + Send + Sync>;
pub struct Watcher {
inner: Inner,
excludes: SharedExcludes,
+ rules: Arc<GitignoreStack>,
}
type SharedExcludes = Arc<RwLock<ExcludeMatcher>>;
@@ -74,6 +75,7 @@ impl Watcher {
let root = dunce::canonicalize(root)?;
let filter = EventFilter::new(root.clone(), &excludes);
let shared = filter.excludes.clone();
+ let rules = filter.gitignore.clone();
let emit = move |batch: &FsBatch| {
sink.emit(IdeEvent::FsChanged {
created: batch.created.iter().map(Into::into).collect(),
@@ -87,7 +89,7 @@ impl Watcher {
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
}?;
- Ok(Self { inner, excludes: shared })
+ Ok(Self { inner, excludes: shared, rules })
}
/// Replaces the exclude globs (Settings › Project Structure / File Types
@@ -97,6 +99,12 @@ impl Watcher {
*self.excludes.write() = ExcludeMatcher::new(excludes);
}
+ /// Explicit refresh for writes to Git common metadata outside the watched root.
+ pub fn reload_ignore_rules(&self) {
+ self.rules.reload_repo_level();
+ self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(Path::new("/")));
+ }
+
/// Number of OS-level watches (1 in recursive and flat mode).
pub fn watch_count(&self) -> usize {
match &self.inner {
@@ -374,13 +382,13 @@ fn merge(prev: Option<Change>, next: Change) -> Change {
pub(crate) struct EventFilter {
root: PathBuf,
excludes: SharedExcludes,
- gitignore: GitignoreStack,
+ gitignore: Arc<GitignoreStack>,
}
impl EventFilter {
pub fn new(root: PathBuf, excludes: &[String]) -> Self {
Self {
- gitignore: GitignoreStack::new(&root),
+ gitignore: Arc::new(GitignoreStack::new(&root)),
excludes: Arc::new(RwLock::new(ExcludeMatcher::new(excludes))),
root,
}
diff --git a/crates/ide-vfs/tests/vfs.rs b/crates/ide-vfs/tests/vfs.rs
index 80e66c71a..efb4199af 100644
--- a/crates/ide-vfs/tests/vfs.rs
+++ b/crates/ide-vfs/tests/vfs.rs
@@ -321,3 +321,47 @@ fn watcher_reports_changes() {
std::thread::sleep(Duration::from_millis(500));
assert_eq!(batches.lock().len(), n, "no events after drop");
}
+
+#[test]
+fn worktree_and_nested_repository_local_excludes_are_reflected_in_listings() {
+ fn git(root: &std::path::Path, args: &[&str]) {
+ let out = std::process::Command::new("git").current_dir(root).args(args).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let root = dunce::canonicalize(tmp.path()).unwrap().join("repo");
+ std::fs::create_dir(&root).unwrap();
+ git(&root, &["init", "-q"]);
+ std::fs::write(root.join("initial"), "x").unwrap();
+ git(&root, &["add", "initial"]);
+ git(
+ &root,
+ &[
+ "-c",
+ "user.name=Test",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "-qm",
+ "initial",
+ ],
+ );
+ let linked = root.parent().unwrap().join("linked");
+ git(&root, &["worktree", "add", "-qb", "linked", linked.to_str().unwrap()]);
+ std::fs::write(linked.join("private"), "x").unwrap();
+ std::fs::write(root.join(".git/info/exclude"), "/private\n").unwrap();
+ let entries = ide_vfs::read_dir(&linked, &[]).unwrap();
+ assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
+ assert!(!entries.iter().find(|e| e.name == "private").unwrap().excluded);
+ let nested = linked.join("nested");
+ std::fs::create_dir(&nested).unwrap();
+ git(&nested, &["init", "-q"]);
+ std::fs::write(nested.join("private"), "x").unwrap();
+ let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
+ assert!(!entries.iter().find(|e| e.name == "private").unwrap().ignored);
+ std::fs::write(nested.join(".git/info/exclude"), "/private\n").unwrap();
+ let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
+ assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
+}
diff --git a/e2e/gitIgnore.spec.ts b/e2e/gitIgnore.spec.ts
new file mode 100644
index 000000000..c6423aa58
--- /dev/null
+++ b/e2e/gitIgnore.spec.ts
@@ -0,0 +1,113 @@
+/** Linux browser acceptance: synthetic MemoryFs + mocked native IPC, real menu/action/refresh UI. */
+import { expect, test } from "./fixtures";
+
+for (const destination of ["gitignore", "localExclude"] as const) {
+ test(`ignore ${destination}: menu dispatch and immediate tree/status refresh`, async ({ workbench: page }) => {
+ await page.evaluate(async (destination) => {
+ const fsModule = "/src/features/project-tree/fs.ts";
+ const storeModule = "/src/features/project-tree/store.ts";
+ const ipcModule = "/src/platform/ipc.ts";
+ const { projectFs } = await import(fsModule);
+ const { reloadAll } = await import(storeModule);
+ const { commands } = await import(ipcModule);
+ const root = "/dev/acme-api";
+ const path = `${root}/scratch.log`;
+ const fs = projectFs(root);
+ await fs.createFile(path);
+ let written = false;
+ commands.vcsAddToIgnore = async (paths: string[], actual: string) => {
+ if (actual !== destination || paths.length !== 1 || paths[0] !== path)
+ throw new Error("Wrong ignore destination or paths");
+ written = true;
+ fs.ignored.add(path);
+ return { status: "ok", data: null };
+ };
+ commands.vcsStatus = async () => {
+ document.body.dataset.ignoreStatusRefresh = written ? "after-write" : "before-write";
+ return {
+ status: "ok",
+ data: written
+ ? []
+ : [{ path, relPath: "scratch.log", staged: null, unstaged: "untracked", renamedFrom: null }],
+ };
+ };
+ commands.vcsRoots = async () => ({
+ status: "ok",
+ data: [{ root, operation: null, head: "main", headCommit: null }],
+ });
+ commands.vcsBranchInfo = async () => ({
+ status: "ok",
+ data: { head: "main", headCommit: null, upstream: null, ahead: 0, behind: 0, operation: null },
+ });
+ const vcsModule = "/src/features/vcs/store.ts";
+ const { useVcs } = await import(vcsModule);
+ useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
+ await reloadAll();
+ const banner = document.createElement("div");
+ banner.textContent = "LINUX BROWSER E2E · SYNTHETIC FIXTURE · NATIVE IPC MOCKED";
+ Object.assign(banner.style, {
+ position: "fixed",
+ bottom: "28px",
+ right: "18px",
+ zIndex: "999999",
+ padding: "10px 14px",
+ background: "#fff4ce",
+ color: "#362a00",
+ font: "bold 12px sans-serif",
+ border: "1px solid #9e8500",
+ borderRadius: "5px",
+ });
+ document.body.append(banner);
+ }, destination);
+ await page.getByRole("treeitem", { name: "scratch.log", exact: true }).click({ button: "right" });
+ await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
+ await page.getByRole("menuitem", { name: "Add to .gitignore", exact: true }).hover();
+ await expect(page.getByRole("menuitem", { name: ".gitignore", exact: true })).toBeVisible();
+ await expect(page.getByRole("menuitem", { name: ".git/info/exclude", exact: true })).toBeVisible();
+ const captureDir = process.env.OPENIDEA_ACCEPTANCE_DIR;
+ if (captureDir && destination === "gitignore")
+ await page.screenshot({ path: `${captureDir}/01-ignore-destinations.png` });
+ await page
+ .getByRole("menuitem", { name: destination === "gitignore" ? ".gitignore" : ".git/info/exclude", exact: true })
+ .click();
+ await expect
+ .poll(async () =>
+ page.evaluate(async () => {
+ const module = "/src/features/project-tree/store.ts";
+ const { useProjectTree } = await import(module);
+ return useProjectTree
+ .getState()
+ .listings.get("/dev/acme-api")
+ ?.find((entry: { name: string }) => entry.name === "scratch.log")?.ignored;
+ }),
+ )
+ .toBe(true);
+ await expect
+ .poll(async () =>
+ page.evaluate(async () => {
+ const module = "/src/features/vcs/store.ts";
+ const { useVcs } = await import(module);
+ return useVcs.getState().status.length;
+ }),
+ )
+ .toBe(0);
+ await expect(page.locator("body")).toHaveAttribute("data-ignore-status-refresh", "after-write");
+ // Display fixture rule text in the actual editor. This is browser memory, not a native disk read.
+ await page.evaluate(async (destination) => {
+ const module = "/src/workbench/contributions.ts";
+ const { editorService } = await import(module);
+ await editorService().openFile(
+ `/dev/acme-api/${destination === "gitignore" ? ".gitignore" : ".git/info/exclude"}`,
+ { focus: true },
+ );
+ }, destination);
+ const content = page.locator(".cm-editor .cm-content").first();
+ await content.fill(
+ `# Synthetic acceptance fixture: ${destination === "gitignore" ? "shared repository rules" : ".git/info/exclude: local rules (common to linked worktrees)"}\n/scratch.log\n`,
+ );
+ if (captureDir)
+ await page.screenshot({
+ path: `${captureDir}/${destination === "gitignore" ? "02-shared-ignore-effect" : "03-local-exclude-effect"}.png`,
+ });
+ });
+}
diff --git a/e2e/projectTree.spec.ts b/e2e/projectTree.spec.ts
index 22745955f..55f89f007 100644
--- a/e2e/projectTree.spec.ts
+++ b/e2e/projectTree.spec.ts
@@ -35,3 +35,16 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await page.keyboard.type("READ");
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
+
+test("Git ignore submenu offers shared and local destinations for files and folders", async ({ workbench: page }) => {
+ for (const name of ["README.md", "src"]) {
+ await page.getByRole("treeitem", { name, exact: true }).click({ button: "right" });
+ await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
+ await page.getByRole("menuitem", { name: "Add to .gitignore", exact: true }).hover();
+ await expect(page.getByRole("menuitem", { name: ".gitignore", exact: true })).toBeVisible();
+ await expect(page.getByRole("menuitem", { name: ".git/info/exclude", exact: true })).toBeVisible();
+ await page.keyboard.press("Escape");
+ await page.keyboard.press("Escape");
+ await page.keyboard.press("Escape");
+ }
+});
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index f130d3873..d743891f6 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -201,6 +201,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_branches,
vcs::vcs_stashes,
vcs::vcs_stage,
+ vcs::vcs_add_to_ignore,
vcs::vcs_unstage,
vcs::vcs_stage_patch,
vcs::vcs_discard,
diff --git a/src-tauri/src/commands/vcs.rs b/src-tauri/src/commands/vcs.rs
index eeeda3ea0..d8a6084cd 100644
--- a/src-tauri/src/commands/vcs.rs
+++ b/src-tauri/src/commands/vcs.rs
@@ -108,6 +108,17 @@ pub async fn vcs_stage(window: Window, state: State<'_, AppState>, paths: Vec<Pa
ide_host::ops::vcs::vcs_stage(&state.host, window.label(), paths).await
}
+#[tauri::command]
+#[specta::specta]
+pub async fn vcs_add_to_ignore(
+ window: Window,
+ state: State<'_, AppState>,
+ paths: Vec<PathBuf>,
+ destination: IgnoreDestination,
+) -> IdeResult<()> {
+ ide_host::ops::vcs::vcs_add_to_ignore(&state.host, window.label(), paths, destination).await
+}
+
#[tauri::command]
#[specta::specta]
pub async fn vcs_unstage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
diff --git a/src/bindings.ts b/src/bindings.ts
index f1994cd64..c0df5986c 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -404,6 +404,7 @@ export const commands = {
vcsBranches: (repo: string | null) => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches", { repo })),
vcsStashes: (repo: string | null) => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes", { repo })),
vcsStage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage", { paths })),
+ vcsAddToIgnore: (paths: string[], destination: IgnoreDestination) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_add_to_ignore", { paths, destination })),
vcsUnstage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_unstage", { paths })),
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
@@ -3338,6 +3339,8 @@ export type IdentifierOccurrence = {
qualified: boolean,
};
+export type IgnoreDestination = "gitignore" | "localExclude";
+
export type IndentConfig = IndentConfig_Serialize | IndentConfig_Deserialize;
export type IndentConfig_Deserialize = {
diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts
index fcb76d43e..6fe42131a 100644
--- a/src/features/project-tree/contextMenu.test.ts
+++ b/src/features/project-tree/contextMenu.test.ts
@@ -111,6 +111,24 @@ describe("project view context menu", () => {
expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]);
});
+ it("offers both ignore destinations for files, directories and multi-selection, separately from IDE exclusion", () => {
+ const dispose = registerActions(
+ ["vcs.ignoreShared", "vcs.ignoreLocal"].map((id) => ({ id, title: id, run: () => undefined })),
+ );
+ try {
+ for (const nodes of [[node("/p/a")], [node("/p/dir", true)], [node("/p/a"), node("/p/dir", true)]]) {
+ const git = resolveMenuItems(contextMenuItems(nodes)).find((item) => item.label === "Git")!;
+ expect(sub(git.submenu!, "Add to .gitignore")).toEqual([".gitignore", ".git/info/exclude"]);
+ }
+ const root = resolveMenuItems(contextMenuItems([node("/p", true, true)])).find((item) => item.label === "Git")!;
+ expect(labels(root.submenu!)).not.toContain("Add to .gitignore");
+ const folder = contextMenuItems([node("/p/dir", true)]);
+ expect(sub(folder, "Mark Directory as")).toContain("Excluded");
+ } finally {
+ dispose();
+ }
+ });
+
it("shows Mark Directory as for folders, without file-only items", () => {
const l = labels(contextMenuItems([node(`${ROOT}/src`, true)]));
expect(l).toContain("Mark Directory as");
diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts
index 635e417b9..11d660a18 100644
--- a/src/features/project-tree/contextMenu.ts
+++ b/src/features/project-tree/contextMenu.ts
@@ -321,6 +321,13 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
[
act("vcs.commit", undefined, dirs || nodes.length > 1 ? "Commit…" : "Commit File…"),
act("vcs.addToVcs", arg, "Add"),
+ nonRoot.length === nodes.length &&
+ nodes.length > 0 &&
+ nodes.every((n) => !n.placeholder) &&
+ submenu("gitIgnore", "Add to .gitignore", [
+ act("vcs.ignoreShared", arg, ".gitignore"),
+ act("vcs.ignoreLocal", arg, ".git/info/exclude"),
+ ]),
{ kind: "separator" },
singleFile && act("vcs.annotate", singleFile.path, "Annotate with Git Blame"),
act("vcs.showDiff", arg, "Show Diff"),
diff --git a/src/features/vcs/__tests__/ignore.test.ts b/src/features/vcs/__tests__/ignore.test.ts
new file mode 100644
index 000000000..2b075ab84
--- /dev/null
+++ b/src/features/vcs/__tests__/ignore.test.ts
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({
+ write: vi.fn(),
+ reload: vi.fn(),
+ refresh: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock("@/platform/ipc", () => ({
+ commands: { vcsAddToIgnore: mocks.write },
+ call: async (result: Promise<unknown>) => result,
+}));
+vi.mock("@/features/project-tree/store", () => ({ reloadAll: mocks.reload }));
+vi.mock("../store", () => ({ refreshNow: mocks.refresh }));
+vi.mock("../ops", () => ({
+ runOp: async (_title: string, run: () => Promise<unknown>) => {
+ try {
+ return await run();
+ } catch (error) {
+ mocks.failure(error);
+ return undefined;
+ }
+ },
+}));
+import { addToIgnore } from "../ignore";
+
+describe("ignore action", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.write.mockResolvedValue(null);
+ });
+ it.each(["gitignore", "localExclude"] as const)(
+ "routes all paths to %s then refreshes status and tree",
+ async (destination) => {
+ await addToIgnore(["/p/file", "/p/directory"], destination);
+ expect(mocks.write).toHaveBeenCalledWith(["/p/file", "/p/directory"], destination);
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ expect(mocks.reload).toHaveBeenCalledOnce();
+ },
+ );
+ it("refreshes after a failed or partially completed multi-repository write", async () => {
+ mocks.write.mockRejectedValue(new Error("locked; retry"));
+ await addToIgnore(["/p/file"], "gitignore");
+ expect(mocks.failure).toHaveBeenCalledOnce();
+ expect(mocks.refresh).toHaveBeenCalledOnce();
+ expect(mocks.reload).toHaveBeenCalledOnce();
+ });
+ it("ignores an empty selection", async () => {
+ await addToIgnore([], "gitignore");
+ expect(mocks.write).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx
index 457562d3e..8b5107e16 100644
--- a/src/features/vcs/actions.tsx
+++ b/src/features/vcs/actions.tsx
@@ -41,6 +41,8 @@ import {
import { refreshNow, repoName } from "./store";
import { tx } from "@/platform/i18n";
+import { addToIgnore } from "./ignore";
+
const VCS = "vcsAvailable";
const IN_COMMIT_WINDOW = "vcsAvailable && activeToolWindow == commit";
@@ -456,6 +458,14 @@ export function registerVcsActions(): () => void {
void revealCommit(id, commit ? commitRepo(commit) : undefined);
},
},
+ ...(["gitignore", "localExclude"] as const).map((destination): Action => ({
+ id: destination === "gitignore" ? "vcs.ignoreShared" : "vcs.ignoreLocal",
+ title: destination === "gitignore" ? "Add to .gitignore" : "Add to .git/info/exclude",
+ category: "Git",
+ when: VCS,
+ keywords: ["ignore", "unversioned", "exclude"],
+ run: ({ arg }) => addToIgnore(contextPaths(arg), destination),
+ })),
{
id: "vcs.addToVcs",
title: "Add to VCS",
diff --git a/src/features/vcs/ignore.ts b/src/features/vcs/ignore.ts
new file mode 100644
index 000000000..7a86ce52e
--- /dev/null
+++ b/src/features/vcs/ignore.ts
@@ -0,0 +1,19 @@
+/** Project-host ignore writes; shared by the project menu and Find Action. */
+import type { IgnoreDestination } from "@/bindings";
+import { call, commands } from "@/platform/ipc";
+import { reloadAll } from "@/features/project-tree/store";
+import { runOp } from "./ops";
+import { refreshNow } from "./store";
+
+export async function addToIgnore(paths: string[], destination: IgnoreDestination) {
+ if (!paths.length) return;
+ await runOp(
+ destination === "gitignore" ? "Add to .gitignore" : "Add to .git/info/exclude",
+ async () => {
+ await call(commands.vcsAddToIgnore(paths, destination));
+ },
+ { refresh: false },
+ );
+ // Also refresh after a partial failure in a multi-repository selection.
+ await Promise.all([refreshNow(), reloadAll()]);
+}
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index 2aae3fffd..fba57530b 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -4734,5 +4734,7 @@
"Add New Interpreter…": "添加新的解释器…",
"Interpreter Settings…": "解释器设置…",
"Cannot select Python interpreter": "无法选择 Python 解释器",
- "Python Interpreter: {label}": "Python 解释器:{label}"
+ "Python Interpreter: {label}": "Python 解释器:{label}",
+ "Add to .gitignore": "添加到 .gitignore",
+ "Add to .git/info/exclude": "添加到 .git/info/exclude"
}
diff --git a/src/platform/remote.test.ts b/src/platform/remote.test.ts
index dc3da0bc0..e87ce8573 100644
--- a/src/platform/remote.test.ts
+++ b/src/platform/remote.test.ts
@@ -18,7 +18,10 @@ describe("remote invoke", () => {
});
it("routes served commands, keeps opening / closing local and sets global settings on both sides", () => {
- const served = new Set(["fs_read_dir", "open_project", "close_project", "settings_set"]);
+ const served = new Set(["vcs_add_to_ignore", "fs_read_dir", "open_project", "close_project", "settings_set"]);
+ expect(remoteRouting("vcs_add_to_ignore", { paths: ["/remote/file"], destination: "localExclude" }, served)).toBe(
+ "remote",
+ );
expect(remoteRouting("fs_read_dir", { path: "/a" }, served)).toBe("remote");
expect(remoteRouting("window_open_settings", {}, served)).toBe("local");
expect(remoteRouting("open_project", { path: "/a" }, served)).toBe("local");