Файли
openidea/crates/ide-workspace/tests/documents.rs
T
ntbang0901 72e1d6afc1 fix(project-tree): never lose an existing file to a copy or paste (#7772)
Copy or Save As of an open file onto a taken name in a folder the tree had not loaded replaced that file without asking, because the Copy dialog only knew loaded folders and copy_as overwrote its target. The dialog now reads the folder, and copy_as refuses any existing target. Pasting a file from the OS clipboard into its own folder (or dropping it there through another path) and choosing Overwrite trashed the source itself; such a file now gets a copy next to it, checked with a new fs_same_file command, and an overwrite whose import fails or is cancelled restores the old file.

Co-authored-by: ntbang0901 <[email protected]>
2026-12-03 18:32:44 +08:00

2317 рядки
97 KiB
Rust

use ide_core::error::ErrorKind;
use ide_core::{ChangeSet, DocId, IdeEvent, LanguageId, Pos, Range, SharedSink, TextChange, TextEdit};
use ide_text::{AppliedChange, LineEnding};
use ide_workspace::documents::DocumentObserver;
use ide_workspace::{DocumentInfo, Documents};
use parking_lot::Mutex;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Default)]
struct Recorder {
log: Mutex<Vec<String>>,
}
impl DocumentObserver for Recorder {
fn opened(&self, info: &DocumentInfo) {
self.log.lock().push(format!("open v{} {}", info.version, info.language));
}
fn changed(&self, _: DocId, _: &Path, version: u32, changes: &[AppliedChange], full: &dyn Fn() -> String) {
self.log.lock().push(format!("change v{version} n{} {:?}", changes.len(), full()));
}
fn saved(&self, _: DocId, _: &Path, text: &str) {
self.log.lock().push(format!("save {text:?}"));
}
fn closed(&self, _: DocId, _: &Path) {
self.log.lock().push("close".into());
}
}
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
docs: Documents,
events: Arc<Mutex<Vec<IdeEvent>>>,
rec: Arc<Recorder>,
}
fn fixture() -> Fixture {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let docs = Documents::new(
sink,
Box::new(|p: &Path, _: Option<&str>| match p.extension().and_then(|e| e.to_str()) {
Some("rs") => LanguageId::new("rust"),
_ => LanguageId::plain_text(),
}),
);
let rec = Arc::new(Recorder::default());
docs.add_observer(rec.clone());
Fixture { _tmp: tmp, root, docs, events, rec }
}
#[test]
fn own_disk_changes_preserve_the_open_documents_encoding() {
let f = fixture();
let path = f.root.join("query.sql");
let original = "SELECT '中文';\r\n";
fs::write(&path, ide_vfs::encode(original, "gbk", false).unwrap()).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults.clone());
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "gbk");
defaults.project_fallback = "windows-1252".into();
f.docs.set_file_defaults(defaults);
f.docs.sync_after_disk_change();
let unchanged = f.docs.snapshot(doc.id).unwrap();
assert_eq!(unchanged.text, doc.text);
assert_eq!(unchanged.encoding, "gbk");
assert!(!unchanged.dirty);
let changed = "SELECT '世界';\r\n";
let bytes = ide_vfs::encode(changed, "gbk", false).unwrap();
fs::write(&path, &bytes).unwrap();
f.docs.sync_after_disk_change();
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!(reloaded.text, changed.replace("\r\n", "\n"));
assert_eq!(reloaded.encoding, "gbk");
assert_eq!(reloaded.line_ending, LineEnding::CrLf);
assert!(!reloaded.dirty);
f.docs.save_all().unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fn change(from: u32, to: u32, insert: &str) -> ChangeSet {
ChangeSet { changes: vec![TextChange { from, to, insert: insert.into() }] }
}
#[test]
fn redetect_reopens_documents_whose_language_changed() {
let tmp = tempfile::tempdir().unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let foo_is_python = Arc::new(Mutex::new(false));
let docs = {
let foo_is_python = foo_is_python.clone();
Documents::new(
sink,
Box::new(move |p: &Path, first: Option<&str>| {
if p.extension().is_some_and(|e| e == "foo") && *foo_is_python.lock() {
LanguageId::new("python")
} else if first.is_some_and(|l| l.starts_with("#!")) {
LanguageId::new("shellscript")
} else {
LanguageId::plain_text()
}
}),
)
};
let rec = Arc::new(Recorder::default());
docs.add_observer(rec.clone());
let foo = tmp.path().join("a.foo");
let script = tmp.path().join("run");
fs::write(&foo, "x = 1\n").unwrap();
fs::write(&script, "#!/bin/sh\necho\n").unwrap();
let a = docs.open(&foo).unwrap();
assert_eq!(a.language.as_str(), "plaintext");
assert_eq!(docs.open(&script).unwrap().language.as_str(), "shellscript", "the first line is detected");
assert!(docs.redetect_languages().is_empty());
*foo_is_python.lock() = true;
assert_eq!(docs.redetect_languages(), vec![a.id]);
assert_eq!(docs.snapshot(a.id).unwrap().language.as_str(), "python");
let log = rec.log.lock().clone();
assert_eq!(log[log.len() - 2..], ["close".to_owned(), "open v0 python".to_owned()]);
assert!(events.lock().iter().any(
|e| matches!(e, IdeEvent::DocLanguage { doc, language, .. } if *doc == a.id && language.as_str() == "python")
));
}
#[test]
fn ui_modes_are_detected_with_the_language() {
let tmp = tempfile::tempdir().unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let tpl_is_html = Arc::new(Mutex::new(false));
let docs = {
let tpl_is_html = tpl_is_html.clone();
Documents::new(
sink,
Box::new(move |p: &Path, _: Option<&str>| match p.extension().and_then(|e| e.to_str()) {
Some("html") => LanguageId::new("html"),
Some("tpl") if *tpl_is_html.lock() => LanguageId::new("html"),
_ => LanguageId::plain_text(),
}),
)
.with_ui_mode_detection(Box::new(|p: &Path, lang: &LanguageId| {
(lang.as_str() == "html" && p.parent().is_some_and(|d| d.ends_with("ng")))
.then(|| "Angular Template".into())
}))
};
fs::create_dir_all(tmp.path().join("ng")).unwrap();
let (template, page, tpl) =
(tmp.path().join("ng/app.html"), tmp.path().join("index.html"), tmp.path().join("ng/a.tpl"));
for p in [&template, &page, &tpl] {
fs::write(p, "<p></p>\n").unwrap();
}
assert_eq!(docs.open(&template).unwrap().ui_mode.as_deref(), Some("Angular Template"));
assert_eq!(docs.open(&page).unwrap().ui_mode, None);
let a = docs.open(&tpl).unwrap();
assert_eq!(a.ui_mode, None);
*tpl_is_html.lock() = true;
assert_eq!(docs.redetect_languages(), vec![a.id]);
assert_eq!(docs.snapshot(a.id).unwrap().ui_mode.as_deref(), Some("Angular Template"));
assert!(events.lock().iter().any(|e| matches!(
e,
IdeEvent::DocLanguage { doc, ui_mode: Some(mode), .. } if *doc == a.id && mode == "Angular Template"
)));
}
#[test]
fn ui_modes_are_redetected_without_a_language_change() {
let tmp = tempfile::tempdir().unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let docs = Documents::new(sink, Box::new(|_: &Path, _: Option<&str>| LanguageId::new("html")))
.with_ui_mode_detection(Box::new(|p: &Path, _: &LanguageId| {
p.parent().is_some_and(|d| d.join("angular.json").exists()).then(|| "Angular Template".into())
}));
let rec = Arc::new(Recorder::default());
docs.add_observer(rec.clone());
let (template, marker) = (tmp.path().join("app.html"), tmp.path().join("angular.json"));
fs::write(&template, "<p></p>\n").unwrap();
let a = docs.open(&template).unwrap();
assert_eq!(a.ui_mode, None);
let opened = rec.log.lock().len();
fs::write(&marker, "{}").unwrap();
assert_eq!(docs.language_of(&template, None).ui_mode.as_deref(), Some("Angular Template"));
assert_eq!(docs.redetect_languages(), vec![a.id]);
assert_eq!(docs.snapshot(a.id).unwrap().ui_mode.as_deref(), Some("Angular Template"));
assert!(docs.redetect_languages().is_empty());
fs::remove_file(&marker).unwrap();
assert_eq!(docs.redetect_languages(), vec![a.id]);
assert_eq!(docs.snapshot(a.id).unwrap().ui_mode, None);
let modes: Vec<Option<String>> = events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::DocLanguage { doc, language, ui_mode } if *doc == a.id && language.as_str() == "html" => {
Some(ui_mode.clone())
}
_ => None,
})
.collect();
assert_eq!(modes, [Some("Angular Template".to_owned()), None]);
assert_eq!(rec.log.lock().len(), opened, "language servers keep the document");
}
fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
fn assert_failed_save_preserves_edit(f: &Fixture, doc: DocId, text: &str, before: usize) {
let snapshot = f.docs.snapshot(doc).unwrap();
assert!(snapshot.dirty, "failed save marked the document clean");
assert_eq!(snapshot.text, text, "failed save changed the unsaved buffer");
assert!(!dirty_events(&f.events.lock()[before..]).contains(&false), "failed save emitted a clean-state event");
}
#[test]
fn unencodable_save_preserves_the_dirty_buffer_and_disk_bytes() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"caf\xe9").unwrap();
let doc = f.docs.open(&path).unwrap().id;
assert_eq!(f.docs.set_encoding(doc, "windows-1252", true).unwrap().encoding, "windows-1252");
let reloaded = f.docs.snapshot(doc).unwrap();
assert_eq!(reloaded.text, "café");
f.docs.edit(doc, reloaded.version, change(4, 4, "漢")).unwrap();
let original = fs::read(&path).unwrap();
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("Windows-1252 cannot encode the edit");
assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}");
assert_failed_save_preserves_edit(&f, doc, "café漢", before);
assert_eq!(fs::read(&path).unwrap(), original, "failed encoding changed disk bytes");
}
#[cfg(unix)]
#[test]
fn permission_denied_save_preserves_the_edit_and_can_be_retried() {
use std::os::unix::fs::PermissionsExt;
struct RestorePermissions<'a>(&'a Path, fs::Permissions);
impl Drop for RestorePermissions<'_> {
fn drop(&mut self) {
let result = fs::set_permissions(self.0, self.1.clone());
if !std::thread::panicking() {
result.expect("restore fixture permissions");
}
}
}
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
{
let _dir_permissions = RestorePermissions(&f.root, fs::metadata(&f.root).unwrap().permissions());
let _file_permissions = RestorePermissions(&path, fs::metadata(&path).unwrap().permissions());
// Deny both sibling temp-file creation and the fallback write to the existing file.
fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap();
fs::set_permissions(&f.root, fs::Permissions::from_mode(0o555)).unwrap();
let sibling = fs::OpenOptions::new().write(true).create_new(true).open(f.root.join("probe"));
let in_place = fs::OpenOptions::new().write(true).open(&path);
for (probe, access) in [(sibling, "create a sibling file"), (in_place, "open the target for writing")] {
match probe {
Ok(_) => {
eprintln!("skipping permission-denied save: test process can {access} despite permission bits");
return;
}
Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{access}: {err}"),
}
}
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("neither atomic nor in-place save should be writable");
assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err}");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert_eq!(fs::read(&path).unwrap(), b"original", "failed write changed disk bytes");
}
let before = f.events.lock().len();
f.docs.save(doc).expect("retry after restoring file and directory permissions");
assert_eq!(fs::read(&path).unwrap(), b"edited");
assert!(!f.docs.snapshot(doc).unwrap().dirty, "successful retry left the document dirty");
assert_eq!(dirty_events(&f.events.lock()[before..]), vec![false]);
}
#[test]
fn save_to_a_path_replaced_by_a_directory_preserves_the_dirty_buffer() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
assert!(f.docs.snapshot(doc).unwrap().dirty);
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
let before = f.events.lock().len();
f.docs.save(doc).expect_err("save must not replace a directory with a file");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert!(fs::symlink_metadata(&path).unwrap().is_dir(), "save removed the replacement directory");
assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "save left artifacts inside the replacement directory");
assert_eq!(fs::read_dir(&f.root).unwrap().count(), 1, "save left artifacts beside the replacement directory");
}
#[test]
fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
// An external write (git checkout, another editor) whose watcher event has not arrived yet.
fs::write(&path, "alpha\nbeta external\n").unwrap();
assert!(!f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
assert!(f.docs.snapshot(info.id).unwrap().dirty);
assert!(
f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { doc, .. } if *doc == info.id)),
"the refused autosave must surface the conflict"
);
}
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
fn rewrite_later(path: &Path, bytes: &[u8]) {
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
fs::write(path, bytes).unwrap();
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
}
#[test]
fn rewriting_the_same_bytes_is_no_disk_conflict() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
rewrite_later(&path, b"alpha\nbeta\n");
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
}
#[test]
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
rewrite_later(&path, b"alpha\nbeta\n");
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
}
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
let f = fixture();
let path = f.root.join(name);
fs::write(&path, bytes).unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
rewrite_later(&path, external);
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
assert_eq!(fs::read(&path).unwrap(), external);
}
#[test]
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
// Same length: only the byte comparison tells them apart.
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&path, "alpha\nbeta external\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
assert!(f.docs.snapshot(info.id).unwrap().dirty);
// An explicit save overwrites, as the warning says; autosave works again after it.
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
let transitions: Vec<_> = f
.events
.lock()
.iter()
.filter_map(|event| match event {
IdeEvent::DocDirty { doc, dirty, version } if *doc == info.id => Some((*version, *dirty)),
_ => None,
})
.collect();
assert_eq!(transitions, [(1, true), (1, false), (2, true), (2, false)]);
}
#[test]
fn closing_a_modified_buffer_reports_it_clean() {
let f = fixture();
let info = f.docs.open_untitled(None).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "draft")).unwrap();
assert_eq!(dirty_events(&f.events.lock()), vec![true]);
f.docs.close(info.id);
assert_eq!(dirty_events(&f.events.lock()), vec![true, false]);
}
#[test]
fn open_edit_save_close() {
let f = fixture();
let path = f.root.join("main.rs");
fs::write(&path, "fn main() {}\r\n").unwrap();
let info = f.docs.open(&path).unwrap();
assert_eq!(info.text, "fn main() {}\n");
assert_eq!(info.line_ending, LineEnding::CrLf);
assert_eq!(info.language.as_str(), "rust");
assert_eq!(info.encoding, "utf-8");
assert!(!info.read_only && !info.dirty);
// Ref-counted re-open shares the buffer.
let again = f.docs.open(&path).unwrap();
assert_eq!(again.id, info.id);
assert_eq!(f.docs.by_path(&path), Some(info.id));
let v = f.docs.edit(info.id, 0, change(12, 12, " // hi")).unwrap();
assert_eq!(v, 1);
let v = f.docs.edit(info.id, 1, change(0, 0, "pub ")).unwrap();
assert_eq!(v, 2);
assert_eq!(f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap_err().kind, ErrorKind::OutOfSync);
assert_eq!(f.docs.text_of(&path).unwrap(), "pub fn main() {} // hi\n");
assert!(f.docs.snapshot(info.id).unwrap().dirty);
assert_eq!(dirty_events(&f.events.lock()), vec![true]);
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "pub fn main() {} // hi\r\n");
assert!(!f.docs.snapshot(info.id).unwrap().dirty);
assert_eq!(dirty_events(&f.events.lock()), vec![true, false]);
// Our own save must not trigger a reload.
let before = f.events.lock().len();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.events.lock().len(), before);
f.docs.close(info.id);
assert!(f.docs.snapshot(info.id).is_ok(), "still referenced once");
f.docs.close(info.id);
assert_eq!(f.docs.snapshot(info.id).unwrap_err().kind, ErrorKind::NotFound);
assert_eq!(f.docs.by_path(&path), None);
assert_eq!(f.docs.text_of(&path), None);
assert_eq!(
*f.rec.log.lock(),
vec![
"open v0 rust".to_string(),
"change v1 n1 \"fn main() {} // hi\\n\"".into(),
"change v2 n1 \"pub fn main() {} // hi\\n\"".into(),
"save \"pub fn main() {} // hi\\n\"".into(),
"close".into(),
]
);
}
#[test]
fn backend_edits_emit_patches() {
let f = fixture();
let path = f.root.join("a.txt");
fs::write(&path, "one\ntwo\nthree\n").unwrap();
let id = f.docs.open(&path).unwrap().id;
let v = f
.docs
.apply_edits(
id,
&[
TextEdit { range: Range::new(Pos::new(2, 0), Pos::new(2, 5)), new_text: "THREE".into() },
TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "ONE".into() },
],
)
.unwrap();
assert_eq!(v, 1);
let v = f.docs.replace_all(id, "ONE\n2\nTHREE\n").unwrap();
assert_eq!(v, 2);
assert_eq!(f.docs.replace_all(id, "ONE\n2\nTHREE\n").unwrap(), 2, "no-op replace keeps version");
assert_eq!(f.docs.apply_edits(id, &[]).unwrap(), 2);
let patches: Vec<(u32, u32, Vec<TextChange>)> = f
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::DocPatched { base_version, version, changes, .. } => {
Some((*base_version, *version, changes.clone()))
}
_ => None,
})
.collect();
assert_eq!(
patches,
vec![
(
0,
1,
vec![
TextChange { from: 0, to: 3, insert: "ONE".into() },
TextChange { from: 8, to: 13, insert: "THREE".into() }
]
),
(1, 2, vec![TextChange { from: 4, to: 7, insert: "2".into() }]),
]
);
let overlapping = [
TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "x".into() },
TextEdit { range: Range::new(Pos::new(0, 1), Pos::new(0, 2)), new_text: "y".into() },
];
assert_eq!(f.docs.apply_edits(id, &overlapping).unwrap_err().kind, ErrorKind::InvalidInput);
f.docs.set_line_ending(id, LineEnding::CrLf).unwrap();
f.docs.save_all().unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "ONE\r\n2\r\nTHREE\r\n");
}
#[test]
fn versioned_background_edits_are_marked_non_undoable() {
let f = fixture();
let path = f.root.join("remote.txt");
fs::write(&path, "one").unwrap();
let doc = f.docs.open(&path).unwrap().id;
let patches = || {
f.events
.lock()
.iter()
.filter_map(|event| match event {
IdeEvent::DocPatched { workspace_edit, .. } => Some(*workspace_edit),
_ => None,
})
.collect::<Vec<_>>()
};
// A command's versioned edit stays an editor Undo step; a background one doesn't.
let edit = |text: &str| [TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 0)), new_text: text.into() }];
assert_eq!(f.docs.apply_edits_at(doc, 0, &edit("a")).unwrap(), Some(1));
assert_eq!(f.docs.apply_background_edits_at(doc, 1, &edit("b")).unwrap(), Some(2));
assert_eq!(patches(), [false, true]);
assert_eq!(f.docs.apply_background_edits_at(doc, 1, &edit("stale")).unwrap(), None);
assert_eq!(
f.docs.apply_edits_at(doc, 0, &[TextEdit { range: Range::default(), new_text: "stale".into() }]).unwrap(),
None
);
}
#[test]
fn external_change_in_two_places_patches_each() {
let f = fixture();
let path = f.root.join("two.txt");
let old: String = (0..400).map(|i| format!("line {i}\n")).collect();
fs::write(&path, &old).unwrap();
let id = f.docs.open(&path).unwrap().id;
std::thread::sleep(std::time::Duration::from_millis(10));
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
fs::write(&path, &new).unwrap();
let started = std::time::Instant::now();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let in_budget = started.elapsed() < ide_text::DIFF_BUDGET;
assert_eq!(f.docs.snapshot(id).unwrap().text, new);
let events = f.events.lock();
let changes = events.iter().find_map(|e| match e {
IdeEvent::DocPatched { changes, .. } => Some(changes),
_ => None,
});
let changes = changes.expect("a patch");
let mut replayed = ide_text::Document::new(&old);
replayed.apply(0, &ChangeSet { changes: changes.clone() }).unwrap();
assert_eq!(replayed.text(), new);
// Merged or not, the patch stays between the two edited lines.
let first = old.find("line 20\n").unwrap() as u32;
let last = (old.find("line 299\n").unwrap() + "line 299\n".len()) as u32;
assert!(changes[0].from >= first && changes[changes.len() - 1].to <= last, "{changes:?}");
// Past the diff budget (a loaded machine) the two regions may come as one, still correctly.
if in_budget {
assert_eq!(changes.len(), 2);
}
}
#[test]
fn external_changes() {
let f = fixture();
let path = f.root.join("ext.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let id = f.docs.open(&path).unwrap().id;
// Clean document: reloads with a minimal patch, stays clean.
std::thread::sleep(std::time::Duration::from_millis(10));
fs::write(&path, "alpha\nBETA\ngamma\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let snap = f.docs.snapshot(id).unwrap();
assert_eq!(snap.text, "alpha\nBETA\ngamma\n");
assert_eq!(snap.version, 1);
assert!(!snap.dirty);
assert!(f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocPatched { base_version: 0, version: 1, .. })));
assert!(dirty_events(&f.events.lock()).is_empty());
// Dirty document: not clobbered, warning instead.
f.docs.edit(id, 1, change(0, 0, "// ")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
fs::write(&path, "something else\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(id).unwrap().text, "// alpha\nBETA\ngamma\n");
let warnings = f
.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path.to_string_lossy()))
.count();
assert_eq!(warnings, 1);
// The same disk state is reported only once.
f.docs.on_disk_changed(std::slice::from_ref(&path));
let warnings = f
.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path.to_string_lossy()))
.count();
assert_eq!(warnings, 1);
// Load Changes from Disk drops the buffer's changes; autosave writes again afterwards.
f.docs.discard_and_reload(id).unwrap();
let reloaded = f.docs.snapshot(id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.dirty), ("something else\n", false));
f.docs.edit(id, reloaded.version, change(0, 0, "# ")).unwrap();
assert!(f.docs.autosave(id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "# something else\n");
// Unknown paths are ignored.
f.docs.on_disk_changed(&[f.root.join("other.txt")]);
}
/// An IDE operation that rewrites a file with the same length and mtime still refreshes
/// the clean buffer.
#[test]
fn own_disk_change_preserving_length_and_mtime_reloads_a_clean_document() {
let f = fixture();
let path = f.root.join("stamp.txt");
fs::write(&path, "first").unwrap();
let id = f.docs.open(&path).unwrap().id;
let mtime = fs::metadata(&path).unwrap().modified().unwrap();
fs::write(&path, "other").unwrap();
fs::File::options().write(true).open(&path).unwrap().set_modified(mtime).unwrap();
f.docs.sync_after_disk_change();
assert_eq!(f.docs.snapshot(id).unwrap().text, "other");
}
/// An external write that keeps the byte length and the mtime (timestamp-preserving
/// tools, coarse-granularity filesystems) leaves the `(mtime, length)` stamp equal:
/// the OS event is still authoritative, so a clean document reloads.
#[test]
fn external_change_preserving_length_and_mtime_reloads_a_clean_document() {
let f = fixture();
let path = f.root.join("stamp.txt");
fs::write(&path, "first").unwrap(); // 5 bytes
let id = f.docs.open(&path).unwrap().id;
let mtime = fs::metadata(&path).unwrap().modified().unwrap();
fs::write(&path, "other").unwrap(); // 5 bytes, different content
fs::File::options().write(true).open(&path).unwrap().set_modified(mtime).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let snap = f.docs.snapshot(id).unwrap();
assert_eq!(snap.text, "other");
assert!(!snap.dirty);
// The reload recorded the new stamp: repeating the same event changes nothing.
let before = f.events.lock().len();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.events.lock().len(), before);
assert_eq!(f.docs.snapshot(id).unwrap().text, "other");
}
#[test]
fn encodings_and_read_only() {
let f = fixture();
let gbk_path = f.root.join("gbk.txt");
let (bytes, _, _) = encoding_rs::GBK.encode("这是一段比较长的中文文本,用于测试编码检测是否正确。\n");
fs::write(&gbk_path, &bytes).unwrap();
let info = f.docs.open(&gbk_path).unwrap();
assert_eq!(info.encoding, "gbk");
f.docs.edit(info.id, 0, change(0, 0, "前言")).unwrap();
f.docs.save(info.id).unwrap();
let saved = fs::read(&gbk_path).unwrap();
let (decoded, _, _) = encoding_rs::GBK.decode(&saved);
assert_eq!(decoded, "前言这是一段比较长的中文文本,用于测试编码检测是否正确。\n");
let bom_path = f.root.join("bom.txt");
fs::write(&bom_path, b"\xEF\xBB\xBFhello").unwrap();
let info = f.docs.open(&bom_path).unwrap();
f.docs.edit(info.id, 0, change(5, 5, "!")).unwrap();
f.docs.save(info.id).unwrap();
assert_eq!(fs::read(&bom_path).unwrap(), b"\xEF\xBB\xBFhello!");
let bin_path = f.root.join("img.png");
fs::write(&bin_path, [0x89, b'P', b'N', b'G', 0, 0, 0, 0]).unwrap();
let info = f.docs.open(&bin_path).unwrap();
assert!(info.read_only);
assert!(info.text.is_empty());
assert_eq!(f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap_err().kind, ErrorKind::PermissionDenied);
f.docs.close(info.id);
// Binary docs are never reported to observers.
let opens = f.rec.log.lock().iter().filter(|l| l.starts_with("open")).count();
assert_eq!(opens, 2);
assert!(!f.rec.log.lock().iter().any(|l| l == "close"));
assert_eq!(f.docs.open(&f.root.join("missing.txt")).unwrap_err().kind, ErrorKind::NotFound);
}
#[test]
fn reload_and_convert_encoding() {
let f = fixture();
let path = f.root.join("mis.txt");
let (bytes, _, _) = encoding_rs::GBK.encode("中文内容");
fs::write(&path, &bytes).unwrap();
let info = f.docs.open(&path).unwrap();
let encoding = f.docs.set_encoding(info.id, "gbk", true).unwrap();
assert_eq!(encoding.encoding, "gbk");
assert!(!encoding.has_bom);
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "中文内容");
// Convert: same text, written in the new encoding on save.
let encoding = f.docs.set_encoding(info.id, "utf-8", false).unwrap();
assert_eq!(encoding.encoding, "utf-8");
assert!(!encoding.has_bom);
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "中文内容");
// Not representable → refused, encoding unchanged.
assert!(f.docs.set_encoding(info.id, "windows-1252", false).is_err());
// Reload refuses unsaved changes.
f.docs.edit(info.id, f.docs.snapshot(info.id).unwrap().version, change(0, 0, "x")).unwrap();
assert!(f.docs.set_encoding(info.id, "gbk", true).is_err());
}
#[test]
fn external_changes_keep_a_chosen_encoding() {
// Valid UTF-8 bytes, so detection alone would read them as UTF-8.
let (first, changed) = (b"caf\xC3\xA9".as_slice(), b"caf\xC3\xA9 \xC3\xA8".as_slice());
for (encoding, reload) in [("windows-1252", true), ("gbk", true), ("windows-1252", false)] {
let f = fixture();
let path = f.root.join("legacy.txt");
fs::write(&path, first).unwrap();
let info = f.docs.open(&path).unwrap();
assert_eq!(info.encoding, "utf-8");
if reload {
f.docs.set_encoding(info.id, encoding, true).unwrap();
} else {
// Convert, then save: the file is now in the chosen encoding.
f.docs.replace_all(info.id, "café").unwrap();
f.docs.set_encoding(info.id, encoding, false).unwrap();
f.docs.save(info.id).unwrap();
}
let expected =
|bytes: &[u8]| encoding_rs::Encoding::for_label(encoding.as_bytes()).unwrap().decode(bytes).0.into_owned();
let changed = if reload { changed.to_vec() } else { ide_vfs::encode("café è", encoding, false).unwrap() };
fs::write(&path, &changed).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let snapshot = f.docs.snapshot(info.id).unwrap();
assert_eq!(snapshot.text, expected(&changed), "{encoding} reload={reload}");
assert_eq!(snapshot.encoding, encoding, "{encoding} reload={reload}");
assert!(!snapshot.dirty);
}
}
#[test]
fn external_changes_redetect_an_encoding_the_user_never_chose() {
let f = fixture();
let path = f.root.join("plain.txt");
fs::write(&path, "plain").unwrap();
let info = f.docs.open(&path).unwrap();
fs::write(&path, ide_vfs::encode("wide", "utf-16le", true).unwrap()).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let snapshot = f.docs.snapshot(info.id).unwrap();
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("wide", "utf-16le"));
}
#[test]
fn external_reload_tells_the_editor_the_new_encoding_and_line_ending() {
let f = fixture();
let path = f.root.join("plain.txt");
fs::write(&path, "a\r\nb\r\n").unwrap();
let info = f.docs.open(&path).unwrap();
fs::write(&path, ide_vfs::encode("a\nb\n", "utf-16le", true).unwrap()).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let seen: Vec<_> = f
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::DocEncoding { doc, encoding, has_bom, line_ending } if *doc == info.id => {
Some((encoding.clone(), *has_bom, line_ending.clone()))
}
_ => None,
})
.collect();
assert_eq!(seen, [("utf-16le".to_owned(), true, "lf".to_owned())]);
// A reload that changes none of them stays quiet.
fs::write(&path, ide_vfs::encode("a\nb\nc\n", "utf-16le", true).unwrap()).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "a\nb\nc\n");
let count = f.events.lock().iter().filter(|e| matches!(e, IdeEvent::DocEncoding { .. })).count();
assert_eq!(count, 1);
}
#[test]
fn load_changes_from_disk_tells_the_editor_a_new_bom() {
let f = fixture();
let path = f.root.join("plain.txt");
fs::write(&path, "text").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.replace_all(info.id, "edited").unwrap();
fs::write(&path, b"\xEF\xBB\xBFtext").unwrap();
f.docs.discard_and_reload(info.id).unwrap();
let seen: Vec<_> = f
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::DocEncoding { doc, encoding, has_bom, .. } if *doc == info.id => {
Some((encoding.clone(), *has_bom))
}
_ => None,
})
.collect();
assert_eq!(seen, [("utf-8".to_owned(), true)]);
}
#[test]
fn utf8_bom_is_added_and_removed_on_save() {
let f = fixture();
let path = f.root.join("bom.txt");
fs::write(&path, "text").unwrap();
let info = f.docs.open(&path).unwrap();
assert!(!info.has_bom);
assert!(f.docs.set_bom(info.id, true).unwrap().has_bom);
assert_eq!(fs::read(&path).unwrap(), b"text", "written on save only");
f.docs.save(info.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"\xEF\xBB\xBFtext");
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "text");
assert!(!f.docs.set_bom(info.id, false).unwrap().has_bom);
f.docs.save(info.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"text");
// Other encodings have no BOM to toggle.
f.docs.set_encoding(info.id, "gbk", false).unwrap();
assert!(f.docs.set_bom(info.id, true).is_err());
}
#[cfg(unix)]
#[test]
fn symlinked_path_maps_to_same_document() {
let f = fixture();
let real = f.root.join("real.txt");
fs::write(&real, "x").unwrap();
let link = f.root.join("link.txt");
std::os::unix::fs::symlink(&real, &link).unwrap();
let a = f.docs.open(&real).unwrap();
assert_eq!(f.docs.by_path(&link), Some(a.id));
let b = f.docs.open(&link).unwrap();
assert_eq!(a.id, b.id);
}
#[derive(Default)]
struct ByteRecorder {
edits: Mutex<Vec<(u32, Vec<ide_text::ByteEdit>)>>,
}
impl DocumentObserver for ByteRecorder {
fn edited(&self, _: DocId, version: u32, edits: &[ide_text::ByteEdit]) {
self.edits.lock().push((version, edits.to_vec()));
}
}
#[test]
fn observers_receive_byte_edits() {
let f = fixture();
let rec = Arc::new(ByteRecorder::default());
f.docs.add_observer(rec.clone());
let path = f.root.join("a.rs");
fs::write(&path, "é\nab\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(3, 4, "XY\n")).unwrap();
f.docs.apply_edits(info.id, &[TextEdit { range: Range::point(Pos::new(0, 0)), new_text: "// ".into() }]).unwrap();
f.docs.replace_all(info.id, "nothing").unwrap();
let edits = rec.edits.lock().clone();
assert_eq!(edits.iter().map(|(v, _)| *v).collect::<Vec<_>>(), vec![1, 2, 3]);
let e = edits[0].1[0];
// "é" is two bytes: offset 3 (UTF-16) = byte 4 = row 1, byte column 1.
assert_eq!((e.start_byte, e.old_end_byte, e.new_end_byte), (4, 5, 7));
assert_eq!((e.start.row, e.start.col, e.new_end.row, e.new_end.col), (1, 1, 2, 0));
let snap = f.docs.text_snapshot(info.id).unwrap();
assert_eq!((snap.version, snap.text.as_str(), snap.large), (3, "nothing", false));
assert_eq!(snap.language, LanguageId::new("rust"));
}
#[test]
fn code_insight_limit_uses_file_bytes_for_disk_and_virtual_documents() {
use ide_core::settings::Settings;
use ide_workspace::FileDefaults;
let f = fixture();
let set_limit = |mb| {
let settings: Settings = serde_json::from_value(serde_json::json!({
"editor": {"maxCodeInsightFileSizeMb": mb},
}))
.unwrap();
f.docs.set_file_defaults(FileDefaults::from_settings(&settings, Some(&f.root)));
};
set_limit(1);
let path = f.root.join("data.go");
// The on-disk UTF-16LE bytes cross 1 MiB, although the decoded buffer is smaller.
let decoded = "x".repeat(512 * 1024);
fs::write(&path, ide_vfs::encode(&decoded, "utf-16le", true).unwrap()).unwrap();
let doc = f.docs.open(&path).unwrap();
assert!(doc.large && !doc.too_large && !doc.read_only);
assert!(f.docs.load_file_as(&path, "utf-16le").unwrap().large);
f.docs.close(doc.id);
set_limit(2);
let reopened = f.docs.open(&path).unwrap();
assert!(!reopened.large);
set_limit(1);
f.docs.set_encoding(reopened.id, "utf-16le", true).unwrap();
assert!(!f.docs.snapshot(reopened.id).unwrap().large, "reloading retains the open document's limit");
fs::write(&path, ide_vfs::encode(&(decoded + "y"), "utf-16le", true).unwrap()).unwrap();
f.docs.sync_after_disk_change();
assert!(!f.docs.snapshot(reopened.id).unwrap().large);
f.docs.close(reopened.id);
let reopened = f.docs.open(&path).unwrap();
assert!(reopened.large, "reopening applies the new limit");
fs::write(&path, ide_vfs::encode("small", "utf-16le", true).unwrap()).unwrap();
f.docs.sync_after_disk_change();
assert!(f.docs.snapshot(reopened.id).unwrap().large, "observers still use the decision made on open");
f.docs.close(reopened.id);
let small = f.docs.open(&path).unwrap();
assert!(!small.large);
set_limit(2);
let mut text = "x".repeat(2 * 1024 * 1024);
let doc = f.docs.open_virtual("test://bytes", LanguageId::new("go"), &text, "utf-8", false, true).unwrap();
assert!(!doc.large, "the configured limit is inclusive");
set_limit(1);
f.docs.replace_virtual(doc.id, &text, "utf-8", false).unwrap();
assert!(!f.docs.snapshot(doc.id).unwrap().large);
text.push('x');
f.docs.replace_virtual(doc.id, &text, "utf-8", false).unwrap();
assert!(!f.docs.snapshot(doc.id).unwrap().large);
f.docs.close(doc.id);
text.pop();
let reopened = f.docs.open_virtual("test://bytes", LanguageId::new("go"), &text, "utf-8", false, true).unwrap();
assert!(reopened.large);
// A user raising the threshold can open a previously degraded file with full analysis.
let larger = f.root.join("generated.pb.go");
fs::write(&larger, "x".repeat(5 * 1024 * 1024 + 1)).unwrap();
set_limit(6);
let doc = f.docs.open(&larger).unwrap();
assert!(!doc.large && !doc.read_only);
}
#[test]
fn large_files_degrade() {
let f = fixture();
let line = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde\n";
let big = line.repeat((ide_vfs::LARGE_FILE_THRESHOLD as usize) / line.len() + 1);
let path = f.root.join("big.log");
fs::write(&path, &big).unwrap();
let info = f.docs.open(&path).unwrap();
assert!(info.large && !info.read_only);
assert_eq!(info.text.len(), big.len());
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
let json = serde_json::to_value(&info).unwrap_or_default();
assert_eq!(json.get("large"), Some(&serde_json::Value::Bool(true)));
let huge_path = f.root.join("huge.log");
let huge = line.repeat((ide_vfs::READ_ONLY_THRESHOLD as usize) / line.len() + 1);
fs::write(&huge_path, &huge).unwrap();
drop(huge);
let start = std::time::Instant::now();
let info = f.docs.open(&huge_path).unwrap();
assert!(info.large && info.read_only);
assert_eq!(f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap_err().kind, ErrorKind::PermissionDenied);
// Generous bound for debug builds; the point is "no quadratic work".
assert!(start.elapsed() < std::time::Duration::from_secs(20), "{:?}", start.elapsed());
let small = f.root.join("small.rs");
fs::write(&small, "fn x() {}\n").unwrap();
let info = f.docs.open(&small).unwrap();
assert!(!info.large);
let json = serde_json::to_value(&info).unwrap_or_default();
assert_eq!(json["editorconfig"], serde_json::Value::Null, "null when no .editorconfig applies");
}
#[test]
fn editorconfig_applies_on_open_and_save() {
let f = fixture();
fs::write(
f.root.join(".editorconfig"),
"root = true\n[*]\nend_of_line = crlf\nindent_style = tab\ntab_width = 3\ninsert_final_newline = true\n\
[*.u16]\ncharset = utf-16le\n[*.keep]\nend_of_line = unset\n",
)
.unwrap();
let path = f.root.join("a.txt");
fs::write(&path, "one\ntwo\n").unwrap();
let info = f.docs.open(&path).unwrap();
assert_eq!(info.line_ending, LineEnding::CrLf);
let ec = info.editorconfig.clone().unwrap();
assert_eq!(
(ec.indent_style, ec.indent_size, ec.tab_width),
(Some(ide_workspace::editorconfig::IndentStyle::Tab), Some(3), Some(3))
);
assert_eq!(ec.insert_final_newline, Some(true));
assert!(!info.dirty);
f.docs.edit(info.id, 0, change(0, 0, "zero\n")).unwrap();
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "zero\r\none\r\ntwo\r\n");
// Without end_of_line the detected ending is kept.
let keep = f.root.join("x.keep");
fs::write(&keep, "a\nb\n").unwrap();
assert_eq!(f.docs.open(&keep).unwrap().line_ending, LineEnding::Lf);
// New (empty) files take the configured charset.
let new = f.root.join("new.u16");
ide_workspace::editorconfig::create_file(f.docs.editorconfig(), &new).unwrap();
assert_eq!(fs::read(&new).unwrap(), [0xFF, 0xFE]);
let empty = f.root.join("empty.u16");
fs::write(&empty, "").unwrap();
let info = f.docs.open(&empty).unwrap();
assert_eq!((info.encoding.as_str(), info.line_ending), ("utf-16le", LineEnding::CrLf));
f.docs.edit(info.id, 0, change(0, 0, "A\nB")).unwrap();
f.docs.save(info.id).unwrap();
let expected: Vec<u8> =
[0xFF, 0xFE].into_iter().chain("A\r\nB".encode_utf16().flat_map(u16::to_le_bytes)).collect();
assert_eq!(fs::read(&empty).unwrap(), expected);
}
#[test]
fn virtual_documents_are_read_only_and_keyed_by_uri() {
let f = fixture();
let uri = "jdt://contents/a.jar/p/C.class?=x";
let info = f.docs.open_virtual(uri, LanguageId::new("java"), "class C {}\n", "utf-8", false, true).unwrap();
assert_eq!(info.uri.as_deref(), Some(uri));
assert_eq!(info.path, PathBuf::from(uri));
assert!(info.read_only && !info.dirty);
assert_eq!(info.language.as_str(), "java");
// Re-opening shares the document; edits and saves never reach a file.
let again = f.docs.open_virtual(uri, LanguageId::new("java"), "ignored", "utf-8", false, true).unwrap();
assert_eq!(again.id, info.id);
assert_eq!(again.text, "class C {}\n");
let err = f.docs.edit(info.id, info.version, change(0, 0, "x")).unwrap_err();
assert_eq!(err.kind, ErrorKind::PermissionDenied);
f.docs.save(info.id).unwrap();
assert!(f.docs.set_encoding(info.id, "utf-16le", true).is_err());
f.docs.close(info.id);
f.docs.close(info.id);
assert!(f.docs.snapshot(info.id).is_err());
assert_eq!(*f.rec.log.lock(), vec!["open v0 java".to_owned(), "close".to_owned()]);
}
#[test]
fn virtual_documents_carry_their_encoding_and_reload_capability() {
let f = fixture();
// Archive sources decoded by the backend report the charset actually used.
let uri = "jar:///m2/lib-1.0-sources.jar!/p/C.java";
let info = f.docs.open_virtual(uri, LanguageId::new("java"), "中文", "gbk", false, true).unwrap();
assert_eq!((info.encoding.as_str(), info.has_bom, info.can_reload_encoding), ("gbk", false, true));
let bom =
f.docs.open_virtual("jar:///m2/b.jar!/p/B.java", LanguageId::new("java"), "x", "utf-8", true, true).unwrap();
assert!(bom.has_bom);
// Server-generated content (decompiled) cannot be re-decoded.
let decompiled = f
.docs
.open_virtual(
"csharp:/p/App.csproj/decompiled/Lib.cs",
LanguageId::new("csharp"),
"class Lib {}",
"utf-8",
false,
false,
)
.unwrap();
assert!(!decompiled.can_reload_encoding);
// File-backed documents can always be re-read from disk.
let path = f.root.join("f.txt");
fs::write(&path, "x").unwrap();
assert!(f.docs.open(&path).unwrap().can_reload_encoding);
}
#[test]
fn virtual_documents_reload_with_another_encoding_without_becoming_editable() {
let f = fixture();
let uri = "jdt://contents/a.jar/p/C.class?=x";
let info = f.docs.open_virtual(uri, LanguageId::new("java"), "涓枃", "utf-8", false, true).unwrap();
let encoding = f.docs.replace_virtual(info.id, "中文", "gbk", false).unwrap();
assert_eq!((encoding.encoding.as_str(), encoding.has_bom), ("gbk", false));
let snap = f.docs.snapshot(info.id).unwrap();
assert_eq!(snap.text, "中文");
assert_eq!(snap.encoding, "gbk");
assert!(snap.read_only && !snap.dirty, "reloading is not an edit");
assert!(snap.version > info.version);
assert_eq!(f.docs.virtual_uri(info.id).unwrap().as_deref(), Some(uri));
// The replacement reached observers and the event stream (editors resync).
assert!(f.rec.log.lock().iter().any(|l| l.starts_with("change v") && l.contains("中文")));
assert!(f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocPatched { doc, .. } if *doc == info.id)));
// Read-only protection is unchanged.
assert_eq!(f.docs.edit(info.id, snap.version, change(0, 0, "x")).unwrap_err().kind, ErrorKind::PermissionDenied);
assert!(f.docs.set_encoding(info.id, "utf-8", false).is_err());
assert!(f.docs.set_encoding(info.id, "gbk", true).is_err(), "the op layer routes virtual reloads");
assert!(f.docs.set_bom(info.id, true).is_err());
f.docs.save(info.id).unwrap();
// Unknown encodings are refused; file-backed documents are not virtual.
assert!(f.docs.replace_virtual(info.id, "x", "not-an-encoding", false).is_err());
let path = f.root.join("f.txt");
fs::write(&path, "x").unwrap();
let file = f.docs.open(&path).unwrap();
assert!(f.docs.replace_virtual(file.id, "y", "utf-8", false).is_err());
assert_eq!(f.docs.virtual_uri(file.id).unwrap(), None);
}
#[test]
fn toggling_the_writable_bit_updates_the_open_document() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "hello").unwrap();
let info = f.docs.open(&path).unwrap();
assert!(!info.read_only);
assert!(f.docs.set_writable(&path, false).unwrap());
assert!(fs::metadata(&path).unwrap().permissions().readonly());
assert!(f.docs.snapshot(info.id).unwrap().read_only);
assert_eq!(f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap_err().kind, ErrorKind::PermissionDenied);
assert!(!f.docs.set_writable(&path, true).unwrap());
assert!(!f.docs.snapshot(info.id).unwrap().read_only);
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "xhello");
// Files that are not open only change on disk.
let other = f.root.join("other.txt");
fs::write(&other, "").unwrap();
assert!(f.docs.set_writable(&other, false).unwrap());
assert!(fs::metadata(&other).unwrap().permissions().readonly());
}
#[test]
fn archive_entries_open_read_only_without_observers() {
use std::io::Write;
let f = fixture();
let jar = f.root.join("lib-sources.jar");
let mut w = zip::ZipWriter::new(fs::File::create(&jar).unwrap());
w.start_file("org/x/Main.rs", zip::write::SimpleFileOptions::default()).unwrap();
w.write_all(b"fn main() {}\n").unwrap();
w.finish().unwrap();
let path = ide_vfs::archive_entry_path(&jar, "org/x/Main.rs");
let info = f.docs.open(&path).unwrap();
assert_eq!((info.text.as_str(), info.language.as_str(), info.read_only), ("fn main() {}\n", "rust", true));
assert_eq!(*info.path, *path);
assert!(f.rec.log.lock().is_empty(), "language servers / history never see archive entries");
fs::remove_file(&jar).unwrap();
f.docs.sync_from_disk();
assert_eq!(f.docs.snapshot(info.id).unwrap().version, info.version);
assert_eq!(f.docs.snapshot(info.id).unwrap().text, info.text);
f.docs.close(info.id);
}
#[test]
fn properties_conversion_uses_displayed_utf16_and_survives_reload() {
let f = fixture();
let path = f.root.join("messages.properties");
let original = "greeting=\\u4f60\\u597d\\uD83D\\uDE00!\r\nliteral=\\\\u0041\r\nbad=\\u12xz\r\n";
fs::write(&path, original).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.native_to_ascii = true;
f.docs.set_file_defaults(defaults);
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.text, "greeting=你好😀!\nliteral=\\\\u0041\nbad=\\u12xz\n");
assert!(!doc.dirty);
assert_eq!(f.docs.text_snapshot(doc.id).unwrap().text, doc.text);
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), original.as_bytes());
// Two BMP characters + one surrogate pair put ! at UTF-16 offset 13.
f.docs.edit(doc.id, doc.version, change(13, 14, "界")).unwrap();
f.docs.save(doc.id).unwrap();
let expected = "greeting=\\u4F60\\u597D\\uD83D\\uDE00\\u754C\r\nliteral=\\\\u0041\r\nbad=\\u12xz\r\n";
assert_eq!(fs::read(&path).unwrap(), expected.as_bytes());
assert!(f.rec.log.lock().iter().any(|line| line.contains("greeting=你好😀界")));
let saved = f.docs.snapshot(doc.id).unwrap();
f.docs.set_encoding(doc.id, "iso-8859-1", true).unwrap();
assert_eq!(f.docs.snapshot(doc.id).unwrap().version, saved.version);
// Force a watcher event even though the serialized contents are identical.
fs::File::options().write(true).open(&path).unwrap().set_modified(std::time::SystemTime::UNIX_EPOCH).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!(reloaded.text, saved.text);
assert_eq!(reloaded.version, saved.version);
assert!(!reloaded.dirty);
fs::write(&path, "greeting=\\u4E16\\u754C\r\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "greeting=世界\n");
assert!(!f.docs.is_dirty(doc.id).unwrap());
}
#[test]
fn properties_pasted_escapes_survive_save_and_decode_on_reload() {
let pasted = "test.key1=Hello\ntest.key2=\\u4F60\\u597D\ntest.key3=\\u4f60\\u597d\n";
let displayed = "test.key1=Hello\ntest.key2=你好\ntest.key3=你好\n";
for encoding in ["utf-8", "iso-8859-1", "utf-16le"] {
for eol in ["\n", "\r\n"] {
let f = fixture();
let path = f.root.join("test_zh_CN.properties");
let source = pasted.replace('\n', eol);
fs::write(&path, ide_vfs::encode(&source, encoding, encoding == "utf-16le").unwrap()).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.native_to_ascii = true;
defaults.properties_fallback = encoding.into();
f.docs.set_file_defaults(defaults.clone());
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.text, displayed);
f.docs.replace_all(doc.id, pasted).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), source.as_bytes(), "{encoding} {eol:?}");
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, pasted);
assert!(!f.docs.is_dirty(doc.id).unwrap());
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, pasted, "own saves do not reload");
f.docs.close(doc.id);
let reopened = f.docs.open(&path).unwrap();
assert_eq!(reopened.text, displayed);
// An edit followed by its inverse preserves the original escape casing.
f.docs.replace_all(reopened.id, pasted).unwrap();
f.docs.replace_all(reopened.id, displayed).unwrap();
f.docs.save(reopened.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), source.as_bytes());
let external = format!("{source}test.key4=\\uD83D\\uDE00{eol}");
fs::write(&path, &external).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(reopened.id).unwrap().text, format!("{displayed}test.key4=😀\n"));
defaults.native_to_ascii = false;
f.docs.set_file_defaults(defaults.clone());
f.docs.reload_properties();
assert_eq!(f.docs.snapshot(reopened.id).unwrap().text, external.replace("\r\n", "\n"));
defaults.native_to_ascii = true;
f.docs.set_file_defaults(defaults);
f.docs.reload_properties();
assert_eq!(f.docs.snapshot(reopened.id).unwrap().text, format!("{displayed}test.key4=😀\n"));
assert_eq!(fs::read_to_string(&path).unwrap(), external);
}
}
}
#[test]
fn properties_toggle_reloads_only_clean_properties_and_pins_dirty_codec() {
let f = fixture();
let paths = ["clean.properties", "dirty.properties", "other.txt"].map(|name| f.root.join(name));
for path in &paths {
fs::write(path, r"value=\u4F60").unwrap();
}
let [clean, dirty, other] = paths.each_ref().map(|p| f.docs.open(p).unwrap());
f.docs.edit(dirty.id, dirty.version, change(12, 12, "!")).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.native_to_ascii = true;
f.docs.set_file_defaults(defaults.clone());
f.docs.reload_properties();
assert_eq!(f.docs.snapshot(clean.id).unwrap().text, "value=你");
assert!(!f.docs.is_dirty(clean.id).unwrap());
assert_eq!(f.docs.snapshot(dirty.id).unwrap().text, r"value=\u4F60!");
assert!(!f.docs.native_to_ascii_for(&paths[1]));
assert_eq!(f.docs.snapshot(other.id).unwrap().text, r"value=\u4F60");
f.docs.save(dirty.id).unwrap();
assert_eq!(fs::read_to_string(&paths[1]).unwrap(), r"value=\u4F60!");
f.docs.reload_properties();
assert_eq!(f.docs.snapshot(dirty.id).unwrap().text, "value=你!");
f.docs.edit(dirty.id, f.docs.snapshot(dirty.id).unwrap().version, change(7, 8, "好")).unwrap();
defaults.native_to_ascii = false;
f.docs.set_file_defaults(defaults);
f.docs.reload_properties();
assert_eq!(f.docs.snapshot(clean.id).unwrap().text, r"value=\u4F60");
assert!(f.docs.native_to_ascii_for(&paths[1]));
f.docs.save(dirty.id).unwrap();
assert_eq!(fs::read_to_string(&paths[1]).unwrap(), r"value=\u4F60\u597D");
}
#[test]
fn properties_ascii_noop_and_charset_conversion() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.native_to_ascii = true;
f.docs.set_file_defaults(defaults);
for (i, source) in ["a=b\r\n# comment\r\n", r"a=\u0041", r"a=\\u0041", r"a=\uD800"].iter().enumerate() {
let path = f.root.join(format!("{i}.properties"));
fs::write(&path, source).unwrap();
let doc = f.docs.open(&path).unwrap();
f.docs.edit(doc.id, doc.version, change(0, 0, "x")).unwrap();
f.docs.edit(doc.id, doc.version + 1, change(0, 1, "")).unwrap();
f.docs.save(doc.id).unwrap();
f.docs.set_encoding(doc.id, "utf-8", true).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read_to_string(path).unwrap(), *source);
}
let path = f.root.join("utf16.properties");
fs::write(&path, ide_vfs::encode("a=你好😀", "utf-16le", true).unwrap()).unwrap();
let doc = f.docs.open(&path).unwrap();
f.docs.replace_all(doc.id, "a=世界😀").unwrap();
f.docs.save(doc.id).unwrap();
assert!(fs::read(&path).unwrap().is_ascii());
f.docs.set_encoding(doc.id, "utf-16le", true).unwrap();
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "a=世界😀");
assert!(!f.docs.is_dirty(doc.id).unwrap());
}
#[test]
fn untitled_buffers_are_editable_and_saved_to_a_chosen_path() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.line_ending = LineEnding::Lf;
f.docs.set_file_defaults(defaults);
let info = f.docs.open_untitled(None).unwrap();
assert_eq!(info.path, PathBuf::from("untitled:Untitled-1"));
assert_eq!(info.uri.as_deref(), Some("untitled:Untitled-1"));
assert_eq!(info.language, LanguageId::plain_text());
assert!(!info.read_only && !info.dirty && !info.large);
// Editing works; nothing is written anywhere.
let version = f.docs.edit(info.id, info.version, change(0, 0, "fn main() {}\n")).unwrap();
assert!(f.docs.is_dirty(info.id).unwrap());
f.docs.save(info.id).unwrap();
assert!(f.docs.is_dirty(info.id).unwrap(), "an untitled buffer has no file to save to");
// Save As: the buffer reaches the disk and becomes a regular file document
// (same id, re-keyed, language re-detected, missing parents created).
let target = f.root.join("new/nested/main.rs");
let saved = f.docs.save_as(info.id, &target).unwrap();
assert_eq!(saved.id, info.id);
assert_eq!(saved.path, target);
assert_eq!(saved.uri, None);
assert_eq!(saved.language, LanguageId::new("rust"));
assert!(!saved.dirty);
assert_eq!(fs::read_to_string(&target).unwrap(), "fn main() {}\n");
assert_eq!(f.docs.by_path(&target), Some(info.id));
assert_eq!(f.docs.by_path(Path::new("untitled:Untitled-1")), None);
f.docs.edit(info.id, version, change(0, 0, "// hi\n")).unwrap();
assert!(f.docs.autosave(info.id).unwrap(), "Save As records the disk state autosave checks");
assert!(!f.docs.is_dirty(info.id).unwrap());
assert_eq!(fs::read_to_string(&target).unwrap(), "// hi\nfn main() {}\n");
// Re-opening the file references the same buffer (split editors share it).
let again = f.docs.open(&target).unwrap();
assert_eq!(again.id, info.id);
f.docs.close(again.id);
assert!(f.docs.snapshot(info.id).is_ok());
f.docs.close(info.id);
assert!(f.docs.snapshot(info.id).is_err());
}
#[test]
fn save_as_copies_dirty_file_without_saving_or_retargeting_source() {
let f = fixture();
let source = f.root.join("source.txt");
fs::write(&source, "saved\n").unwrap();
let info = f.docs.open(&source).unwrap();
let version = f.docs.edit(info.id, info.version, change(0, 0, "dirty ")).unwrap();
assert!(f.docs.is_dirty(info.id).unwrap());
f.rec.log.lock().clear();
let target = f.root.join("nested/copy.txt");
f.docs.copy_as(info.id, &target).unwrap();
assert_eq!(fs::read_to_string(&source).unwrap(), "saved\n");
assert_eq!(fs::read_to_string(&target).unwrap(), "dirty saved\n");
let after = f.docs.snapshot(info.id).unwrap();
assert_eq!(after.id, info.id);
assert_eq!(after.path, source);
assert_eq!(after.version, version);
assert_eq!(after.text, "dirty saved\n");
assert!(after.dirty);
assert_eq!(f.docs.by_path(&source), Some(info.id));
assert_eq!(f.docs.by_path(&target), None, "the copy is opened through the normal document service");
assert!(!f.rec.log.lock().iter().any(|entry| entry.starts_with("save ")));
let copy = f.docs.open(&target).unwrap();
assert_ne!(copy.id, info.id);
assert_eq!(copy.text, "dirty saved\n");
assert!(!copy.dirty);
assert!(f.docs.is_dirty(info.id).unwrap());
}
#[test]
fn save_as_same_path_is_a_noop_and_copy_failures_leave_the_source_unchanged() {
let f = fixture();
let source = f.root.join("source.txt");
fs::write(&source, "saved\n").unwrap();
let info = f.docs.open(&source).unwrap();
f.docs.edit(info.id, info.version, change(0, 0, "dirty ")).unwrap();
fs::create_dir(f.root.join("sub")).unwrap();
// A different spelling of the source must not write its dirty buffer to disk.
assert!(!f.docs.copy_as(info.id, &f.root.join("sub/../source.txt")).unwrap());
assert_eq!(fs::read_to_string(&source).unwrap(), "saved\n");
assert!(f.docs.is_dirty(info.id).unwrap());
let blocked = f.root.join("blocked");
fs::write(&blocked, "not a directory").unwrap();
assert!(f.docs.copy_as(info.id, &blocked.join("copy.txt")).is_err());
assert_eq!(fs::read_to_string(&source).unwrap(), "saved\n");
assert!(f.docs.is_dirty(info.id).unwrap());
let taken = f.root.join("taken.txt");
fs::write(&taken, "taken\n").unwrap();
let other = f.docs.open(&taken).unwrap();
assert!(f.docs.copy_as(info.id, &taken).is_err());
assert_eq!(fs::read_to_string(&taken).unwrap(), "taken\n");
assert_eq!(f.docs.snapshot(other.id).unwrap().text, "taken\n");
}
#[test]
fn save_as_never_replaces_what_exists_at_the_target() {
let f = fixture();
let source = f.root.join("source.txt");
fs::write(&source, "saved\n").unwrap();
let info = f.docs.open(&source).unwrap();
f.docs.edit(info.id, info.version, change(0, 0, "dirty ")).unwrap();
let file = f.root.join("sub/closed.txt");
fs::create_dir(f.root.join("sub")).unwrap();
fs::write(&file, "precious\n").unwrap();
let folder = f.root.join("folder");
fs::create_dir(&folder).unwrap();
for target in [&file, &folder] {
assert_eq!(f.docs.copy_as(info.id, target).unwrap_err().kind, ErrorKind::AlreadyExists);
}
assert_eq!(fs::read_to_string(&file).unwrap(), "precious\n");
assert!(folder.is_dir());
// A link to nowhere is still a name that is taken.
#[cfg(unix)]
{
let link = f.root.join("link.txt");
let missing = f.root.join("missing.txt");
std::os::unix::fs::symlink(&missing, &link).unwrap();
assert_eq!(f.docs.copy_as(info.id, &link).unwrap_err().kind, ErrorKind::AlreadyExists);
assert!(!missing.exists());
}
assert!(f.docs.is_dirty(info.id).unwrap());
}
#[test]
fn a_failed_save_as_leaves_no_file_behind() {
let f = fixture();
let source = f.root.join("source.txt");
fs::write(&source, "saved\n").unwrap();
let info = f.docs.open(&source).unwrap();
f.docs.set_encoding(info.id, "ISO-8859-1", false).unwrap();
f.docs.edit(info.id, info.version, change(0, 0, "中")).unwrap();
let target = f.root.join("copy.txt");
assert!(f.docs.copy_as(info.id, &target).is_err());
assert!(!target.exists());
}
#[test]
fn save_as_rejects_paths_opened_elsewhere_and_reuses_free_names() {
let f = fixture();
let first = f.root.join("taken.txt");
fs::write(&first, "taken").unwrap();
let taken = f.docs.open(&first).unwrap();
let a = f.docs.open_untitled(None).unwrap();
let b = f.docs.open_untitled(None).unwrap();
assert_eq!(a.path, PathBuf::from("untitled:Untitled-1"));
assert_eq!(b.path, PathBuf::from("untitled:Untitled-2"));
f.docs.edit(a.id, a.version, change(0, 0, "draft")).unwrap();
let err = f.docs.save_as(a.id, &first).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput);
assert!(f.docs.is_dirty(a.id).unwrap(), "nothing was written");
assert_eq!(fs::read_to_string(&first).unwrap(), "taken");
let err = f.docs.save_as(a.id, Path::new("untitled:Untitled-2")).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput);
// The smallest free name is minted again after a buffer closes.
f.docs.close(a.id);
let c = f.docs.open_untitled(None).unwrap();
assert_eq!(c.path, PathBuf::from("untitled:Untitled-1"));
// Non-untitled documents cannot be re-keyed.
let err = f.docs.save_as(taken.id, &f.root.join("other.txt")).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput);
}
#[test]
fn untitled_buffers_take_file_defaults_and_refuse_encoding_reloads() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.line_ending = LineEnding::CrLf;
defaults.encoding = "utf-8".into();
defaults.utf8_bom = true;
f.docs.set_file_defaults(defaults);
let info = f.docs.open_untitled(None).unwrap();
assert_eq!(info.line_ending, LineEnding::CrLf);
assert!(info.has_bom);
assert!(!info.can_reload_encoding, "there is no file to re-read yet");
// Converting the encoding of the unsaved text works; re-decoding does not.
let encoding = f.docs.set_encoding(info.id, "utf-16le", false).unwrap();
assert_eq!(encoding.encoding, "utf-16le");
let err = f.docs.set_encoding(info.id, "utf-8", true).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidInput);
// Disk syncs never touch an untitled buffer.
f.docs.edit(info.id, info.version, change(0, 0, "draft")).unwrap();
f.docs.sync_after_disk_change();
assert!(f.docs.is_dirty(info.id).unwrap());
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "draft");
}
/// Previews and diffs show a file in the language opening it gives: from the hashbang of
/// the shown text (a revision's), else of its open buffer or the file on disk.
#[test]
fn language_of_a_closed_file_reads_the_hashbang() {
let tmp = tempfile::tempdir().unwrap();
let sink: SharedSink = Arc::new(|_: IdeEvent| {});
let docs = Documents::new(
sink,
Box::new(|p: &Path, first: Option<&str>| match first {
Some(l) if l.starts_with("#!/usr/bin/env bash") => LanguageId::new("shellscript"),
Some(l) if l.starts_with("#!/usr/bin/env python") => LanguageId::new("python"),
_ if p.extension().is_some_and(|e| e == "sh") => LanguageId::new("shellscript"),
_ => LanguageId::plain_text(),
}),
);
let deploy = tmp.path().join("deploy");
fs::write(&deploy, "#!/usr/bin/env bash\necho hi\n").unwrap();
let language = |first: Option<&str>| docs.language_of(&deploy, first).language.to_string();
assert_eq!(language(None), "shellscript", "the file's own first line");
assert_eq!(language(Some("#!/usr/bin/env python3")), "python", "the shown revision's first line");
assert_eq!(language(Some("echo")), LanguageId::plain_text().to_string());
assert_eq!(docs.language_of(&tmp.path().join("gone"), None).language, LanguageId::plain_text());
let doc = docs.open(&deploy).unwrap();
let all = Range::new(Pos::new(0, 0), Pos::new(0, 19));
docs.apply_edits(doc.id, &[TextEdit { range: all, new_text: "#!/usr/bin/env python3".into() }]).unwrap();
assert_eq!(language(None), "python", "the open buffer's first line");
}
fn latin_project(f: &Fixture) {
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "iso-8859-15".into();
f.docs.set_file_defaults(defaults);
}
#[test]
fn ascii_file_in_a_latin_project_saves_new_characters_in_the_project_encoding() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "iso-8859-15");
f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n");
}
#[test]
fn ascii_file_stays_utf8_when_the_project_encoding_is_utf8() {
let f = fixture();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.edit(doc.id, doc.version, change(0, 0, "// ç\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), "// ç\nclass A {}\n".as_bytes());
}
#[test]
fn utf8_text_with_accents_keeps_utf8_in_a_latin_project() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, "// ação\n").unwrap();
assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8");
}
#[test]
fn typing_a_character_latin9_lacks_into_an_ascii_file_fails_the_save() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
f.docs.edit(doc.id, doc.version, change(0, 0, "// 漢\n")).unwrap();
let before = f.events.lock().len();
let err = f.docs.save(doc.id).expect_err("ISO-8859-15 cannot encode the edit");
assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}");
assert_failed_save_preserves_edit(&f, doc.id, "// 漢\nclass A {}\n", before);
assert_eq!(fs::read(&path).unwrap(), b"class A {}\n");
}
#[test]
fn editorconfig_utf8_charset_wins_over_a_latin_project_for_ascii_files() {
let f = fixture();
latin_project(&f);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes());
}
#[test]
fn ascii_properties_file_stays_utf8_by_default() {
let f = fixture();
let path = f.root.join("messages.properties");
fs::write(&path, b"greeting=Hello\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8", "the properties encoding only decodes bytes that are not UTF-8");
f.docs.edit(doc.id, doc.version, change(9, 14, "Olá")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), "greeting=Olá\n".as_bytes());
}
#[test]
fn latin_properties_file_still_decodes_with_the_properties_encoding() {
let f = fixture();
let path = f.root.join("messages.properties");
fs::write(&path, b"greeting=Ol\xe1\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "windows-1252");
assert_eq!(f.docs.text_of(&path).as_deref(), Some("greeting=Olá\n"));
}
#[test]
fn editorconfig_charset_leaves_a_bomless_utf16_file_alone() {
let f = fixture();
fs::write(f.root.join(".editorconfig"), "root = true\n[*.txt]\ncharset = latin1\n").unwrap();
let path = f.root.join("a.txt");
fs::write(&path, b"a\x00b\x00c\x00d\x00").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-16le");
f.docs.edit(doc.id, doc.version, change(4, 4, "e")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"a\x00b\x00c\x00d\x00e\x00");
}
#[test]
fn an_external_change_keeps_the_editorconfig_charset_of_an_ascii_file() {
let f = fixture();
latin_project(&f);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&path, b"class B {}\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class B {}\n", "utf-8"));
}
#[test]
fn editorconfig_charset_applies_to_a_native_to_ascii_properties_file() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.native_to_ascii = true;
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = latin1\n").unwrap();
let path = f.root.join("messages.properties");
fs::write(&path, b"greeting=Ol\\u00e1\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "windows-1252", "the escapes are ASCII bytes");
assert_eq!(f.docs.text_of(&path).as_deref(), Some("greeting=Olá\n"));
}
/// Undoing back to the text on disk leaves the document clean (as in IntelliJ);
/// redo, a save in between, or a pending line-ending change make it modified again.
#[test]
fn undo_back_to_the_disk_text_leaves_the_document_clean() {
let f = fixture();
let path = f.root.join("undo.txt");
fs::write(&path, "alpha\n").unwrap();
let id = f.docs.open(&path).unwrap().id;
let v = f.docs.edit(id, 0, change(0, 0, "x")).unwrap();
assert!(f.docs.is_dirty(id).unwrap());
let v = f.docs.edit(id, v, change(0, 1, "")).unwrap();
assert!(!f.docs.is_dirty(id).unwrap(), "undo back to the disk text");
let v = f.docs.edit(id, v, change(0, 0, "x")).unwrap();
assert!(f.docs.is_dirty(id).unwrap(), "redo");
assert_eq!(dirty_events(&f.events.lock()), vec![true, false, true]);
// After saving "xalpha", undoing to "alpha" differs from the file again.
f.docs.save(id).unwrap();
let v = f.docs.edit(id, v, change(0, 1, "")).unwrap();
assert!(f.docs.is_dirty(id).unwrap(), "undo past a save");
let v = f.docs.edit(id, v, change(0, 0, "x")).unwrap();
assert!(!f.docs.is_dirty(id).unwrap(), "redo back to the saved text");
// A pending line-ending change is written on save whatever the text.
f.docs.set_line_ending(id, LineEnding::CrLf).unwrap();
let v = f.docs.edit(id, v, change(0, 0, "y")).unwrap();
f.docs.edit(id, v, change(0, 1, "")).unwrap();
assert!(f.docs.is_dirty(id).unwrap(), "line ending still differs from the file");
}
#[test]
fn undo_clean_snapshot_keeps_its_file_byte_limit_when_code_insight_changes() {
// UTF-16 source bytes determine the snapshot budget, even when the rope is smaller.
for (insight_limit, units, expect_clean) in [(1, 1024 * 1024, true), (50, 5 * 1024 * 1024 / 2, false)] {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.max_code_insight_bytes = insight_limit * 1024 * 1024;
f.docs.set_file_defaults(defaults);
let path = f.root.join("undo.txt");
let bytes = ide_vfs::encode(&"x".repeat(units), "utf-16le", true).unwrap();
fs::write(&path, bytes).unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.large, expect_clean);
let undo = |version| {
let version = f.docs.edit(doc.id, version, change(0, 0, "a")).unwrap();
let version = f.docs.edit(doc.id, version, change(0, 1, "")).unwrap();
assert_eq!(!f.docs.is_dirty(doc.id).unwrap(), expect_clean);
version
};
let version = undo(doc.version);
let version = f.docs.edit(doc.id, version, change(0, 0, "b")).unwrap();
f.docs.save(doc.id).unwrap();
undo(version);
f.docs.discard_and_reload(doc.id).unwrap();
undo(f.docs.snapshot(doc.id).unwrap().version);
}
}
/// A buffer undone back to the disk text follows a checkout instead of warning about it.
#[test]
fn undo_back_to_the_disk_text_reloads_on_checkout() {
let f = fixture();
let path = f.root.join("undo.txt");
fs::write(&path, "alpha\n").unwrap();
let id = f.docs.open(&path).unwrap().id;
let v = f.docs.edit(id, 0, change(0, 0, "x")).unwrap();
f.docs.edit(id, v, change(0, 1, "")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
fs::write(&path, "checked out\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(id).unwrap().text, "checked out\n");
}
fn project_encoding(f: &Fixture, label: &str) {
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = label.into();
f.docs.set_file_defaults(defaults);
}
fn latin9_editorconfig(f: &Fixture) {
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
}
#[test]
fn editorconfig_charset_applies_to_an_existing_ascii_file_over_the_project_encoding() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "iso-8859-15");
f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n");
}
#[test]
fn editorconfig_charset_decodes_a_legacy_file_over_the_project_encoding() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
let bytes = b"// a\xe7\xe3o \xa4\n";
fs::write(&path, bytes).unwrap();
assert_eq!(f.docs.detect_encoding(&path, bytes), encoding_rs::ISO_8859_15);
for loaded in [f.docs.load_file(&path).unwrap(), f.docs.load_file_bounded(&path, 1024).unwrap()] {
assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
#[test]
fn editorconfig_charset_survives_a_reload_from_disk() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
fs::write(&path, b"class A { int changed; }\n").unwrap();
f.docs.sync_from_disk();
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "iso-8859-15"));
}
#[test]
fn editorconfig_without_a_usable_charset_leaves_the_encoding_alone() {
let open = |project: Option<&str>, editorconfig: &str, enabled: bool| {
let f = fixture();
let mut defaults = f.docs.file_defaults();
if let Some(project) = project {
defaults.project_fallback = project.into();
}
defaults.editorconfig = enabled;
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), format!("root = true\n[*.java]\n{editorconfig}\n")).unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
f.docs.open(&path).unwrap().encoding
};
assert_eq!(open(None, "indent_size = 2", true), "utf-8", "nothing configured");
assert_eq!(open(None, "charset = ebcdic", true), "utf-8", "unknown charset");
assert_eq!(open(Some("iso-8859-15"), "indent_size = 2", true), "iso-8859-15", "no charset: the project's");
assert_eq!(open(Some("iso-8859-15"), "charset = ebcdic", true), "iso-8859-15", "unknown charset: the project's");
assert_eq!(open(Some("iso-8859-15"), "charset = gbk", false), "iso-8859-15", "EditorConfig support is off");
assert_eq!(open(Some("iso-8859-15"), "charset = utf-16le", true), "iso-8859-15", "UTF-16 is detected, not assumed");
}
#[test]
fn utf16_text_without_a_bom_keeps_utf16_under_a_utf8_charset() {
let f = fixture();
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, ide_vfs::encode("class A {}\n", "utf-16le", false).unwrap()).unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("class A {}\n", "utf-16le"));
}
#[test]
fn valid_utf8_text_keeps_utf8_under_a_legacy_charset() {
let f = fixture();
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, "// ação\n").unwrap();
assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8");
}
#[test]
fn editorconfig_utf8_charset_survives_a_reload_from_disk() {
let f = fixture();
latin_project(&f);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
fs::write(&path, b"class A { int changed; }\n").unwrap();
f.docs.sync_from_disk();
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "utf-8"));
}
#[test]
fn editorconfig_charset_wins_over_the_properties_encoding() {
let f = fixture();
fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = iso-8859-15\n").unwrap();
let path = f.root.join("messages.properties");
fs::write(&path, b"price=10 \xa4\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("price=10 €\n", "iso-8859-15"));
assert_eq!(f.docs.detect_encoding(&path, b"price=10\n"), encoding_rs::ISO_8859_15);
assert_eq!(f.docs.detect_encoding(&f.root.join("unmatched.txt"), b"price=10\n"), encoding_rs::UTF_8);
}
#[test]
fn switching_editorconfig_support_off_stops_the_charset_on_reload() {
let f = fixture();
project_encoding(&f, "gbk");
latin9_editorconfig(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
let doc = f.docs.open(&path).unwrap();
let mut defaults = f.docs.file_defaults();
defaults.editorconfig = false;
f.docs.set_file_defaults(defaults);
fs::write(&path, b"class A { int changed; }\n").unwrap();
f.docs.sync_from_disk();
assert_eq!(f.docs.snapshot(doc.id).unwrap().encoding, "gbk");
}
#[test]
fn a_file_declared_utf8_that_is_not_utf8_is_decoded_with_the_project_encoding() {
let f = fixture();
latin_project(&f);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
let path = f.root.join("A.java");
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
/// `[editor.encodings.mappings]` as the host hands it over: project paths with their labels.
fn encoding_mappings(f: &Fixture, entries: &[(&str, &str)]) {
let mut defaults = f.docs.file_defaults();
defaults.mappings = entries.iter().map(|(rel, label)| (in_root(f, rel), (*label).to_owned())).collect();
f.docs.set_file_defaults(defaults);
}
fn in_root(f: &Fixture, rel: &str) -> PathBuf {
rel.split('/').fold(f.root.clone(), |path, segment| path.join(segment))
}
#[test]
fn encoding_mapping_of_a_file_survives_closing_and_reopening_it() {
let f = fixture();
let path = f.root.join("A.java");
fs::write(&path, "// ação\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.set_encoding(doc.id, "iso-8859-15", true).unwrap();
let chosen = f.docs.snapshot(doc.id).unwrap();
assert_eq!(chosen.text, "// ação\n");
f.docs.close(doc.id);
encoding_mappings(&f, &[("A.java", "iso-8859-15")]);
let reopened = f.docs.open(&path).unwrap();
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", chosen.text.as_str()));
// A later change on disk is read in the remembered encoding too.
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reloaded = f.docs.snapshot(reopened.id).unwrap();
assert_eq!((reloaded.encoding.as_str(), reloaded.text.as_str()), ("iso-8859-15", "// ação €\n"));
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "iso-8859-15", "closed-file readers agree");
}
#[test]
fn encoding_mapping_of_a_file_to_utf8_holds_in_a_latin_project() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
encoding_mappings(&f, &[("A.java", "utf-8")]);
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap();
f.docs.save(doc.id).unwrap();
assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes());
}
#[test]
fn encoding_mapping_of_a_file_beats_editorconfig_and_a_folder_mapping_loses_to_it() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\nend_of_line = crlf\n").unwrap();
fs::create_dir(f.root.join("src")).unwrap();
for name in ["src/A.java", "src/B.java", "src/notes.txt", "other.txt"] {
fs::write(in_root(&f, name), b"plain ascii\n").unwrap();
}
fs::write(in_root(&f, "src/new.txt"), b"").unwrap();
fs::write(in_root(&f, "src/latin.txt"), b"a\xe7\xe3o \xa4\n").unwrap();
encoding_mappings(&f, &[("src", "iso-8859-15"), ("src/A.java", "koi8-r")]);
let open = |name: &str| f.docs.open(&in_root(&f, name)).unwrap();
let file = open("src/A.java");
assert_eq!(file.encoding, "koi8-r", "the file's own mapping beats .editorconfig");
assert_eq!(file.line_ending, LineEnding::CrLf, ".editorconfig still sets the rest");
assert_eq!(open("src/B.java").encoding, "windows-1252", ".editorconfig beats the folder mapping");
assert_eq!(open("src/notes.txt").encoding, "iso-8859-15", "the folder mapping beats the project encoding");
assert_eq!(open("src/new.txt").encoding, "iso-8859-15", "a new file takes its folder's encoding");
assert_eq!(open("other.txt").encoding, "gbk");
let latin = open("src/latin.txt");
assert_eq!((latin.encoding.as_str(), latin.text.as_str()), ("iso-8859-15", "ação €\n"));
}
#[test]
fn encoding_mapping_of_a_folder_is_left_out_where_editorconfig_sets_the_charset() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\n").unwrap();
fs::create_dir(f.root.join("src")).unwrap();
let path = in_root(&f, "src/B.java");
fs::write(&path, b"// \xd6\xd0\n").unwrap();
let unmapped = f.docs.open(&path).unwrap();
f.docs.close(unmapped.id);
encoding_mappings(&f, &[("src", "koi8-r")]);
let mapped = f.docs.open(&path).unwrap();
assert_eq!((mapped.encoding, mapped.text), (unmapped.encoding, unmapped.text));
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "windows-1252", "closed-file readers agree");
}
#[test]
fn encoding_mapping_a_file_no_longer_decodes_in_falls_back_to_detection() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"// a\xe7\xe3o\n").unwrap();
encoding_mappings(&f, &[("A.java", "utf-8")]);
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.encoding.as_str(), doc.text.as_str()), ("iso-8859-15", "// ação\n"));
}
#[test]
fn without_encoding_mappings_files_open_as_before() {
let f = fixture();
let settings = ide_core::settings::Settings::default();
f.docs.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&f.root)));
assert!(f.docs.file_defaults().mappings.is_empty());
for (name, bytes) in [
("ascii.java", &b"class A {}\n"[..]),
("utf8.java", "// ação\n".as_bytes()),
("latin.java", &b"// a\xe7\xe3o de gra\xe7a, cora\xe7\xe3o\n"[..]),
("empty.java", &b""[..]),
] {
let path = f.root.join(name);
fs::write(&path, bytes).unwrap();
let detected = ide_vfs::load_text(&path).unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.encoding, doc.text), (detected.encoding, detected.text), "{name}");
}
}
fn disk_conflicts(f: &Fixture, path: &Path) -> usize {
let path = path.to_string_lossy();
f.events.lock().iter().filter(|e| matches!(e, IdeEvent::DocDiskConflict { path: p, .. } if *p == path)).count()
}
#[test]
fn a_file_replaced_by_binary_content_keeps_its_text_and_reports_the_change() {
// Valid UTF-8 and windows-1252, so only the binary check can tell it apart from text.
let binary = b"\x7FELF\x02\x01\x01\x00\x00\x00binary\x00".to_vec();
let mut failures = Vec::new();
for case in ["chosen", "remembered", "remembered, not text on open", "ide operation"] {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"caf\xe9\n").unwrap();
match case {
"remembered" => encoding_mappings(&f, &[("notes.txt", "windows-1252")]),
// The file is not UTF-8, so it opens detected; reloads still try the mapping first.
"remembered, not text on open" => encoding_mappings(&f, &[("notes.txt", "utf-8")]),
_ => {}
}
let doc = f.docs.open(&path).unwrap();
if case == "chosen" {
f.docs.set_encoding(doc.id, "windows-1252", true).unwrap();
}
let before = f.docs.snapshot(doc.id).unwrap();
fs::write(&path, &binary).unwrap();
if case == "ide operation" {
f.docs.sync_after_disk_change();
} else {
f.docs.on_disk_changed(std::slice::from_ref(&path));
}
let after = f.docs.snapshot(doc.id).unwrap();
// The same disk state again, through every sync path: reported once.
f.docs.on_disk_changed(std::slice::from_ref(&path));
f.docs.sync_after_disk_change();
f.docs.sync_from_disk();
let conflicts = disk_conflicts(&f, &path);
f.docs.edit(doc.id, after.version, change(0, 0, "x")).unwrap();
let autosaved = f.docs.autosave(doc.id).unwrap();
let on_disk = fs::read(&path).unwrap();
if after.text != before.text || after.dirty || conflicts != 1 || autosaved || on_disk != binary {
failures.push(format!(
"{case}: text {:?} dirty {} conflicts {conflicts} autosaved {autosaved} disk kept {}",
after.text,
after.dirty,
on_disk == binary
));
}
}
assert!(failures.is_empty(), "{failures:#?}");
}
#[test]
fn nul_bytes_written_under_a_chosen_encoding_are_reported_and_can_be_loaded() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "key=value\n").unwrap();
let doc = f.docs.open(&path).unwrap();
f.docs.set_encoding(doc.id, "windows-1252", true).unwrap();
fs::write(&path, b"key\0value\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "key=value\n");
assert_eq!(disk_conflicts(&f, &path), 1);
f.docs.discard_and_reload(doc.id).unwrap();
let loaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!((loaded.text.as_str(), loaded.dirty), ("key\0value\n", false));
}
#[test]
fn a_utf16_document_reloads_mostly_non_ascii_text_without_a_bom() {
let utf16 = |text: &str| text.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>();
// A NUL byte outside the ASCII-heavy UTF-16 pattern: the head check alone calls it binary.
let (first, changed) = (utf16("plain 中文\n"), utf16("中文中文中文\n"));
assert!(ide_vfs::looks_binary(&changed));
for remembered in [false, true] {
let f = fixture();
let path = f.root.join("wide.txt");
fs::write(&path, &first).unwrap();
if remembered {
encoding_mappings(&f, &[("wide.txt", "utf-16le")]);
}
let doc = f.docs.open(&path).unwrap();
if remembered {
assert_eq!(doc.text, "plain 中文\n");
} else {
f.docs.set_encoding(doc.id, "utf-16le", true).unwrap();
}
fs::write(&path, &changed).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reloaded = f.docs.snapshot(doc.id).unwrap();
assert_eq!(
(reloaded.text.as_str(), reloaded.encoding.as_str()),
("中文中文中文\n", "utf-16le"),
"{remembered}"
);
}
}
#[test]
fn a_file_opened_as_text_despite_nul_bytes_keeps_reloading() {
let f = fixture();
let path = f.root.join("dump.txt");
fs::write(&path, b"key\0value\n").unwrap();
encoding_mappings(&f, &[("dump.txt", "windows-1252")]);
assert!(ide_vfs::looks_binary(b"key\0other value\n"));
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.text, "key\0value\n");
fs::write(&path, b"key\0other value\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "key\0other value\n");
assert_eq!(disk_conflicts(&f, &path), 0);
}
#[test]
fn a_detected_text_file_replaced_by_binary_content_is_reported_and_not_autosaved() {
let binary = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00".to_vec();
let mut failures = Vec::new();
for dirty in [false, true] {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "hello\n").unwrap();
let doc = f.docs.open(&path).unwrap();
if dirty {
f.docs.edit(doc.id, doc.version, change(0, 0, "x")).unwrap();
}
let before = f.docs.snapshot(doc.id).unwrap();
fs::write(&path, &binary).unwrap();
// The file watcher's path, as the editor sees it: reported on the first event, and
// the next edit is not autosaved over the file.
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reported = disk_conflicts(&f, &path);
let after = f.docs.snapshot(doc.id).unwrap();
f.docs.edit(doc.id, after.version, change(0, 0, "y")).unwrap();
let autosaved = f.docs.autosave(doc.id).unwrap();
let on_disk = fs::read(&path).unwrap();
// The same disk state again, through every sync path: reported once.
f.docs.on_disk_changed(std::slice::from_ref(&path));
f.docs.sync_after_disk_change();
f.docs.sync_from_disk();
let conflicts = disk_conflicts(&f, &path);
if after.text != before.text || reported != 1 || conflicts != 1 || autosaved || on_disk != binary {
failures.push(format!(
"dirty {dirty}: text {:?} reported {reported} conflicts {conflicts} autosaved {autosaved} disk kept {}",
after.text,
on_disk == binary
));
}
}
assert!(failures.is_empty(), "{failures:#?}");
}
/// A file deleted outside the editor is not recreated by an autosave.
#[test]
fn autosave_does_not_recreate_a_deleted_file() {
let f = fixture();
let path = f.root.join("gone.txt");
fs::write(&path, "old\n").unwrap();
let id = f.docs.open(&path).unwrap().id;
f.docs.edit(id, 0, change(0, 0, "x")).unwrap();
fs::remove_file(&path).unwrap();
let _ = f.docs.autosave(id);
assert!(!path.exists());
assert!(f.docs.is_dirty(id).unwrap());
// Saving it explicitly recreates it.
f.docs.save(id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "xold\n");
}
/// The refused autosave reports the same conflict as an external write, and autosave works
/// again once the user has saved the file back.
#[test]
fn a_deleted_file_is_reported_as_a_disk_conflict_until_saved() {
let f = fixture();
let path = f.root.join("gone.txt");
fs::write(&path, "old\n").unwrap();
let id = f.docs.open(&path).unwrap().id;
f.docs.edit(id, 0, change(0, 0, "x")).unwrap();
fs::remove_file(&path).unwrap();
assert!(!f.docs.autosave(id).unwrap());
assert!(!f.docs.autosave(id).unwrap());
assert!(!path.exists());
assert_eq!(
f.events.lock().iter().filter(|e| matches!(e, IdeEvent::DocDiskConflict { doc, .. } if *doc == id)).count(),
1
);
f.docs.save(id).unwrap();
f.docs.edit(id, 1, change(0, 0, "y")).unwrap();
assert!(f.docs.autosave(id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "yxold\n");
}