Файли
openidea/crates/ide-host/tests/vcs_documents.rs
T
Isaac Gallartтаigallart 091dd85ef0 fix(vcs): use symlink target history in the editor (#7891)
The repository scan skips symlinks, so a file opened through a file symlink or a symlinked directory whose target lies outside the registered Git roots had no Git Blame or change markers, even when Git tracked the target. Read-only editor commands (blame, line hunks) now use the target's repository, discovered with the restricted read policy and never registered for status or Commit; excluded mappings and a disabled Git integration are honoured. The editor probes once per open file whether the link has committed history: only then do Annotate and the markers apply, and ordinary files in projects without Git make no further backend calls on edits.

Co-authored-by: igallart <[email protected]>
2026-12-04 18:57:51 +08:00

360 рядки
16 KiB
Rust

mod common;
use ide_core::{ChangeSet, TextChange};
use ide_host::{Host, Project, ops::vcs};
use std::{path::Path, process::Command, sync::Arc, time::Duration};
const ORIGINAL: &str = "SELECT *\nFROM patients\n\tLIMIT 10 OFFSET 0";
const OTHER: &str = "SELECT id\nFROM patients\n\tLIMIT 20 OFFSET 0";
fn git(root: &Path, args: &[&str]) -> String {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap()
}
struct Fixture {
host: Host,
project: Arc<Project>,
path: std::path::PathBuf,
doc: ide_core::DocId,
_temp: tempfile::TempDir,
}
impl Fixture {
async fn new() -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
// The command must synchronize documents even when watcher delivery is excluded.
let path = root.join("node_modules/query.sql");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
git(&root, &["config", "core.autocrlf", "false"]);
std::fs::write(&path, ORIGINAL).unwrap();
git(&root, &["add", "-f", "node_modules/query.sql"]);
git(&root, &["commit", "-m", "original"]);
git(&root, &["switch", "-c", "other"]);
std::fs::write(&path, OTHER).unwrap();
git(&root, &["commit", "-am", "other"]);
git(&root, &["switch", "main"]);
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let doc = project.documents.open(&path).unwrap().id;
Self { host, project, path, doc, _temp: temp }
}
fn saved_edit(&self, text: &str) {
self.project.documents.replace_all(self.doc, text).unwrap();
self.project.documents.save(self.doc).unwrap();
}
fn assert_clean(&self, text: &str) {
let snapshot = self.project.documents.snapshot(self.doc).unwrap();
assert_eq!(snapshot.text, text);
assert!(!snapshot.dirty);
self.project.documents.save_all().unwrap();
assert_eq!(std::fs::read_to_string(&self.path).unwrap(), text);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
self.host.close_project("main");
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn linked_editor_files_use_target_history_and_unsaved_text() {
use ide_workspace::settings::SettingsScope;
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let target = base.join("target");
let root = base.join("workspace");
std::fs::create_dir(&target).unwrap();
std::fs::create_dir(&root).unwrap();
let target_file = target.join("notes.txt");
let original = "first\nsecond\n";
std::fs::write(&target_file, original).unwrap();
git(&target, &["init", "-b", "main"]);
git(&target, &["add", "notes.txt"]);
git(
&target,
&[
"-c",
"user.name=Target",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"Add notes",
],
);
symlink("../target", root.join("linked")).unwrap();
let directory_link_file = root.join("linked/notes.txt");
let file_link = root.join("notes.txt");
symlink("../target/notes.txt", &file_link).unwrap();
let new_file = target.join("new.txt");
std::fs::write(&new_file, "not committed\n").unwrap();
git(&target, &["add", "new.txt"]);
symlink("../target/new.txt", root.join("new.txt")).unwrap();
std::fs::write(root.join("plain.txt"), "not a link\n").unwrap();
let host = Host::new(common::host_config(&base));
let project = host.open_project("main", &root).unwrap();
for path in [root.join("plain.txt"), root.join("new.txt"), new_file] {
assert!(!vcs::vcs_linked_file_has_history(&host, "main", path).await.unwrap());
}
for path in [&directory_link_file, &file_link] {
assert!(vcs::vcs_linked_file_has_history(&host, "main", path.clone()).await.unwrap());
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
assert_eq!(blame.len(), 2);
assert!(blame.iter().all(|line| line.author == "Target"));
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
let doc = project.documents.open(path).unwrap().id;
project.documents.replace_all(doc, "first\nupdated\n").unwrap();
let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
assert_eq!(hunks.len(), 1);
assert_eq!((hunks[0].start, hunks[0].lines, hunks[0].old_text.as_str()), (1, 1, "second\n"));
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
assert_eq!(blame[0].author, "Target");
assert!(blame[1].commit.chars().all(|character| character == '0'));
assert!(vcs::vcs_staging_line_hunks(&host, "main", path.clone(), None).await.unwrap().is_none());
project.documents.close(doc);
}
assert_eq!(std::fs::read_to_string(&target_file).unwrap(), original);
assert!(project.repos().is_empty());
assert!(vcs::vcs_line_hunks(&host, "main", target_file).await.is_err());
// The workspace's Git history can contain the link itself, but the editor reads its target.
git(&root, &["init", "-b", "main"]);
git(&root, &["add", "linked", "notes.txt"]);
git(
&root,
&[
"-c",
"user.name=Workspace",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"Add links",
],
);
project.refresh_repositories();
assert_eq!(project.repos().roots(), vec![root.clone()]);
let blame = vcs::vcs_blame(&host, "main", file_link.clone(), None, None).await.unwrap();
assert_eq!(blame[0].author, "Target");
assert!(vcs::vcs_staging_line_hunks(&host, "main", file_link, None).await.unwrap().is_none());
for excluded in ["linked".to_owned(), target.to_string_lossy().into_owned()] {
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([excluded])).unwrap();
assert!(vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.is_err());
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
assert!(vcs::vcs_blame(&host, "main", directory_link_file.clone(), None, None).await.is_err());
}
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([])).unwrap();
project.settings.set(SettingsScope::Project, "vcs.git.enabled", serde_json::json!(false)).unwrap();
assert!(!vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.unwrap());
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
assert!(vcs::vcs_blame(&host, "main", directory_link_file, None, None).await.is_err());
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn checkout_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None, None).await.unwrap();
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn rollback_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
f.saved_edit(&format!("{ORIGINAL}\n"));
vcs::vcs_discard(&f.host, "main", vec![f.path.clone()]).await.unwrap();
f.assert_clean(ORIGINAL);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stash_and_unstash_reload_clean_open_documents_before_returning() {
let f = Fixture::new().await;
let edited = format!("{ORIGINAL}\n");
f.saved_edit(&edited);
vcs::vcs_stash_push(&f.host, "main", None, None, false, false, None).await.unwrap();
f.assert_clean(ORIGINAL);
let selected = vcs::vcs_stashes(&f.host, "main", None).await.unwrap().remove(0);
vcs::vcs_stash_apply(&f.host, "main", None, selected, true, false, None).await.unwrap();
f.assert_clean(&edited);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn applying_patch_reloads_clean_open_documents_before_returning() {
let f = Fixture::new().await;
std::fs::write(&f.path, OTHER).unwrap();
let patch = git(&f.project.root, &["diff"]);
git(&f.project.root, &["restore", "."]);
vcs::vcs_apply_patch(&f.host, "main", None, patch, None).await.unwrap();
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn writing_patch_file_reloads_its_clean_open_document() {
let f = Fixture::new().await;
vcs::vcs_write_patch(&f.host, "main", f.path.clone(), OTHER.into(), None).await.unwrap();
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn patch_file_encoding_round_trips_without_normalizing_hunks() {
let f = Fixture::new().await;
let path = f.project.root.join("export.patch");
let patch =
"diff --git a/notes.txt b/notes.txt\n--- a/notes.txt\n+++ b/notes.txt\n@@ -1 +1 @@\n-Café\r\n+Voilà\r\n";
vcs::vcs_write_patch(&f.host, "main", path.clone(), patch.into(), Some("utf-16le".into())).await.unwrap();
assert!(std::fs::read(&path).unwrap().starts_with(&[0xff, 0xfe]));
assert_eq!(vcs::vcs_read_patch(&f.host, "main", path.clone()).await.unwrap(), patch);
vcs::vcs_write_patch(&f.host, "main", path.clone(), patch.into(), Some("windows-1252".into())).await.unwrap();
let encoded = std::fs::read(&path).unwrap();
assert!(encoded.windows(5).any(|bytes| bytes == b"Caf\xe9\r"));
assert!(
vcs::vcs_write_patch(&f.host, "main", path.clone(), "你好".into(), Some("windows-1252".into())).await.is_err()
);
assert_eq!(std::fs::read(&path).unwrap(), encoded);
std::fs::write(&path, patch).unwrap();
assert_eq!(vcs::vcs_read_patch(&f.host, "main", path).await.unwrap(), patch);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn directory_compare_overwrite_reloads_clean_open_documents() {
let f = Fixture::new().await;
let base = f.project.root.parent().unwrap();
let source = base.join("source");
let destination = base.join("destination");
std::fs::create_dir_all(&source).unwrap();
std::fs::create_dir_all(&destination).unwrap();
std::fs::write(source.join("query.sql"), OTHER).unwrap();
let path = destination.join("query.sql");
std::fs::write(&path, ORIGINAL).unwrap();
let doc = f.project.documents.open(&path).unwrap();
ide_host::ops::fs::fs_copy_merge(&f.host, "main", source, destination, "query.sql".into(), true).await.unwrap();
let snapshot = f.project.documents.snapshot(doc.id).unwrap();
assert_eq!(snapshot.text, OTHER);
assert!(!snapshot.dirty);
f.project.documents.save_all().unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_working_tree_operation_synchronizes_partial_disk_changes() {
let f = Fixture::new().await;
let result: ide_core::IdeResult<()> = f.project.with_repo_recorded(None, Some("Git merge"), |_| {
std::fs::write(&f.path, OTHER).unwrap();
Err(ide_core::IdeError::invalid("merge stopped with conflicts"))
});
assert!(result.is_err());
f.assert_clean(OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn working_tree_operation_reloads_same_size_same_timestamp_changes() {
let f = Fixture::new().await;
let modified = std::fs::metadata(&f.path).unwrap().modified().unwrap();
let replacement = ORIGINAL.replace("LIMIT 10", "LIMIT 20");
f.project
.with_repo_recorded(None, Some("Git checkout"), |_| {
std::fs::write(&f.path, &replacement).unwrap();
std::fs::File::options()
.write(true)
.open(&f.path)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(modified))
.unwrap();
Ok(())
})
.unwrap();
f.assert_clean(&replacement);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn working_tree_operation_does_not_discard_unsaved_edits() {
let f = Fixture::new().await;
let version = f.project.documents.snapshot(f.doc).unwrap().version;
f.project
.documents
.edit(f.doc, version, ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "-- local\n".into() }] })
.unwrap();
vcs::vcs_checkout(&f.host, "main", None, "other".into(), false, None, None).await.unwrap();
let snapshot = f.project.documents.snapshot(f.doc).unwrap();
assert_eq!(snapshot.text, format!("-- local\n{ORIGINAL}"));
assert!(snapshot.dirty);
assert_eq!(std::fs::read_to_string(&f.path).unwrap(), OTHER);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn adding_local_exclude_reloads_open_ignore_document() {
let f = Fixture::new().await;
let path = f.project.root.join(".git/info/exclude");
let doc = f.project.documents.open(&path).unwrap();
let ignored = f.project.root.join("generated.txt");
std::fs::write(&ignored, "generated\n").unwrap();
vcs::vcs_add_to_ignore(&f.host, "main", vec![ignored], ide_vcs::IgnoreDestination::LocalExclude).await.unwrap();
let disk = std::fs::read_to_string(&path).unwrap();
assert!(disk.contains("/generated.txt"));
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().text, disk);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn commit_hook_reloads_clean_open_documents() {
use std::os::unix::fs::PermissionsExt;
let f = Fixture::new().await;
f.saved_edit(&format!("{ORIGINAL}\n"));
git(&f.project.root, &["add", "-u"]);
let hook = f.project.root.join(".git/hooks/pre-commit");
std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > node_modules/query.sql\n").unwrap();
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
vcs::vcs_commit(
&f.host,
"main",
None,
"commit with hook".into(),
ide_vcs::CommitOptions { run_hooks: true, ..Default::default() },
)
.await
.unwrap();
f.assert_clean("SELECT hook;");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn worktree_checkout_hook_reloads_clean_open_documents() {
use std::os::unix::fs::PermissionsExt;
let f = Fixture::new().await;
let hook = f.project.root.join(".git/hooks/post-checkout");
std::fs::write(&hook, "#!/bin/sh\nprintf 'SELECT hook;' > ../project/node_modules/query.sql\n").unwrap();
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
let linked = f.project.root.parent().unwrap().join("linked");
vcs::vcs_add_worktree(&f.host, "main", None, linked, "other".into(), None, None, None).await.unwrap();
f.assert_clean("SELECT hook;");
}