use std::path::Path;
const ACTIONS: &[(char, &str)] = &[
('p', "pick"),
('r', "reword"),
('e', "edit"),
('s', "squash"),
('f', "fixup"),
('d', "drop"),
];
const SPELLINGS: &[&str] = &[
"pick", "p", "reword", "r", "edit", "e", "squash", "s", "fixup", "f", "drop", "d",
];
pub const HINT: &str = "Rebase: p pick \u{00b7} r reword \u{00b7} e edit \u{00b7} s squash \u{00b7} f fixup \u{00b7} d drop \u{00b7} Alt+\u{2191}\u{2193} reorder \u{00b7} save and close to start (an empty list aborts)";
pub fn is_todo(path: &Path) -> bool {
path.file_name().is_some_and(|n| n == "git-rebase-todo")
}
pub fn action_for_key(key: char) -> Option<&'static str> {
ACTIONS
.iter()
.find(|(k, _)| *k == key)
.map(|(_, action)| *action)
}
pub fn set_action(line: &str, action: &str) -> Option<String> {
let trimmed = line.trim_start();
let (word, rest) = trimmed.split_once(char::is_whitespace)?;
if !SPELLINGS.contains(&word) || rest.trim().is_empty() {
return None;
}
let mut rest = rest.trim_start();
if action != "fixup"
&& let Some(after) = rest
.strip_prefix("-C ")
.or_else(|| rest.strip_prefix("-c "))
{
rest = after.trim_start();
}
Some(format!("{action} {rest}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_fixup_flag_goes_when_the_action_is_no_longer_fixup() {
assert_eq!(
set_action("fixup -C 1a2b Tidy", "pick").as_deref(),
Some("pick 1a2b Tidy")
);
assert_eq!(
set_action("fixup -c 1a2b Tidy", "drop").as_deref(),
Some("drop 1a2b Tidy")
);
assert_eq!(
set_action("fixup -C 1a2b Tidy", "fixup").as_deref(),
Some("fixup -C 1a2b Tidy")
);
}
#[test]
fn a_key_rewrites_a_commit_lines_action() {
assert_eq!(
set_action("pick 1a2b3c Add parser", "squash").as_deref(),
Some("squash 1a2b3c Add parser")
);
assert_eq!(
set_action("f 1a2b3c Tidy", "reword").as_deref(),
Some("reword 1a2b3c Tidy"),
"short spellings count"
);
}
#[test]
fn comments_blanks_and_other_commands_are_left_alone() {
assert_eq!(set_action("# Rebase 1a2b..9f8e onto 1a2b", "drop"), None);
assert_eq!(set_action("", "drop"), None);
assert_eq!(set_action("exec cargo test", "drop"), None);
assert_eq!(set_action("pick", "drop"), None, "no hash, no commit");
}
#[test]
fn only_the_six_action_keys_map() {
assert_eq!(action_for_key('s'), Some("squash"));
assert_eq!(action_for_key('x'), None);
}
#[test]
fn only_gits_todo_file_is_a_todo() {
assert!(is_todo(Path::new("/r/.git/rebase-merge/git-rebase-todo")));
assert!(!is_todo(Path::new("/r/todo.txt")));
}
}