//! Workspace commands and events against real folders in temp directories. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing )] use std::fs; use std::path::Path; use std::time::{Duration, Instant}; use lutra_engine::{Command, CommandSpec, Engine, EngineError, Event, Outcome, State}; use serde_json::{Value, json}; use tempfile::TempDir; /// A temp folder with a few files, opened in a fresh engine. fn open_project(files: &[(&str, &[u8])]) -> (TempDir, Engine, Vec) { let dir = tempfile::tempdir().unwrap(); for (path, bytes) in files { let abs = dir.path().join(path); fs::create_dir_all(abs.parent().unwrap()).unwrap(); fs::write(abs, bytes).unwrap(); } let mut engine = Engine::new().unwrap(); let out = engine .execute("project.open", json!({"path": dir.path()})) .unwrap(); (dir, engine, out.events) } fn run(engine: &mut Engine, command: &str, params: Value) -> Outcome { engine .execute(command, params) .unwrap_or_else(|e| panic!("{command} failed: {e}")) } fn open_file(engine: &mut Engine, path: &str) -> (u64, Value) { let out = run(engine, "file.open", json!({"path": path})); (out.value["id"].as_u64().unwrap(), out.value) } /// Pumps VFS events until `pred` matches one, or fails after five seconds. fn wait_for(engine: &mut Engine, pred: impl Fn(&Event) -> bool) -> Vec { let deadline = Instant::now() + Duration::from_secs(5); let mut seen = Vec::new(); while Instant::now() < deadline { let events = engine.pump_vfs().unwrap(); let hit = events.iter().any(&pred); seen.extend(events); if hit { return seen; } std::thread::sleep(Duration::from_millis(25)); } panic!("event not seen within 5 s; got {seen:?}"); } #[test] fn file_commands_are_disabled_without_a_project() { let mut engine = Engine::new().unwrap(); for (command, params) in [ ("project.children", json!({})), ("project.close", json!({})), ("file.open", json!({"path": "a.php"})), ("file.save", json!({"id": 1})), ("file.saveAll", Value::Null), ("buffer.get", json!({"id": 1})), ( "buffer.edit", json!({"id": 1, "baseVersion": 1, "edits": []}), ), ("buffer.close", json!({"id": 1})), ] { let err = engine.execute(command, params).unwrap_err(); assert_eq!(err.code(), "disabled", "{command}"); } } #[test] fn opening_a_missing_folder_fails_and_keeps_state() { let mut engine = Engine::new().unwrap(); let err = engine .execute("project.open", json!({"path": "/definitely/not/here"})) .unwrap_err(); assert_eq!(err.code(), "failed"); assert!(!engine.state().has_project()); } #[test] fn open_lists_children_and_reports_the_project() { let (dir, mut engine, events) = open_project(&[ ("src/Kernel.php", b" = out.value["entries"] .as_array() .unwrap() .iter() .map(|e| e["name"].as_str().unwrap()) .collect(); assert_eq!(names, ["src", "vendor", ".gitignore", "A.txt", "b.txt"]); let entries = out.value["entries"].as_array().unwrap(); let by_name = |n: &str| entries.iter().find(|e| e["name"] == n).unwrap(); assert_eq!(by_name("b.txt")["ignored"], true); assert_eq!(by_name("vendor")["role"], "library"); assert_eq!(by_name("src")["kind"], "directory"); let out = run(&mut engine, "project.children", json!({"dir": "src"})); assert_eq!(out.value["entries"][0]["path"], "src/Kernel.php"); let err = engine .execute("project.children", json!({"dir": "../.."})) .unwrap_err(); assert_eq!(err.code(), "failed"); } #[test] fn edit_save_and_dirty_state() { let (dir, mut engine, _) = open_project(&[("a.php", ""}]}), ); } let out = run(&mut engine, "file.saveAll", Value::Null); assert_eq!(out.value, json!({"saved": [a, b], "failed": []})); assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b"); } #[test] fn absolute_paths_must_be_inside_the_project() { let (dir, mut engine, _) = open_project(&[("a.php", b"a")]); let inside = fs::canonicalize(dir.path()).unwrap().join("a.php"); let (id, value) = open_file(&mut engine, inside.to_str().unwrap()); assert_eq!(value["path"], "a.php"); assert!(id > 0); let other = tempfile::tempdir().unwrap(); fs::write(other.path().join("x.php"), "x").unwrap(); let outside = fs::canonicalize(other.path()).unwrap().join("x.php"); let err = engine .execute("file.open", json!({"path": outside})) .unwrap_err(); assert_eq!(err.code(), "failed"); let err = engine .execute("file.open", json!({"path": "../x.php"})) .unwrap_err(); assert_eq!(err.code(), "failed"); } #[test] fn clean_buffers_reload_and_dirty_ones_report_conflicts() { let (dir, mut engine, _) = open_project(&[("clean.php", b"one"), ("dirty.php", b"one")]); let (clean, _) = open_file(&mut engine, "clean.php"); let (dirty, _) = open_file(&mut engine, "dirty.php"); run( &mut engine, "buffer.edit", json!({"id": dirty, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "mine "}]}), ); fs::write(dir.path().join("clean.php"), "two, longer").unwrap(); fs::write(dir.path().join("dirty.php"), "theirs, longer").unwrap(); let mut events = wait_for( &mut engine, |e| matches!(e, Event::BufferChanged { id, .. } if *id == clean), ); if !events .iter() .any(|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty)) { events = wait_for( &mut engine, |e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty), ); } assert!( events .iter() .all(|e| !matches!(e, Event::FileChangedOnDisk { id, .. } if *id == clean)) ); let clean_now = run(&mut engine, "buffer.get", json!({"id": clean})).value; assert_eq!(clean_now["text"], "two, longer"); assert_eq!(clean_now["dirty"], false); let dirty_now = run(&mut engine, "buffer.get", json!({"id": dirty})).value; assert_eq!(dirty_now["text"], "mine one"); assert_eq!(dirty_now["dirty"], true); fs::remove_file(dir.path().join("clean.php")).unwrap(); wait_for( &mut engine, |e| matches!(e, Event::FileChangedOnDisk { id, removed: true, .. } if *id == clean), ); } #[test] fn own_saves_do_not_reload() { let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]); let (id, _) = open_file(&mut engine, "a.php"); run( &mut engine, "buffer.edit", json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "b"}]}), ); run(&mut engine, "file.save", json!({"id": id})); let deadline = Instant::now() + Duration::from_millis(600); while Instant::now() < deadline { let events = engine.pump_vfs().unwrap(); assert!( !events.iter().any(|e| matches!( e, Event::BufferChanged { .. } | Event::FileChangedOnDisk { .. } )), "{events:?}" ); std::thread::sleep(Duration::from_millis(25)); } assert_eq!( run(&mut engine, "buffer.get", json!({"id": id})).value["version"], 2 ); } #[test] fn tree_changes_are_reported_for_listed_directories() { let (dir, mut engine, _) = open_project(&[("src/a.php", b"a")]); run(&mut engine, "project.children", json!({"dir": "src"})); fs::write(dir.path().join("new.php"), "n").unwrap(); wait_for( &mut engine, |e| matches!(e, Event::TreeChanged { dir } if dir.is_empty()), ); fs::write(dir.path().join("src").join("b.php"), "b").unwrap(); wait_for( &mut engine, |e| matches!(e, Event::TreeChanged { dir } if dir == "src"), ); } #[test] fn watched_directories_are_capped_least_recently_listed_first() { let (dir, mut engine, _) = open_project(&[]); let limit = engine.state().project.as_ref().unwrap().watch_limit(); assert!(limit > 0, "the watcher should start on a temp dir"); let count = limit + 5; for n in 0..count { fs::create_dir(dir.path().join(format!("d{n:04}"))).unwrap(); } for n in 0..count { run( &mut engine, "project.children", json!({"dir": format!("d{n:04}")}), ); } run(&mut engine, "project.children", json!({"dir": "d0000"})); let watched = engine.state().project.as_ref().unwrap().watched_dirs(); assert_eq!(watched.len(), limit); assert_eq!(watched.last().unwrap(), Path::new("d0000")); assert!(!watched.iter().any(|d| d == Path::new("d0001"))); assert!(!watched.iter().any(|d| d == Path::new("d0005"))); assert!(watched.iter().any(|d| d == Path::new("d0006"))); } #[test] fn files_in_never_listed_folders_report_changes_on_disk() { let (dir, mut engine, _) = open_project(&[("src/deep/clean.php", b"one"), ("lib/dirty.php", b"one")]); let (clean, _) = open_file(&mut engine, "src/deep/clean.php"); let (dirty, _) = open_file(&mut engine, "lib/dirty.php"); let workspace = engine.state().project.as_ref().unwrap(); assert_eq!( workspace.pinned_dirs(), vec![ Path::new("lib").to_path_buf(), Path::new("src/deep").to_path_buf() ] ); run( &mut engine, "buffer.edit", json!({"id": dirty, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "mine "}]}), ); fs::write(dir.path().join("src/deep/clean.php"), "two, longer").unwrap(); fs::write(dir.path().join("lib/dirty.php"), "theirs, longer").unwrap(); let mut events = wait_for( &mut engine, |e| matches!(e, Event::BufferChanged { id, .. } if *id == clean), ); if !events .iter() .any(|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty)) { events = wait_for( &mut engine, |e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty), ); } assert!(!events.is_empty()); assert_eq!( run(&mut engine, "buffer.get", json!({"id": clean})).value["text"], "two, longer" ); } #[test] fn parent_dirs_of_open_buffers_are_never_evicted_and_age_out_after_close() { let (dir, mut engine, _) = open_project(&[("pinned/a.php", b"a")]); let limit = engine.state().project.as_ref().unwrap().watch_limit(); assert!(limit > 0, "the watcher should start on a temp dir"); let (id, _) = open_file(&mut engine, "pinned/a.php"); let count = limit + 5; for n in 0..count { fs::create_dir(dir.path().join(format!("d{n:04}"))).unwrap(); run( &mut engine, "project.children", json!({"dir": format!("d{n:04}")}), ); } let watched = engine.state().project.as_ref().unwrap().watched_dirs(); assert_eq!(watched.len(), limit); assert!(watched.iter().any(|d| d == Path::new("pinned"))); assert!(!watched.iter().any(|d| d == Path::new("d0000"))); run(&mut engine, "buffer.close", json!({"id": id})); let workspace = engine.state().project.as_ref().unwrap(); assert!(workspace.pinned_dirs().is_empty()); run(&mut engine, "project.children", json!({"dir": "d0000"})); let watched = engine.state().project.as_ref().unwrap().watched_dirs(); assert_eq!(watched.len(), limit); assert!(!watched.iter().any(|d| d == Path::new("pinned"))); } #[test] fn opening_an_open_file_again_focuses_its_buffer() { let (_dir, mut engine, _) = open_project(&[("a.php", b"a"), ("src/b.php", b"b")]); let first = run(&mut engine, "file.open", json!({"path": "src/b.php"})); let id = first.value["id"].as_u64().unwrap(); assert!(first.events.contains(&Event::BufferOpened { id, path: "src/b.php".into() })); open_file(&mut engine, "a.php"); let again = run(&mut engine, "file.open", json!({"path": "src/b.php"})); assert_eq!(again.value["id"], id); assert_eq!(again.events, vec![Event::BufferFocused { id }]); assert_eq!(engine.state().buffers.len(), 2); } /// A command that reads the state and then panics on an index. struct PanicsMidway; impl Command for PanicsMidway { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "test.panicsMidway", label: "Panics", menu_path: None, default_shortcut: None, params: "none", } } fn run(&self, state: &mut State, _params: Value) -> Result { let _ = state.buffers.len(); let empty: Vec = Vec::new(); Ok(Outcome::value(json!(empty[3]))) } } #[test] fn a_panicking_command_leaves_open_buffers_intact() { let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]); engine.register(Box::new(PanicsMidway)).unwrap(); let (id, _) = open_file(&mut engine, "a.php"); run( &mut engine, "buffer.edit", json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": " unsaved"}]}), ); let err = engine .execute("test.panicsMidway", Value::Null) .unwrap_err(); assert_eq!(err.code(), "internal"); let got = run(&mut engine, "buffer.get", json!({"id": id})).value; assert_eq!(got["text"], "a unsaved"); assert_eq!(got["dirty"], true); run(&mut engine, "file.save", json!({"id": id})); } #[test] fn buffer_list_names_open_buffers_without_text() { let mut engine = Engine::new().unwrap(); assert_eq!( run(&mut engine, "buffer.list", Value::Null).value, json!([]) ); let (_dir, mut engine, _) = open_project(&[("a.php", b"a"), ("src/b.php", b"b")]); let (a, _) = open_file(&mut engine, "a.php"); let (b, _) = open_file(&mut engine, "src/b.php"); run( &mut engine, "buffer.edit", json!({"id": b, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "!"}]}), ); let out = run(&mut engine, "buffer.list", json!({})); assert_eq!( out.value, json!([ {"id": a, "path": "a.php", "version": 1, "dirty": false}, {"id": b, "path": "src/b.php", "version": 2, "dirty": true}, ]) ); assert!(out.events.is_empty()); }