use anyhow::{bail, Result};
use crossterm::event::{KeyCode, KeyModifiers};
use std::sync::atomic::{AtomicBool, Ordering};
use crate::{
git::{self, Opts},
input::{self, Input, CANCELLED},
mascot::Mood,
model::{Config, Level},
policy::Verdict,
screen,
};
const LIST_HINT: &str =
"Up/Down or W/S move ยท PgUp/PgDn ยท Home/End ยท Enter or click select ยท Esc/Q back";
const PAGER_HINT: &str = "Up/Down or W/S scroll ยท PgUp/PgDn ยท Home/End ยท Esc/Q back";
const CHECK_HINT: &str =
"Up/Down move ยท Space or click toggle ยท A all/none ยท Enter confirm ยท Esc/Q cancel";
const TYPED_HINT: &str = "Type the text ยท Enter confirm ยท Esc/Ctrl+C cancel";
#[derive(Debug)]
pub struct JobPanic;
impl std::fmt::Display for JobPanic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "git step panicked")
}
}
impl std::error::Error for JobPanic {}
fn clean(line: &str) -> String {
line.replace('\t', " ").replace('\r', "")
}
fn strip_ansi(line: &str) -> String {
let mut out = String::with_capacity(line.len());
let mut chars = line.chars();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
if chars.next() == Some('[') {
for c in chars.by_ref() {
if ('@'..='~').contains(&c) {
break;
}
}
}
} else {
out.push(ch);
}
}
out
}
fn scroll_to(index: usize, offset: usize, visible: usize) -> usize {
let visible = visible.max(1);
if index < offset {
index
} else if index >= offset + visible {
index + 1 - visible
} else {
offset
}
}
fn step(index: usize, delta: i32, len: usize) -> usize {
input::scrolled(index, delta).min(len.saturating_sub(1))
}
pub fn pick_list(
title: &str,
items: &[String],
index: &mut usize,
hint: &str,
) -> Result<Option<usize>> {
let hint = if hint.is_empty() { LIST_HINT } else { hint };
let rows: Vec<String> = items.iter().map(|item| clean(item)).collect();
let mut offset = 0usize;
loop {
*index = (*index).min(rows.len().saturating_sub(1));
let visible = screen::body_rows().saturating_sub(2).max(1);
offset = scroll_to(*index, offset, visible);
let mut body = vec![screen::accent(title), String::new()];
if rows.is_empty() {
body.push(screen::muted(" (nothing here)"));
}
body.extend(
rows.iter()
.enumerate()
.skip(offset)
.take(visible)
.map(|(position, row)| input::styled_menu_line(position == *index, row)),
);
screen::draw(&body, hint, None)?;
let key = match input::read_input()? {
None => continue,
Some(Input::Scroll(lines)) => {
*index = step(*index, lines, rows.len());
continue;
}
Some(Input::Click(line)) => match line.checked_sub(2).map(|row| row + offset) {
Some(position) if position < rows.len() => {
*index = position;
return Ok(Some(position));
}
_ => continue,
},
Some(Input::Key(key)) => key,
};
if input::is_interrupt(&key) {
bail!(CANCELLED);
}
let last = rows.len().saturating_sub(1);
match input::mapped_code(&key) {
KeyCode::Up | KeyCode::Char('w' | 'W') => *index = index.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => *index = (*index + 1).min(last),
KeyCode::PageUp => *index = index.saturating_sub(visible),
KeyCode::PageDown => *index = (*index + visible).min(last),
KeyCode::Home => *index = 0,
KeyCode::End => *index = last,
KeyCode::Enter | KeyCode::Char(' ') if !rows.is_empty() => return Ok(Some(*index)),
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(None),
_ => {}
}
}
}
fn colorize(line: &str) -> String {
let line = clean(line);
if line.contains('\x1b') {
line
} else if line.starts_with("@@") {
format!("\x1b[36m{line}\x1b[0m")
} else if line.starts_with('+') {
screen::success(line)
} else if line.starts_with('-') {
screen::danger(line)
} else if line.starts_with("diff ") || line.starts_with("commit ") {
format!("\x1b[1m{line}\x1b[0m")
} else {
line
}
}
pub fn pager(title: &str, lines: &[String], hint: &str) -> Result<()> {
let hint = if hint.is_empty() { PAGER_HINT } else { hint };
let rows: Vec<String> = lines.iter().map(|line| colorize(line)).collect();
let mut offset = 0usize;
loop {
let visible = screen::body_rows().saturating_sub(1).max(1);
offset = offset.min(rows.len().saturating_sub(visible));
let mut body = vec![screen::accent(title)];
if rows.is_empty() {
body.push(screen::muted("(empty)"));
}
body.extend(rows.iter().skip(offset).take(visible).cloned());
screen::draw(&body, hint, None)?;
let key = match input::read_input()? {
Some(Input::Key(key)) => key,
Some(Input::Scroll(lines)) => {
offset = input::scrolled(offset, lines);
continue;
}
Some(Input::Click(_)) | None => continue,
};
if input::is_interrupt(&key) {
bail!(CANCELLED);
}
match input::mapped_code(&key) {
KeyCode::Up | KeyCode::Char('w' | 'W') => offset = offset.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => offset = offset.saturating_add(1),
KeyCode::PageUp => offset = offset.saturating_sub(visible),
KeyCode::PageDown => offset = offset.saturating_add(visible),
KeyCode::Home => offset = 0,
KeyCode::End => offset = usize::MAX,
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
_ => {}
}
}
}
pub fn notice(title: &str, lines: &[String]) -> Result<()> {
let mut body = vec![screen::accent(title), String::new()];
body.extend(lines.iter().map(|line| clean(line)));
input::wait_key(&body, "Press any key to continue")
}
pub fn ask(prompt: &str, initial: &str) -> Result<Option<String>> {
let answer = input::read_line(prompt, initial, false)?;
Ok(if answer.is_empty() && initial.is_empty() {
None
} else {
Some(answer)
})
}
pub fn confirm_danger(config: &Config, what: &str, command: &str) -> Result<bool> {
if !config.confirm_destructive {
return Ok(true);
}
danger_prompt(what, command)
}
fn danger_prompt(what: &str, command: &str) -> Result<bool> {
screen::set_mood(Mood::Error);
let mut context = vec![screen::danger(format!("Warning: {what}"))];
if !command.is_empty() {
context.push(String::new());
context.push(format!(
"{} {}",
screen::muted("Command:"),
screen::accent(command)
));
}
let answer = input::confirm(&context, "Run it?", false);
screen::set_mood(Mood::Idle);
answer
}
#[allow(dead_code)] pub fn git(args: &[&str]) -> Result<String> {
crate::git::run(args)
}
const FRAMES: [&str; 10] = ["โ ", "โ ", "โ น", "โ ธ", "โ ผ", "โ ด", "โ ฆ", "โ ง", "โ ", "โ "];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Wait {
Running,
Asked,
Stopping,
}
impl Wait {
fn on_stop_key(self) -> Wait {
match self {
Wait::Running => Wait::Asked,
Wait::Asked | Wait::Stopping => Wait::Stopping,
}
}
fn frame(self, tick: usize, message: &str) -> (Vec<String>, &'static str) {
let spinner = FRAMES[tick % FRAMES.len()];
match self {
Wait::Running => (vec![screen::accent(format!("{spinner} {message}"))], "Please wait..."),
Wait::Asked => (
vec![
screen::accent(format!("{spinner} {message}")),
String::new(),
screen::warning(
"git is still running. Press Esc again to stop waiting (this may leave a lock file)",
),
],
"Esc stop waiting ยท any other key keep waiting",
),
Wait::Stopping => (vec![screen::accent(format!("{spinner} Stopping git..."))], "Please wait..."),
}
}
}
fn is_stop_key(key: &crossterm::event::KeyEvent) -> bool {
key.kind == crossterm::event::KeyEventKind::Press
&& (key.code == KeyCode::Esc || input::is_interrupt(key))
}
pub fn git_job<T: Send>(message: &str, job: impl FnOnce() -> Result<T> + Send) -> Result<T> {
use crossterm::event::{self, Event};
use std::{sync::Arc, time::Duration};
screen::set_mood(Mood::Thinking);
let flag = Arc::new(AtomicBool::new(false));
let ctx = git::ctx_snapshot().with_cancel(Arc::clone(&flag));
std::thread::scope(|scope| {
let handle = scope.spawn(move || {
git::ctx_restore(ctx);
job()
});
let mut tick = 0;
let mut wait = Wait::Running;
while !handle.is_finished() {
let (body, hint) = wait.frame(tick, message);
let _ = screen::draw(&body, hint, None);
tick += 1;
let started = std::time::Instant::now();
match event::poll(Duration::from_millis(80)) {
Ok(true) => match event::read() {
Ok(Event::Key(key)) if is_stop_key(&key) => {
wait = wait.on_stop_key();
if wait == Wait::Stopping {
flag.store(true, Ordering::Relaxed);
}
}
Ok(Event::Key(key))
if wait == Wait::Asked
&& key.kind == crossterm::event::KeyEventKind::Press =>
{
wait = Wait::Running;
}
Ok(Event::Resize(..)) => screen::invalidate(),
_ => {}
},
Ok(false) => {}
Err(_) => std::thread::sleep(Duration::from_millis(80)),
}
if let Some(rest) = Duration::from_millis(80).checked_sub(started.elapsed()) {
std::thread::sleep(rest);
}
}
let result = handle.join().map_err(|_| anyhow::Error::new(JobPanic))?;
if wait == Wait::Stopping && result.is_err() {
bail!(CANCELLED);
}
result
})
}
pub fn git_job_cancellable<T: Send>(
msg: &str,
job: impl FnOnce(&AtomicBool) -> Result<T> + Send,
) -> Result<T> {
use crossterm::event::{self, Event, KeyEventKind};
screen::set_mood(Mood::Thinking);
let flag = AtomicBool::new(false);
let ctx = git::ctx_snapshot();
let flag_ref = &flag;
std::thread::scope(|scope| {
let handle = scope.spawn(move || {
git::ctx_restore(ctx);
job(flag_ref)
});
let mut tick = 0;
while !handle.is_finished() {
let cancelling = flag_ref.load(Ordering::Relaxed);
let line = format!(
"{} {}",
FRAMES[tick % FRAMES.len()],
if cancelling { "Cancelling..." } else { msg }
);
let _ = screen::draw(
&[screen::accent(line)],
"Please wait... ยท Esc cancel",
None,
);
tick += 1;
if event::poll(std::time::Duration::from_millis(80)).unwrap_or(false) {
match event::read() {
Ok(Event::Key(key))
if key.kind == KeyEventKind::Press
&& (key.code == KeyCode::Esc || input::is_interrupt(&key)) =>
{
flag_ref.store(true, Ordering::Relaxed);
}
Ok(Event::Resize(..)) => screen::invalidate(),
_ => {}
}
}
}
handle.join().map_err(|_| anyhow::Error::new(JobPanic))?
})
}
pub fn run_git(cfg: &Config, label: &str, args: &[&str]) -> Result<String> {
let message = if cfg.show_commands {
command_label(args)
} else {
label.to_string()
};
git_job(&message, || git::git_ok(args, &Opts::default()))
}
fn command_label(args: &[&str]) -> String {
let mut parts = Vec::with_capacity(args.len());
let mut after_c = false;
for arg in args {
let shown = match arg.split_once('=') {
Some((key, _)) if after_c && key.to_ascii_lowercase().contains("extraheader") => {
format!("{key}=***")
}
_ => (*arg).to_string(),
};
after_c = *arg == "-c";
parts.push(shown);
}
crate::cmdlog::mask(&format!("$ git {}", parts.join(" ")))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Key {
pub key: char,
pub label: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Choice {
Open(usize),
Action(char, usize),
Back,
}
const RESERVED: [char; 4] = ['w', 's', 'q', '/'];
const DIFF_RESERVED: [char; 3] = ['n', '[', ']'];
fn key_collides(key: char, extra: &[char]) -> bool {
let lower = key.to_ascii_lowercase();
key == ' ' || key.is_control() || RESERVED.contains(&lower) || extra.contains(&lower)
}
fn usable_keys(keys: &[Key], extra: &[char]) -> Vec<Key> {
keys.iter()
.copied()
.filter(|k| {
let ok = !key_collides(k.key, extra);
debug_assert!(ok, "action key {:?} collides with a navigation key", k.key);
ok
})
.collect()
}
fn match_key(keys: &[Key], typed: char) -> Option<char> {
keys.iter()
.find(|k| k.key == typed)
.or_else(|| keys.iter().find(|k| k.key.eq_ignore_ascii_case(&typed)))
.map(|k| k.key)
}
fn key_hints(keys: &[Key]) -> String {
keys.iter()
.map(|k| format!("{} {}", k.key.to_ascii_uppercase(), k.label))
.collect::<Vec<_>>()
.join(" ยท ")
}
fn filter_rows(rows: &[String], query: &str) -> Vec<usize> {
let query = query.to_lowercase();
rows.iter()
.enumerate()
.filter(|(_, row)| query.is_empty() || strip_ansi(row).to_lowercase().contains(&query))
.map(|(index, _)| index)
.collect()
}
pub fn action_list(
title: &str,
header: &[String],
rows: &[String],
keys: &[Key],
index: &mut usize,
) -> Result<Choice> {
let keys = usable_keys(keys, &[]);
let cleaned: Vec<String> = rows.iter().map(|row| clean(row)).collect();
let mut query = String::new();
let mut typing = false;
let mut shown = filter_rows(&cleaned, &query);
let mut pos = shown.iter().position(|i| *i == *index).unwrap_or(0);
let mut offset = 0usize;
let extra = key_hints(&keys);
loop {
pos = pos.min(shown.len().saturating_sub(1));
if let Some(row) = shown.get(pos) {
*index = *row;
}
let mut body = vec![screen::accent(title)];
body.extend(header.iter().map(|line| clean(line)));
if typing || !query.is_empty() {
let cursor = if typing { "_" } else { "" };
body.push(format!("{} {query}{cursor}", screen::muted("Filter:")));
}
body.push(String::new());
let top = body.len();
let visible = screen::body_rows().saturating_sub(top).max(1);
offset = scroll_to(pos, offset, visible);
if shown.is_empty() {
body.push(screen::muted(if rows.is_empty() {
" (nothing here)"
} else {
" (no match)"
}));
}
body.extend(
shown
.iter()
.enumerate()
.skip(offset)
.take(visible)
.map(|(p, row)| input::styled_menu_line(p == pos, &cleaned[*row])),
);
let hint = if typing {
"Type to filter ยท Enter keep ยท Esc clear".to_string()
} else if extra.is_empty() {
"Up/Down move ยท Enter open ยท / filter ยท Esc/Q back".to_string()
} else {
format!("Up/Down move ยท Enter open ยท {extra} ยท / filter ยท Esc/Q back")
};
screen::draw(&body, &hint, None)?;
let selected = shown.get(pos).copied().unwrap_or(rows.len());
let key = match input::read_input()? {
None => continue,
Some(Input::Scroll(lines)) => {
pos = step(pos, lines, shown.len());
continue;
}
Some(Input::Click(line)) => match line.checked_sub(top).map(|row| row + offset) {
Some(p) if p < shown.len() => {
*index = shown[p];
return Ok(Choice::Open(shown[p]));
}
_ => continue,
},
Some(Input::Key(key)) => key,
};
if input::is_interrupt(&key) {
bail!(CANCELLED);
}
let last = shown.len().saturating_sub(1);
if typing {
match key.code {
KeyCode::Enter => typing = false,
KeyCode::Esc => {
typing = false;
query.clear();
}
KeyCode::Backspace => {
query.pop();
}
KeyCode::Up => pos = pos.saturating_sub(1),
KeyCode::Down => pos = (pos + 1).min(last),
KeyCode::Char(ch) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
query.push(ch);
pos = 0;
}
_ => {}
}
if matches!(
key.code,
KeyCode::Esc | KeyCode::Backspace | KeyCode::Char(_)
) {
shown = filter_rows(&cleaned, &query);
}
continue;
}
if let KeyCode::Char(ch) = key.code {
if !key.modifiers.contains(KeyModifiers::CONTROL) {
if let Some(action) = match_key(&keys, ch) {
return Ok(Choice::Action(action, selected));
}
}
}
match input::mapped_code(&key) {
KeyCode::Up | KeyCode::Char('w' | 'W') => pos = pos.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => pos = (pos + 1).min(last),
KeyCode::PageUp => pos = pos.saturating_sub(visible),
KeyCode::PageDown => pos = (pos + visible).min(last),
KeyCode::Home => pos = 0,
KeyCode::End => pos = last,
KeyCode::Char('/') => typing = true,
KeyCode::Enter | KeyCode::Char(' ') if !shown.is_empty() => {
return Ok(Choice::Open(selected))
}
KeyCode::Esc if !query.is_empty() => {
query.clear();
shown = filter_rows(&cleaned, &query);
pos = shown.iter().position(|i| *i == selected).unwrap_or(0);
}
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(Choice::Back),
_ => {}
}
}
}
pub fn check_list(title: &str, items: &[String], checked: &mut [bool]) -> Result<bool> {
let rows: Vec<String> = items.iter().map(|item| clean(item)).collect();
let mut index = 0usize;
let mut offset = 0usize;
loop {
index = index.min(rows.len().saturating_sub(1));
let count = checked.iter().take(rows.len()).filter(|c| **c).count();
let mut body = vec![
screen::accent(title),
screen::muted(format!("{count} of {} selected", rows.len())),
];
let top = body.len();
let visible = screen::body_rows().saturating_sub(top).max(1);
offset = scroll_to(index, offset, visible);
if rows.is_empty() {
body.push(screen::muted(" (nothing here)"));
}
body.extend(
rows.iter()
.enumerate()
.skip(offset)
.take(visible)
.map(|(i, row)| {
let mark = if checked.get(i).copied().unwrap_or(false) {
"[x]"
} else {
"[ ]"
};
input::styled_menu_line(i == index, &format!("{mark} {row}"))
}),
);
screen::draw(&body, CHECK_HINT, None)?;
let key = match input::read_input()? {
None => continue,
Some(Input::Scroll(lines)) => {
index = step(index, lines, rows.len());
continue;
}
Some(Input::Click(line)) => {
if let Some(i) = line.checked_sub(top).map(|row| row + offset) {
if let Some(flag) = checked.get_mut(i).filter(|_| i < rows.len()) {
*flag = !*flag;
index = i;
}
}
continue;
}
Some(Input::Key(key)) => key,
};
if input::is_interrupt(&key) {
bail!(CANCELLED);
}
let last = rows.len().saturating_sub(1);
match input::mapped_code(&key) {
KeyCode::Up | KeyCode::Char('w' | 'W') => index = index.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => index = (index + 1).min(last),
KeyCode::PageUp => index = index.saturating_sub(visible),
KeyCode::PageDown => index = (index + visible).min(last),
KeyCode::Home => index = 0,
KeyCode::End => index = last,
KeyCode::Char(' ') => {
if let Some(flag) = checked.get_mut(index).filter(|_| !rows.is_empty()) {
*flag = !*flag;
}
}
KeyCode::Char('a' | 'A') => {
let len = rows.len().min(checked.len());
toggle_all(&mut checked[..len]);
}
KeyCode::Enter => return Ok(true),
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(false),
_ => {}
}
}
}
fn toggle_all(checked: &mut [bool]) {
let value = !checked.iter().all(|c| *c);
checked.iter_mut().for_each(|c| *c = value);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffChoice {
Action(char, usize),
Back,
}
fn hunk_lines(lines: &[String]) -> Vec<usize> {
lines
.iter()
.enumerate()
.filter(|(_, line)| strip_ansi(line).starts_with("@@"))
.map(|(i, _)| i)
.collect()
}
fn anchor_lines(lines: &[String]) -> Vec<usize> {
lines
.iter()
.enumerate()
.filter(|(_, line)| {
let plain = strip_ansi(line);
plain.starts_with("@@") || plain.starts_with("diff --git")
})
.map(|(i, _)| i)
.collect()
}
fn current_hunk(hunks: &[usize], files: &[usize], focus: usize) -> Option<usize> {
let above = hunks.iter().rposition(|h| *h <= focus);
let file = files.iter().rev().find(|f| **f <= focus);
match above {
Some(h) if file.is_none_or(|f| *f < hunks[h]) => Some(h),
_ => hunks
.iter()
.position(|h| *h > focus)
.or(above)
.or(if hunks.is_empty() { None } else { Some(0) }),
}
}
fn next_anchor(anchors: &[usize], focus: usize, forward: bool) -> Option<usize> {
if forward {
anchors.iter().copied().find(|a| *a > focus)
} else {
anchors.iter().copied().rev().find(|a| *a < focus)
}
}
fn find_match(plain: &[String], query: &str, from: usize, forward: bool) -> Option<usize> {
if query.is_empty() || plain.is_empty() {
return None;
}
let len = plain.len();
(1..=len)
.map(|k| {
if forward {
(from + k) % len
} else {
(from + len * 2 - k) % len
}
})
.find(|i| plain[*i].contains(query))
}
pub fn diff_view(title: &str, lines: &[String], keys: &[Key]) -> Result<DiffChoice> {
let keys = usable_keys(keys, &DIFF_RESERVED);
let rows: Vec<String> = lines.iter().map(|line| colorize(line)).collect();
let plain: Vec<String> = lines
.iter()
.map(|line| strip_ansi(line).to_lowercase())
.collect();
let hunks = hunk_lines(lines);
let anchors = anchor_lines(lines);
let files: Vec<usize> = anchors
.iter()
.copied()
.filter(|a| !hunks.contains(a))
.collect();
let extra = key_hints(&keys);
let mut offset = 0usize;
let mut focus = 0usize;
let mut query = String::new();
let mut typing = false;
let mut status: Option<&str> = None;
loop {
let visible = screen::body_rows().saturating_sub(2).max(1);
let max_offset = rows.len().saturating_sub(visible);
offset = offset.min(max_offset);
let hunk = current_hunk(&hunks, &files, focus);
let mut info = match hunk {
Some(h) => format!("hunk {}/{}", h + 1, hunks.len()),
None => "no hunks".to_string(),
};
if typing {
info = format!("Search: {query}_");
} else if !query.is_empty() {
info.push_str(&format!(" ยท /{query}"));
}
if let Some(message) = status.take() {
info.push_str(&format!(" ยท {message}"));
}
let mut body = vec![screen::accent(title), screen::muted(info)];
if rows.is_empty() {
body.push(screen::muted("(empty)"));
}
let header = hunk.map(|h| hunks[h]);
body.extend(
rows.iter()
.enumerate()
.skip(offset)
.take(visible)
.map(|(i, row)| {
if Some(i) == header {
screen::selected(strip_ansi(&clean(&lines[i])))
} else {
row.clone()
}
}),
);
let hint = if typing {
"Type to search ยท Enter find ยท Esc cancel".to_string()
} else {
let base = "Up/Down scroll ยท ] [ hunk ยท / search ยท n/N next";
if extra.is_empty() {
format!("{base} ยท Esc/Q back")
} else {
format!("{base} ยท {extra} ยท Esc/Q back")
}
};
screen::draw(&body, &hint, None)?;
let key = match input::read_input()? {
Some(Input::Key(key)) => key,
Some(Input::Scroll(lines)) => {
offset = input::scrolled(offset, lines).min(max_offset);
focus = offset;
continue;
}
Some(Input::Click(_)) | None => continue,
};
if input::is_interrupt(&key) {
bail!(CANCELLED);
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if typing {
match key.code {
KeyCode::Esc => {
typing = false;
query.clear();
}
KeyCode::Enter => {
typing = false;
match find_match(&plain, &query.to_lowercase(), focus, true) {
Some(line) => focus = line,
None if !query.is_empty() => status = Some("not found"),
None => {}
}
offset = focus.min(max_offset);
}
KeyCode::Backspace => {
query.pop();
}
KeyCode::Char(ch) if !ctrl => query.push(ch),
_ => {}
}
continue;
}
if let KeyCode::Char(ch) = key.code {
if !ctrl {
if let Some(action) = match_key(&keys, ch) {
return Ok(DiffChoice::Action(action, hunk.unwrap_or(hunks.len())));
}
}
}
let mut jumped = None;
match input::mapped_code(&key) {
KeyCode::Up | KeyCode::Char('w' | 'W') => offset = offset.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => offset = (offset + 1).min(max_offset),
KeyCode::PageUp => offset = offset.saturating_sub(visible),
KeyCode::PageDown => offset = (offset + visible).min(max_offset),
KeyCode::Home => offset = 0,
KeyCode::End => offset = max_offset,
KeyCode::Char(']') => jumped = next_anchor(&anchors, focus, true),
KeyCode::Char('[') => jumped = next_anchor(&anchors, focus, false),
KeyCode::Char('/') => {
typing = true;
query.clear();
continue;
}
KeyCode::Char(c @ ('n' | 'N')) => {
match find_match(&plain, &query.to_lowercase(), focus, c == 'n') {
Some(line) => jumped = Some(line),
None if !query.is_empty() => status = Some("not found"),
None => {}
}
}
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(DiffChoice::Back),
_ => continue,
}
match jumped {
Some(line) => {
focus = line;
offset = line.min(max_offset);
}
None => focus = offset,
}
}
}
pub fn choose(title: &str, context: &[String], options: &[&str]) -> Result<Option<usize>> {
let rows: Vec<String> = options.iter().map(|o| o.to_string()).collect();
let mut index = 0usize;
Ok(match action_list(title, context, &rows, &[], &mut index)? {
Choice::Open(i) if i < rows.len() => Some(i),
_ => None,
})
}
pub fn confirm_action(cfg: &Config, what: &str, command: &str) -> Result<bool> {
if !cfg.confirm_destructive {
return Ok(true);
}
let mut context = vec![what.to_string()];
if !command.is_empty() {
context.push(String::new());
context.push(format!(
"{} {}",
screen::muted("Command:"),
screen::accent(command)
));
}
input::confirm(&context, "Continue?", true)
}
pub fn confirm_typed(what: &str, command: &str, expected: &str) -> Result<bool> {
screen::set_mood(Mood::Error);
let result = typed_loop(what, command, expected);
screen::set_mood(Mood::Idle);
result
}
fn typed_loop(what: &str, command: &str, expected: &str) -> Result<bool> {
let mut typed = String::new();
let mut wrong = false;
loop {
let mut body = vec![screen::danger(format!("Warning: {what}"))];
if !command.is_empty() {
body.push(String::new());
body.push(format!(
"{} {}",
screen::muted("Command:"),
screen::accent(command)
));
}
body.push(String::new());
body.push(format!("Type {} to confirm:", screen::accent(expected)));
body.push(format!("> {typed}"));
let row = body.len() - 1;
if wrong {
body.push(screen::danger(
"That does not match; try again or press Esc.",
));
}
let column = 2 + typed.chars().count();
screen::draw(&body, TYPED_HINT, Some((row as u16, column as u16)))?;
let Some(key) = input::read_key()? else {
continue;
};
if input::is_interrupt(&key) {
bail!(CANCELLED);
}
match key.code {
KeyCode::Esc => return Ok(false),
KeyCode::Enter if typed == expected => return Ok(true),
KeyCode::Enter => wrong = true,
KeyCode::Backspace => {
typed.pop();
}
KeyCode::Char(ch) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
typed.push(ch);
wrong = false;
}
_ => {}
}
}
}
pub fn gate(cfg: &Config, v: &Verdict, what: &str, command: &str) -> Result<bool> {
match v {
Verdict::Allow => Ok(true),
Verdict::Confirm => confirm_action(cfg, what, command),
Verdict::Danger => danger_prompt(what, command),
Verdict::Typed(expected) => confirm_typed(what, command, expected),
Verdict::Deny(message) => {
screen::set_mood(Mood::Error);
let shown = notice(
"Not allowed",
&[screen::danger(message), String::new(), what.into()],
);
screen::set_mood(Mood::Idle);
shown.map(|()| false)
}
}
}
pub fn suspended<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
struct Resume(bool);
impl Drop for Resume {
fn drop(&mut self) {
if self.0 {
let _ = screen::resume();
}
}
}
screen::suspend();
let mut guard = Resume(true);
let result = f();
guard.0 = false;
screen::resume()?;
result
}
fn ref_names(local: bool, remote: bool, tags: bool) -> Result<Vec<(&'static str, String)>> {
let mut patterns = Vec::new();
if local {
patterns.push("refs/heads");
}
if remote {
patterns.push("refs/remotes");
}
if tags {
patterns.push("refs/tags");
}
if patterns.is_empty() {
return Ok(Vec::new());
}
let mut args = vec!["for-each-ref", "--format=%(refname)"];
args.extend(patterns);
let text = git::git_ok(&args, &Opts::default())?;
Ok(text
.lines()
.filter(|name| !name.ends_with("/HEAD"))
.filter_map(|name| {
[
("refs/heads/", "branch"),
("refs/remotes/", "remote"),
("refs/tags/", "tag"),
]
.into_iter()
.find_map(|(prefix, kind)| {
name.strip_prefix(prefix)
.map(|short| (kind, short.to_string()))
})
})
.collect())
}
fn is_commit(rev: &str) -> bool {
git::git_raw(
&[
"rev-parse",
"--verify",
"--quiet",
&format!("{rev}^{{commit}}"),
],
&Opts::default(),
)
.is_ok_and(|out| out.ok())
}
pub fn pick_ref(title: &str, local: bool, remote: bool, tags: bool) -> Result<Option<String>> {
let refs = ref_names(local, remote, tags)?;
let mut rows = vec![screen::muted("Type a revision (hash, HEAD~2, ...)")];
rows.extend(
refs.iter()
.map(|(kind, name)| format!("{name} {}", screen::muted(kind))),
);
let mut index = if refs.is_empty() { 0 } else { 1 };
loop {
match action_list(title, &[], &rows, &[], &mut index)? {
Choice::Open(0) => {
let Some(rev) = ask("Revision:", "")? else {
continue;
};
let rev = rev.trim().to_string();
if is_commit(&rev) {
return Ok(Some(rev));
}
notice(
"Unknown revision",
&[format!("'{rev}' is not a commit in this repository.")],
)?;
}
Choice::Open(i) => return Ok(refs.get(i - 1).map(|(_, name)| name.clone())),
_ => return Ok(None),
}
}
}
pub fn explain(cfg: &Config, lines: &[&str]) -> Vec<String> {
if cfg.level() == Level::Beginner {
lines.iter().map(screen::muted).collect()
} else {
Vec::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn s(lines: &[&str]) -> Vec<String> {
lines.iter().map(|l| l.to_string()).collect()
}
#[test]
fn git_job_needs_two_stop_keys() {
use crossterm::event::{KeyEvent, KeyEventKind};
assert_eq!(Wait::Running.on_stop_key(), Wait::Asked);
assert_eq!(Wait::Asked.on_stop_key(), Wait::Stopping);
assert_eq!(Wait::Stopping.on_stop_key(), Wait::Stopping);
let (body, hint) = Wait::Running.frame(0, "Creating commit...");
assert_eq!(
body,
[screen::accent(format!("{} Creating commit...", FRAMES[0]))]
);
assert_eq!(hint, "Please wait...");
let (body, _) = Wait::Asked.frame(3, "Creating commit...");
assert_eq!(
body[0],
screen::accent(format!("{} Creating commit...", FRAMES[3]))
);
assert!(body.iter().any(|line| line.contains(
"git is still running. Press Esc again to stop waiting (this may leave a lock file)"
)));
let esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
let other = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE);
let mut release = esc;
release.kind = KeyEventKind::Release;
assert!(is_stop_key(&esc) && is_stop_key(&ctrl_c));
assert!(!is_stop_key(&other) && !is_stop_key(&release));
}
#[test]
fn command_label_hides_secrets() {
assert_eq!(
command_label(&["status", "--short"]),
"$ git status --short"
);
assert_eq!(
command_label(&[
"-c",
"http.extraheader=AUTHORIZATION: basic c2VjcmV0",
"fetch"
]),
"$ git -c http.extraheader=*** fetch"
);
assert_eq!(
command_label(&["-c", "http.https://x.com/.extraHeader=Bearer t", "push"]),
"$ git -c http.https://x.com/.extraHeader=*** push"
);
assert_eq!(
command_label(&["push", "https://u:pa55@github.com/o/r.git", "main"]),
"$ git push https://***@github.com/o/r.git main"
);
assert_eq!(
command_label(&["log", "extraheader=x"]),
"$ git log extraheader=x"
);
assert_eq!(command_label(&[]), "$ git ");
}
#[test]
fn scroll_keeps_index_visible() {
assert_eq!(scroll_to(0, 0, 5), 0);
assert_eq!(scroll_to(7, 0, 5), 3);
assert_eq!(scroll_to(2, 3, 5), 2);
assert_eq!(scroll_to(4, 3, 5), 3);
assert_eq!(scroll_to(9, 0, 0), 9);
assert_eq!(step(2, -3, 10), 0);
assert_eq!(step(2, 3, 10), 5);
assert_eq!(step(8, 3, 10), 9);
assert_eq!(step(0, 3, 0), 0);
}
#[test]
fn pager_colors() {
assert_eq!(colorize("+a"), screen::success("+a"));
assert_eq!(colorize("-a"), screen::danger("-a"));
assert_eq!(colorize("@@ -1 +1 @@"), "\x1b[36m@@ -1 +1 @@\x1b[0m");
assert_eq!(colorize("commit abc"), "\x1b[1mcommit abc\x1b[0m");
assert_eq!(colorize("plain\tx"), "plain x");
assert_eq!(colorize("\x1b[31m+x\x1b[0m"), "\x1b[31m+x\x1b[0m");
}
#[test]
fn filters_rows_ignoring_case_and_ansi() {
let rows = s(&["Main branch", "\x1b[32mdev\x1b[0m", "feature/Login", "รผnรฏ"]);
assert_eq!(filter_rows(&rows, ""), [0, 1, 2, 3]);
assert_eq!(filter_rows(&rows, "MAIN"), [0]);
assert_eq!(filter_rows(&rows, "dev"), [1]);
assert_eq!(filter_rows(&rows, "32m"), Vec::<usize>::new());
assert_eq!(filter_rows(&rows, "in"), [0, 2]);
assert_eq!(filter_rows(&rows, "รnรฏ"), [3]);
assert_eq!(strip_ansi("\x1b[1;30;46ma\x1b[0mb"), "ab");
}
#[test]
fn action_keys_avoid_navigation() {
for c in ['w', 'W', 's', 'S', 'q', 'Q', ' ', '/', '\n'] {
assert!(key_collides(c, &[]), "{c:?}");
}
for c in ['d', 'D', 'n', 'x', '+', '?'] {
assert!(!key_collides(c, &[]), "{c:?}");
}
assert!(key_collides('N', &DIFF_RESERVED));
assert!(key_collides(']', &DIFF_RESERVED));
let keys = [
Key {
key: 'd',
label: "delete",
},
Key {
key: 'R',
label: "rename",
},
];
assert_eq!(match_key(&keys, 'd'), Some('d'));
assert_eq!(match_key(&keys, 'D'), Some('d'));
assert_eq!(match_key(&keys, 'r'), Some('R'));
assert_eq!(match_key(&keys, 'x'), None);
assert_eq!(key_hints(&keys), "D delete ยท R rename");
let mut all = [true, false];
toggle_all(&mut all);
assert_eq!(all, [true, true]);
toggle_all(&mut all);
assert_eq!(all, [false, false]);
}
#[test]
fn hunk_math() {
let diff = s(&[
"diff --git a/x b/x", "--- a/x",
"+++ b/x",
"@@ -1 +1 @@", "-a",
"+b",
"@@ -9 +9 @@", " c",
"diff --git a/y b/y", "--- a/y",
"+++ b/y",
"@@ -1 +1 @@", "+z",
]);
let hunks = hunk_lines(&diff);
assert_eq!(hunks, [3, 6, 11]);
let anchors = anchor_lines(&diff);
assert_eq!(anchors, [0, 3, 6, 8, 11]);
let files = [0, 8];
assert_eq!(current_hunk(&hunks, &files, 0), Some(0)); assert_eq!(current_hunk(&hunks, &files, 4), Some(0));
assert_eq!(current_hunk(&hunks, &files, 6), Some(1));
assert_eq!(current_hunk(&hunks, &files, 7), Some(1));
assert_eq!(current_hunk(&hunks, &files, 9), Some(2)); assert_eq!(current_hunk(&hunks, &files, 12), Some(2));
assert_eq!(current_hunk(&[], &[], 3), None);
assert_eq!(next_anchor(&anchors, 3, true), Some(6));
assert_eq!(next_anchor(&anchors, 3, false), Some(0));
assert_eq!(next_anchor(&anchors, 11, true), None);
assert_eq!(next_anchor(&anchors, 0, false), None);
let plain: Vec<String> = diff.iter().map(|l| l.to_lowercase()).collect();
assert_eq!(find_match(&plain, "+b", 0, true), Some(5));
assert_eq!(find_match(&plain, "diff", 8, true), Some(0)); assert_eq!(find_match(&plain, "diff", 8, false), Some(0));
assert_eq!(find_match(&plain, "diff", 0, false), Some(8));
assert_eq!(find_match(&plain, "nope", 0, true), None);
assert_eq!(find_match(&plain, "", 0, true), None);
}
#[test]
fn explain_only_for_beginners() {
let mut cfg = Config::default();
assert!(explain(&cfg, &["x"]).is_empty());
cfg.experience = "beginner".into();
assert_eq!(explain(&cfg, &["x"]), [screen::muted("x")]);
}
}