use super::files::{describe_change, parse_name_status, top_spec, NameStatus};
use crate::git::{self, Opts};
use crate::history::{self, LogEntry};
use crate::{model::Config, ui};
use anyhow::{bail, Result};
const DIFF_MAX_LINES: usize = 5000;
pub fn parse_left_right_count(text: &str) -> Option<(usize, usize)> {
let mut f = text.split_whitespace();
let left = f.next()?.parse().ok()?;
let right = f.next()?.parse().ok()?;
Some((left, right))
}
pub fn compare_args(a: &str, b: &str, three_dot: bool) -> Vec<String> {
if three_dot {
vec![format!("{a}...{b}")]
} else {
vec![a.to_string(), b.to_string()]
}
}
pub fn describe_counts(a: &str, b: &str, left: usize, right: usize) -> String {
let s = |n: usize| if n == 1 { "commit" } else { "commits" };
match (right, left) {
(0, 0) => format!("{b} and {a} point at the same history."),
(r, 0) => format!("{b} is {r} {} ahead of {a} (and 0 behind)", s(r)),
(0, l) => format!("{b} is 0 ahead, {l} {} behind {a}", s(l)),
(r, l) => format!("{b} is {r} {} ahead, {l} {} behind {a}", s(r), s(l)),
}
}
pub fn dots_explanation(three_dot: bool) -> &'static str {
if three_dot {
"Three dots (A...B): only what B changed since the two branched apart."
} else {
"Two dots (A..B): every difference between the two tips right now, including A's own new work."
}
}
pub fn parse_marked_log(text: &str) -> Vec<(char, LogEntry)> {
text.split('\u{1e}')
.filter_map(|rec| {
let rec = rec.trim_start_matches(['\n', '\r', ' ']);
let (mark, rest) = rec.split_once('\u{1d}')?;
let entry = history::parse_log(&format!("{rest}\u{1e}"))
.into_iter()
.next()?;
Some((mark.chars().next().unwrap_or('?'), entry))
})
.collect()
}
fn check_rev(rev: &str) -> Result<()> {
if rev.trim().is_empty() || rev.starts_with('-') {
bail!("Invalid revision: {rev}");
}
Ok(())
}
fn row_text(n: &NameStatus) -> String {
format!("{} {} ({})", n.status, n.path, describe_change(n))
}
#[derive(Debug, Clone)]
pub struct Comparison {
pub header: Vec<String>,
pub files: Vec<NameStatus>,
pub three_dot: bool,
}
fn rev_oid(rev: &str) -> Result<String> {
let spec = format!("{rev}^{{commit}}");
git::git_ok(
&["rev-parse", "--verify", "--end-of-options", &spec],
&Opts::default(),
)
}
pub fn compare(a: &str, b: &str, want_three_dot: bool) -> Result<Comparison> {
check_rev(a)?;
check_rev(b)?;
let (oa, ob) = (rev_oid(a)?, rev_oid(b)?);
let mut header = Vec::new();
let mut three_dot = want_three_dot;
if three_dot
&& git::git_raw(&["merge-base", &oa, &ob], &Opts::default())?
.text()
.is_empty()
{
three_dot = false;
header.push(
"Warning: these two share no history; comparing the tips directly (two dots)."
.to_string(),
);
}
if oa == ob {
header.insert(0, format!("{a} and {b} are the same commit."));
return Ok(Comparison {
header,
files: vec![],
three_dot,
});
}
let sym = format!("{oa}...{ob}");
let counts = git::git_ok(
&["rev-list", "--left-right", "--count", &sym],
&Opts::default(),
)?;
if let Some((l, r)) = parse_left_right_count(&counts) {
header.insert(0, describe_counts(a, b, l, r));
}
header.push(dots_explanation(three_dot).to_string());
let range = compare_args(&oa, &ob, three_dot);
let mut args: Vec<&str> = vec![
"-c",
"core.quotepath=false",
"diff",
"--name-status",
"-z",
"-M",
];
args.extend(range.iter().map(String::as_str));
let text = git::git_ok(
&args,
&Opts {
max_lines: Some(20_000),
..Opts::default()
},
)?;
let files = parse_name_status(&text);
if files.is_empty() {
header.push("Nothing differs: the files are identical.".into());
}
Ok(Comparison {
header,
files,
three_dot,
})
}
pub fn file_diff(a: &str, b: &str, three_dot: bool, f: &NameStatus) -> Result<Vec<String>> {
check_rev(a)?;
check_rev(b)?;
let range = compare_args(a, b, three_dot);
let mut specs = vec![top_spec(&f.path)];
if let Some(old) = &f.old {
specs.push(top_spec(old));
}
let mut args: Vec<&str> = vec!["diff", "-M", "--no-color"];
args.extend(range.iter().map(String::as_str));
args.push("--");
args.extend(specs.iter().map(String::as_str));
let text = git::git_ok(
&args,
&Opts {
max_lines: Some(DIFF_MAX_LINES),
..Opts::default()
},
)?;
Ok(text.lines().map(String::from).collect())
}
pub fn side_commits(a: &str, b: &str) -> Result<Vec<(char, LogEntry)>> {
check_rev(a)?;
check_rev(b)?;
let fmt = format!("--format=%m%x1d{}", history::LOG_FORMAT);
let sym = format!("{a}...{b}");
let text = git::git_ok(
&[
"log",
"--left-right",
"--cherry-mark",
&fmt,
"-n",
"300",
&sym,
],
&Opts {
max_lines: Some(5000),
..Opts::default()
},
)?;
Ok(parse_marked_log(&text))
}
pub fn run(config: &mut Config) -> Result<()> {
let Some(a) = ui::pick_ref("Compare: pick A (the base)", true, true, true)? else {
return Ok(());
};
let Some(b) = ui::pick_ref("Compare: pick B (what to look at)", true, true, true)? else {
return Ok(());
};
open(config, &a, &b)
}
pub fn open(cfg: &mut Config, a: &str, b: &str) -> Result<()> {
let (mut a, mut b) = (a.to_string(), b.to_string());
let mut three_dot = true;
let mut index = 0;
loop {
let (x, y) = (a.clone(), b.clone());
let cmp = match ui::git_job("Comparing...", move || compare(&x, &y, three_dot)) {
Ok(c) => c,
Err(e) if e.to_string() == crate::input::CANCELLED => return Err(e),
Err(e) => {
ui::notice("Compare", &[e.to_string()])?;
return Ok(());
}
};
three_dot = cmp.three_dot;
let mut header = vec![format!("A = {a} B = {b}")];
header.extend(cmp.header.iter().cloned());
header.push("Enter shows a file diff. M opens the menu.".into());
let rows: Vec<String> = cmp.files.iter().map(row_text).collect();
let keys = [
ui::Key {
key: 't',
label: "two/three dots",
},
ui::Key {
key: 'c',
label: "commits",
},
ui::Key {
key: 'x',
label: "swap A and B",
},
ui::Key {
key: 'r',
label: "refresh",
},
ui::Key {
key: 'm',
label: "menu",
},
];
let action = match ui::action_list("Compare", &header, &rows, &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Open(i) => {
if let Some(f) = cmp.files.get(i) {
show_file(&a, &b, cmp.three_dot, f)?;
}
continue;
}
ui::Choice::Action(c, _) => c,
};
let action = if action == 'm' {
let ctx = vec![format!("{a} vs {b}")];
let opts = [
"Commits on each side",
"Switch two/three dots",
"Swap A and B",
"Pick A again",
"Pick B again",
"Refresh",
];
match ui::choose("Compare menu", &ctx, &opts)? {
Some(0) => 'c',
Some(1) => 't',
Some(2) => 'x',
Some(3) => 'A',
Some(4) => 'B',
Some(5) => 'r',
_ => continue,
}
} else {
action
};
match action {
't' => {
three_dot = !three_dot;
index = 0;
}
'x' => {
std::mem::swap(&mut a, &mut b);
index = 0;
}
'A' => {
if let Some(r) = ui::pick_ref("Compare: pick A", true, true, true)? {
a = r;
index = 0;
}
}
'B' => {
if let Some(r) = ui::pick_ref("Compare: pick B", true, true, true)? {
b = r;
index = 0;
}
}
'c' => commits_view(cfg, &a, &b)?,
_ => {}
}
}
}
fn show_file(a: &str, b: &str, three_dot: bool, f: &NameStatus) -> Result<()> {
let (x, y, f2) = (a.to_string(), b.to_string(), f.clone());
let lines = match ui::git_job("Reading diff...", move || file_diff(&x, &y, three_dot, &f2)) {
Ok(l) => l,
Err(e) if e.to_string() == crate::input::CANCELLED => return Err(e),
Err(e) => return ui::notice("Compare", &[e.to_string()]),
};
let binary = lines
.iter()
.any(|l| l.starts_with("Binary files") || l.starts_with("GIT binary patch"));
if binary {
return ui::notice("Compare", &[format!("Binary files differ: {}", f.path)]);
}
if lines.is_empty() {
return ui::notice("Compare", &["Nothing differs in this file.".into()]);
}
ui::diff_view(&format!("{} ({a} vs {b})", f.path), &lines, &[])?;
Ok(())
}
fn commits_view(cfg: &mut Config, a: &str, b: &str) -> Result<()> {
let (x, y) = (a.to_string(), b.to_string());
let commits = ui::git_job("Reading commits...", move || side_commits(&x, &y))?;
if commits.is_empty() {
return ui::notice("Commits", &["No commits differ between these two.".into()]);
}
let rows: Vec<String> = commits
.iter()
.map(|(m, e)| {
format!(
"{m} {} {} {:<14.14} {}",
e.short,
e.author_date.get(..10).unwrap_or(""),
e.author,
e.subject
)
})
.collect();
let header = vec![
format!("< only in A ({a}) > only in B ({b}) = same change on both"),
"Enter opens the commit.".into(),
];
let mut index = 0;
loop {
match ui::action_list("Commits", &header, &rows, &[], &mut index)? {
ui::Choice::Open(i) => {
if let Some((_, e)) = commits.get(i) {
super::log::show(cfg, &e.oid)?;
}
}
ui::Choice::Action(_, _) => {}
ui::Choice::Back => return Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn counts_and_args() {
assert_eq!(parse_left_right_count("1\t3\n"), Some((1, 3)));
assert_eq!(parse_left_right_count(""), None);
assert_eq!(parse_left_right_count("x y"), None);
assert_eq!(compare_args("main", "dev", true), vec!["main...dev"]);
assert_eq!(compare_args("main", "dev", false), vec!["main", "dev"]);
assert_eq!(
describe_counts("main", "dev", 1, 3),
"dev is 3 commits ahead, 1 commit behind main"
);
assert!(describe_counts("a", "b", 0, 0).contains("same"));
assert!(dots_explanation(true).contains("Three dots"));
assert!(dots_explanation(false).contains("Two dots"));
}
#[test]
fn marked_log_parses() {
let rec = |m: &str, o: &str| {
format!("{m}\u{1d}{o}\u{1f}{}\u{1f}\u{1f}An\u{1f}a@x\u{1f}2024-01-01T00:00:00+00:00\u{1f}2024-01-01T00:00:00+00:00\u{1f}\u{1f}subj\u{1e}\n", &o[..3])
};
let text = format!("{}{}", rec("<", &"1".repeat(40)), rec(">", &"2".repeat(40)));
let v = parse_marked_log(&text);
assert_eq!(v.len(), 2);
assert_eq!(v[0].0, '<');
assert_eq!(v[1].0, '>');
assert_eq!(v[1].1.subject, "subj");
}
fn diverged() -> TempRepo {
let repo = TempRepo::new(2);
repo.git(&["checkout", "-qb", "dev"]);
repo.write("dev.txt", "d\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "dev 1"]);
repo.write("dev2.txt", "d\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "dev 2"]);
repo.git(&["checkout", "-q", "main"]);
repo.write("main.txt", "m\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "main 1"]);
repo
}
#[test]
fn compare_counts_after_divergence() {
let repo = diverged();
let c = repo.run(|| compare("main", "dev", true)).unwrap();
assert!(c.three_dot && !c.files.is_empty());
assert_eq!(c.header[0], "dev is 2 commits ahead, 1 commit behind main");
let paths: Vec<&str> = c.files.iter().map(|f| f.path.as_str()).collect();
assert_eq!(paths, vec!["dev.txt", "dev2.txt"]);
let two = repo.run(|| compare("main", "dev", false)).unwrap();
assert_eq!(two.files.len(), 3);
let commits = repo.run(|| side_commits("main", "dev")).unwrap();
assert_eq!(commits.iter().filter(|(m, _)| *m == '>').count(), 2);
assert_eq!(commits.iter().filter(|(m, _)| *m == '<').count(), 1);
let f = c.files[0].clone();
let d = repo.run(|| file_diff("main", "dev", true, &f)).unwrap();
assert!(d.iter().any(|l| l == "+d"));
}
#[test]
fn compare_identical_and_unrelated() {
let repo = TempRepo::new(2);
let c = repo.run(|| compare("main", "HEAD", true)).unwrap();
assert!(c.files.is_empty());
assert!(c.header[0].contains("same commit"));
repo.git(&["checkout", "-q", "--orphan", "other"]);
repo.write("o.txt", "o\n");
repo.git(&["add", "o.txt"]);
repo.git(&["commit", "-qm", "orphan"]);
let u = repo.run(|| compare("main", "other", true)).unwrap();
assert!(!u.three_dot);
assert!(u.header.iter().any(|h| h.starts_with("Warning")));
assert!(!u.files.is_empty());
assert!(repo.run(|| compare("-x", "main", true)).is_err());
}
}