use crate::tui::TuiError;
use crate::tui::app::{
App, AttachRequest, ClickTarget, Command, DOUBLE_CLICK_WINDOW, KillWindow, LaunchRejection,
Mode, View,
};
use crate::tui::dialogs::switcher::WorktreeRow;
use crate::tui::ui;
use crate::tui::views::terminals::tmux::{attach_tmux, refresh_tmux_windows};
use crossterm::{
event::{
DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind,
KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
},
execute,
terminal::{
EnterAlternateScreen, LeaveAlternateScreen, SetTitle, disable_raw_mode, enable_raw_mode,
},
};
use ratatui::{Terminal, backend::CrosstermBackend};
use std::io::{Stdout, Write, stdout};
use std::time::Duration;
use tokio::sync::mpsc;
use tracing::warn;
const POLL_INTERVAL_MS: u64 = 100;
const TICK_INTERVAL_MS: u64 = 250;
#[derive(Debug)]
pub enum DriveOutcome {
Quit,
SwitchWorktree {
path: std::path::PathBuf,
view: View,
},
}
pub async fn run_event_loop(app: &mut App, initial_view: View) -> Result<DriveOutcome, TuiError> {
let title = terminal_title(app);
let mut terminal = enter_terminal(&title)?;
match initial_view {
View::Terminals => {
app.request_tmux_probe();
refresh_tmux_windows(app, false).await;
}
View::Diff => {
app.request_diff_reload();
}
View::ControlCenter => {}
}
let result = drive(&mut terminal, app).await;
leave_terminal(&mut terminal)?;
let diagnostics = app.drain_diagnostics();
if !diagnostics.is_empty() {
eprintln!();
for line in diagnostics {
eprintln!("{line}");
}
}
result
}
fn terminal_title(app: &App) -> String {
let project = app
.config()
.project
.name
.clone()
.unwrap_or_else(|| "croft".into());
format!("croft — {project}")
}
async fn drive(
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
app: &mut App,
) -> Result<DriveOutcome, TuiError> {
app.spawn_service_tails().await;
let mut events = spawn_event_reader();
'outer: loop {
app.drain_boot_results();
app.drain_worker_snapshots();
app.drain_messages();
app.drain_runs();
app.poll_runs();
app.drain_services();
app.tick_watchers();
terminal.draw(|f| ui::render(app, f))?;
if app.should_quit() {
return Ok(DriveOutcome::Quit);
}
for cmd in app.drain_commands() {
match cmd {
Command::EmitBell => {
let mut out = stdout();
let _ = out.write_all(b"\x07");
let _ = out.flush();
}
Command::SwitchWorktree(path) => {
return Ok(DriveOutcome::SwitchWorktree {
path,
view: app.view(),
});
}
Command::AttachTmux(req) => {
run_attach(app, req, &mut events, terminal).await?;
continue 'outer;
}
Command::KillTmuxWindow(kill) => {
run_kill_window(app, kill).await;
}
Command::OpenLazygit => {
run_lazygit(app, &mut events, terminal).await?;
continue 'outer;
}
Command::OpenEditor { target } => {
let suspended = run_editor(app, &mut events, terminal, &target).await?;
if suspended {
continue 'outer;
}
}
}
}
tokio::select! {
biased;
ev = events.recv() => {
let Some(ev) = ev else { return Ok(DriveOutcome::Quit) };
handle_event(app, ev).await;
}
_ = tokio::time::sleep(Duration::from_millis(TICK_INTERVAL_MS)) => {
}
}
}
}
async fn run_attach(
app: &mut App,
req: AttachRequest,
events: &mut mpsc::UnboundedReceiver<Event>,
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
) -> Result<(), TuiError> {
if let Some(ensure) = &req.ensure
&& let Err(e) = ensure.backend.ensure_up().await
{
app.flash(format!("devcontainer ensure-up failed: {e}"));
return Ok(());
}
let old_events = std::mem::replace(events, mpsc::unbounded_channel().1);
drop(old_events);
leave_terminal(terminal)?;
attach_tmux(&req).await;
*terminal = enter_terminal(&terminal_title(app))?;
terminal.clear()?;
*events = spawn_event_reader();
let verbose = std::env::var("CROFT_DEBUG_INPUT")
.map(|v| !v.is_empty() && v != "0")
.unwrap_or(false);
let drain_deadline = std::time::Instant::now() + Duration::from_millis(150);
let mut drained_count = 0usize;
while std::time::Instant::now() < drain_deadline {
match tokio::time::timeout(Duration::from_millis(30), events.recv()).await {
Ok(Some(ev)) => {
drained_count += 1;
if verbose {
app.diagnostic(format!("[input] {ev:?}"));
}
}
Ok(None) => break,
Err(_) => {} }
}
if verbose && drained_count > 0 {
app.diagnostic(format!(
"[input] discarded {drained_count} post-detach phantom event(s) — terminal mode-restore artefacts"
));
}
app.discard_pending_tmux_snapshots();
app.terminals_mut().silence_next_bell();
refresh_tmux_windows(app, true).await;
terminal.draw(|f| ui::render(app, f))?;
Ok(())
}
async fn run_kill_window(app: &mut App, kill: KillWindow) {
let _ = tokio::process::Command::new("tmux")
.args([
"kill-window",
"-t",
&format!("{}:{}", kill.session, kill.index),
])
.status()
.await;
refresh_tmux_windows(app, false).await;
}
async fn run_lazygit(
app: &mut App,
events: &mut mpsc::UnboundedReceiver<Event>,
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
) -> Result<(), TuiError> {
let old_events = std::mem::replace(events, mpsc::unbounded_channel().1);
drop(old_events);
leave_terminal(terminal)?;
if let Err(msg) = crate::tui::lazygit::run(app.project_root()).await {
app.flash(msg.clone());
app.diagnostic(format!("[lazygit] {msg}"));
}
*terminal = enter_terminal(&terminal_title(app))?;
terminal.clear()?;
*events = spawn_event_reader();
app.diff_mut().mark_stale();
app.request_diff_reload();
terminal.draw(|f| ui::render(app, f))?;
Ok(())
}
async fn run_editor(
app: &mut App,
events: &mut mpsc::UnboundedReceiver<Event>,
terminal: &mut Terminal<CrosstermBackend<Stdout>>,
target: &std::path::Path,
) -> Result<bool, TuiError> {
let editor = app.editor().clone();
match editor.mode {
crate::tui::editor::LaunchMode::Terminal => {
let old_events = std::mem::replace(events, mpsc::unbounded_channel().1);
drop(old_events);
leave_terminal(terminal)?;
if let Err(msg) =
crate::tui::editor::run_terminal(app.project_root(), &editor, target).await
{
app.flash(msg.clone());
app.diagnostic(format!("[editor] {msg}"));
}
*terminal = enter_terminal(&terminal_title(app))?;
terminal.clear()?;
*events = spawn_event_reader();
app.diff_mut().mark_stale();
app.request_diff_reload();
terminal.draw(|f| ui::render(app, f))?;
Ok(true)
}
crate::tui::editor::LaunchMode::Gui => {
match crate::tui::editor::spawn_gui(app.project_root(), &editor, target) {
Ok(()) => {
let name = editor.display_name();
let shown = target.display();
app.flash(format!("opened {shown} in {name}"));
}
Err(msg) => {
app.flash(msg.clone());
app.diagnostic(format!("[editor] {msg}"));
}
}
Ok(false)
}
}
}
pub(crate) async fn handle_event(app: &mut App, event: Event) {
match event {
Event::Key(KeyEvent {
kind: KeyEventKind::Press,
code,
modifiers,
..
}) => {
app.clear_flash();
match app.mode() {
Mode::Normal => handle_key_normal(app, code, modifiers).await,
Mode::Palette => {
crate::tui::dialogs::palette_input::handle_key(app, code, modifiers).await
}
Mode::Confirm => {
crate::tui::dialogs::confirm_input::handle_key(app, code, modifiers)
}
Mode::ArgsPrompt => {
crate::tui::dialogs::args_prompt_input::handle_key(app, code, modifiers)
}
Mode::WorktreeSwitcher => {
crate::tui::dialogs::switcher_input::handle_key(app, code, modifiers).await
}
}
}
Event::Mouse(me) => handle_mouse(app, me).await,
Event::Resize(_, _) => {
}
_ => {}
}
}
async fn handle_mouse(app: &mut App, me: MouseEvent) {
match app.mode() {
Mode::Palette => crate::tui::dialogs::palette_input::handle_mouse(app, me).await,
Mode::Confirm => crate::tui::dialogs::confirm_input::handle_mouse(app, me),
Mode::WorktreeSwitcher => crate::tui::dialogs::switcher_input::handle_mouse(app, me).await,
Mode::ArgsPrompt => {}
Mode::Normal => match app.view() {
View::ControlCenter => handle_mouse_control_center(app, me).await,
View::Terminals => crate::tui::views::terminals::input::handle_mouse(app, me),
View::Diff => crate::tui::views::diff::input::handle_mouse(app, me).await,
},
}
}
pub(crate) fn hit_test(rects: &[ratatui::layout::Rect], col: u16, row: u16) -> Option<usize> {
rects.iter().position(|r| rect_contains(*r, col, row))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ClickKind {
Select,
Activate,
}
pub(crate) fn resolve_click(app: &mut App, target: ClickTarget) -> ClickKind {
let now = std::time::Instant::now();
let activate = app
.last_click
.map(|(t, prev)| prev == target && now.duration_since(t) <= DOUBLE_CLICK_WINDOW)
.unwrap_or(false);
if activate {
app.last_click = None;
ClickKind::Activate
} else {
app.last_click = Some((now, target));
ClickKind::Select
}
}
pub(crate) fn rect_contains(rect: ratatui::layout::Rect, col: u16, row: u16) -> bool {
col >= rect.x
&& col < rect.x.saturating_add(rect.width)
&& row >= rect.y
&& row < rect.y.saturating_add(rect.height)
}
pub(crate) const WHEEL_LINES: i32 = 3;
async fn handle_mouse_control_center(app: &mut App, me: MouseEvent) {
match me.kind {
MouseEventKind::Down(MouseButton::Left) => {
let hit = {
let rects = app.sidebar_item_rects.borrow();
hit_test(&rects, me.column, me.row)
};
let Some(idx) = hit else {
return;
};
let target = ClickTarget::SidebarItem(idx);
match resolve_click(app, target) {
ClickKind::Select => app.select_at(idx),
ClickKind::Activate => {
app.select_at(idx);
activate_control_center_selection(app).await;
}
}
}
MouseEventKind::ScrollDown => {
for _ in 0..WHEEL_LINES {
app.select_next();
}
}
MouseEventKind::ScrollUp => {
for _ in 0..WHEEL_LINES {
app.select_prev();
}
}
_ => {}
}
}
async fn handle_key_normal(app: &mut App, code: KeyCode, modifiers: KeyModifiers) {
if modifiers.contains(KeyModifiers::CONTROL) {
match code {
KeyCode::Char('c') => app.quit(),
KeyCode::Char('k') | KeyCode::Char('p') => app.open_palette(),
_ => {}
}
return;
}
match code {
KeyCode::Char('T') => {
app.switch_view(View::Terminals);
app.request_tmux_probe();
refresh_tmux_windows(app, false).await;
return;
}
KeyCode::Char('G') => {
app.switch_view(View::Diff);
app.request_diff_reload();
return;
}
KeyCode::Char('C') if app.view() != View::ControlCenter => {
app.switch_view(View::ControlCenter);
return;
}
KeyCode::Char('W') => {
let entries = build_worktree_rows(app).await;
app.open_worktree_switcher(entries);
return;
}
KeyCode::Char('E') => {
if app.editor().opens_directory {
app.request_open_worktree_in_editor();
} else {
let name = app.editor().display_name().to_owned();
app.flash(format!(
"E (open worktree) needs an editor that handles directories; {name} doesn't — set [editor] in croft.toml"
));
}
return;
}
_ => {}
}
if app.view() == View::Terminals {
crate::tui::views::terminals::input::handle_key(app, code, modifiers).await;
return;
}
if app.view() == View::Diff {
crate::tui::views::diff::input::handle_key(app, code, modifiers).await;
return;
}
match code {
KeyCode::Char('q') => app.quit(),
KeyCode::Down | KeyCode::Char('j') => app.select_next(),
KeyCode::Up | KeyCode::Char('k') => app.select_prev(),
KeyCode::Home => app.select_first(),
KeyCode::End => app.select_last(),
KeyCode::Char(':') | KeyCode::Char('/') => app.open_palette(),
KeyCode::Char('s') => {
if app.abort_selected_run() {
app.flash("aborted run");
} else if app.abort_lifecycle_run() {
app.flash("aborted lifecycle run");
} else if let Some(service) = app.selected_service().map(|s| s.name.clone())
&& let Err(rej) = app
.run_service_action(crate::container::service_action::STOP, &[service.as_str()])
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Char('S') => {
if app.abort_lifecycle_run() {
app.flash("aborted lifecycle run");
} else if let Err(rej) = app
.run_service_action(crate::container::service_action::STOP, &[])
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Char('r') => {
if let Some(service) = app.selected_service().map(|s| s.name.clone())
&& let Err(rej) = app
.run_service_action(
crate::container::service_action::RESTART,
&[service.as_str()],
)
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Char('R') => {
if let Err(rej) = app
.run_service_action(crate::container::service_action::RESTART, &[])
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Char('u') => {
if let Some(service) = app.selected_service().map(|s| s.name.clone())
&& let Err(rej) = app
.run_service_action(crate::container::service_action::UP, &[service.as_str()])
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Char('U') => {
if let Err(rej) = app
.run_service_action(crate::container::service_action::UP, &[])
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Char('D') => {
if let Err(rej) = app
.run_service_action(crate::container::service_action::DOWN, &[])
.await
{
app.flash(launch_message(rej));
}
}
KeyCode::Enter => activate_control_center_selection(app).await,
_ => {}
}
}
async fn activate_control_center_selection(app: &mut App) {
if let Some(service) = app.selected_service().map(|s| s.name.clone()) {
app.request_tmux_probe();
if app.terminals().tmux_available == Some(false) {
app.flash("tmux not installed — install it to attach");
} else if let Err(msg) = app.queue_service_attach(&service) {
app.flash(msg);
}
} else if app.selected_accepts_args() && !selected_is_running(app) {
app.open_args_prompt();
} else {
match app.try_launch_selected() {
Ok(()) => {}
Err(LaunchRejection::AlreadyRunning) => {
app.open_kill_restart_confirm();
}
Err(rej) => {
app.flash(launch_message(rej));
}
}
}
}
fn selected_is_running(app: &App) -> bool {
app.selected_run().is_some_and(|r| !r.is_done())
}
async fn build_worktree_rows(app: &App) -> Vec<WorktreeRow> {
let project_root = app.project_root().to_path_buf();
let entries = crate::runtime::worktree::list_worktrees(&project_root).await;
let current = std::fs::canonicalize(&project_root).unwrap_or(project_root);
entries
.into_iter()
.map(|e| {
let path_buf = std::path::PathBuf::from(&e.path);
let canonical = std::fs::canonicalize(&path_buf).unwrap_or_else(|_| path_buf.clone());
let slug = derive_slug_from_entry(&e);
WorktreeRow {
path: path_buf,
branch: e.branch.clone(),
slug,
is_current: canonical == current,
}
})
.collect()
}
fn derive_slug_from_entry(e: &crate::runtime::WorktreeListEntry) -> String {
if let Some(branch) = e.branch.as_deref() {
return crate::runtime::worktree::slugify(branch);
}
if e.detached {
return crate::runtime::worktree::slugify(
std::path::Path::new(&e.path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(""),
);
}
String::new()
}
pub(crate) fn launch_message(rejection: LaunchRejection) -> String {
use LaunchRejection::*;
match rejection {
NoExecutor => "no backend wired into the TUI".into(),
AlreadyRunning => "another run is in progress".into(),
NotRunnable(msg) => msg,
}
}
fn enter_terminal(title: &str) -> Result<Terminal<CrosstermBackend<Stdout>>, TuiError> {
enable_raw_mode()?;
let mut out = stdout();
execute!(
out,
EnterAlternateScreen,
EnableMouseCapture,
SetTitle(title)
)?;
let backend = CrosstermBackend::new(out);
Ok(Terminal::new(backend)?)
}
fn leave_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<(), TuiError> {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture,
SetTitle(""),
)?;
terminal.show_cursor()?;
Ok(())
}
fn spawn_event_reader() -> mpsc::UnboundedReceiver<Event> {
let (tx, rx) = mpsc::unbounded_channel();
tokio::task::spawn_blocking(move || {
loop {
if tx.is_closed() {
return;
}
match crossterm::event::poll(Duration::from_millis(POLL_INTERVAL_MS)) {
Ok(true) => match crossterm::event::read() {
Ok(ev) => {
if tx.send(ev).is_err() {
return;
}
}
Err(e) => {
warn!("crossterm read error: {e}");
return;
}
},
Ok(false) => {}
Err(e) => {
warn!("crossterm poll error: {e}");
return;
}
}
}
});
rx
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tui::views::diff::git::{
annotate_read_with_diff, enrich_diff_lines, parse_diff_name_status, parse_hunk_header,
parse_numstat, parse_status_porcelain, resolve_numstat_destination,
};
use crate::tui::views::diff::state::{
DiffLine, DiffLineKind, DiffStatus, ReadLine, ReadLineKind,
};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use std::sync::Arc;
fn press(code: KeyCode) -> Event {
Event::Key(KeyEvent {
code,
modifiers: KeyModifiers::NONE,
kind: KeyEventKind::Press,
state: crossterm::event::KeyEventState::NONE,
})
}
fn ctrl(code: KeyCode) -> Event {
Event::Key(KeyEvent {
code,
modifiers: KeyModifiers::CONTROL,
kind: KeyEventKind::Press,
state: crossterm::event::KeyEventState::NONE,
})
}
fn app_with(toml: &str) -> App {
let prefix = if toml.contains("[runtime]") {
String::new()
} else {
String::from("[runtime]\nbackend = \"none\"\n")
};
App::new(Arc::new(
crate::config::parse_str(&format!("{prefix}{toml}")).unwrap(),
))
}
#[tokio::test]
async fn q_quits() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
handle_key_normal(&mut app, KeyCode::Char('q'), KeyModifiers::NONE).await;
assert!(app.should_quit());
}
#[tokio::test]
async fn ctrl_c_quits() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
handle_event(&mut app, ctrl(KeyCode::Char('c'))).await;
assert!(app.should_quit());
}
#[tokio::test]
async fn navigation_moves_selection() {
let mut app = app_with(
"[command.a]\nrun = \"true\"\n[command.b]\nrun = \"true\"\n[command.c]\nrun = \"true\"\n",
);
assert_eq!(app.selected_index(), 0);
handle_event(&mut app, press(KeyCode::Char('j'))).await;
assert_eq!(app.selected_index(), 1);
handle_event(&mut app, press(KeyCode::Down)).await;
assert_eq!(app.selected_index(), 2);
handle_event(&mut app, press(KeyCode::End)).await;
assert_eq!(app.selected_index(), 2);
handle_event(&mut app, press(KeyCode::Home)).await;
assert_eq!(app.selected_index(), 0);
}
#[tokio::test]
async fn capital_t_switches_to_terminals_view() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
assert_eq!(app.view(), View::ControlCenter);
handle_event(&mut app, press(KeyCode::Char('T'))).await;
assert_eq!(app.view(), View::Terminals);
}
#[tokio::test]
async fn capital_w_works_from_terminals_view() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
app.switch_view(View::Terminals);
handle_event(&mut app, press(KeyCode::Char('W'))).await;
assert_eq!(app.mode(), Mode::WorktreeSwitcher);
}
#[tokio::test]
async fn capital_w_works_from_diff_view() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
app.switch_view(View::Diff);
handle_event(&mut app, press(KeyCode::Char('W'))).await;
assert_eq!(app.mode(), Mode::WorktreeSwitcher);
}
#[tokio::test]
async fn capital_g_switches_to_diff_view() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
handle_event(&mut app, press(KeyCode::Char('G'))).await;
assert_eq!(app.view(), View::Diff);
}
#[tokio::test]
async fn lowercase_g_does_not_switch_views() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
handle_event(&mut app, press(KeyCode::Char('g'))).await;
assert_eq!(app.view(), View::ControlCenter);
}
#[test]
fn parse_status_porcelain_classifies_each_line() {
use DiffStatus;
let input = concat!(
" M src/main.rs\n",
"A src/lib.rs\n",
"?? notes.txt\n",
" D Cargo.toml\n",
"R old.txt -> new.txt\n",
);
let files = parse_status_porcelain(input);
assert_eq!(files.len(), 5);
assert_eq!(files[0].status, DiffStatus::Modified);
assert_eq!(files[0].path, "src/main.rs");
assert_eq!(files[1].status, DiffStatus::Added);
assert_eq!(files[2].status, DiffStatus::Untracked);
assert_eq!(files[2].path, "notes.txt");
assert_eq!(files[3].status, DiffStatus::Deleted);
assert_eq!(files[4].status, DiffStatus::Renamed);
assert_eq!(files[4].path, "new.txt");
}
#[test]
fn parse_diff_name_status_basic() {
use DiffStatus;
let input = "M\tsrc/main.rs\nA\tsrc/lib.rs\nD\tCargo.toml\nR090\told.txt\tnew.txt\n";
let entries = parse_diff_name_status(input);
assert_eq!(entries.len(), 4);
assert_eq!(entries[0].status, DiffStatus::Modified);
assert_eq!(entries[0].path, "src/main.rs");
assert_eq!(entries[1].status, DiffStatus::Added);
assert_eq!(entries[2].status, DiffStatus::Deleted);
assert_eq!(entries[3].status, DiffStatus::Renamed);
assert_eq!(entries[3].path, "new.txt");
}
#[test]
fn parse_diff_name_status_skips_blank_and_malformed() {
let input = "\nM\n\t\nM\tok.rs\n";
let entries = parse_diff_name_status(input);
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].path, "ok.rs");
}
#[test]
fn parse_numstat_text_and_binary() {
let input = "10\t3\tsrc/main.rs\n0\t5\tCargo.toml\n-\t-\tassets/logo.png\n";
let entries = parse_numstat(input);
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].path, "src/main.rs");
assert_eq!(entries[0].additions, 10);
assert_eq!(entries[0].deletions, 3);
assert!(!entries[0].binary);
assert_eq!(entries[1].additions, 0);
assert_eq!(entries[1].deletions, 5);
assert_eq!(entries[2].path, "assets/logo.png");
assert!(entries[2].binary);
assert_eq!(entries[2].additions, 0);
assert_eq!(entries[2].deletions, 0);
}
#[test]
fn parse_numstat_rename_uses_destination_path() {
let input = "5\t2\told.txt => new.txt\n";
let entries = parse_numstat(input);
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].path, "new.txt");
assert_eq!(entries[0].additions, 5);
}
#[test]
fn parse_hunk_header_basic() {
assert_eq!(parse_hunk_header("@@ -1,7 +1,9 @@"), Some((1, 1)));
assert_eq!(
parse_hunk_header("@@ -100 +200 @@ fn foo()"),
Some((100, 200))
);
assert_eq!(parse_hunk_header("not a hunk"), None);
}
#[test]
fn enrich_diff_lines_tracks_line_numbers_through_hunks() {
use DiffLineKind;
let body = "\
diff --git a/foo.rs b/foo.rs
index abc..def 100644
--- a/foo.rs
+++ b/foo.rs
@@ -1,3 +1,3 @@
-let a = 1;
+let a = 2;
keep
@@ -10,2 +10,3 @@
keep10
+inserted
";
let lines = enrich_diff_lines(body, "foo.rs");
let pick: Vec<(&str, Option<u32>, Option<u32>)> = lines
.iter()
.filter(|l| {
matches!(
l.kind,
DiffLineKind::Added | DiffLineKind::Removed | DiffLineKind::Context,
)
})
.map(|l| (l.text.as_str(), l.old_lineno, l.new_lineno))
.collect();
assert_eq!(
pick,
vec![
("-let a = 1;", Some(1), None),
("+let a = 2;", None, Some(1)),
(" keep", Some(2), Some(2)),
(" keep10", Some(10), Some(10)),
("+inserted", None, Some(11)),
]
);
}
#[tokio::test]
async fn capital_c_returns_to_control_center() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
app.switch_view(View::Diff);
handle_event(&mut app, press(KeyCode::Char('C'))).await;
assert_eq!(app.view(), View::ControlCenter);
}
#[tokio::test]
async fn drive_returns_when_app_quits() {
let mut app = app_with("[command.x]\nrun = \"true\"\n");
app.quit();
assert!(app.should_quit());
}
#[tokio::test]
async fn unrelated_keys_do_nothing() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
let before = app.selected_index();
handle_event(&mut app, press(KeyCode::Char('z'))).await;
assert_eq!(app.selected_index(), before);
assert!(!app.should_quit());
}
#[tokio::test]
async fn colon_opens_palette() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
handle_event(&mut app, press(KeyCode::Char(':'))).await;
assert_eq!(app.mode(), Mode::Palette);
}
#[tokio::test]
async fn slash_opens_palette() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
handle_event(&mut app, press(KeyCode::Char('/'))).await;
assert_eq!(app.mode(), Mode::Palette);
}
#[tokio::test]
async fn ctrl_k_opens_palette() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
handle_event(&mut app, ctrl(KeyCode::Char('k'))).await;
assert_eq!(app.mode(), Mode::Palette);
}
#[tokio::test]
async fn ctrl_p_opens_palette() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
handle_event(&mut app, ctrl(KeyCode::Char('p'))).await;
assert_eq!(app.mode(), Mode::Palette);
}
#[tokio::test]
async fn esc_in_normal_does_not_quit() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
handle_event(&mut app, press(KeyCode::Esc)).await;
assert!(!app.should_quit());
}
#[tokio::test]
async fn esc_in_palette_closes_it() {
let mut app = app_with("[command.a]\nrun = \"true\"\n");
app.open_palette();
handle_event(&mut app, press(KeyCode::Esc)).await;
assert_eq!(app.mode(), Mode::Normal);
}
#[tokio::test]
async fn typing_in_palette_filters() {
let mut app =
app_with("[command.test]\nrun = \"true\"\n[command.migrate]\nrun = \"true\"\n");
app.open_palette();
handle_event(&mut app, press(KeyCode::Char('m'))).await;
let palette = app.palette().unwrap();
let names: Vec<_> = palette
.matches()
.iter()
.map(|m| app.items()[m.item_index].name.clone())
.collect();
assert!(names.contains(&"migrate".to_string()));
}
#[tokio::test]
async fn enter_in_palette_moves_selection() {
let mut app =
app_with("[command.test]\nrun = \"true\"\n[command.migrate]\nrun = \"true\"\n");
app.open_palette();
handle_event(&mut app, press(KeyCode::Enter)).await;
assert_eq!(app.mode(), Mode::Normal);
assert_eq!(app.items()[app.selected_index()].name, "migrate");
}
fn dl_h(text: &str) -> DiffLine {
DiffLine {
kind: DiffLineKind::Header,
text: text.into(),
old_lineno: None,
new_lineno: None,
spans: vec![],
}
}
fn dl_hunk() -> DiffLine {
DiffLine {
kind: DiffLineKind::Hunk,
text: "@@".into(),
old_lineno: None,
new_lineno: None,
spans: vec![],
}
}
fn dl_ctx(o: u32, n: u32) -> DiffLine {
DiffLine {
kind: DiffLineKind::Context,
text: " ".into(),
old_lineno: Some(o),
new_lineno: Some(n),
spans: vec![],
}
}
fn dl_add(n: u32) -> DiffLine {
DiffLine {
kind: DiffLineKind::Added,
text: "+".into(),
old_lineno: None,
new_lineno: Some(n),
spans: vec![],
}
}
fn dl_rem(o: u32) -> DiffLine {
DiffLine {
kind: DiffLineKind::Removed,
text: "-".into(),
old_lineno: Some(o),
new_lineno: None,
spans: vec![],
}
}
fn rl(n: u32) -> ReadLine {
ReadLine {
kind: ReadLineKind::Plain,
lineno: n,
text: format!("L{n}"),
spans: vec![],
}
}
#[test]
fn annotate_marks_pure_additions_green() {
let diff = vec![
dl_h("--- a"),
dl_hunk(),
dl_ctx(1, 1),
dl_add(2),
dl_ctx(2, 3),
];
let read = vec![rl(1), rl(2), rl(3)];
let out = annotate_read_with_diff(read, &diff);
let kinds: Vec<_> = out.iter().map(|l| l.kind).collect();
assert_eq!(
kinds,
vec![
ReadLineKind::Plain,
ReadLineKind::Added,
ReadLineKind::Plain
]
);
}
#[test]
fn annotate_marks_modifications_blue() {
let diff = vec![
dl_h("--- a"),
dl_hunk(),
dl_ctx(1, 1),
dl_rem(2),
dl_add(2),
dl_ctx(3, 3),
];
let read = vec![rl(1), rl(2), rl(3)];
let out = annotate_read_with_diff(read, &diff);
let kinds: Vec<_> = out.iter().map(|l| l.kind).collect();
assert_eq!(
kinds,
vec![
ReadLineKind::Plain,
ReadLineKind::Modified,
ReadLineKind::Plain
]
);
}
#[test]
fn annotate_inserts_separator_for_pure_deletion() {
let diff = vec![
dl_h("--- a"),
dl_hunk(),
dl_ctx(1, 1),
dl_rem(2),
dl_ctx(3, 2),
dl_ctx(4, 3),
];
let read = vec![rl(1), rl(2), rl(3)];
let out = annotate_read_with_diff(read, &diff);
assert_eq!(out.len(), 4);
assert_eq!(out[0].kind, ReadLineKind::Plain);
assert_eq!(out[0].lineno, 1);
assert_eq!(out[1].kind, ReadLineKind::Separator { removed: 1 });
assert_eq!(out[2].kind, ReadLineKind::Plain);
assert_eq!(out[2].lineno, 2);
assert_eq!(out[3].kind, ReadLineKind::Plain);
}
#[test]
fn annotate_handles_deletion_before_first_line() {
let diff = vec![dl_h("--- a"), dl_hunk(), dl_rem(1), dl_rem(2), dl_ctx(3, 1)];
let read = vec![rl(1)];
let out = annotate_read_with_diff(read, &diff);
assert_eq!(out.len(), 2);
assert_eq!(out[0].kind, ReadLineKind::Separator { removed: 2 });
assert_eq!(out[1].kind, ReadLineKind::Plain);
assert_eq!(out[1].lineno, 1);
}
#[test]
fn name_status_captures_rename_old_path() {
let input = "R100\t.keel/commands/seed\t.croft/commands/seed\nM\tREADME.md\n";
let entries = parse_diff_name_status(input);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].path, ".croft/commands/seed");
assert_eq!(entries[0].old_path.as_deref(), Some(".keel/commands/seed"));
assert_eq!(entries[1].path, "README.md");
assert!(entries[1].old_path.is_none());
}
#[test]
fn numstat_resolves_plain_rename_form() {
assert_eq!(resolve_numstat_destination("foo => bar"), "bar".to_string());
assert_eq!(
resolve_numstat_destination("src/old.rs => src/new.rs"),
"src/new.rs".to_string()
);
}
#[test]
fn numstat_resolves_brace_rename_with_common_suffix() {
assert_eq!(
resolve_numstat_destination(".{keel => croft}/commands/seed"),
".croft/commands/seed".to_string()
);
assert_eq!(
resolve_numstat_destination("src/{old => new}/lib.rs"),
"src/new/lib.rs".to_string()
);
}
#[test]
fn numstat_resolves_brace_rename_at_either_end() {
assert_eq!(
resolve_numstat_destination("{old => new}/path"),
"new/path".to_string()
);
assert_eq!(
resolve_numstat_destination("path/{old => new}"),
"path/new".to_string()
);
}
#[test]
fn numstat_resolves_empty_side_renames() {
assert_eq!(
resolve_numstat_destination("dir/{sub => }/file.rs"),
"dir/file.rs".to_string()
);
assert_eq!(
resolve_numstat_destination("dir/{ => sub}/file.rs"),
"dir/sub/file.rs".to_string()
);
}
#[test]
fn numstat_passes_through_non_rename_path() {
assert_eq!(
resolve_numstat_destination("src/main.rs"),
"src/main.rs".to_string()
);
}
#[test]
fn parse_numstat_picks_destination_for_renamed_file() {
let input = "5\t0\t.{keel => croft}/commands/seed\n9\t9\tREADME.md\n";
let entries = parse_numstat(input);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].path, ".croft/commands/seed");
assert_eq!(entries[0].additions, 5);
assert_eq!(entries[0].deletions, 0);
assert_eq!(entries[1].path, "README.md");
}
#[test]
fn annotate_handles_trailing_deletion() {
let diff = vec![dl_h("--- a"), dl_hunk(), dl_ctx(1, 1), dl_rem(2), dl_rem(3)];
let read = vec![rl(1)];
let out = annotate_read_with_diff(read, &diff);
assert_eq!(out.len(), 2);
assert_eq!(out[0].kind, ReadLineKind::Plain);
assert_eq!(out[1].kind, ReadLineKind::Separator { removed: 2 });
}
}