- Disk conflicts per buffer (changed / removed), reported in buffer.get as diskConflict; diskConflictResolved when settled. - Every watcher event only means "look again": delete + create (git checkout, atomic saves) reloads instead of losing the buffer; a file that disappears keeps its buffer as unsaved. - file.save checks mtime + hash and fails with disk_changed instead of overwriting a newer file (overwrite: true after asking); saveAll lists such buffers under diskChanged. New file.reload and file.readDisk. - Local History store in the data dir (content-addressed SHA-256 blobs, index.jsonl, 14 days / 200 MB, pruned on open); snapshots on save, before reloads, on deletion, before lsp.rename and file-changing git commands. Commands history.list / history.read / history.revert. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
8.1 KiB
Rust
260 lines
8.1 KiB
Rust
//! Local History (C10 A2) through the engine: snapshots on save, reload,
|
|
//! deletion and revert, stored in the data directory, never in the project.
|
|
|
|
#![allow(
|
|
clippy::unwrap_used,
|
|
clippy::expect_used,
|
|
clippy::panic,
|
|
clippy::indexing_slicing
|
|
)]
|
|
|
|
use std::fs;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use lutra_engine::{Engine, EngineConfig, Event, Outcome};
|
|
use serde_json::{Value, json};
|
|
use tempfile::TempDir;
|
|
|
|
/// A project folder, a data directory and an engine with that project open.
|
|
struct Fixture {
|
|
project: TempDir,
|
|
data: TempDir,
|
|
_config: TempDir,
|
|
engine: Engine,
|
|
}
|
|
|
|
fn fixture(files: &[(&str, &str)]) -> Fixture {
|
|
let project = tempfile::tempdir().unwrap();
|
|
for (path, text) in files {
|
|
fs::write(project.path().join(path), text).unwrap();
|
|
}
|
|
let data = tempfile::tempdir().unwrap();
|
|
let config = tempfile::tempdir().unwrap();
|
|
let mut engine = Engine::with_config(EngineConfig {
|
|
config_dir: config.path().to_path_buf(),
|
|
data_dir: data.path().to_path_buf(),
|
|
})
|
|
.unwrap();
|
|
engine
|
|
.execute("project.open", json!({"path": project.path()}))
|
|
.unwrap();
|
|
Fixture {
|
|
project,
|
|
data,
|
|
_config: config,
|
|
engine,
|
|
}
|
|
}
|
|
|
|
fn run(engine: &mut Engine, command: &str, params: Value) -> Outcome {
|
|
engine
|
|
.execute(command, params)
|
|
.unwrap_or_else(|e| panic!("{command} failed: {e}"))
|
|
}
|
|
|
|
fn open(engine: &mut Engine, path: &str) -> u64 {
|
|
run(engine, "file.open", json!({"path": path})).value["id"]
|
|
.as_u64()
|
|
.unwrap()
|
|
}
|
|
|
|
fn replace(engine: &mut Engine, id: u64, text: &str) {
|
|
let now = run(engine, "buffer.get", json!({"id": id})).value;
|
|
let len = now["text"].as_str().unwrap().encode_utf16().count();
|
|
run(
|
|
engine,
|
|
"buffer.edit",
|
|
json!({"id": id, "baseVersion": now["version"], "edits": [{"from": 0, "to": len, "insert": text}]}),
|
|
);
|
|
}
|
|
|
|
/// `(reason, text)` of every entry of `path`, newest first.
|
|
fn entries(engine: &mut Engine, path: &str) -> Vec<(String, String)> {
|
|
let list = run(engine, "history.list", json!({"path": path})).value;
|
|
list["entries"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|e| {
|
|
let text =
|
|
run(engine, "history.read", json!({"path": path, "id": e["id"]})).value["text"]
|
|
.as_str()
|
|
.unwrap()
|
|
.to_string();
|
|
(e["reason"].as_str().unwrap().to_string(), text)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn pair(reason: &str, text: &str) -> (String, String) {
|
|
(reason.to_string(), text.to_string())
|
|
}
|
|
|
|
fn wait_for(engine: &mut Engine, pred: impl Fn(&Event) -> bool) {
|
|
let deadline = Instant::now() + Duration::from_secs(5);
|
|
while Instant::now() < deadline {
|
|
if engine.pump_vfs().unwrap().iter().any(&pred) {
|
|
return;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(25));
|
|
}
|
|
panic!("event not seen within 5 s");
|
|
}
|
|
|
|
#[test]
|
|
fn saves_keep_the_original_and_every_saved_text() {
|
|
let mut f = fixture(&[("a.php", "original")]);
|
|
let id = open(&mut f.engine, "a.php");
|
|
replace(&mut f.engine, id, "first");
|
|
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
replace(&mut f.engine, id, "second");
|
|
run(&mut f.engine, "file.saveAll", json!({}));
|
|
assert_eq!(
|
|
entries(&mut f.engine, "a.php"),
|
|
vec![
|
|
pair("save", "second"),
|
|
pair("save", "first"),
|
|
pair("beforeSave", "original"),
|
|
],
|
|
"a save of an unchanged text adds nothing"
|
|
);
|
|
let list = run(&mut f.engine, "history.list", json!({"path": "a.php"})).value;
|
|
let entry = &list["entries"][0];
|
|
assert!(entry["time"].as_u64().unwrap() > 0);
|
|
assert_eq!(entry["size"], 6);
|
|
}
|
|
|
|
#[test]
|
|
fn the_history_lives_in_the_data_dir_and_survives_a_reopen() {
|
|
let mut f = fixture(&[("a.php", "one")]);
|
|
let id = open(&mut f.engine, "a.php");
|
|
replace(&mut f.engine, id, "two");
|
|
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
let names: Vec<String> = fs::read_dir(f.project.path())
|
|
.unwrap()
|
|
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
|
.collect();
|
|
assert_eq!(
|
|
names,
|
|
vec!["a.php".to_string()],
|
|
"nothing inside the project"
|
|
);
|
|
assert!(f.data.path().join("history").is_dir());
|
|
run(
|
|
&mut f.engine,
|
|
"project.open",
|
|
json!({"path": f.project.path()}),
|
|
);
|
|
assert_eq!(entries(&mut f.engine, "a.php").len(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn reloads_and_deletions_keep_the_buffers_text() {
|
|
let mut f = fixture(&[("a.php", "mine")]);
|
|
let id = open(&mut f.engine, "a.php");
|
|
replace(&mut f.engine, id, "unsaved");
|
|
fs::write(f.project.path().join("a.php"), "theirs").unwrap();
|
|
wait_for(&mut f.engine, |e| {
|
|
matches!(e, Event::FileChangedOnDisk { removed: false, .. })
|
|
});
|
|
run(&mut f.engine, "file.reload", json!({"id": id}));
|
|
assert_eq!(
|
|
entries(&mut f.engine, "a.php"),
|
|
vec![
|
|
pair("beforeReload", "unsaved"),
|
|
pair("externalChange", "theirs")
|
|
]
|
|
);
|
|
fs::remove_file(f.project.path().join("a.php")).unwrap();
|
|
wait_for(&mut f.engine, |e| {
|
|
matches!(e, Event::FileChangedOnDisk { removed: true, .. })
|
|
});
|
|
assert_eq!(
|
|
entries(&mut f.engine, "a.php")[0],
|
|
pair("deleted", "theirs")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn revert_edits_the_buffer_and_keeps_what_it_replaced() {
|
|
let mut f = fixture(&[("a.php", "one")]);
|
|
let id = open(&mut f.engine, "a.php");
|
|
replace(&mut f.engine, id, "two");
|
|
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
replace(&mut f.engine, id, "three, unsaved");
|
|
let list = run(&mut f.engine, "history.list", json!({"path": "a.php"})).value;
|
|
let original = list["entries"][1]["id"].clone();
|
|
let out = run(
|
|
&mut f.engine,
|
|
"history.revert",
|
|
json!({"path": "a.php", "id": original}),
|
|
);
|
|
assert_eq!(out.value["id"], id);
|
|
assert_eq!(out.value["dirty"], true, "an ordinary, unsaved edit");
|
|
assert!(
|
|
out.events
|
|
.iter()
|
|
.any(|e| matches!(e, Event::BufferChanged { id: got, .. } if *got == id))
|
|
);
|
|
let now = run(&mut f.engine, "buffer.get", json!({"id": id})).value;
|
|
assert_eq!(now["text"], "one");
|
|
assert_eq!(
|
|
fs::read_to_string(f.project.path().join("a.php")).unwrap(),
|
|
"two"
|
|
);
|
|
assert_eq!(
|
|
entries(&mut f.engine, "a.php")[0],
|
|
pair("beforeRevert", "three, unsaved")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn revert_opens_a_closed_file() {
|
|
let mut f = fixture(&[("a.php", "one")]);
|
|
let id = open(&mut f.engine, "a.php");
|
|
replace(&mut f.engine, id, "two");
|
|
run(&mut f.engine, "file.save", json!({"id": id}));
|
|
run(&mut f.engine, "buffer.close", json!({"id": id}));
|
|
let list = run(&mut f.engine, "history.list", json!({"path": "a.php"})).value;
|
|
let out = run(
|
|
&mut f.engine,
|
|
"history.revert",
|
|
json!({"path": "a.php", "id": list["entries"][1]["id"]}),
|
|
);
|
|
let new_id = out.value["id"].as_u64().unwrap();
|
|
assert!(
|
|
out.events
|
|
.iter()
|
|
.any(|e| matches!(e, Event::BufferOpened { id, .. } if *id == new_id))
|
|
);
|
|
let now = run(&mut f.engine, "buffer.get", json!({"id": new_id})).value;
|
|
assert_eq!(now["text"], "one");
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_entries_and_projects_without_history_fail_clearly() {
|
|
let mut f = fixture(&[("a.php", "one")]);
|
|
let err = f
|
|
.engine
|
|
.execute("history.read", json!({"path": "a.php", "id": 99}))
|
|
.unwrap_err();
|
|
assert_eq!(err.code(), "failed");
|
|
assert!(
|
|
err.to_string().contains("no Local History entry 99"),
|
|
"{err}"
|
|
);
|
|
assert_eq!(
|
|
run(&mut f.engine, "history.list", json!({"path": "a.php"})).value["entries"],
|
|
json!([])
|
|
);
|
|
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let mut bare = Engine::new().unwrap();
|
|
bare.execute("project.open", json!({"path": dir.path()}))
|
|
.unwrap();
|
|
let err = bare
|
|
.execute("history.list", json!({"path": "a.php"}))
|
|
.unwrap_err();
|
|
assert!(err.to_string().contains("not available"), "{err}");
|
|
}
|