//! Chunk commands (C8 C3) through the engine against real temp //! repositories: `git.chunks` of an edited, unsaved buffer, staging and //! unstaging one chunk (with `gitChanged`), reverting one as an unsaved //! buffer edit, and the refusal of a stale token. Skips with a message //! when git is not installed. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing )] use std::path::Path; use std::process::Command; use std::sync::Mutex; use lutra_engine::{Engine, EngineError, Event, run_waiting}; use serde_json::{Value, json}; /// Whether git is installed; prints why a test is skipped. fn have_git() -> bool { let ok = Command::new("git") .arg("--version") .output() .is_ok_and(|o| o.status.success()); if !ok { eprintln!("skipped: git is not installed"); } ok } /// Runs git for test setup and returns its output. fn git(dir: &Path, args: &[&str]) -> String { let out = Command::new("git") .args(args) .current_dir(dir) .output() .unwrap(); assert!( out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8(out.stdout).unwrap() } /// A repository with `a.php` committed as `text`. fn repo(dir: &Path, text: &str) { git(dir, &["init", "-q", "-b", "main"]); for (key, value) in [ ("user.name", "Lutra Test"), ("user.email", "test@lutra.invalid"), ("commit.gpgsign", "false"), ("core.autocrlf", "false"), ("core.hooksPath", ".git/hooks"), ] { git(dir, &["config", key, value]); } std::fs::write(dir.join("a.php"), text).unwrap(); git(dir, &["add", "-A"]); git(dir, &["commit", "-q", "-m", "base"]); } /// An engine behind a lock, like a host, recording every event. struct Host { /// The engine. engine: Mutex, /// Events published so far. events: Mutex>, } impl Host { /// An engine with `root` open as the project. fn open(root: &Path) -> Self { let host = Self { engine: Mutex::new(Engine::new().unwrap()), events: Mutex::new(Vec::new()), }; host.run("project.open", json!({"path": root})).unwrap(); host } /// Runs a command the way hosts do, waiting without the lock. fn run(&self, command: &str, params: Value) -> Result { run_waiting( || self.engine.lock().unwrap(), command, params, |events| self.events.lock().unwrap().extend_from_slice(events), ) .map(|o| o.value) } /// Takes the number of `gitChanged` events seen so far. fn git_changes(&self) -> usize { let mut events = self.events.lock().unwrap(); let count = events .iter() .filter(|e| matches!(e, Event::GitChanged(_))) .count(); events.clear(); count } /// Replaces the whole text of buffer `id`. fn set_text(&self, id: u64, text: &str) { let current = self.run("buffer.get", json!({"id": id})).unwrap(); let len = current["text"].as_str().unwrap().encode_utf16().count(); self.run( "buffer.edit", json!({ "id": id, "baseVersion": current["version"], "edits": [{"from": 0, "to": len, "insert": text}], }), ) .unwrap(); } /// The text of buffer `id`. fn text(&self, id: u64) -> String { self.run("buffer.get", json!({"id": id})).unwrap()["text"] .as_str() .unwrap() .to_string() } } /// Ten numbered lines. const TEN: &str = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"; #[test] fn stages_unstages_and_reverts_chunks_of_an_unsaved_buffer() { if !have_git() { return; } let dir = tempfile::tempdir().unwrap(); repo(dir.path(), TEN); let host = Host::open(dir.path()); let id = host.run("file.open", json!({"path": "a.php"})).unwrap()["id"] .as_u64() .unwrap(); host.set_text(id, "1\ntwo\n3\n4\n5\n6\n7\n8\nnine\n10\n"); let chunks = host.run("git.chunks", json!({"id": id})).unwrap(); assert_eq!(chunks["unstaged"].as_array().unwrap().len(), 2); assert_eq!( chunks["unstaged"][1], json!({ "kind": "modified", "startLine": 8, "endLine": 9, "oldStart": 8, "oldEnd": 9, "newStart": 8, "newEnd": 9, "removed": ["9"], "added": ["nine"], "truncated": false, }) ); let token = chunks["token"].clone(); host.git_changes(); host.run( "git.stageChunk", json!({"id": id, "index": 1, "token": token}), ) .unwrap(); assert_eq!(host.git_changes(), 1); assert_eq!( git(dir.path(), &["show", ":0:a.php"]), "1\n2\n3\n4\n5\n6\n7\n8\nnine\n10\n" ); assert_eq!( std::fs::read_to_string(dir.path().join("a.php")).unwrap(), TEN ); let stale = host.run( "git.stageChunk", json!({"id": id, "index": 0, "token": token}), ); assert!( matches!(&stale, Err(EngineError::Failed(m)) if m.contains("changed since")), "{stale:?}" ); let chunks = host.run("git.chunks", json!({"id": id})).unwrap(); assert_eq!(chunks["staged"][0]["startLine"], 8); let token = chunks["token"].clone(); let reverted = host .run( "git.revertChunk", json!({"id": id, "index": 0, "token": token}), ) .unwrap(); assert_eq!(reverted["dirty"], true); assert_eq!(host.text(id), "1\n2\n3\n4\n5\n6\n7\n8\nnine\n10\n"); let chunks = host.run("git.chunks", json!({"id": id})).unwrap(); assert!(chunks["unstaged"].as_array().unwrap().is_empty()); host.run( "git.unstageChunk", json!({"id": id, "index": 0, "token": chunks["token"]}), ) .unwrap(); assert_eq!(git(dir.path(), &["show", ":0:a.php"]), TEN); } #[test] fn refuses_unknown_buffers_and_bad_params() { if !have_git() { return; } let dir = tempfile::tempdir().unwrap(); repo(dir.path(), TEN); let host = Host::open(dir.path()); assert!(matches!( host.run("git.chunks", json!({"id": 999})), Err(EngineError::Failed(_)) )); assert!(matches!( host.run("git.stageChunk", json!({"id": 1})), Err(EngineError::InvalidParams { .. }) )); assert!(matches!( host.run( "git.stageChunk", json!({"id": 1, "index": 0, "token": "x".repeat(65)}) ), Err(EngineError::InvalidParams { .. }) )); }