use super::*;
use crate::gradient::lerp_rgb;
use crate::test_git::*;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
mod agents;
mod codeql;
mod collab;
mod debug;
mod diff_merge;
mod editing;
mod editor_view;
mod explorer;
mod extensions;
mod files;
#[cfg(target_os = "linux")]
mod golden;
mod hot_exit;
mod input;
#[cfg(target_os = "linux")]
mod key_ledger;
mod keybindings;
mod layout;
mod lsp;
mod menus;
mod misc;
mod navigation;
mod notebook;
mod palette;
mod popups;
mod problems;
mod remote;
mod review;
mod sarif;
mod scm;
mod search;
mod settings;
mod tabs;
mod tasks;
mod terminal;
mod terminal_panes;
mod testing;
mod tick;
mod updates;
mod viewers;
mod vim;
mod welcome;
fn rust_files_under(dir: &std::path::Path) -> Vec<PathBuf> {
let mut files = Vec::new();
let mut dirs = vec![dir.to_path_buf()];
while let Some(dir) = dirs.pop() {
let entries = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("cannot list {}: {e}", dir.display()));
for entry in entries {
let entry = entry.unwrap();
if entry.file_name().to_string_lossy().starts_with('.') {
continue;
}
let path = entry.path();
if path.is_dir() {
dirs.push(path);
} else if path.extension().is_some_and(|ext| ext == "rs") {
files.push(path);
}
}
}
files.sort();
files
}
fn app_source_files() -> Vec<(PathBuf, String)> {
let app = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app");
let tests = app.join("tests");
rust_files_under(&app)
.into_iter()
.filter(|path| !path.starts_with(&tests))
.map(|path| {
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
(path, text)
})
.collect()
}
fn app_source() -> String {
let mut all = String::new();
for (_, text) in app_source_files() {
all.push('\n');
all.push_str(&text);
}
all
}
fn crash_slot_lock() -> std::sync::MutexGuard<'static, ()> {
static SLOT: std::sync::Mutex<()> = std::sync::Mutex::new(());
SLOT.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(super) struct CaretBackend {
pub(super) inner: ratatui::backend::TestBackend,
pub(super) caret_shown: bool,
}
impl ratatui::backend::Backend for CaretBackend {
type Error = std::convert::Infallible;
fn draw<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
where
I: Iterator<Item = (u16, u16, &'a ratatui::buffer::Cell)>,
{
ratatui::backend::Backend::draw(&mut self.inner, content)
}
fn hide_cursor(&mut self) -> Result<(), Self::Error> {
self.caret_shown = false;
ratatui::backend::Backend::hide_cursor(&mut self.inner)
}
fn show_cursor(&mut self) -> Result<(), Self::Error> {
self.caret_shown = true;
ratatui::backend::Backend::show_cursor(&mut self.inner)
}
fn get_cursor_position(&mut self) -> Result<ratatui::layout::Position, Self::Error> {
ratatui::backend::Backend::get_cursor_position(&mut self.inner)
}
fn set_cursor_position<P: Into<ratatui::layout::Position>>(
&mut self,
position: P,
) -> Result<(), Self::Error> {
ratatui::backend::Backend::set_cursor_position(&mut self.inner, position)
}
fn clear(&mut self) -> Result<(), Self::Error> {
ratatui::backend::Backend::clear(&mut self.inner)
}
fn clear_region(&mut self, clear_type: ratatui::backend::ClearType) -> Result<(), Self::Error> {
ratatui::backend::Backend::clear_region(&mut self.inner, clear_type)
}
fn size(&self) -> Result<ratatui::layout::Size, Self::Error> {
ratatui::backend::Backend::size(&self.inner)
}
fn window_size(&mut self) -> Result<ratatui::backend::WindowSize, Self::Error> {
ratatui::backend::Backend::window_size(&mut self.inner)
}
fn flush(&mut self) -> Result<(), Self::Error> {
ratatui::backend::Backend::flush(&mut self.inner)
}
}
fn key(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
KeyEvent::new(code, mods)
}
#[cfg(not(target_os = "macos"))]
type KeyPredicate = fn(KeyEvent) -> bool;
#[cfg(not(target_os = "macos"))]
fn key_predicates() -> Vec<(&'static str, KeyPredicate)> {
macro_rules! preds {
($($p:ident),* $(,)?) => { vec![$((stringify!($p), $p as KeyPredicate)),*] };
}
fn leader_in_editor(key: KeyEvent) -> bool {
is_cmd_k_leader_key(key, ctrl_k_leads(false, false, false))
}
fn leader_in_shell(key: KeyEvent) -> bool {
is_cmd_k_leader_key(key, ctrl_k_leads(false, true, false))
}
fn is_save_key_reporting_shift(key: KeyEvent) -> bool {
is_save_key(key, true)
}
let mut predicates: Vec<(&str, KeyPredicate)> = preds![
is_terminal_copy_key,
is_compare_key,
is_search_jump_key,
is_editor_find_key,
is_terminal_find_key,
is_editor_replace_key,
is_file_finder_key,
is_command_palette_key,
is_go_to_symbol_key,
is_focus_breadcrumbs_key,
is_toggle_line_comment_key,
is_toggle_block_comment_key,
is_toggle_wrap_key,
is_switch_header_source_key,
is_tree_zoxide_jump_key,
is_tree_new_file_key,
is_tree_new_folder_key,
is_tree_rename_key,
is_reveal_in_finder_key,
is_copy_path_key,
is_tree_make_root_key,
is_tree_make_parent_root_key,
is_explorer_jump_key,
is_source_control_jump_key,
is_run_debug_jump_key,
is_remote_jump_key,
is_extensions_jump_key,
is_run_build_task_key,
is_markdown_preview_key,
is_run_fence_key,
is_sidebar_toggle_key,
is_secondary_sidebar_toggle_key,
is_minimap_toggle_key,
is_terminal_toggle_key,
is_terminal_maximize_key,
is_quick_select_key,
is_copy_mode_key,
is_command_history_key,
is_terminal_split_key,
is_editor_split_key,
is_goto_bracket_key,
is_select_to_bracket_key,
is_navigate_back_key,
is_navigate_forward_key,
is_transpose_key,
is_indentation_to_spaces_key,
is_indentation_to_tabs_key,
is_trim_final_newlines_key,
is_toggle_bookmark_key,
is_switch_debug_session_key,
is_clear_bookmarks_key,
is_next_bookmark_key,
is_prev_bookmark_key,
is_join_lines_key,
is_transform_upper_key,
is_transform_lower_key,
is_copy_relative_path_key,
is_sort_lines_asc_key,
is_sort_lines_desc_key,
is_trim_trailing_whitespace_key,
is_increment_number_key,
is_decrement_number_key,
is_format_document_key,
is_emmet_expand_key,
is_quick_fix_key,
is_focus_group_left_key,
is_focus_group_right_key,
is_terminal_focus_key,
is_terminal_close_key,
is_terminal_cycle_key,
is_terminal_cycle_back_key,
is_delete_node_key,
is_completion_trigger_key,
is_save_all_key,
is_new_untitled_file_key,
is_replace_in_files_key,
is_search_details_key,
is_show_output_key,
is_show_problems_key,
is_update_croft_key,
is_editor_copy_key,
is_editor_cut_key,
is_search_paste_key,
is_editor_paste_key,
is_clipboard_paste_key,
is_editor_select_all_key,
is_editor_undo_key,
is_editor_redo_key,
is_rename_symbol_key,
is_change_all_occurrences_key,
is_select_all_occurrences_key,
is_add_cursors_to_line_ends_key,
is_expand_line_selection_key,
is_select_next_occurrence_key,
is_delete_line_key,
is_go_to_definition_key,
is_peek_definition_key,
is_go_to_references_key,
is_run_to_cursor_key,
is_peek_references_key,
is_go_to_declaration_key,
is_go_to_type_definition_key,
is_go_to_implementation_key,
is_vim_toggle_key,
is_editor_line_home_key,
is_editor_line_end_key,
is_editor_kill_to_eol_key,
is_editor_kill_to_bol_key,
is_editor_open_line_below_key,
is_editor_open_line_above_key,
is_close_tab_key,
];
predicates.push(("is_save_key", is_save_key_reporting_shift));
predicates.push(("is_cmd_k_leader_key", leader_in_editor));
predicates.push(("is_cmd_k_leader_key@shell", leader_in_shell));
predicates
}
fn probe_command(probe: &str) -> String {
let (head, tail) = probe.split_at(1);
format!("printf '%s%s\\n' '{head}' '{tail}'\r")
}
fn await_terminal_probe(app: &mut App, probe: &str) {
app.terminal_mut()
.write_input(probe_command(probe).as_bytes());
let base = crate::test_budget::tests::TERMINAL_PROBE_BASE;
let budget = crate::test_budget::spawn_budget(base);
let started = std::time::Instant::now();
while started.elapsed() < budget {
if app.terminal().visible_text().contains(probe) {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
panic!(
"the shell never printed the probe {probe:?} within {budget:?} ({base:?} base x{} total \
for calibration and load); if this is a real failure it would also fail at 1x, so \
re-run the full suite on the unmodified merge base under the same load before \
suspecting your diff. Terminal showed:\n{}",
budget.as_millis() / base.as_millis().max(1),
app.terminal().visible_text()
);
}
fn menu_label(e: &MenuEntry) -> &str {
match e {
MenuEntry::Item { label, .. }
| MenuEntry::Submenu { label, .. }
| MenuEntry::Header(label) => label,
MenuEntry::Separator => "---",
}
}
fn menu_labels(items: &[MenuEntry]) -> Vec<&str> {
items.iter().map(menu_label).collect()
}
fn menu_action_of<'a>(items: &'a [MenuEntry], label: &str) -> Option<&'a MenuAction> {
items.iter().find_map(|e| match e {
MenuEntry::Item { label: l, action } if l == label => Some(action),
_ => None,
})
}
fn menu_row_actions(app: &App, file: &Path) -> Vec<MenuAction> {
fn actions(entries: Vec<MenuEntry>) -> Vec<MenuAction> {
entries
.into_iter()
.flat_map(|e| match e {
MenuEntry::Item { action, .. } => vec![action],
MenuEntry::Submenu { items, .. } => actions(items),
_ => Vec::new(),
})
.collect()
}
let root = file.parent().unwrap();
let mut all = actions(app.customize_layout_items());
all.extend(actions(build_tab_context_menu_items(
0,
3,
true,
Some(file),
true,
true,
false,
)));
let copied = ExplorerClipboard {
mode: ExplorerClipMode::Copy,
paths: vec![file.to_path_buf()],
};
let tree = build_tree_context_menu_items(
Some(&file_node(file)),
root,
&[file.to_path_buf()],
root,
Some(&copied),
Some(&root.join("selected-for-compare.rs")),
);
all.extend(tree.into_iter().map(|(_, a)| a));
let (row, col, line) = (0, 0, 0);
let path = file.to_path_buf();
all.extend([
MenuAction::RenameSymbolAt { row, col },
MenuAction::ChangeAllOccurrencesAt { row, col },
MenuAction::GoToDefinitionAt { row, col },
MenuAction::GoToDeclarationAt { row, col },
MenuAction::GoToTypeDefinitionAt { row, col },
MenuAction::GoToImplementationAt { row, col },
MenuAction::GoToReferencesAt { row, col },
MenuAction::ShowCallsAt {
row,
col,
incoming: true,
},
MenuAction::ShowCallsAt {
row,
col,
incoming: false,
},
MenuAction::NavigateBack,
MenuAction::NavigateForward,
MenuAction::QuickFixAt { row, col },
MenuAction::AskNavigatorSelection { start: 0, end: 0 },
MenuAction::EditorCut,
MenuAction::EditorCopy,
MenuAction::EditorPaste,
MenuAction::ShowCommandPalette,
MenuAction::OpenThemePicker,
MenuAction::ToggleBreakpointAt { line },
MenuAction::EditBreakpointConditionAt { line },
MenuAction::EditLogpointAt { line },
MenuAction::ToggleBookmarkAt { line },
MenuAction::NextBookmark,
MenuAction::PreviousBookmark,
MenuAction::AskNavigatorAt { line },
MenuAction::GoToOutlineSymbol {
path: path.clone(),
line: 0,
col: 0,
},
MenuAction::OpenSymbolTab {
path,
name: String::from("main"),
first: 0,
last: 0,
},
MenuAction::MakeRoot(root.join("src")),
MenuAction::TerminalCopySelection,
MenuAction::TerminalPaste,
MenuAction::TerminalQuickSelect,
MenuAction::TerminalCopyMode,
MenuAction::TerminalCommandHistory,
MenuAction::OpenScrollbackInEditor,
MenuAction::ToggleBroadcastInput,
MenuAction::ToggleBroadcastExclusion,
MenuAction::UndoCloseTerminal,
MenuAction::SplitTerminal,
MenuAction::RenameTerminal(0),
MenuAction::ToggleMaximizeTerminal(0),
MenuAction::KillTerminal(0),
MenuAction::ClearTerminal(0),
MenuAction::ConvertIndentation(true),
MenuAction::ConvertIndentation(false),
]);
let finished = crate::widgets::terminal::CommandDecoration {
id: 0,
line: 0,
exit: Some(0),
duration: None,
input: None,
output_start: 0,
output_end: 0,
};
all.extend([
MenuAction::CopyCommandOutput(0, finished),
MenuAction::SelectCommandOutput(0, finished),
MenuAction::RerunCommand(0, finished),
MenuAction::AskNavigatorAboutCapture,
]);
all
}
fn empty_activity_images() -> ActivityBarImages {
ActivityBarImages {
icons: ActivityIcon::ALL.map(|icon| ActivityIconImages {
active: (icon != ActivityIcon::Sponsor).then(String::new),
inactive: String::new(),
hovered: String::new(),
}),
..ActivityBarImages::default()
}
}
fn dummy_activity_images() -> ActivityBarImages {
let s = || String::from("\x1b]1337;File=inline=1:Zm9v\x07");
ActivityBarImages {
icons: ActivityIcon::ALL.map(|icon| ActivityIconImages {
active: (icon != ActivityIcon::Sponsor).then(s),
inactive: s(),
hovered: s(),
}),
layout_sidebar_on: s(),
layout_sidebar_on_hover: s(),
layout_sidebar_off: s(),
layout_sidebar_off_hover: s(),
layout_panel_on: s(),
layout_panel_on_hover: s(),
layout_panel_off: s(),
layout_panel_off_hover: s(),
layout_customize: s(),
layout_customize_hover: s(),
}
}
fn app_with_open_file_and_editor_cell() -> (App, tempfile::TempDir, u16, u16) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.py");
std::fs::write(&f, "value = compute()\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
draw(&mut app, 100, 30);
let col = app.editor.last_inner.x + app.editor.last_gutter_width as u16 + 3;
let row = app.editor.last_inner.y + 1;
assert!(
rect_contains(app.editor.last_area, col, row),
"test cell must land inside the editor body"
);
(app, tmp, col, row)
}
fn cells_of(pane: &crate::widgets::terminal::PtyTerminal) -> impl Iterator<Item = (u16, u16)> {
let area = pane.last_area;
(area.y..area.y + area.height)
.flat_map(move |r| (area.x..area.x + area.width).map(move |c| (c, r)))
}
fn cell_carrying(pane: &crate::widgets::terminal::PtyTerminal, needle: &str) -> Option<(u16, u16)> {
cells_of(pane).find(|&(c, r)| {
pane.line_text_at(c, r).is_some_and(|(text, idx)| {
text.find(needle).is_some_and(|byte_start| {
let start = text[..byte_start].chars().count();
(start..start + needle.chars().count()).contains(&idx)
})
})
})
}
fn cell_with_link(pane: &crate::widgets::terminal::PtyTerminal, uri: &str) -> Option<(u16, u16)> {
cells_of(pane).find(|&(c, r)| pane.hyperlink_at_screen(c, r).as_deref() == Some(uri))
}
fn mouse(
kind: crossterm::event::MouseEventKind,
col: u16,
row: u16,
) -> crossterm::event::MouseEvent {
crossterm::event::MouseEvent {
kind,
column: col,
row,
modifiers: KeyModifiers::NONE,
}
}
fn tree_app_with_keymap(json: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.rs");
std::fs::write(&f, "let name = value;\nfn main() {}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.keymap = crate::keymap::Keymap::from_json(json);
draw(&mut app, 100, 30);
(app, tmp)
}
fn three_tab_app(json: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for (name, text) in [("a.py", "a\n"), ("b.txt", "b\n"), ("c.txt", "c\n")] {
let f = tmp.path().join(name);
std::fs::write(&f, text).unwrap();
app.editor.open_pinned(&f).unwrap();
}
app.keymap = crate::keymap::Keymap::from_json(json);
draw(&mut app, 100, 30);
(app, tmp)
}
fn tab_names(app: &App) -> Vec<String> {
(0..app.editor.tab_count())
.map(|i| {
app.editor
.tab_path(i)
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.unwrap_or_default()
})
.collect()
}
fn tab_cell(app: &App, idx: usize) -> (u16, u16) {
let y = app.editor.tab_strip_y_for_test();
let x = (0..app.editor.last_inner.right())
.find(|&x| app.editor.tab_at(x, y) == Some(idx))
.expect("the tab is drawn");
(x, y)
}
fn press(app: &mut App, button: crossterm::event::MouseButton, (x, y): (u16, u16)) {
use crossterm::event::MouseEventKind;
app.handle_mouse(mouse(MouseEventKind::Down(button), x, y));
app.handle_mouse(mouse(MouseEventKind::Up(button), x, y));
}
fn app_with_painted_file(text: &str) -> (App, tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("prog.py");
std::fs::write(&f, text).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
draw(&mut app, 100, 30);
(app, tmp, f)
}
fn click_and_release(app: &mut App, col: u16, row: u16) {
use crossterm::event::{MouseButton, MouseEventKind};
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
}
fn open_tab_paths(app: &App) -> Vec<PathBuf> {
app.editor
.editors
.iter()
.filter_map(|e| e.path.clone())
.collect()
}
fn preview_nav_fixture() -> (tempfile::TempDir, App, PathBuf, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let mc = tmp.path().join("m.c");
let main = tmp.path().join("main.c");
let mh = tmp.path().join("m.h");
std::fs::write(&mh, "#pragma once\nint add(int a, int b);\n").unwrap();
std::fs::write(
&mc,
"#include \"m.h\"\nint add(int a, int b) { return a + b; }\n",
)
.unwrap();
std::fs::write(
&main,
"#include \"m.h\"\nint main(void) { return add(1, 2); }\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&mc).unwrap();
(tmp, app, mc, main, mh)
}
fn nav_switch_fixture() -> (tempfile::TempDir, App, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let a = root.join("a.txt");
let b = root.join("b.txt");
let lines = |name: &str, n: usize| -> String {
(1..=n).map(|i| format!("{name} line {i}\n")).collect()
};
std::fs::write(&a, lines("alpha", 120)).unwrap();
std::fs::write(&b, lines("beta", 60) + "needle here\n").unwrap();
let mut app = App::new(root).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 39;
(tmp, app, a, b)
}
fn file_node(path: &Path) -> crate::widgets::file_tree::Node {
crate::widgets::file_tree::Node {
path: path.to_path_buf(),
depth: 1,
is_dir: false,
expanded: false,
loaded: false,
folded: 0,
}
}
fn type_into_sheet(app: &mut App, text: &str) {
for ch in text.chars() {
app.handle_sheet_key(key(KeyCode::Char(ch), KeyModifiers::NONE));
}
}
fn prices_xlsx_app() -> (tempfile::TempDir, std::path::PathBuf, App) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("prices.xlsx");
let mut book = umya_spreadsheet::new_file();
let ws = book.sheet_mut(0).unwrap();
ws.cell_mut((1u32, 1u32)).set_value("item");
ws.cell_mut((2u32, 1u32)).set_value("price");
for (row, (item, price)) in [("bolt", 4), ("nut", 9), ("washer", 25)].iter().enumerate() {
ws.cell_mut((1u32, row as u32 + 2)).set_value(*item);
ws.cell_mut((2u32, row as u32 + 2)).set_value_number(*price);
}
umya_spreadsheet::writer::xlsx::write(&book, &p).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
assert!(app.editor.sheet.is_some());
draw(&mut app, 120, 40);
(tmp, p, app)
}
fn sheet_cell_on_screen(app: &App, row: usize, col: usize) -> (u16, u16) {
let view = app.editor.sheet.as_ref().unwrap();
(0..40)
.flat_map(|y| (0..120).map(move |x| (x, y)))
.find(|&(x, y)| sheet_cell_at(view, x, y) == Some((row, col)))
.expect("the cell is on screen")
}
fn xlsx_value(p: &std::path::Path, col: u32, row: u32) -> String {
let book = umya_spreadsheet::reader::xlsx::read(p).unwrap();
book.sheet(0)
.unwrap()
.cell((col, row))
.unwrap()
.value()
.to_string()
}
fn press_ctrl_q(app: &mut App) {
app.handle_key(key(KeyCode::Char('q'), KeyModifiers::CONTROL))
.unwrap();
}
fn app_with_unsaved_file(tmp: &std::path::Path) -> (App, PathBuf) {
let mut app = app_with_open_file(tmp, "a.txt", "alpha\n");
type_keys(&mut app, "x");
assert!(app.editor.dirty, "setup: typing leaves the buffer dirty");
(app, tmp.join("a.txt"))
}
fn ready_to_hand_off(app: &mut App, event: crate::install_session::InstallEvent) {
let adopted = crate::remote::AdoptedMaster {
host: String::from("devbox"),
socket_dir: PathBuf::from("/nonexistent/croft-test-ctl"),
socket_path: PathBuf::from("/nonexistent/croft-test-ctl/ctl"),
};
app.install_session = Some(crate::install_session::InstallSession::with_events(
"devbox",
None,
Some(adopted),
vec![event],
));
}
fn with_hot_exit(mut app: App, cache: &std::path::Path) -> App {
app.hot_exit_dir = Some(cache.to_path_buf());
app
}
fn settle_hot_exit(app: &mut App) {
app.tick_hot_exit(std::time::Instant::now() + std::time::Duration::from_secs(60));
}
fn hot_exit_files(cache: &std::path::Path, root: &std::path::Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(crate::hot_exit::workspace_dir(cache, root)) else {
return Vec::new();
};
let mut files: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "json"))
.collect();
files.sort();
files
}
fn hot_exit_texts_of(
cache: &std::path::Path,
root: &std::path::Path,
file: &std::path::Path,
) -> Vec<String> {
let mut texts: Vec<String> = hot_exit_files(cache, root)
.iter()
.flat_map(|f| crate::hot_exit::Backup::load(f).unwrap().buffers)
.filter(|b| b.tab.path.as_deref() == Some(file))
.filter_map(|b| b.tab.unsaved_text)
.collect();
texts.sort();
texts
}
fn app_with_run_script() -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("r.sh");
std::fs::write(
&p,
"echo one\necho two\nfor i in 1 2; do\n echo loop $i\ndone\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&p).unwrap();
app.focus_pane(Pane::Editor);
(tmp, app)
}
fn run_palette_row_titled(app: &mut App, title: &str) -> bool {
app.handle_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
type_keys(app, title);
let palette = app.command_palette.as_mut().expect("the palette opened");
let Some(row) = palette.results.iter().position(|i| i.title() == title) else {
app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
return false;
};
palette.selected = row;
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
true
}
fn markdown_fence_app(dir: &Path) -> App {
let mut app = app_with_open_file(dir, "R.md", "# Run\n\n```sh\necho hi\n```\n");
app.editor.cursor_row = 3;
app
}
fn make_committed_repo() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
git_init_with_identity(p);
std::fs::write(p.join("seed.txt"), b"seed\n").unwrap();
let _ = git_succeeds(p, &["add", "seed.txt"]);
let _ = git_succeeds(p, &["commit", "-q", "-m", "init"]);
tmp
}
fn wait_for_changes(app: &mut App, predicate: impl Fn(&App) -> bool) -> bool {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
let mut next_kick = std::time::Instant::now();
while std::time::Instant::now() < deadline {
if std::time::Instant::now() >= next_kick {
app.refresh_source_control();
next_kick = std::time::Instant::now() + std::time::Duration::from_millis(200);
}
app.drain_git_responses();
if predicate(app) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
predicate(app)
}
fn app_with_change_bars() -> (App, tempfile::TempDir) {
let tmp = make_committed_repo();
let root = tmp.path();
let f = root.join("v.txt");
let body: String = (1..=20).map(|i| format!("value_{i}\n")).collect();
std::fs::write(&f, &body).unwrap();
git_ok(root, &["add", "v.txt"]);
git_ok(root, &["commit", "-q", "-m", "values"]);
let edited: String = (1..=20)
.filter(|&i| i != 9)
.map(|i| {
if i == 5 {
String::from("value_FIVE\n")
} else {
format!("value_{i}\n")
}
})
.collect();
std::fs::write(&f, edited).unwrap();
let mut app = App::new(root.to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app.sync_git_gutters();
(app, tmp)
}
fn wait_for_git_net(app: &mut App) {
crate::test_budget::await_spawned(
std::time::Duration::from_secs(10),
"the network git operation",
|| {
app.drain_git_net();
app.git_net_job.is_none()
},
);
}
fn settle_test_root(app: &mut App) {
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the Testing folder to be worked out",
|| {
app.drain_git_responses();
let key = (app.active_workspace_root(), app.editor.path.clone());
app.test_root_pending.is_none()
&& app
.test_root_follow
.as_ref()
.is_some_and(|(k, _)| *k == key)
},
);
}
fn diverged_repo() -> tempfile::TempDir {
let tmp = make_committed_repo();
let p = tmp.path();
let f = p.join("f");
std::fs::write(&f, "base\n").unwrap();
assert!(git_succeeds(p, &["add", "f"]) && git_succeeds(p, &["commit", "-qm", "base"]));
assert!(git_succeeds(p, &["checkout", "-qb", "feat"]));
std::fs::write(&f, "feat\n").unwrap();
assert!(git_succeeds(p, &["commit", "-qam", "feat"]));
assert!(git_succeeds(p, &["checkout", "-q", "main"]));
std::fs::write(&f, "mainline\n").unwrap();
assert!(git_succeeds(p, &["commit", "-qam", "main"]));
tmp
}
fn scm_ready_to_commit() -> (tempfile::TempDir, App) {
let tmp = make_committed_repo();
std::fs::write(tmp.path().join("seed.txt"), b"changed\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
wait_for_changes(&mut app, |a| {
a.source_control
.entries
.iter()
.any(|e| e.path == "seed.txt")
});
app.set_sidebar_view(SidebarView::SourceControl);
(tmp, app)
}
fn scm_with_unsaved_tab() -> (tempfile::TempDir, App) {
let (tmp, mut app) = scm_ready_to_commit();
app.editor
.open_pinned(&tmp.path().join("seed.txt"))
.unwrap();
app.editor.insert_str("edited ");
assert!(app.editor.dirty);
app.source_control.message = "bump seed".to_string();
app.source_control.message_cursor = app.source_control.message.chars().count();
(tmp, app)
}
fn last_commit_message(root: &std::path::Path) -> String {
git_stdout_untrimmed(root, &["log", "-1", "--format=%B"])
}
fn editor_app_with_lines(lines: &[&str]) -> App {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor.lines = lines.iter().map(|s| (*s).to_string()).collect();
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app
}
fn wait_for_seats(root: &std::path::Path, f: &std::path::Path, millis: u64) {
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the provenance sidecar",
|| crate::history::seats_for(root, f, millis).is_some(),
);
}
fn wait_for_snapshots(
root: &std::path::Path,
f: &std::path::Path,
) -> Vec<crate::history::Snapshot> {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let snaps = crate::history::entries_in(root, f);
if !snaps.is_empty() || std::time::Instant::now() > deadline {
return snaps;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
fn scratch_config(manifests: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let croft = tmp.path().join("croft");
for (id, text) in manifests {
let dir = croft.join("extensions").join(id);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("extension.toml"), text).unwrap();
}
(tmp, croft)
}
fn consent_on_disk(croft: &Path) -> std::collections::BTreeSet<String> {
crate::prefs::Prefs::load(&croft.join("config.json"))
.unwrap_or_default()
.mcp_consented
}
fn relay_test_lock() -> &'static std::sync::Mutex<()> {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
&LOCK
}
const TEST_RELAY_KEY: &str = "0123456789abcdef";
fn own_settings(app: &mut App) -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
app.config_dir = dir.path().to_path_buf();
dir
}
fn relay_copied(app: &mut App, copy: impl FnOnce(&mut App)) -> Option<String> {
let home = tempfile::tempdir().unwrap();
app.is_relay_session = true;
let (log, inbox) = with_relay_home(home.path(), || {
let log = app.relay_log_path().expect("relay log path derivable");
let inbox = app.relay_inbox_path().expect("relay inbox path derivable");
copy(app);
(log, inbox)
});
let written = std::fs::read_to_string(&log).ok()?;
let id = written.lines().last()?.strip_prefix("copy\t")?.to_string();
std::fs::read_to_string(inbox.join(format!("{id}.txt"))).ok()
}
fn with_relay_home<T>(home: &std::path::Path, body: impl FnOnce() -> T) -> T {
struct RestoreRelayGlobals {
prev_key: Option<std::ffi::OsString>,
}
impl Drop for RestoreRelayGlobals {
fn drop(&mut self) {
*crate::paths::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
unsafe {
match self.prev_key.take() {
Some(k) => std::env::set_var("CROFT_RELAY_KEY", k),
None => std::env::remove_var("CROFT_RELAY_KEY"),
}
}
}
}
let _restore = RestoreRelayGlobals {
prev_key: std::env::var_os("CROFT_RELAY_KEY"),
};
*crate::paths::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() =
Some(home.join(".cache").join("croft"));
unsafe {
std::env::set_var("CROFT_RELAY_KEY", TEST_RELAY_KEY);
}
body()
}
struct CacheDirOverride;
impl Drop for CacheDirOverride {
fn drop(&mut self) {
*crate::paths::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = None;
}
}
fn override_cache_dir(dir: PathBuf) -> CacheDirOverride {
*crate::paths::CACHE_DIR_OVERRIDE_FOR_TEST.lock().unwrap() = Some(dir);
CacheDirOverride
}
fn make_venv(dir: &Path, venv_name: &str) -> PathBuf {
let bin = dir.join(venv_name).join("bin");
std::fs::create_dir_all(&bin).unwrap();
let py = bin.join("python");
std::fs::write(&py, b"#!/bin/sh\nexit 0\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = std::fs::metadata(&py).unwrap().permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&py, perms).unwrap();
}
py
}
fn app_with_unsaved_pinned_file(name: &str) -> (tempfile::TempDir, App, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let file = root.join(name);
std::fs::write(&file, "old\n").unwrap();
let mut app = App::new(root).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.insert_str("new\n");
assert!(app.editor.dirty);
(tmp, app, file)
}
fn vim_app(content: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("buf.txt");
std::fs::write(&f, content).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus = Pane::Editor;
app.vim.enabled = true;
(app, tmp)
}
fn app_with_vscode_excludes() -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in [".vscode", "src", "tests/fixtures", "generated"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::write(
root.join(".vscode/settings.json"),
r#"{ "files.exclude": { "**/generated": true },
"search.exclude": { "**/tests/fixtures": true } }"#,
)
.unwrap();
std::fs::write(root.join("src/orders.py"), "def parse_order(x): return x\n").unwrap();
for i in 1..=6 {
std::fs::write(
root.join(format!("tests/fixtures/case{i}.txt")),
format!("parse_order fixture {i}\n"),
)
.unwrap();
}
std::fs::write(
root.join("generated/api_pb2.py"),
"# parse_order generated stub\n",
)
.unwrap();
let app = App::new(root.to_path_buf()).unwrap();
(app, tmp)
}
fn search_hit_paths(app: &mut App, root: &std::path::Path, query: &str) -> Vec<String> {
app.search.query = String::from(query);
app.submit_search_query();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.search.progress != SearchProgress::Finished && std::time::Instant::now() < deadline {
app.drain_search_results();
std::thread::sleep(std::time::Duration::from_millis(20));
}
assert_eq!(
app.search.progress,
SearchProgress::Finished,
"the search must finish"
);
let mut paths: Vec<String> = app
.search
.hits
.iter()
.map(|h| {
h.path
.strip_prefix(root)
.unwrap_or(&h.path)
.to_string_lossy()
.into_owned()
})
.collect();
paths.sort();
paths
}
fn app_with_open_file(tmp: &std::path::Path, name: &str, body: &str) -> App {
let f = tmp.join(name);
std::fs::write(&f, body).unwrap();
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app
}
fn python_module(defs: usize) -> String {
(0..defs)
.map(|i| format!("def f{i}(x):\n return x + {i}\n"))
.collect()
}
fn note_edit_for_outline(app: &mut App) {
let path = app.editor.path.clone().unwrap();
app.lsp_last_seen.insert(path, app.editor.edit_seq);
}
fn diag(
start_char: u32,
end_char: u32,
severity: crate::lsp::manager::DiagnosticSeverity,
) -> crate::lsp::manager::Diagnostic {
crate::lsp::manager::Diagnostic {
start_line: 0,
start_char,
end_line: 0,
end_char,
severity,
message: String::from("test"),
tags: Default::default(),
code: None,
origin: None,
}
}
fn run_typed_line(line: &str, cwd: &std::path::Path) -> String {
let out = std::process::Command::new("sh")
.args(["-c", line.trim_end_matches('\r')])
.current_dir(cwd)
.output()
.unwrap();
String::from_utf8(out.stdout).unwrap() + &String::from_utf8(out.stderr).unwrap()
}
fn left_click(app: &mut App, column: u16, row: u16) {
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column,
row,
modifiers: KeyModifiers::empty(),
});
}
fn draw_terminal(
app: &mut App,
w: u16,
h: u16,
) -> ratatui::Terminal<ratatui::backend::TestBackend> {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();
term.draw(|f| app.render(f)).unwrap();
term
}
fn draw(app: &mut App, w: u16, h: u16) {
draw_terminal(app, w, h);
}
fn draw_buffer(app: &mut App, w: u16, h: u16) -> ratatui::buffer::Buffer {
draw_terminal(app, w, h).backend().buffer().clone()
}
fn draw_screen(app: &mut App, w: u16, h: u16) -> String {
screen_text(&draw_terminal(app, w, h))
}
fn draw_and_find(app: &mut App, w: u16, h: u16, needle: &str) -> Option<(u16, u16)> {
find_painted(&draw_terminal(app, w, h), needle, 0..w)
}
fn count_bg(buf: &ratatui::buffer::Buffer, c: Color) -> usize {
let a = buf.area;
(a.y..a.y + a.height)
.flat_map(|y| (a.x..a.x + a.width).map(move |x| (x, y)))
.filter(|&(x, y)| buf[(x, y)].bg == c)
.count()
}
fn zen_app() -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path().join("t.py");
std::fs::write(&p, "x = 1\ny = 2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&p).unwrap();
app.focus = Pane::Editor;
(tmp, app)
}
fn sym(
name: &str,
kind: crate::lsp::manager::OutlineKind,
depth: u16,
start: u32,
end: u32,
) -> crate::lsp::manager::OutlineSymbol {
crate::lsp::manager::OutlineSymbol {
name: name.to_string(),
detail: None,
kind,
depth,
line: start,
character: 0,
range_start_line: start,
range_end_line: end,
range_start_character: 0,
range_end_character: u32::MAX,
}
}
fn occurrences_app(tmp: &Path) -> App {
app_with_open_file(tmp, "s.py", "foo = 1\nbar = foo\nfoo += 2\nfood = 3")
}
fn select(app: &mut App, anchor: (usize, usize), head: (usize, usize)) {
app.editor.selection = Some(crate::widgets::editor::EditorSelection { anchor, head });
(app.editor.cursor_row, app.editor.cursor_col) = head;
}
fn cmd_shift_l(app: &mut App) {
app.handle_key(key(
KeyCode::Char('l'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
}
fn type_char(app: &mut App, c: char) {
app.handle_key(key(KeyCode::Char(c), KeyModifiers::NONE))
.unwrap();
}
fn app_on_src_f2(f2: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
std::fs::create_dir_all(src.join("sub")).unwrap();
for f in ["f1.rs", "f3.rs"] {
std::fs::write(src.join(f), format!("// {f}\n")).unwrap();
}
std::fs::write(src.join("f2.rs"), f2).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&src.join("f2.rs")).unwrap();
app.focus_pane(Pane::Editor);
draw(&mut app, 100, 30);
(app, tmp)
}
fn click_crumb(app: &mut App, i: usize) {
let (x, below) = app.editor.breadcrumb_anchor(i).expect("crumb on screen");
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), x, below - 1));
}
fn app_with_vscode_settings(vscode: &str) -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(tmp.path().join(".vscode/settings.json"), vscode).unwrap();
for (name, body) in [
("m.c", "int x;\n"),
("m.py", "x=1\n"),
("README.md", "# r\n"),
] {
std::fs::write(tmp.path().join(name), body).unwrap();
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let merged = app.merged_settings_here();
app.apply_merged_settings(&merged.prefs);
(tmp, app)
}
fn replace_chord() -> KeyEvent {
key(KeyCode::Char('f'), KeyModifiers::ALT | KeyModifiers::SUPER)
}
const FIND_IN_SELECTION_SRC: &str =
"def a(x):\n return x + 1\n\ndef b(x):\n return x * 2\n\ndef c(x):\n return x - 3";
fn find_in_selection_app(tmp: &Path) -> App {
let mut app = app_with_open_file(tmp, "f.py", FIND_IN_SELECTION_SRC);
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (3, 0),
head: (5, 0),
});
(app.editor.cursor_row, app.editor.cursor_col) = (5, 0);
app.handle_key(replace_chord()).unwrap();
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
app
}
fn alt_l(app: &mut App) {
app.handle_key(key(KeyCode::Char('l'), KeyModifiers::ALT))
.unwrap();
}
fn find_count(app: &App) -> usize {
app.editor_find
.as_ref()
.expect("the bar is open")
.match_count
}
const CONFLICTED_BODY: &str =
"fn main() {\n<<<<<<< HEAD\n ours();\n=======\n theirs();\n>>>>>>> feature\n}";
fn age_last_edit(e: &mut crate::widgets::editor::Editor) {
e.last_edit_at = std::time::Instant::now().checked_sub(std::time::Duration::from_secs(5));
}
fn quick_open_typing(app: &mut App, typed: &str) {
app.handle_key(key(KeyCode::Char('p'), KeyModifiers::SUPER))
.unwrap();
assert!(app.file_finder.is_some(), "Cmd+P opens Quick Open");
type_keys(app, typed);
}
fn local_test_spawn(cfg: &crate::pair::PairConfig) -> anyhow::Result<crate::pair_host::PairHost> {
crate::pair_host::PairHost::spawn(crate::pair::PairConfig {
socket: cfg.socket.clone(),
workspace: cfg.workspace.clone(),
name: cfg.name.clone(),
model: Some(String::from("test-model")),
task: None,
provider: crate::pair::Provider::Local {
base_url: String::from("http://127.0.0.1:9"),
},
})
}
fn owner_and_pilot_on(tmp: &tempfile::TempDir, text: &str) -> (App, crate::collab::CollabSession) {
use std::time::{Duration, Instant};
let file = tmp.path().join("f.txt");
std::fs::write(&file, text).unwrap();
let socket = tmp.path().join("collab.sock");
{
let s = socket.clone();
std::thread::spawn(move || {
let _ = crate::collab::relay_serve(&s);
});
}
let deadline = Instant::now() + Duration::from_secs(5);
while !crate::session::is_alive(&socket) {
assert!(Instant::now() < deadline, "relay never came up");
std::thread::sleep(Duration::from_millis(10));
}
let mut owner = App::new(tmp.path().to_path_buf()).unwrap();
owner.collab_config = Some((socket.clone(), crate::collab::CollabRole::Owner));
owner.open_file_at_launch(&file);
let deadline = Instant::now() + Duration::from_secs(5);
while owner.collab.is_none() {
assert!(Instant::now() < deadline, "owner never joined the relay");
owner.poll_collab();
std::thread::sleep(Duration::from_millis(5));
}
let mut pilot = {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Some(ch) =
crate::collab::CollabChannel::connect(&socket, crate::collab::CollabRole::Guest)
{
break crate::collab::CollabSession::new(ch, "pilot".into());
}
assert!(Instant::now() < deadline, "pilot never connected");
std::thread::sleep(Duration::from_millis(10));
}
};
pilot.request_file("f.txt");
let deadline = Instant::now() + Duration::from_secs(10);
while !pilot.is_live("f.txt") {
assert!(Instant::now() < deadline, "the pilot never got the file");
owner.poll_collab();
pilot.poll(|_| None);
std::thread::sleep(Duration::from_millis(5));
}
(owner, pilot)
}
fn pilot_writes(owner: &mut App, pilot: &mut crate::collab::CollabSession, text: &str) {
use std::time::{Duration, Instant};
assert!(pilot.local_change("f.txt", text));
std::thread::sleep(Duration::from_millis(100));
let deadline = Instant::now() + Duration::from_secs(5);
while owner.editor.lines.join("\n") != text {
assert!(Instant::now() < deadline, "the owner never saw {text:?}");
owner.poll_collab();
pilot.poll(|_| None);
std::thread::sleep(Duration::from_millis(5));
}
}
fn write_three_page_pdf(path: &std::path::Path) {
let pdf = concat!(
"%PDF-1.4\n",
"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n",
"2 0 obj<</Type/Pages/Kids[3 0 R 4 0 R 5 0 R]/Count 3>>endobj\n",
"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 6 0 R>>endobj\n",
"4 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 7 0 R>>endobj\n",
"5 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]/Contents 8 0 R>>endobj\n",
"6 0 obj<</Length 27>>stream\n0 0 1 rg 10 10 100 100 re f\nendstream endobj\n",
"7 0 obj<</Length 27>>stream\n1 0 0 rg 10 10 100 100 re f\nendstream endobj\n",
"8 0 obj<</Length 27>>stream\n0 1 0 rg 10 10 100 100 re f\nendstream endobj\n",
"trailer<</Root 1 0 R/Size 9>>\n%%EOF\n",
);
std::fs::write(path, pdf).unwrap();
}
fn write_test_png(path: &std::path::Path) {
let mut png = Vec::new();
image::RgbaImage::from_pixel(8, 8, image::Rgba([10, 200, 30, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("encode test png");
std::fs::write(path, &png).unwrap();
}
fn csv_body(rows: usize) -> String {
let mut s = String::from("name,qty,price\n");
for i in 0..rows {
s.push_str(&format!("row{i},{i},{i}.50\n"));
}
s
}
fn open_from_explorer(app: &mut App, name: &str) {
let idx = app
.tree
.nodes
.iter()
.position(|n| n.path.file_name().is_some_and(|f| f == name))
.unwrap_or_else(|| panic!("{name} must be visible in the Explorer"));
app.tree.selected = idx;
app.focus_pane(Pane::Tree);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
}
fn place_editor_pane(app: &mut App) -> (u16, u16) {
let area = Rect {
x: 20,
y: 2,
width: 60,
height: 30,
};
app.editor.last_area = area;
app.editor.last_full_area = area;
app.editor.last_inner = Rect {
x: area.x + 1,
y: area.y + 2,
width: area.width - 2,
height: area.height - 3,
};
(area.x + 10, area.y + 10)
}
fn wheel(app: &mut App, kind: crossterm::event::MouseEventKind, col: u16, row: u16) {
app.handle_mouse(mouse(kind, col, row));
}
fn require_pdf_backend() {
assert!(
crate::pdf::detect_backend().is_some(),
"these tests need a PDF rasteriser (poppler's pdftoppm, or sips on macOS)"
);
}
fn click_open_in_explorer(app: &mut App, name: &str) {
app.tree.last_area = Rect {
x: 4,
y: 0,
width: 32,
height: 20,
};
app.tree.last_inner = Rect {
x: 5,
y: 1,
width: 30,
height: 18,
};
app.focus_pane(Pane::Tree);
let idx = app
.tree
.nodes
.iter()
.position(|n| n.path.file_name().is_some_and(|f| f == name))
.unwrap_or_else(|| panic!("{name} must be visible in the Explorer"));
let row = app.tree.last_inner.y + idx as u16;
let col = app.tree.last_inner.x + 2;
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row));
}
fn wide_short_png() -> Vec<u8> {
let mut png = Vec::new();
image::RgbaImage::from_pixel(100, 1, image::Rgba([0, 0, 255, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.expect("encode test png");
png
}
fn app_with_baked_terminal_image(
protocol: crate::iterm2_inline::InlineImageProtocol,
) -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.inline_protocol = protocol;
app.cell_pixel = Some((8, 16));
draw(&mut app, 100, 30);
let mut quiet = 0;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while quiet < 2 && std::time::Instant::now() < deadline {
let _ = app.terminals[0].take_dirty();
std::thread::sleep(std::time::Duration::from_millis(60));
if app.terminals[0].peek_pending_bytes() == 0 && !app.terminals[0].peek_dirty() {
quiet += 1;
} else {
quiet = 0;
}
}
assert!(
quiet >= 2,
"the pane's shell never went quiet within 10s, so the fixture cannot bake against a stable grid"
);
let h = app.terminals[0].last_inner.height as usize;
app.terminals[0].feed_bytes_for_test("\r\n".repeat(h * 2).as_bytes());
app.terminals[0].push_image_for_test(wide_short_png());
app.update_terminal_image_overlay();
assert!(
app.overlays.terminal_image.has_image(),
"staging: the picture must have baked"
);
(tmp, app)
}
fn conflicted_repo(tmp: &std::path::Path) {
let git = |args: &[&str]| git_succeeds(tmp, args);
git_init(tmp);
std::fs::write(
tmp.join("shared.txt"),
"alpha\nbase-one\nm1\nm2\nm3\nm4\nm5\nbase-two\nomega\n",
)
.unwrap();
std::fs::write(tmp.join("clean.txt"), "untouched\n").unwrap();
git(&["add", "-A"]);
git(&["commit", "-qm", "base"]);
git(&["checkout", "-q", "-b", "feature"]);
std::fs::write(
tmp.join("shared.txt"),
"alpha\nfeature-one\nm1\nm2\nm3\nm4\nm5\nfeature-two\nomega\n",
)
.unwrap();
git(&["commit", "-aqm", "feature edit"]);
git(&["checkout", "-q", "main"]);
std::fs::write(
tmp.join("shared.txt"),
"alpha\nmain-one\nm1\nm2\nm3\nm4\nm5\nmain-two\nomega\n",
)
.unwrap();
git(&["commit", "-aqm", "main edit"]);
assert!(
!git(&["merge", "feature"]),
"the merge must conflict for these tests"
);
}
fn wait_for_conflicted_entry(app: &mut App) -> usize {
app.set_sidebar_view(SidebarView::SourceControl);
let mut found = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(1000),
"the git worker to report the conflicted entry",
|| {
let _ = app.drain_git_responses();
found = app
.source_control
.entries
.iter()
.position(|e| e.kind == crate::git::ChangeKind::Conflicted);
found.is_some()
},
);
found.expect("await_spawned returns only once the entry is present")
}
fn modify_delete_repo(tmp: &std::path::Path, deleted_on_feature: bool) {
let git = |args: &[&str]| git_succeeds(tmp, args);
git_init(tmp);
std::fs::write(tmp.join("gone.txt"), "x\ny\n").unwrap();
git(&["add", "-A"]);
git(&["commit", "-qm", "base"]);
git(&["checkout", "-q", "-b", "feature"]);
if deleted_on_feature {
git(&["rm", "-q", "gone.txt"]);
git(&["commit", "-qm", "delete"]);
} else {
std::fs::write(tmp.join("gone.txt"), "x\ny-feature\n").unwrap();
git(&["commit", "-aqm", "edit"]);
}
git(&["checkout", "-q", "main"]);
if deleted_on_feature {
std::fs::write(tmp.join("gone.txt"), "x\ny-main\n").unwrap();
git(&["commit", "-aqm", "edit"]);
} else {
git(&["rm", "-q", "gone.txt"]);
git(&["commit", "-qm", "delete"]);
}
assert!(!git(&["merge", "feature"]), "modify/delete must conflict");
}
fn open_modify_delete(tmp: &std::path::Path, deleted_on_feature: bool) -> App {
modify_delete_repo(tmp, deleted_on_feature);
let mut app = App::new(tmp.to_path_buf()).unwrap();
let idx = wait_for_conflicted_entry_named(&mut app, "gone.txt");
app.open_source_control_entry(idx);
assert!(app.editor.merge.is_some(), "{}", app.status);
app
}
fn wait_for_conflicted_entry_named(app: &mut App, name: &str) -> usize {
app.set_sidebar_view(SidebarView::SourceControl);
let mut found = None;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(1000),
"the git worker to report the conflicted entry",
|| {
let _ = app.drain_git_responses();
found = app.source_control.entries.iter().position(|e| {
e.kind == crate::git::ChangeKind::Conflicted && e.path.ends_with(name)
});
found.is_some()
},
);
found.unwrap()
}
fn lsp_nav_app(keymap: &str) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("lib.rs"),
"fn main() {\n let value = 1;\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9;
app.keymap = crate::keymap::Keymap::from_json(keymap);
(app, tmp)
}
fn linked_ts_app(dir: &std::path::Path) -> App {
std::fs::write(
dir.join("app.ts"),
"import { add } from \"./math\";\nconsole.log(add(1, 2));\n",
)
.unwrap();
let mut app = App::new(dir.to_path_buf()).unwrap();
app.editor.open_pinned(&dir.join("app.ts")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 5;
app
}
fn linked_wake(app: &mut App) -> Option<u64> {
let sent = linked_tick_only(app);
if let Some(id) = sent {
answer_linked(app, id, Vec::new());
}
app.drain_lsp_linked_editing();
sent
}
fn linked_tick_only(app: &mut App) -> Option<u64> {
let before = app.linked_request.as_ref().map(|r| r.id);
app.linked_observed_at = std::time::Instant::now() - std::time::Duration::from_secs(1);
app.tick_linked_editing();
app.linked_request
.as_ref()
.map(|r| r.id)
.filter(|id| Some(*id) != before)
}
fn answer_linked(app: &App, id: u64, ranges: Vec<(u32, u32, u32, u32)>) {
app.lsp.as_ref().unwrap().push_linked_editing_for_test(
crate::lsp::manager::LinkedEditingResult {
request_id: id,
ranges,
},
);
}
fn app_with_symbol_tab_on_b(tmp: &tempfile::TempDir) -> (App, std::path::PathBuf) {
let file = tmp.path().join("two.rs");
std::fs::write(&file, "fn a() {\n 1\n}\nfn b() {\n 2\n}").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.editor.cursor_row = 4;
app.run_command(crate::widgets::command_palette::Command::OpenAsSymbolTab);
(app, file)
}
fn greet_to_welcome(
file: &std::path::Path,
) -> Vec<(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)> {
let edit = |row| crate::widgets::editor::TextSpanEdit {
start: (row, 0),
end: (row, 5),
new_text: String::from("welcome"),
utf16: false,
};
vec![(file.to_path_buf(), vec![edit(0), edit(1)])]
}
fn app_with_calc_open(tmp: &tempfile::TempDir) -> (App, PathBuf) {
let root = tmp.path().canonicalize().unwrap();
let file = root.join("calc.srn");
std::fs::write(&file, "total = 1\nprint(total)\ntotal += 2\n").unwrap();
let mut app = App::new(root).unwrap();
app.editor.open_pinned(&file).unwrap();
app.focus = Pane::Editor;
(app, file)
}
fn rename_total_to_sum(file: &Path) -> Vec<(PathBuf, Vec<crate::widgets::editor::TextSpanEdit>)> {
let span = |row, col| crate::widgets::editor::TextSpanEdit {
start: (row, col),
end: (row, col + 5),
new_text: String::from("sum"),
utf16: false,
};
vec![(file.to_path_buf(), vec![span(0, 0), span(1, 6), span(2, 0)])]
}
fn type_a_header_line(app: &mut App) {
app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
.unwrap();
type_keys(app, "# header");
}
fn app_with_terminal_panes(
n: usize,
) -> (
tempfile::TempDir,
App,
ratatui::Terminal<ratatui::backend::TestBackend>,
) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for _ in 1..n {
app.split_terminal().unwrap();
}
let term = draw_terminal(&mut app, 160, 30);
(tmp, app, term)
}
fn focused_terminal_app(dir: &std::path::Path) -> App {
let mut app = App::new(dir.to_path_buf()).unwrap();
app.focus_pane(Pane::Terminal);
app.bottom_panel_tab = BottomPanelTab::Terminal;
app.clipboard_reader = || Some(String::from("CLIP"));
app
}
fn no_paths() -> std::collections::BTreeSet<std::path::PathBuf> {
std::collections::BTreeSet::new()
}
fn repo_with_seed(text: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
git_init_with_identity(&root);
let f = root.join("seed.txt");
std::fs::write(&f, text).unwrap();
git_ok(&root, &["add", "."]);
git_ok(&root, &["commit", "-m", "init", "--quiet"]);
(tmp, f)
}
fn rewrite_later(path: &std::path::Path, text: &str) {
let stamp = |p: &std::path::Path| {
std::fs::metadata(p)
.ok()
.and_then(|m| Some((m.modified().ok()?, m.len())))
};
let before = stamp(path);
std::fs::write(path, text).unwrap();
let mut spins = 0;
while stamp(path) == before && spins < 400 {
std::thread::sleep(std::time::Duration::from_millis(5));
std::fs::write(path, text).unwrap();
spins += 1;
}
assert_ne!(
stamp(path),
before,
"the rewrite must move the file's stamp"
);
}
fn init_lane_repo(dir: &std::path::Path) {
std::fs::create_dir_all(dir).unwrap();
git_init_with_identity(dir);
std::fs::write(dir.join("seed.txt"), "one\n").unwrap();
git_ok(dir, &["add", "."]);
git_ok(dir, &["commit", "-q", "-m", "init"]);
}
fn queue_edit_proposal(
app: &mut App,
dir: &Path,
file: &Path,
old: &str,
new: &str,
) -> std::os::unix::net::UnixStream {
use std::io::Write;
let sock = dir.join("hook.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
app.hook_listener = Some(listener);
let mut hook = std::os::unix::net::UnixStream::connect(&sock).unwrap();
let req = crate::agent_hook::EditRequest {
agent: "claude-code".into(),
tool: "Edit".into(),
input: serde_json::json!({"file_path": file, "old_string": old, "new_string": new}),
cwd: dir.into(),
};
writeln!(hook, "{}", serde_json::to_string(&req).unwrap()).unwrap();
assert!(app.drain_hook_requests());
hook
}
fn seat_view_listener(app: &mut App, dir: &std::path::Path) -> std::path::PathBuf {
let sock = dir.join("view-test.sock");
let listener = crate::app::prepare_view_listener(&sock).unwrap();
app.view_listener = Some(listener);
sock
}
fn accept_when_ready(
listener: &std::os::unix::net::UnixListener,
) -> std::os::unix::net::UnixStream {
let budget = crate::test_budget::spawn_budget(crate::test_budget::tests::VIEW_ACCEPT_BASE);
let started = std::time::Instant::now();
loop {
match listener.accept() {
Ok((stream, _)) => return stream,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
assert!(
started.elapsed() < budget,
"no client connected within {budget:?}"
);
std::thread::sleep(std::time::Duration::from_millis(5));
}
Err(e) => panic!("accept failed: {e}"),
}
}
}
fn view_from_a_pane(
sock: &std::path::Path,
path: &std::path::Path,
) -> std::thread::JoinHandle<crate::view_ipc::ViewReply> {
let sock = sock.to_path_buf();
let path = path.to_path_buf();
std::thread::spawn(move || {
crate::view_ipc::send(&sock, &crate::view_ipc::ViewRequest::new(&path)).unwrap()
})
}
fn drain_until_answered(
app: &mut App,
client: &std::thread::JoinHandle<crate::view_ipc::ViewReply>,
) {
crate::test_budget::await_spawned(
crate::test_budget::tests::VIEW_DRAIN_BASE,
"the view request to be answered",
|| {
app.drain_view_requests();
client.is_finished()
},
);
}
fn stub_member(ends: bool) -> crate::dap::session::DapSession {
let script = if ends {
"printf 'Content-Length: %d\r\n\r\n%s' 45 '{\"seq\":1,\"type\":\"event\",\"event\":\"terminated\"}'; sleep 30"
} else {
"sleep 30"
};
crate::dap::session::DapSession::launch_with(
"sh",
&[String::from("-c"), String::from(script)],
std::path::Path::new("."),
serde_json::json!({"seq": 2, "type": "request", "command": "launch", "arguments": {}}),
std::collections::BTreeMap::new(),
)
.expect("sh spawns")
}
fn app_with_breakpoints() -> (tempfile::TempDir, App, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.rs");
let b = tmp.path().join("b.rs");
std::fs::write(&a, "fn a() {}\nfn b() {}\nfn c() {}\n").unwrap();
std::fs::write(&b, "x\ny\nz\nw\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.breakpoints
.entry(b.clone())
.or_default()
.insert(4);
app.editor
.breakpoints
.entry(a.clone())
.or_default()
.extend([3, 1]);
app.editor
.breakpoint_conditions
.entry(a.clone())
.or_default()
.insert(3, String::from("n > 2"));
app.editor
.breakpoint_logs
.entry(b.clone())
.or_default()
.insert(4, String::from("at {i}"));
(tmp, app, a, b)
}
fn poll_until_shrinks(app: &mut App, from: usize) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
while app.debug_sessions.len() >= from && std::time::Instant::now() < deadline {
app.poll_dap();
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
fn app_with_cleanup_task() -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/tasks.json"),
r#"{ "version": "2.0.0", "tasks": [
{ "label": "cleanup", "type": "shell", "command": "true" }
]}"#,
)
.unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
(tmp, app)
}
fn last_task_label(app: &App) -> Option<String> {
app.last_task.as_ref().map(|t| t.label.clone())
}
fn app_with_history(root: &std::path::Path) -> (App, tempfile::TempDir) {
let hist = tempfile::tempdir().unwrap();
let mut app = App::new(root.to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
(app, hist)
}
fn lens_at(line: usize, text: &str, title: &str, command: &str) -> crate::code_lens::EditorLens {
crate::code_lens::EditorLens {
line,
line_text: text.to_string(),
title: title.to_string(),
command: Some(command.to_string()),
arguments: Vec::new(),
server_side: false,
}
}
fn scrub_repo() -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
let git = |args: &[&str]| git_ok(tmp.path(), args);
git_init_with_identity(tmp.path());
let mut text = String::new();
for v in ["v1", "v2", "v3"] {
text.push_str(v);
text.push('\n');
std::fs::write(tmp.path().join("a.txt"), &text).unwrap();
git(&["add", "a.txt"]);
git(&["commit", "-q", "-m", v]);
}
tmp
}
fn codeql_app(root: PathBuf) -> App {
let mut app = App::new(root).unwrap();
app.installed_extensions.insert(String::from("codeql"));
app
}
fn add_codeql_in(config_dir: &Path) {
let dir = config_dir.join("extensions").join("codeql");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("extension.toml"),
crate::mcp::registry_index::CODEQL_MANIFEST,
)
.unwrap();
}
fn add_codeql(app: &mut App) -> tempfile::TempDir {
let config = tempfile::tempdir().unwrap();
add_codeql_in(config.path());
app.config_dir = config.path().to_path_buf();
app.test_worker
.set_extensions_dir(config.path().join("extensions"));
app.installed_extensions.insert(String::from("codeql"));
config
}
#[cfg(unix)]
struct CodeqlStandIn {
app: App,
root: String,
out: std::path::PathBuf,
code: std::path::PathBuf,
_dirs: [tempfile::TempDir; 3],
}
#[cfg(unix)]
const STAND_IN_PASS: &str = "[1/1 comp 1s eval 9ms] PASSED @ROOT@/test/Find/Find.qlref\n";
#[cfg(unix)]
impl CodeqlStandIn {
fn new() -> Self {
use crate::testing::model::{TestCase, TestStatus};
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::fs::create_dir_all(root.join("test/Find")).unwrap();
std::fs::write(root.join("test/qlpack.yml"), "name: acme/tests\ntests: .\n").unwrap();
std::fs::write(root.join("test/Find/Find.qlref"), "Find.ql\n").unwrap();
std::fs::write(root.join("test/Find/Find.expected"), "").unwrap();
let bin = tempfile::tempdir().unwrap();
let (out, code) = (bin.path().join("out"), bin.path().join("code"));
let program = bin.path().join("codeql");
std::fs::write(
&program,
format!(
"#!/bin/sh\ncat '{}'\nexit \"$(cat '{}')\"\n",
out.display(),
code.display()
),
)
.unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut app = App::new(root.clone()).unwrap();
let config = add_codeql(&mut app);
app.set_codeql_program(program);
app.testing.apply_case(TestCase {
name: "test/Find::Find.qlref".into(),
status: TestStatus::NotRun,
});
Self {
app,
root: root.display().to_string(),
out,
code,
_dirs: [tmp, bin, config],
}
}
fn will(&self, stdout: &str, exit: i32) {
std::fs::write(&self.out, stdout.replace("@ROOT@", &self.root)).unwrap();
std::fs::write(&self.code, exit.to_string()).unwrap();
}
fn finish(&mut self) {
let app = &mut self.app;
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the stand-in test run to finish",
|| {
let _ = app.test_worker.drain(&mut app.testing);
if app.testing.take_refusal() {
app.status = String::from(crate::testing::NO_RUNNER_STATUS);
}
app.sync_coverage();
app.tick_test_watch();
!app.testing.is_busy() && app.test_run_status.is_none()
},
);
}
}
fn long_task(label: &str) -> crate::tasks::Task {
crate::tasks::Task {
label: label.to_string(),
command: String::from("sleep 600"),
source: String::from("test"),
is_build: false,
is_default: false,
problem_matcher: None,
is_background: false,
vscode: None,
}
}
fn finish_pane_command(app: &mut App, uid: u64, exit: Option<i32>, millis: u64) {
app.terminals
.iter()
.find(|t| t.uid() == uid)
.expect("the pane is still open")
.finish_command_for_test(exit, std::time::Duration::from_millis(millis));
app.drain_terminal_bells();
}
fn sarif_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(
tmp.path().join("src/a.rs"),
"fn main() {\n let q = format!(\"{}\", id);\n}\n",
)
.unwrap();
let log = tmp.path().join("results.sarif");
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"lint","rules":[{"id":"R1","name":"Taint"}]}},
"results":[{"ruleId":"R1","level":"error","message":{"text":"Query built from user input."},
"locations":[{"physicalLocation":{"artifactLocation":{"uri":"src/a.rs"},
"region":{"startLine":2,"startColumn":9}}}]}]}]}"#,
)
.unwrap();
(tmp, log)
}
fn screen_text(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
let buf = term.backend().buffer();
let mut all = String::new();
for y in 0..buf.area.height {
for x in 0..buf.area.width {
all.push_str(buf[(x, y)].symbol());
}
all.push('\n');
}
all
}
fn screen_char_rows(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
let buf = term.backend().buffer();
(0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
.collect()
})
.collect()
}
#[cfg(unix)]
fn fake_codeql(dir: &std::path::Path, body: &str, code: i32, err: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let reply = dir.join("codeql-reply");
std::fs::write(&reply, body).unwrap();
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{log}'\nfor a in \"$@\"; do case \"$a\" in --output=*) cp '{reply}' \"${{a#--output=}}\" ;; esac; done\n[ -n '{err}' ] && echo '{err}' >&2\nexit {code}\n",
log = dir.join("codeql-calls.log").display(),
reply = reply.display(),
);
let bin = dir.join("codeql");
std::fs::write(&bin, script).unwrap();
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
bin
}
fn wait_for_codeql(app: &mut App) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.codeql_run.is_some() {
app.drain_codeql_run();
assert!(
std::time::Instant::now() < deadline,
"the query run never finished"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
fn codeql_query_fixture(tmp: &std::path::Path, source: &str) -> App {
let db = tmp.join("dbs/app");
std::fs::create_dir_all(&db).unwrap();
let store = crate::codeql_db::DatabaseStore {
databases: vec![crate::codeql_db::DbEntry {
name: String::from("app"),
path: db,
language: Some(String::from("rust")),
added: 0,
former_names: Vec::new(),
}],
current: Some(0),
sort_by: None,
};
store.save(&App::codeql_db_store_path()).unwrap();
let q = tmp.join("q.ql");
std::fs::write(&q, source).unwrap();
let mut app = codeql_app(tmp.to_path_buf());
app.editor.open(&q).unwrap();
app
}
#[cfg(unix)]
fn fake_query_server(dir: &std::path::Path, result: &str, csv: &str) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
std::fs::write(dir.join("result.json"), result).unwrap();
std::fs::write(dir.join("reply.csv"), csv).unwrap();
let script = format!(
r#"#!/usr/bin/env python3
import json, sys, shutil
d = {dir:?}
args = sys.argv[1:]
if args[:2] == ["execute", "query-server2"]:
inp, out = sys.stdin.buffer, sys.stdout.buffer
while True:
n = None
while True:
line = inp.readline()
if not line:
sys.exit(0)
line = line.strip()
if not line and n is not None:
break
if line.lower().startswith(b"content-length:"):
n = int(line.split(b":")[1])
msg = json.loads(inp.read(n))
with open(d + "/requests.jsonl", "a") as f:
f.write(json.dumps(msg) + "\n")
if msg["method"] == "evaluation/runQuery":
open(msg["params"]["body"]["outputPath"], "w").write("bqrs")
res = json.load(open(d + "/result.json"))
else:
res = {{}}
body = json.dumps({{"jsonrpc": "2.0", "id": msg["id"], "result": res}}).encode()
out.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
out.flush()
for a in args:
if a.startswith("--output="):
shutil.copy(d + "/reply.csv", a[len("--output="):])
"#,
dir = dir.display().to_string()
);
let program = dir.join("codeql");
std::fs::write(&program, script).unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
program
}
fn sarif_nav_fixture() -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "l1\nl2\nl3\nl4\nl5\nl6\n").unwrap();
std::fs::write(tmp.path().join("b.rs"), "m1\nm2\n").unwrap();
let log = tmp.path().join("nav.sarif");
let r = |uri: &str, line: u32, msg: &str| {
format!(
r#"{{"message":{{"text":"{msg}"}},"locations":[{{"physicalLocation":{{"artifactLocation":{{"uri":"{uri}"}},"region":{{"startLine":{line},"startColumn":1}}}}}}]}}"#
)
};
std::fs::write(
&log,
format!(
r#"{{"version":"2.1.0","runs":[{{"tool":{{"driver":{{"name":"lint"}}}},"results":[{},{},{}]}}]}}"#,
r("a.rs", 2, "first"),
r("a.rs", 5, "second"),
r("b.rs", 1, "third")
),
)
.unwrap();
(tmp, log)
}
fn codeql_run_on(tmp: &std::path::Path, db: &std::path::Path) -> PathBuf {
let log = tmp.join("results/run-1/results.sarif");
std::fs::create_dir_all(log.parent().unwrap()).unwrap();
std::fs::write(
&log,
r#"{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL"}},"results":[
{"message":{"text":"execute call"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"web.py","uriBaseId":"%SRCROOT%"},"region":{"startLine":4,"startColumn":5}}}]}
]}]}"#,
)
.unwrap();
let mut history = crate::codeql_query::History::default();
history.push(crate::codeql_query::HistoryEntry {
query: tmp.join("find_calls.ql"),
database: String::from("db"),
database_path: Some(db.to_path_buf()),
started: 1,
seconds: 3,
status: crate::codeql_query::RunStatus::Succeeded,
output: log.clone(),
name: None,
results: Some(1),
});
history.save(&App::codeql_history_path()).unwrap();
log
}
const WEB_PY_1369: &str = "import sqlite3\n\ndef q(cur, name):\n cur.execute(name)\n";
fn status_row(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
let buf = term.backend().buffer();
let y = buf.area.height - 1;
(0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect()
}
fn viewed_sync_gh(
dir: &std::path::Path,
graphql: &str,
) -> (std::path::PathBuf, std::path::PathBuf) {
use std::os::unix::fs::PermissionsExt;
let log = dir.join("gh-args");
let gh = dir.join("gh");
std::fs::write(
&gh,
format!(
r#"#!/bin/sh
echo "$@" >> '{}'
case "$*" in
"pr view"*) echo '{{"number": 42, "title": "t", "url": "https://github.com/x/y/pull/42", "author": {{"login": "a"}}, "files": [{{"path": "a.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}, {{"path": "b.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}, {{"path": "c.rs", "additions": 1, "deletions": 0, "changeType": "ADDED"}}], "statusCheckRollup": []}}' ;;
{graphql}
esac
"#,
log.display()
),
)
.unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
(gh, log)
}
fn settle_viewed_writes(app: &mut App) {
crate::test_budget::await_spawned(
std::time::Duration::from_secs(5),
"the viewed mutations",
|| {
app.poll_pr_gh();
app.pr_viewed_queue.is_empty() && app.pr_viewed_write.is_none()
},
);
}
fn assert_one_line_858(app: &App) {
let feedback = app
.source_control
.commit_feedback
.clone()
.unwrap_or_default();
for text in [&app.status, &feedback] {
assert!(!text.contains('\n'), "one line: {text:?}");
assert!(!text.contains("From "), "no fetch source: {text:?}");
assert!(!text.contains("To "), "no push destination: {text:?}");
}
}
fn app_with_plan_whose_folder_was_removed(tmp: &std::path::Path) -> App {
std::fs::create_dir(tmp.join("notes")).unwrap();
let mut app = app_with_open_file(tmp, "notes/plan.md", "# Plan\n\n- step one\n");
app.editor.cursor_row = 2;
app.editor.cursor_col = "- step one".len();
app.editor.insert_str("\n- step two");
std::fs::remove_dir_all(tmp.join("notes")).unwrap();
app
}
fn save_as(app: &mut App, answer: &str) {
let cmd = crate::widgets::command_palette::Command::from_id("save_as")
.expect("there is a File: Save As… command");
app.run_command(cmd);
let prompt = app.prompt.as_mut().expect("Save As asks for a path");
prompt.buffer = answer.to_string();
app.commit_prompt();
}
fn new_untitled_chords() -> Vec<KeyModifiers> {
if cfg!(target_os = "macos") {
vec![KeyModifiers::SUPER]
} else {
vec![KeyModifiers::CONTROL, KeyModifiers::SUPER]
}
}
fn revert_file(app: &mut App) {
let cmd = crate::widgets::command_palette::Command::from_id("revert_file")
.expect("there is a File: Revert File command");
app.run_command(cmd);
}
fn open_palette_852(app: &mut App) {
app.handle_key(key(
KeyCode::Char('p'),
KeyModifiers::SUPER | KeyModifiers::SHIFT,
))
.unwrap();
assert!(
app.command_palette.is_some(),
"Cmd+Shift+P opens the palette"
);
}
fn tabs_app_852(names: &[&str]) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.auto_save = false;
app.auto_save_on_focus_change = false;
for name in names {
let p = tmp.path().join(name);
std::fs::write(&p, "x\n").unwrap();
app.editor.open_pinned(&p).unwrap();
}
app.focus_pane(Pane::Editor);
(app, tmp)
}
fn tab_names_852(tabs: &crate::widgets::editor::EditorTabs) -> Vec<String> {
tabs.editors
.iter()
.map(|e| {
e.path
.as_deref()
.and_then(Path::file_name)
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
})
.collect()
}
fn run_palette_top_match(app: &mut App, query: &str) -> Option<String> {
open_palette_852(app);
type_keys(app, query);
let ran = app
.command_palette
.as_ref()
.and_then(|p| p.selected_item())
.map(|item| item.title().to_string());
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
ran
}
fn type_into_active_tab_852(app: &mut App) {
app.focus_pane(Pane::Editor);
app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
.unwrap();
assert!(
app.editor.dirty,
"fixture: the active tab has unsaved edits"
);
}
fn split_tabs_app_852(active: &str) -> (App, tempfile::TempDir) {
let (mut app, tmp) = tabs_app_852(&["a.rs", "b.rs"]);
app.split_editor();
assert!(app.editor_layout.is_split(), "fixture: two groups");
for name in ["c.rs", "d.rs", "e.rs"] {
let p = tmp.path().join(name);
std::fs::write(&p, "x\n").unwrap();
app.editor.open_pinned(&p).unwrap();
}
app.editor.toggle_pin(0);
app.editor.select(1);
let p = tmp.path().join("p.rs");
std::fs::write(&p, "x\n").unwrap();
app.editor.open_preview(&p).unwrap();
app.editor.select(3);
type_into_active_tab_852(&mut app);
assert_eq!(
tab_names_852(&app.editor),
["b.rs", "c.rs", "p.rs", "d.rs", "e.rs"],
"fixture"
);
let idx = tab_names_852(&app.editor)
.iter()
.position(|n| n == active)
.unwrap();
app.editor.select(idx);
app.status.clear();
(app, tmp)
}
type TabsSnapshot852 = (
Vec<Vec<(String, bool, bool, bool)>>,
usize,
bool,
String,
Vec<String>,
);
fn tabs_snapshot_852(app: &App) -> TabsSnapshot852 {
let group = |tabs: &crate::widgets::editor::EditorTabs| {
tab_names_852(tabs)
.into_iter()
.zip(&tabs.editors)
.map(|(n, e)| (n, e.pinned, e.preview, e.dirty))
.collect::<Vec<_>>()
};
let mut groups = vec![group(&app.editor)];
groups.extend(app.editor_layout.inactive_groups().map(group));
(
groups,
app.editor.active_index(),
app.editor_layout.is_split(),
app.status.clone(),
app.closed_tabs
.iter()
.map(|t| t.path.file_name().unwrap().to_string_lossy().into_owned())
.collect(),
)
}
fn plain_paste_app() -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 30")],
tmp.path(),
)
.unwrap();
app.active_terminal = 0;
app.focus_pane(Pane::Terminal);
(app, tmp)
}
fn pasted(app: &App) -> String {
String::from_utf8_lossy(&app.terminals[0].written_bytes_for_test()).into_owned()
}
const TWO_LINES: &str = "echo first-line\ntouch pasted-ran\n";
fn two_pane_paste_app() -> (App, tempfile::TempDir) {
let (mut app, tmp) = plain_paste_app();
app.split_terminal().unwrap();
app.active_terminal = 0;
app.focus_pane(Pane::Terminal);
app.terminal_pane_maximized = true;
draw(&mut app, 180, 40);
(app, tmp)
}
fn wide_line_app(tmp: &std::path::Path) -> (App, ratatui::Terminal<ratatui::backend::TestBackend>) {
let line = format!(
"start {} END",
(0..120)
.map(|i| format!("w{i:03}"))
.collect::<Vec<_>>()
.join(" ")
);
let mut app = app_with_open_file(tmp, "h300.txt", &format!("{line}\nshort\n"));
app.focus_pane(Pane::Editor);
let term = draw_terminal(&mut app, 100, 30);
(app, term)
}
fn encoded_repo(name: &str, head: &[u8], added: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = make_committed_repo();
let f = tmp.path().join(name);
std::fs::write(&f, head).unwrap();
let _ = git_succeeds(tmp.path(), &["add", name]);
let _ = git_succeeds(tmp.path(), &["commit", "-qm", "encoded"]);
std::fs::write(&f, [head, added].concat()).unwrap();
(tmp, f)
}
const LATIN1_HEAD: &[u8] = b"name;city\nM\xfcller;K\xf6ln\nJos\xe9;M\xe1laga\n";
const LATIN1_ADDED: &[u8] = b"Zo\xeb;Z\xfcrich\n";
fn app_with_a_disk_conflict(tmp: &std::path::Path) -> (App, std::path::PathBuf) {
let f = tmp.join("tax.py");
std::fs::write(&f, "RATE = 0.1\n").unwrap();
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.history_root = tmp.join(".history");
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 0;
app.editor.cursor_col = "RATE = 0.1".len();
app.editor
.insert_str("\ndef tax(amount):\n return amount * RATE");
assert!(app.editor.dirty);
std::fs::write(&f, "RATE = 0.2 # from the other branch\n").unwrap();
app.reload_open_file_after_external_change();
assert!(
matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::ReloadConflict { .. })
),
"the conflict prompt opens"
);
(app, f)
}
fn type_keys(app: &mut App, text: &str) {
for c in text.chars() {
type_char(app, c);
}
}
fn append_and_submit_prompt(app: &mut App, text: &str) {
for c in text.chars() {
app.input_prompt.as_mut().unwrap().push_char(c);
}
app.submit_input_prompt();
}
fn find_seed_app(row: usize, col: usize) -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("orders.py");
std::fs::write(
&f,
"def loadOrders(path):\n return readRows(path)\n\n\ndef saveOrders(path, rows):\n writeRows(path, rows)\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = row;
app.editor.cursor_col = col;
(app, tmp)
}
fn ctrl(c: char) -> KeyEvent {
key(KeyCode::Char(c), KeyModifiers::CONTROL)
}
fn find_query(app: &App) -> String {
app.editor_find.as_ref().map(|s| s.query.clone()).unwrap()
}
fn secondary_outline_app(tmp: &tempfile::TempDir, n: u32) -> (App, std::path::PathBuf) {
use crate::lsp::manager::{OutlineKind, OutlineSymbol};
let f = tmp.path().join("m.py");
let text: String = (0..n)
.map(|i| format!("def sym_{i:03}(x):\n return x\n"))
.collect();
std::fs::write(&f, text).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.explorer_views = Default::default();
app.editor.open_pinned(&f).unwrap();
let syms = (0..n)
.map(|i| OutlineSymbol {
name: format!("sym_{i:03}"),
detail: None,
kind: OutlineKind::Function,
depth: 0,
line: 2 * i,
character: 4,
range_start_line: 2 * i,
range_start_character: 0,
range_end_line: 2 * i + 1,
range_end_character: 12,
})
.collect();
app.outline.set_symbols(f.clone(), syms);
app.outline.collapsed = false;
app.secondary_side_bar_visible = true;
(app, f)
}
fn outline_hosts(app: &App) -> (std::ops::Range<u16>, std::ops::Range<u16>) {
let e = app.editor.last_full_area;
(0..e.x, e.x + e.width..e.x + e.width + 60)
}
fn find_painted(
term: &ratatui::Terminal<ratatui::backend::TestBackend>,
text: &str,
xs: std::ops::Range<u16>,
) -> Option<(u16, u16)> {
let buf = term.backend().buffer();
(0..buf.area.height).find_map(|y| {
let row: String = xs
.clone()
.filter_map(|x| buf.cell((x, y)).map(|c| c.symbol().to_string()))
.collect();
let at = row.find(text)?;
Some((xs.start + row[..at].chars().count() as u16, y))
})
}
#[cfg(unix)]
fn fake_tsc_workspace(tsconfig: &str) -> tempfile::TempDir {
use std::os::unix::fs::PermissionsExt as _;
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("tsconfig.json"), tsconfig).unwrap();
std::fs::create_dir_all(tmp.path().join("src")).unwrap();
std::fs::write(tmp.path().join("src/main.ts"), "const n: string = 1;\n").unwrap();
let bin = tmp.path().join("node_modules/.bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(
bin.join("tsc"),
"#!/bin/sh\necho \"$*\" >> calls.log\ncase \"$*\" in *tsconfig.app.json*) \
echo \"src/main.ts(1,7): error TS2322: Type 'number' is not assignable to type 'string'.\"; \
exit 2;; esac\nexit 0\n",
)
.unwrap();
std::fs::set_permissions(bin.join("tsc"), std::fs::Permissions::from_mode(0o755)).unwrap();
tmp
}
#[cfg(unix)]
fn run_project_check(tmp: &tempfile::TempDir) -> (String, String) {
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(crate::widgets::command_palette::Command::ProblemsCheckProject);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while app.project_check.is_some() && std::time::Instant::now() < deadline {
if !app.drain_project_check() {
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
let calls = std::fs::read_to_string(tmp.path().join("calls.log")).unwrap_or_default();
(app.status.clone(), calls)
}
fn app_with_a_saved_edit() -> (tempfile::TempDir, std::path::PathBuf, App) {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.py");
std::fs::write(&a, "value = 1\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.focus_pane(Pane::Editor);
app.handle_editor_key(key(KeyCode::End, KeyModifiers::NONE));
type_keys(&mut app, "00");
app.handle_key(ctrl('s')).unwrap();
assert_eq!(std::fs::read_to_string(&a).unwrap(), "value = 100\n");
assert!(!app.editor.dirty);
(tmp, a, app)
}
fn app_on_a_pushed_github_file() -> (App, tempfile::TempDir, String) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
let git = |args: &[&str]| git_ok(p, args);
git_init(p);
std::fs::create_dir(p.join("src")).unwrap();
std::fs::write(
p.join("src/main.rs"),
"fn main() {\n println!(\"hi\");\n println!(\"there\");\n}\n",
)
.unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "init"]);
git(&["remote", "add", "origin", "git@github.com:acme/widgets.git"]);
git(&["update-ref", "refs/remotes/origin/main", "HEAD"]);
let sha = git(&["rev-parse", "HEAD"]);
let mut app = App::new(p.to_path_buf()).unwrap();
app.editor.open_pinned(&p.join("src/main.rs")).unwrap();
app.focus_pane(Pane::Editor);
(app, tmp, sha)
}
fn three_tab_app_1565() -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "a = 1\n");
app.editor.pin_active();
for name in ["b.py", "c.py"] {
let p = tmp.path().join(name);
std::fs::write(&p, "x = 1\n").unwrap();
app.editor.open_pinned(&p).unwrap();
}
app.focus_pane(Pane::Editor);
assert_eq!(tab_names_852(&app.editor), ["a.py", "b.py", "c.py"]);
(app, tmp)
}
fn app_with_merge_editor_open(dir: &std::path::Path) -> (App, std::path::PathBuf) {
let file = dir.join("f.txt");
std::fs::write(
&file,
"top\n<<<<<<< HEAD\nmine\n=======\nyours\n>>>>>>> other\nbottom\n",
)
.unwrap();
let mut app = App::new(dir.to_path_buf()).unwrap();
app.editor.open_pinned(&file).unwrap();
app.focus_pane(Pane::Editor);
app.run_command(crate::widgets::command_palette::Command::MergeOpenEditor);
assert!(app.editor.merge.is_some(), "setup: the merge editor is up");
app.run_command(crate::widgets::command_palette::Command::MergeAcceptCurrent);
assert!(app.editor.dirty, "setup: the Result is unsaved");
(app, file)
}