From 479981cacf83f4c188002fb59995aa9351880aaf Mon Sep 17 00:00:00 2001 From: Eric Wolf Date: Fri, 20 Nov 2026 08:57:40 +0100 Subject: [PATCH] Add commit shortstats In Log commit panel and commit info panels. --- CHANGELOG.md | 2 + asyncgit/src/commit_stats.rs | 118 ++++++++++ asyncgit/src/lib.rs | 4 + asyncgit/src/sync/commit_stats.rs | 230 +++++++++++++++++++ asyncgit/src/sync/mod.rs | 2 + asyncgit/src/sync/repository.rs | 2 +- asyncgit/src/sync/reword.rs | 3 +- src/app.rs | 6 +- src/components/commit_details/details.rs | 221 +++++++++++++++++- src/components/commit_details/mod.rs | 5 + src/components/commitlist.rs | 250 +++++++++++++++++++- src/components/commitlist/stats.rs | 279 +++++++++++++++++++++++ src/options.rs | 45 ++++ src/popups/branchlist.rs | 3 +- src/popups/inspect_commit.rs | 4 +- src/popups/options.rs | 76 +++++- src/tabs/revlog.rs | 25 +- 17 files changed, 1254 insertions(+), 21 deletions(-) create mode 100644 asyncgit/src/commit_stats.rs create mode 100644 asyncgit/src/sync/commit_stats.rs create mode 100644 src/components/commitlist/stats.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a1ca0eaac2..86720b3841 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added * support x509 commit signing [[@kaden-l-nelson](https://github.com/kaden-l-nelson)] ([#2514](https://github.com/gitui-org/gitui/issues/2514)) +* show theme-colored added/deleted line counts (`Lines: +123 -45`) in commit and stash Info panels, using first-parent diffs for merges and including stashed untracked files +* add an optional diff statistics column after the author in the Log tab, enabled through Options → Log → Show diff stats (off by default and saved per repository) ### Changed * use [tombi](https://github.com/tombi-toml/tombi) for all toml file formatting diff --git a/asyncgit/src/commit_stats.rs b/asyncgit/src/commit_stats.rs new file mode 100644 index 0000000000..e972983669 --- /dev/null +++ b/asyncgit/src/commit_stats.rs @@ -0,0 +1,118 @@ +use crate::{ + asyncjob::{AsyncJob, RunParams}, + sync::{get_commit_stats, CommitId, CommitStats, RepoPath}, + AsyncGitNotification, Result, +}; + +/// A coalescible batch of independent commit statistics requests. +#[derive(Clone)] +pub struct AsyncCommitStatsJob { + /// Repository identity, used to reject stale completions. + pub repo: RepoPath, + /// Requested commits, in viewport order (one commit for Info). + pub commits: Vec, + /// One result per commit. `None` means statistics were unavailable. + pub results: Vec<(CommitId, Option)>, +} + +impl AsyncCommitStatsJob { + /// Create a batch for use with `AsyncSingleJob`. + pub const fn new(repo: RepoPath, commits: Vec) -> Self { + Self { + repo, + commits, + results: Vec::new(), + } + } +} + +impl AsyncJob for AsyncCommitStatsJob { + type Notification = AsyncGitNotification; + type Progress = (); + + fn run( + &mut self, + _params: RunParams, + ) -> Result { + self.results = self + .commits + .iter() + .map(|&id| { + let result = get_commit_stats(&self.repo, id) + .map_err(|err| { + log::error!("commit stats for {id}: {err}"); + }) + .ok(); + (id, result) + }) + .collect(); + Ok(AsyncGitNotification::CommitStats) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + asyncjob::AsyncSingleJob, + sync::tests::{repo_init, write_commit_file}, + }; + use std::time::Duration; + + #[test] + fn batch_keeps_successes_and_failures_and_always_notifies() { + let (dir, repo) = repo_init().unwrap(); + let first = + write_commit_file(&repo, "file", "one\n", "first"); + let second = write_commit_file( + &repo, + "file", + "two\nthree\n", + "second", + ); + let path: RepoPath = dir.path().to_path_buf().into(); + let (sender, receiver) = crossbeam_channel::unbounded(); + let job = AsyncSingleJob::new(sender); + job.spawn(AsyncCommitStatsJob::new( + path.clone(), + vec![first, CommitId::default(), second], + )); + assert_eq!( + receiver.recv_timeout(Duration::from_secs(10)).unwrap(), + AsyncGitNotification::CommitStats + ); + let result = job.take_last().unwrap(); + assert_eq!(result.repo, path); + assert_eq!( + result.results, + vec![ + ( + first, + Some(CommitStats { + insertions: 1, + deletions: 0, + is_merge: false + }) + ), + (CommitId::default(), None), + ( + second, + Some(CommitStats { + insertions: 2, + deletions: 1, + is_merge: false + }) + ), + ] + ); + job.spawn(AsyncCommitStatsJob::new( + dir.path().join("missing").into(), + vec![first, second], + )); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + assert_eq!( + job.take_last().unwrap().results, + vec![(first, None), (second, None)] + ); + } +} diff --git a/asyncgit/src/lib.rs b/asyncgit/src/lib.rs index 98cc7238f9..8ea99b68d3 100644 --- a/asyncgit/src/lib.rs +++ b/asyncgit/src/lib.rs @@ -48,6 +48,7 @@ mod blame; mod branches; pub mod cached; mod commit_files; +mod commit_stats; mod diff; mod error; mod fetch_job; @@ -68,6 +69,7 @@ pub use crate::{ blame::{AsyncBlame, BlameParams}, branches::AsyncBranchesJob, commit_files::{AsyncCommitFiles, CommitFilesParams}, + commit_stats::AsyncCommitStatsJob, diff::{AsyncDiff, DiffParams, DiffType}, error::{Error, Result}, fetch_job::AsyncFetchJob, @@ -108,6 +110,8 @@ pub enum AsyncGitNotification { FileLog, /// CommitFiles, + /// A batch of commit statistics is ready. + CommitStats, /// Tags, /// diff --git a/asyncgit/src/sync/commit_stats.rs b/asyncgit/src/sync/commit_stats.rs new file mode 100644 index 0000000000..0351704458 --- /dev/null +++ b/asyncgit/src/sync/commit_stats.rs @@ -0,0 +1,230 @@ +use super::{ + commit_files::get_commit_diff, get_stashes, repository::repo, + CommitId, RepoPath, +}; +use crate::error::Result; + +/// Text-line totals relative to the first parent (or an empty tree). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CommitStats { + /// Added text lines; binary changes do not contribute. + pub insertions: usize, + /// Removed text lines; binary changes do not contribute. + pub deletions: usize, + /// Whether to explain the first-parent comparison in commit Info. + pub is_merge: bool, +} + +/// Get shortstats using the same diff, including untracked stash files, +/// as commit inspection. Whitespace changes count; unchanged renames do not. +pub fn get_commit_stats( + repo_path: &RepoPath, + id: CommitId, +) -> Result { + let repo = repo(repo_path)?; + let commit = repo.find_commit(id.into())?; + // The inspection diff tolerates missing parents. Stats must not mistake + // an unavailable parent object or tree for a genuine root commit. + if commit.parent_count() > 0 { + commit.parent(0)?.tree()?; + } + let stashes = get_stashes(repo_path)?.into_iter().collect(); + let mut diff = + get_commit_diff(&repo, id, None, None, Some(&stashes))?; + diff.find_similar(Some( + git2::DiffFindOptions::new().renames(true), + ))?; + let stats = diff.stats()?; + Ok(CommitStats { + insertions: stats.insertions(), + deletions: stats.deletions(), + is_merge: commit.parent_count() > 1 && !stashes.contains(&id), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sync::{ + get_commit_details, stage_add_file, stash_save, + tests::{repo_init, repo_init_empty, write_commit_file}, + }; + use git2::{ObjectType, Repository}; + use std::{fs, path::Path}; + + fn make_commit( + repo: &Repository, + files: &[(&str, &[u8])], + parents: &[CommitId], + ) -> CommitId { + let mut builder = repo.treebuilder(None).unwrap(); + for (name, content) in files { + builder + .insert(*name, repo.blob(content).unwrap(), 0o100644) + .unwrap(); + } + let tree = repo.find_tree(builder.write().unwrap()).unwrap(); + let parents: Vec<_> = parents + .iter() + .map(|id| repo.find_commit((*id).into()).unwrap()) + .collect(); + let sig = repo.signature().unwrap(); + repo.commit( + None, + &sig, + &sig, + "stats test", + &tree, + &parents.iter().collect::>(), + ) + .unwrap() + .into() + } + + fn check( + repo: &Repository, + id: CommitId, + insertions: usize, + deletions: usize, + is_merge: bool, + ) { + let path = repo.path().to_path_buf().into(); + assert_eq!( + get_commit_stats(&path, id).unwrap(), + CommitStats { + insertions, + deletions, + is_merge + } + ); + } + + #[test] + fn root_ordinary_empty_and_whitespace() { + let (_dir, repo) = repo_init_empty().unwrap(); + let root = + make_commit(&repo, &[("file", b"one\ntwo\n")], &[]); + check(&repo, root, 2, 0, false); + let ordinary = make_commit( + &repo, + &[("file", b"one\nthree\nfour\n")], + &[root], + ); + check(&repo, ordinary, 2, 1, false); + let empty = make_commit( + &repo, + &[("file", b"one\nthree\nfour\n")], + &[ordinary], + ); + check(&repo, empty, 0, 0, false); + let whitespace = make_commit( + &repo, + &[("file", b"one \nthree\nfour\n")], + &[empty], + ); + check(&repo, whitespace, 1, 1, false); + let empty_root = make_commit(&repo, &[], &[]); + check(&repo, empty_root, 0, 0, false); + } + + #[test] + fn binary_changes_have_no_text_counts() { + let (_dir, repo) = repo_init_empty().unwrap(); + let root = make_commit(&repo, &[("binary", b"a\0b\n")], &[]); + check(&repo, root, 0, 0, false); + let changed = + make_commit(&repo, &[("binary", b"c\0d\n")], &[root]); + check(&repo, changed, 0, 0, false); + let deleted = make_commit(&repo, &[], &[changed]); + check(&repo, deleted, 0, 0, false); + } + + #[test] + fn renamed_files_do_not_inflate_counts() { + let (_dir, repo) = repo_init_empty().unwrap(); + let root = make_commit( + &repo, + &[("before", b"one\ntwo\nthree\nfour\n")], + &[], + ); + let renamed = make_commit( + &repo, + &[("after", b"one\ntwo\nthree\nfour\n")], + &[root], + ); + check(&repo, renamed, 0, 0, false); + let edited = make_commit( + &repo, + &[("again", b"one\ntwo\nthree\nfive\n")], + &[renamed], + ); + check(&repo, edited, 1, 1, false); + } + + #[test] + fn merge_and_octopus_use_only_first_parent() { + let (_dir, repo) = repo_init_empty().unwrap(); + let first = + make_commit(&repo, &[("file", b"one\ntwo\n")], &[]); + let second = + make_commit(&repo, &[("other", b"unrelated\n")], &[]); + let third = make_commit( + &repo, + &[("third", b"not stash untracked\n")], + &[], + ); + for parents in + [vec![first, second], vec![first, second, third]] + { + let merge = make_commit( + &repo, + &[("file", b"one\nmerged\nextra\n")], + &parents, + ); + check(&repo, merge, 2, 1, true); + } + } + + #[test] + fn stash_includes_staged_unstaged_and_untracked() { + let (dir, repo) = repo_init().unwrap(); + let path = dir.path().to_path_buf().into(); + write_commit_file(&repo, "tracked", "old\nkeep\n", "base"); + fs::write(dir.path().join("tracked"), "new\nkeep\n").unwrap(); + stage_add_file(&path, Path::new("tracked")).unwrap(); + fs::write(dir.path().join("tracked"), "new\nkeep\nextra\n") + .unwrap(); + fs::write(dir.path().join("untracked"), "u1\nu2\n").unwrap(); + let stash = stash_save(&path, None, true, false).unwrap(); + check(&repo, stash, 4, 1, false); + fs::write(dir.path().join("tracked"), "new\nkeep\n").unwrap(); + let tracked_only = + stash_save(&path, None, false, false).unwrap(); + check(&repo, tracked_only, 1, 1, false); + } + + #[test] + fn missing_parent_or_parent_tree_is_unavailable_but_metadata_survives( + ) { + let (_dir, repo) = repo_init_empty().unwrap(); + let root = + make_commit(&repo, &[("file", b"one\ntwo\n")], &[]); + let tree = repo.find_commit(root.into()).unwrap().tree_id(); + let missing = "ffffffffffffffffffffffffffffffffffffffff"; + let broken_parent = repo.odb().unwrap().write(ObjectType::Commit, format!("tree {missing}\nauthor A 1 +0000\ncommitter A 1 +0000\n\nparent\n").as_bytes()).unwrap(); + for parent in [missing.to_string(), broken_parent.to_string()] + { + let id = repo.odb().unwrap().write(ObjectType::Commit, format!("tree {tree}\nparent {parent}\nauthor A 1 +0000\ncommitter A 1 +0000\n\nchild\n").as_bytes()).unwrap().into(); + let path = repo.path().to_path_buf().into(); + assert!(get_commit_stats(&path, id).is_err()); + assert_eq!( + get_commit_details(&path, id) + .unwrap() + .message + .unwrap() + .subject, + "child" + ); + } + } +} diff --git a/asyncgit/src/sync/mod.rs b/asyncgit/src/sync/mod.rs index 2cd358d065..eb02019e55 100644 --- a/asyncgit/src/sync/mod.rs +++ b/asyncgit/src/sync/mod.rs @@ -10,6 +10,7 @@ mod commit_details; pub mod commit_files; mod commit_filter; mod commit_revert; +mod commit_stats; mod commits_info; mod config; pub mod cred; @@ -56,6 +57,7 @@ pub use commit_filter::{ SharedCommitFilterFn, }; pub use commit_revert::{commit_revert, revert_commit, revert_head}; +pub use commit_stats::{get_commit_stats, CommitStats}; pub use commits_info::{ get_commit_info, get_commits_info, CommitId, CommitInfo, }; diff --git a/asyncgit/src/sync/repository.rs b/asyncgit/src/sync/repository.rs index c49795fb7c..11a67fbcfd 100644 --- a/asyncgit/src/sync/repository.rs +++ b/asyncgit/src/sync/repository.rs @@ -11,7 +11,7 @@ use crate::error::Result; pub type RepoPathRef = RefCell; /// -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum RepoPath { /// Path(PathBuf), diff --git a/asyncgit/src/sync/reword.rs b/asyncgit/src/sync/reword.rs index a3c2829aea..986729e837 100644 --- a/asyncgit/src/sync/reword.rs +++ b/asyncgit/src/sync/reword.rs @@ -32,7 +32,8 @@ pub fn reword( if repo .diff_tree_to_index(Some(&tree), None, None)? .deltas() - .len() == 0 + .len() + == 0 { undo_last_commit(repo_path)?; return super::commit(repo_path, message); diff --git a/src/app.rs b/src/app.rs index ddb157af3f..a9e4ffcd56 100644 --- a/src/app.rs +++ b/src/app.rs @@ -861,6 +861,9 @@ impl App { } InternalEvent::OptionSwitched(o) => { match o { + AppOption::LogShowDiffStats => { + self.revlog.update_diff_stats_option(); + } AppOption::StatusShowUntracked => { self.status_tab.update()?; } @@ -1182,7 +1185,8 @@ impl App { tab_labels.iter().map(Span::width).sum::() + tab_labels.len().saturating_sub(1) * (divider.width() + DIVIDER_PAD_SPACES) - + SIDE_PADS + MARGIN_LEFT_AND_RIGHT; + + SIDE_PADS + + MARGIN_LEFT_AND_RIGHT; let left_right = Layout::default() .direction(Direction::Horizontal) diff --git a/src/components/commit_details/details.rs b/src/components/commit_details/details.rs index 42825900a0..f17d46c128 100644 --- a/src/components/commit_details/details.rs +++ b/src/components/commit_details/details.rs @@ -13,7 +13,11 @@ use crate::{ }; use anyhow::Result; use asyncgit::sync::{ - self, CommitDetails, CommitId, CommitMessage, RepoPathRef, Tag, + self, CommitDetails, CommitId, CommitMessage, CommitStats, + RepoPath, RepoPathRef, Tag, +}; +use asyncgit::{ + asyncjob::AsyncSingleJob, AsyncCommitStatsJob, DiffLineType, }; use crossterm::event::Event; use ratatui::{ @@ -27,9 +31,19 @@ use sync::CommitTags; use super::style::Detail; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum StatsState { + Loading, + Ready(CommitStats), + Unavailable, +} + pub struct DetailsComponent { repo: RepoPathRef, data: Option, + commit: Option<(RepoPath, CommitId)>, + stats: StatsState, + stats_job: AsyncSingleJob, tags: Vec, theme: SharedTheme, focused: bool, @@ -48,6 +62,9 @@ impl DetailsComponent { Self { repo: env.repo.clone(), data: None, + commit: None, + stats: StatsState::Loading, + stats_job: AsyncSingleJob::new(env.sender_git.clone()), tags: Vec::new(), theme: env.theme.clone(), focused, @@ -63,6 +80,19 @@ impl DetailsComponent { id: Option, tags: Option, ) { + let commit = id.map(|id| (self.repo.borrow().clone(), id)); + if self.commit != commit { + self.stats_job.cancel(); + self.stats = StatsState::Loading; + if let Some((repo, id)) = &commit { + self.stats_job.spawn(AsyncCommitStatsJob::new( + repo.clone(), + vec![*id], + )); + } + self.commit = commit; + } + self.update_stats(); self.tags.clear(); self.data = id.and_then(|id| { @@ -76,6 +106,63 @@ impl DetailsComponent { } } + pub fn update_stats(&mut self) { + if let Some(job) = self.stats_job.take_last() { + for (id, stats) in job.results { + if self.commit.as_ref().is_some_and( + |(repo, commit)| { + *repo == job.repo && *commit == id + }, + ) { + self.stats = stats.map_or( + StatsState::Unavailable, + StatsState::Ready, + ); + } + } + } + } + + pub fn stats_pending(&self) -> bool { + self.stats_job.is_pending() + } + + fn stats_line(&self) -> Line<'_> { + let text = self.theme.text(true, false); + let mut line = match self.stats { + StatsState::Ready(stats) => { + let mut spans = vec![ + Span::styled( + format!("+{}", stats.insertions), + self.theme + .diff_line(DiffLineType::Add, false), + ), + Span::styled(" ", text), + Span::styled( + format!("-{}", stats.deletions), + self.theme + .diff_line(DiffLineType::Delete, false), + ), + ]; + if stats.is_merge { + spans.push(Span::styled(" (first parent)", text)); + } + Line::from(spans) + } + StatsState::Unavailable => { + Line::from(Span::styled("Stats unavailable", text)) + } + StatsState::Loading => { + Line::from(Span::styled("…", text)) + } + }; + line.spans.insert( + 0, + Span::styled("Lines: ", self.theme.text(false, false)), + ); + line + } + fn wrap_commit_details( message: &CommitMessage, width: usize, @@ -217,6 +304,8 @@ impl DetailsComponent { ), ])); + res.push(self.stats_line()); + if !self.tags.is_empty() { res.push(Line::from(style_detail( &self.theme, @@ -261,7 +350,8 @@ impl DrawableComponent for DetailsComponent { let chunks = Layout::default() .direction(Direction::Vertical) .constraints( - [Constraint::Length(8), Constraint::Min(10)].as_ref(), + [Constraint::Length(10), Constraint::Min(10)] + .as_ref(), ) .split(rect); @@ -430,6 +520,133 @@ mod tests { [&wrapped_title[..], &wrapped_message[..]].concat() } + #[test] + fn stats_survive_refreshes_and_reject_stale_completions() { + use std::time::Duration; + let (dir, repo) = git2_testing::repo_init(); + let mut env = Environment::test_env(); + env.repo.replace(dir.path().to_path_buf().into()); + let (sender, receiver) = crossbeam_channel::unbounded(); + env.sender_git = sender; + let id = repo.head().unwrap().target().unwrap().into(); + let mut details = DetailsComponent::new(&env, false); + details.set_commit(Some(id), None); + assert_eq!(details.stats_line().to_string(), "Lines: …"); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + for _ in 0..5 { + details.set_commit(Some(id), None); + assert_eq!( + details.stats, + StatsState::Ready(CommitStats::default()) + ); + } + assert!(receiver.is_empty()); + + // A result for another repository must not overwrite this commit. + details.stats_job.spawn(AsyncCommitStatsJob::new( + dir.path().join("other").into(), + vec![id], + )); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + details.update_stats(); + assert_eq!( + details.stats, + StatsState::Ready(CommitStats::default()) + ); + // Nor may a result for a different selection in this repository. + details.stats_job.spawn(AsyncCommitStatsJob::new( + env.repo.borrow().clone(), + vec![CommitId::default()], + )); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + details.update_stats(); + assert_eq!( + details.stats, + StatsState::Ready(CommitStats::default()) + ); + details.set_commit(None, None); + assert_eq!(details.stats, StatsState::Loading); + } + + #[test] + fn info_stats_placement_colors_and_sizing_with_committer_and_tags( + ) { + use asyncgit::sync::CommitSignature; + use ratatui::{backend::TestBackend, Terminal}; + let env = Environment::test_env(); + let mut details = DetailsComponent::new(&env, false); + details.data = Some(CommitDetails { + hash: "abcdef0123456789".into(), + author: CommitSignature { + name: "作者".into(), + email: "a@b".into(), + time: 0, + }, + committer: Some(CommitSignature { + name: "Committer".into(), + email: "c@d".into(), + time: 1, + }), + message: Some(CommitMessage::from("subject")), + }); + details.tags = vec![Tag::new("v1")]; + details.stats = StatsState::Ready(CommitStats { + insertions: 123, + deletions: 45, + is_merge: true, + }); + let text = details.get_text_info(); + assert!(text[4].to_string().contains("abcdef")); + assert_eq!( + text[5].to_string(), + "Lines: +123 -45 (first parent)" + ); + assert_eq!( + text[5].spans[0].style, + env.theme.text(false, false) + ); + assert_eq!( + text[5].spans[1].style, + env.theme.diff_line(DiffLineType::Add, false) + ); + assert_eq!( + text[5].spans[3].style, + env.theme.diff_line(DiffLineType::Delete, false) + ); + assert!(text[6].to_string().contains("Tags")); + assert_eq!(text[7].to_string(), "v1"); + let mut terminal = + Terminal::new(TestBackend::new(80, 20)).unwrap(); + terminal + .draw(|f| details.draw(f, f.area()).unwrap()) + .unwrap(); + let screen = format!("{}", terminal.backend()); + assert!(screen.contains("Lines: +123 -45 (first parent)")); + assert!(screen.contains("v1")); + assert!(screen.contains("subject")); + for (width, height) in [(28, 12), (10, 4), (1, 1)] { + let mut terminal = + Terminal::new(TestBackend::new(width, height)) + .unwrap(); + terminal + .draw(|f| details.draw(f, f.area()).unwrap()) + .unwrap(); + } + details.stats = StatsState::Unavailable; + assert_eq!( + details.get_text_info()[5].to_string(), + "Lines: Stats unavailable" + ); + assert!(details.get_text_info()[4] + .to_string() + .contains("abcdef")); + details.stats = StatsState::Loading; + assert_eq!( + details.get_text_info()[5].to_string(), + "Lines: …" + ); + } + #[test] fn test_textwrap() { let message = CommitMessage::from("Commit message"); diff --git a/src/components/commit_details/mod.rs b/src/components/commit_details/mod.rs index b8872c396b..043b2ab356 100644 --- a/src/components/commit_details/mod.rs +++ b/src/components/commit_details/mod.rs @@ -113,6 +113,11 @@ impl CommitDetailsComponent { /// pub fn any_work_pending(&self) -> bool { self.git_commit_files.is_pending() + || self.single_details.stats_pending() + } + + pub fn update_stats(&mut self) { + self.single_details.update_stats(); } /// diff --git a/src/components/commitlist.rs b/src/components/commitlist.rs index e97754ecb4..436893bbd7 100644 --- a/src/components/commitlist.rs +++ b/src/components/commitlist.rs @@ -1,3 +1,5 @@ +mod stats; + use super::utils::logitems::{ItemBatch, LogEntry}; use crate::{ app::Environment, @@ -28,8 +30,13 @@ use ratatui::{ widgets::{Block, Borders, Paragraph}, Frame, }; +use stats::ListStats; use std::{ - borrow::Cow, cell::Cell, cmp, collections::BTreeMap, rc::Rc, + borrow::Cow, + cell::{Cell, RefCell}, + cmp, + collections::BTreeMap, + rc::Rc, time::Instant, }; @@ -43,6 +50,7 @@ pub struct CommitList { selection: usize, highlighted_selection: Option, items: ItemBatch, + stats: RefCell, highlights: Option>>, commits: IndexSet, /// The marked commits. @@ -66,6 +74,10 @@ impl CommitList { Self { repo: env.repo.clone(), items: ItemBatch::default(), + stats: RefCell::new(ListStats::new( + env.repo.borrow().clone(), + env.sender_git.clone(), + )), marked: Vec::with_capacity(2), selection: 0, highlighted_selection: None, @@ -84,6 +96,14 @@ impl CommitList { } } + pub fn set_show_diff_stats(&self, show: bool) { + self.stats.borrow_mut().set_enabled(show); + } + + pub fn stats_pending(&self) -> bool { + self.stats.borrow().job.is_pending() + } + /// pub const fn tags(&self) -> Option<&Tags> { self.tags.as_ref() @@ -92,6 +112,7 @@ impl CommitList { /// pub fn clear(&mut self) { self.items.clear(); + self.stats.borrow_mut().retain(&self.items); self.commits.clear(); } @@ -354,7 +375,8 @@ impl CommitList { self.update_scroll_speed(); #[allow(clippy::cast_possible_truncation)] - let speed_int = usize::try_from(self.scroll_state.1 as i64)?.max(1); + let speed_int = + usize::try_from(self.scroll_state.1 as i64)?.max(1); let page_offset = usize::from( self.current_size.get().unwrap_or_default().1, @@ -439,7 +461,7 @@ impl CommitList { } } - #[allow(clippy::too_many_arguments)] + #[allow(clippy::too_many_arguments, clippy::too_many_lines)] fn get_entry_to_add<'a>( &self, e: &'a LogEntry, @@ -451,6 +473,7 @@ impl CommitList { width: usize, now: DateTime, marked: Option, + stats_widths: Option<(usize, usize)>, ) -> Line<'a> { let mut txt: Vec = Vec::with_capacity( ELEMENTS_PER_LINE + if marked.is_some() { 2 } else { 0 }, @@ -526,8 +549,10 @@ impl CommitList { txt.push(splitter.clone()); + let stats_width = + stats_widths.map_or(0, |(add, del)| add + del + 2); let author_width = - (width.saturating_sub(19) / 3).clamp(3, 20); + (width.saturating_sub(19 + stats_width) / 3).clamp(3, 20); let author = string_width_align(&e.author, author_width); // commit author @@ -535,6 +560,15 @@ impl CommitList { txt.push(splitter.clone()); + if let Some(widths) = stats_widths { + txt.extend( + self.stats + .borrow() + .spans(e.id, widths, normal, selected, theme), + ); + txt.push(splitter.clone()); + } + // commit tags if let Some(tags) = tags { txt.push(splitter.clone()); @@ -552,9 +586,12 @@ impl CommitList { txt.push(splitter); - let message_width = width.saturating_sub( - txt.iter().map(|span| span.content.len()).sum(), - ); + let message_width = + width.saturating_sub(if stats_widths.is_some() { + txt.iter().map(Span::width).sum() + } else { + txt.iter().map(|span| span.content.len()).sum() + }); // commit msg txt.push(Span::styled( @@ -573,6 +610,11 @@ impl CommitList { let now = Local::now(); let any_marked = !self.marked.is_empty(); + let stats_widths = self.stats.borrow().widths( + &self.items, + self.scroll_top.get(), + height, + ); for (idx, e) in self .items @@ -616,6 +658,7 @@ impl CommitList { width, now, marked, + stats_widths, )); } @@ -765,6 +808,7 @@ impl CommitList { commits, self.highlights.as_ref(), ); + self.stats.borrow_mut().retain(&self.items); } } } @@ -787,6 +831,13 @@ impl DrawableComponent for CommitList { selection, )); + self.stats.borrow_mut().update( + &self.repo.borrow(), + &self.items, + self.scroll_top.get(), + height_in_lines, + ); + let title = format!( "{} {}/{}", self.title, @@ -897,6 +948,7 @@ impl Component for CommitList { #[cfg(test)] mod tests { use asyncgit::sync::CommitInfo; + use asyncgit::DiffLineType; use super::*; @@ -909,6 +961,10 @@ mod tests { highlights: Option::None, tags: Option::None, items: ItemBatch::default(), + stats: RefCell::new(ListStats::new( + sync::RepoPath::Path(Default::default()), + crossbeam_channel::unbounded().0, + )), commits: IndexSet::default(), marked: Vec::default(), scroll_top: Cell::default(), @@ -926,6 +982,183 @@ mod tests { } } + #[test] + fn stats_column_alignment_colors_and_visible_widths() { + use asyncgit::sync::{CommitStats, Tag}; + let mut list = CommitList::default(); + let ids: Vec<_> = (1..=5) + .map(|id| { + CommitId::from_str_unchecked(&format!("{id:040}")) + .unwrap() + }) + .collect(); + list.items.set_items( + 0, + ids.iter() + .map(|&id| CommitInfo { + id, + author: "作者 Å".into(), + message: "message".into(), + time: 0, + }) + .collect(), + None, + ); + list.tags = Some([(ids[0], vec![Tag::new("v1")])].into()); + assert!(!list.stats.borrow().enabled); + assert!(!list.get_text(4, 100)[0].to_string().contains('+')); + list.set_show_diff_stats(true); + list.stats.borrow_mut().cache.extend([ + ( + ids[0], + Some(CommitStats { + insertions: 123, + deletions: 4, + is_merge: true, + }), + ), + ( + ids[1], + Some(CommitStats { + insertions: 1, + deletions: 4567, + is_merge: false, + }), + ), + (ids[2], None), + ( + ids[4], + Some(CommitStats { + insertions: usize::MAX, + deletions: usize::MAX, + is_merge: false, + }), + ), + ]); + let lines = list.get_text(4, 100); + assert_eq!(lines[0].spans[6].content, "+123"); + assert_eq!(lines[0].spans[8].content, " -4"); + assert_eq!(lines[1].spans[6].content, " +1"); + assert_eq!(lines[1].spans[8].content, "-4567"); + assert_eq!(lines[2].spans[6].content, "— "); + assert_eq!(lines[3].spans[6].content, "… "); + let first = lines[0].to_string(); + assert!( + first.find("作者").unwrap() < first.find("+123").unwrap() + ); + assert!( + first.find("-4").unwrap() < first.find("").unwrap() + ); + assert!( + first.find("").unwrap() + < first.find("message").unwrap() + ); + assert!(!first.contains("first parent")); + assert_eq!(lines[0].width(), 100); + assert_eq!(lines[1].width(), 100); + assert_eq!( + lines[0].spans[6].style, + list.theme.diff_line(DiffLineType::Add, true) + ); + assert_eq!( + lines[0].spans[8].style, + list.theme.diff_line(DiffLineType::Delete, true) + ); + assert_eq!( + lines[1].spans[6].style, + list.theme.diff_line(DiffLineType::Add, false) + ); + assert_eq!( + lines[1].spans[8].style, + list.theme.diff_line(DiffLineType::Delete, false) + ); + let all = list.get_text(5, 140); + assert!(all[4].to_string().contains(&format!( + "+{} -{}", + usize::MAX, + usize::MAX + ))); + assert_eq!(all[0].spans[6].width(), all[4].spans[6].width()); + assert_eq!(all[0].spans[8].width(), all[4].spans[8].width()); + let row = list + .get_entry_to_add( + list.items.iter().next().unwrap(), + false, + Some("".into()), + Some("{branch}".into()), + Some("[remote]".into()), + &list.theme, + 120, + Local::now(), + None, + Some((4, 5)), + ) + .to_string(); + assert!(row.contains("-4 {branch} [remote] message")); + list.set_show_diff_stats(false); + assert!(!list.get_text(4, 100)[0] + .to_string() + .contains("+123")); + } + + #[test] + fn stats_column_search_highlighting_and_constrained_widths() { + use asyncgit::sync::CommitStats; + use ratatui::{backend::TestBackend, Terminal}; + let mut list = build_commit_list_with_some_commits(); + let ids: Vec<_> = list.items.iter().map(|e| e.id).collect(); + list.commits = ids.iter().copied().collect(); + let highlights = Rc::new([ids[0]].into_iter().collect()); + list.items.set_items( + 0, + ids.iter() + .map(|&id| CommitInfo { + id, + author: "作者".into(), + message: "message".into(), + time: 0, + }) + .collect(), + Some(&highlights), + ); + list.selection = 0; + list.set_show_diff_stats(true); + list.stats.borrow_mut().cache.extend(ids.iter().map(|&id| { + ( + id, + Some(CommitStats { + insertions: 1234567, + deletions: 12345678, + is_merge: false, + }), + ) + })); + let lines = list.get_text(2, 100); + assert_eq!( + lines[0].spans[6].style, + list.theme.diff_line(DiffLineType::Add, true) + ); + assert_eq!( + lines[1].spans[6].style, + list.theme.commit_unhighlighted() + ); + assert_eq!( + lines[1].spans[8].style, + list.theme.commit_unhighlighted() + ); + for width in [80, 50, 30, 12, 1] { + let mut terminal = + Terminal::new(TestBackend::new(width, 5)).unwrap(); + terminal + .draw(|f| list.draw(f, f.area()).unwrap()) + .unwrap(); + if width >= 50 { + assert!(format!("{}", terminal.backend()) + .contains("+1234567 -12345678")); + } + } + } + #[test] fn test_string_width_align() { assert_eq!(string_width_align("123", 3), "123"); @@ -949,7 +1182,8 @@ mod tests { } /// Build a commit list with a few commits loaded - fn build_commit_list_with_some_commits() -> CommitList { + pub(super) fn build_commit_list_with_some_commits() -> CommitList + { let mut items = ItemBatch::default(); let basic_commit_info = CommitInfo { message: String::default(), diff --git a/src/components/commitlist/stats.rs b/src/components/commitlist/stats.rs new file mode 100644 index 0000000000..7effec2046 --- /dev/null +++ b/src/components/commitlist/stats.rs @@ -0,0 +1,279 @@ +use super::ItemBatch; +use crate::ui::style::Theme; +use asyncgit::{ + asyncjob::AsyncSingleJob, + sync::{CommitId, CommitStats, RepoPath}, + AsyncCommitStatsJob, AsyncGitNotification, DiffLineType, +}; +use crossbeam_channel::Sender; +use ratatui::{style::Style, text::Span}; +use std::collections::{HashMap, HashSet}; + +/// Local to one list; only the Log tab enables it. +pub(super) struct ListStats { + pub enabled: bool, + pub cache: HashMap>, + pub job: AsyncSingleJob, + repo: RepoPath, + requested: Vec, +} + +impl ListStats { + pub fn new( + repo: RepoPath, + sender: Sender, + ) -> Self { + Self { + enabled: false, + cache: HashMap::new(), + job: AsyncSingleJob::new(sender), + repo, + requested: Vec::new(), + } + } + + pub fn set_enabled(&mut self, enabled: bool) { + self.enabled = enabled; + if !enabled { + self.job.cancel(); + self.requested.clear(); + } + } + + pub fn retain(&mut self, items: &ItemBatch) { + if self.cache.is_empty() { + return; + } + let ids: HashSet<_> = + items.iter().map(|entry| entry.id).collect(); + self.cache.retain(|id, _| ids.contains(id)); + } + + pub fn update( + &mut self, + repo: &RepoPath, + items: &ItemBatch, + top: usize, + height: usize, + ) { + if self.repo != *repo { + self.job.cancel(); + self.cache.clear(); + self.requested.clear(); + self.repo = repo.clone(); + } + if let Some(job) = self.job.take_last() { + self.apply(job); + } + self.retain(items); + if !self.enabled { + return; + } + let missing: Vec<_> = items + .iter() + .skip(top) + .take(height) + .map(|entry| entry.id) + .filter(|id| !self.cache.contains_key(id)) + .collect(); + if missing.is_empty() { + self.job.cancel(); + self.requested.clear(); + } else if missing != self.requested { + self.requested.clone_from(&missing); + self.job.spawn(AsyncCommitStatsJob::new( + repo.clone(), + missing, + )); + } + } + + fn apply(&mut self, job: AsyncCommitStatsJob) { + if job.repo == self.repo { + if job.commits == self.requested { + self.requested.clear(); + } + self.cache.extend(job.results); + } + } + + pub fn spans( + &self, + id: CommitId, + (added_width, removed_width): (usize, usize), + normal: bool, + selected: bool, + theme: &Theme, + ) -> Vec> { + let text = if normal { + theme.text(true, selected) + } else { + theme.commit_unhighlighted() + }; + let style = |kind| { + if normal { + theme.diff_line(kind, selected) + } else { + theme.commit_unhighlighted() + } + }; + match self.cache.get(&id) { + Some(Some(stats)) => vec![ + Span::styled( + format!( + "{:>added_width$}", + format!("+{}", stats.insertions) + ), + style(DiffLineType::Add), + ), + Span::styled( + " ", + if normal { text } else { Style::default() }, + ), + Span::styled( + format!( + "{:>removed_width$}", + format!("-{}", stats.deletions) + ), + style(DiffLineType::Delete), + ), + ], + result => vec![Span::styled( + format!( + "{: Option<(usize, usize)> { + self.enabled.then(|| { + items + .iter() + .skip(top) + .take(height) + .filter_map(|entry| { + self.cache.get(&entry.id).copied().flatten() + }) + .fold((2, 2), |(added, removed), stats| { + ( + added.max( + stats.insertions.to_string().len() + 1, + ), + removed.max( + stats.deletions.to_string().len() + 1, + ), + ) + }) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::components::commitlist::tests::build_commit_list_with_some_commits; + use std::time::Duration; + + #[test] + fn visible_rows_only_cache_reuse_and_batch_eviction() { + let list = build_commit_list_with_some_commits(); + let items = &list.items; + let (sender, receiver) = crossbeam_channel::unbounded(); + let dir = tempfile::tempdir().unwrap(); + let repo = dir.path().to_path_buf().into(); + let mut stats = ListStats::new(repo, sender); + let repo = stats.repo.clone(); + stats.update(&repo, items, 0, 3); + assert!(stats.requested.is_empty()); // Default off, as in other lists. + stats.set_enabled(true); + stats.update(&repo, items, 2, 3); + let expected: Vec<_> = + items.iter().skip(2).take(3).map(|e| e.id).collect(); + assert_eq!(stats.requested, expected); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + stats.update(&repo, items, 2, 3); + assert_eq!(stats.cache.len(), 3); + assert!(expected + .iter() + .all(|id| stats.cache.get(id) == Some(&None))); + for _ in 0..5 { + stats.update(&repo, items, 2, 3); + assert!(stats.requested.is_empty()); + } + assert!(receiver.is_empty()); + stats.set_enabled(false); + stats.set_enabled(true); + stats.update(&repo, items, 2, 3); + assert!(stats.requested.is_empty()); + stats.update(&repo, items, 3, 3); + assert_eq!( + stats.requested, + vec![items.iter().nth(5).unwrap().id] + ); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + stats.update(&repo, items, 3, 3); + assert_eq!(stats.cache.len(), 4); + stats.retain(&ItemBatch::default()); + assert!(stats.cache.is_empty()); + } + + #[test] + fn stale_completions_match_repository_and_loaded_batch() { + let list = build_commit_list_with_some_commits(); + let (sender, _receiver) = crossbeam_channel::unbounded(); + let repo: RepoPath = "/first".into(); + let mut stats = ListStats::new(repo.clone(), sender); + let id = list.items.iter().next().unwrap().id; + let other = list.items.iter().nth(1).unwrap().id; + stats.requested = vec![other]; + let mut completion = + AsyncCommitStatsJob::new("/second".into(), vec![id]); + completion.results = vec![(id, Some(CommitStats::default()))]; + stats.apply(completion.clone()); + assert!(stats.cache.is_empty()); + completion.repo = repo.clone(); + stats.apply(completion); + assert!(stats.cache.contains_key(&id)); + assert_eq!(stats.requested, [other]); + stats.update(&repo, &ItemBatch::default(), 0, 3); + assert!(stats.cache.is_empty()); + // Same commit IDs in another repository cannot reuse old results. + stats.cache.insert(id, None); + stats.update(&"/second".into(), &list.items, 0, 3); + assert!(stats.cache.is_empty()); + } + + #[test] + fn disabling_during_loading_drops_queued_work() { + let list = build_commit_list_with_some_commits(); + let (sender, receiver) = crossbeam_channel::unbounded(); + let dir = tempfile::tempdir().unwrap(); + let repo = dir.path().to_path_buf().into(); + let mut stats = ListStats::new(repo, sender); + let repo = stats.repo.clone(); + stats.set_enabled(true); + stats.update(&repo, &list.items, 0, 2); + stats.set_enabled(false); + assert!(stats.requested.is_empty()); + assert!(!stats.job.cancel()); // No queued list work remains. + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + stats.update(&repo, &list.items, 4, 3); + assert_eq!(stats.cache.len(), 2); // In-flight result can finish. + assert!(stats.requested.is_empty()); + stats.set_enabled(true); + stats.update(&repo, &list.items, 4, 3); + assert_eq!(stats.requested.len(), 3); + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + stats.update(&repo, &list.items, 4, 3); + assert_eq!(stats.cache.len(), 5); + } +} diff --git a/src/options.rs b/src/options.rs index a80e5cb80f..52b595f7c8 100644 --- a/src/options.rs +++ b/src/options.rs @@ -22,6 +22,8 @@ struct OptionsData { pub diff: DiffOptions, pub status_show_untracked: Option, pub commit_msgs: Vec, + #[serde(default)] + pub log_show_diff_stats: bool, } const COMMIT_MSG_HISTORY_LENGTH: usize = 20; @@ -80,6 +82,15 @@ impl Options { self.save(); } + pub const fn log_show_diff_stats(&self) -> bool { + self.data.log_show_diff_stats + } + + pub fn set_log_show_diff_stats(&mut self, show: bool) { + self.data.log_show_diff_stats = show; + self.save(); + } + pub fn diff_context_change(&mut self, increase: bool) { self.data.diff.context = if increase { self.data.diff.context.saturating_add(1) @@ -169,3 +180,37 @@ impl Options { Ok(dir) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn diff_stats_default_off_and_legacy_options() { + assert!(!Options::test_env().log_show_diff_stats()); + let old = br#"(tab: 2, diff: (context: 7, interhunk_lines: 2, ignore_whitespace: true), status_show_untracked: None, commit_msgs: ["saved message"])"#; + let data: OptionsData = from_bytes(old).unwrap(); + assert!(!data.log_show_diff_stats); + assert_eq!(data.tab, 2); + assert_eq!(data.diff.context, 7); + assert_eq!(data.commit_msgs, ["saved message"]); + } + + #[test] + fn diff_stats_persist_per_repository() { + let (first, _repo) = git2_testing::repo_init(); + let (second, _other) = git2_testing::repo_init(); + let path = || RefCell::new(first.path().to_path_buf().into()); + let options = Options::new(path()); + assert!(!options.borrow().log_show_diff_stats()); + options.borrow_mut().set_log_show_diff_stats(true); + assert!(Options::new(path()).borrow().log_show_diff_stats()); + assert!(!Options::new(RefCell::new( + second.path().to_path_buf().into() + )) + .borrow() + .log_show_diff_stats()); + options.borrow_mut().set_log_show_diff_stats(false); + assert!(!Options::new(path()).borrow().log_show_diff_stats()); + } +} diff --git a/src/popups/branchlist.rs b/src/popups/branchlist.rs index fa66ffffad..c411d78845 100644 --- a/src/popups/branchlist.rs +++ b/src/popups/branchlist.rs @@ -418,7 +418,8 @@ impl BranchListPopup { && *index == self.selection as usize }) }) - .count() > 0 + .count() + > 0 } // top commit of selected branch diff --git a/src/popups/inspect_commit.rs b/src/popups/inspect_commit.rs index 4acfe88e90..4e59335b46 100644 --- a/src/popups/inspect_commit.rs +++ b/src/popups/inspect_commit.rs @@ -253,7 +253,9 @@ impl InspectCommitPopup { ev: AsyncGitNotification, ) -> Result<()> { if self.is_visible() { - if ev == AsyncGitNotification::CommitFiles { + if ev == AsyncGitNotification::CommitStats { + self.details.update_stats(); + } else if ev == AsyncGitNotification::CommitFiles { self.update()?; } else if ev == AsyncGitNotification::Diff { self.update_diff()?; diff --git a/src/popups/options.rs b/src/popups/options.rs index b365c64817..c16de69f4b 100644 --- a/src/popups/options.rs +++ b/src/popups/options.rs @@ -24,6 +24,7 @@ use ratatui::{ #[derive(Clone, Copy, PartialEq, Eq)] pub enum AppOption { StatusShowUntracked, + LogShowDiffStats, DiffIgnoreWhitespaces, DiffContextLines, DiffInterhunkLines, @@ -76,6 +77,16 @@ impl OptionsPopup { ); Self::add_header(txt, ""); + Self::add_header(txt, "Log"); + self.add_entry( + txt, + width, + "Show diff stats", + &self.options.borrow().log_show_diff_stats().to_string(), + self.is_select(AppOption::LogShowDiffStats), + ); + Self::add_header(txt, ""); + let diff = self.options.borrow().diff_options(); Self::add_header(txt, "Diff"); self.add_entry( @@ -140,9 +151,12 @@ impl OptionsPopup { AppOption::StatusShowUntracked => { AppOption::DiffInterhunkLines } - AppOption::DiffIgnoreWhitespaces => { + AppOption::LogShowDiffStats => { AppOption::StatusShowUntracked } + AppOption::DiffIgnoreWhitespaces => { + AppOption::LogShowDiffStats + } AppOption::DiffContextLines => { AppOption::DiffIgnoreWhitespaces } @@ -153,6 +167,9 @@ impl OptionsPopup { } else { self.selection = match self.selection { AppOption::StatusShowUntracked => { + AppOption::LogShowDiffStats + } + AppOption::LogShowDiffStats => { AppOption::DiffIgnoreWhitespaces } AppOption::DiffIgnoreWhitespaces => { @@ -171,6 +188,13 @@ impl OptionsPopup { fn switch_option(&self, right: bool) { if right { match self.selection { + AppOption::LogShowDiffStats => { + let show = + !self.options.borrow().log_show_diff_stats(); + self.options + .borrow_mut() + .set_log_show_diff_stats(show); + } AppOption::StatusShowUntracked => { let untracked = self.options.borrow().status_show_untracked(); @@ -210,6 +234,13 @@ impl OptionsPopup { } } else { match self.selection { + AppOption::LogShowDiffStats => { + let show = + !self.options.borrow().log_show_diff_stats(); + self.options + .borrow_mut() + .set_log_show_diff_stats(show); + } AppOption::StatusShowUntracked => { let untracked = self.options.borrow().status_show_untracked(); @@ -257,7 +288,7 @@ impl OptionsPopup { impl DrawableComponent for OptionsPopup { fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> { if self.is_visible() { - const SIZE: (u16, u16) = (50, 10); + const SIZE: (u16, u16) = (50, 13); let area = ui::centered_rect_absolute(SIZE.0, SIZE.1, area); @@ -363,3 +394,44 @@ impl Component for OptionsPopup { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use ratatui::{backend::TestBackend, Terminal}; + + #[test] + fn log_diff_stats_option_navigation_event_and_size() { + let (dir, _repo) = git2_testing::repo_init(); + let mut env = Environment::test_env(); + env.options = crate::options::Options::new( + std::cell::RefCell::new(dir.path().to_path_buf().into()), + ); + let mut popup = OptionsPopup::new(&env); + popup.move_selection(false); + assert!(popup.is_select(AppOption::LogShowDiffStats)); + popup.switch_option(true); + assert!(env.options.borrow().log_show_diff_stats()); + assert!(matches!( + env.queue.pop(), + Some(InternalEvent::OptionSwitched( + AppOption::LogShowDiffStats + )) + )); + popup.switch_option(false); + assert!(!env.options.borrow().log_show_diff_stats()); + popup.move_selection(false); + assert!(popup.is_select(AppOption::DiffIgnoreWhitespaces)); + popup.move_selection(true); + assert!(popup.is_select(AppOption::LogShowDiffStats)); + popup.move_selection(true); + assert!(popup.is_select(AppOption::StatusShowUntracked)); + popup.show().unwrap(); + let mut terminal = + Terminal::new(TestBackend::new(60, 20)).unwrap(); + terminal.draw(|f| popup.draw(f, f.area()).unwrap()).unwrap(); + let screen = format!("{}", terminal.backend()); + assert!(screen.contains("Show diff stats")); + assert!(screen.contains("Inter hunk lines")); + } +} diff --git a/src/tabs/revlog.rs b/src/tabs/revlog.rs index 9200c93f00..42f80112d1 100644 --- a/src/tabs/revlog.rs +++ b/src/tabs/revlog.rs @@ -6,6 +6,7 @@ use crate::{ DrawableComponent, EventState, }, keys::{key_match, SharedKeyConfig}, + options::SharedOptions, popups::{FileTreeOpen, InspectCommitOpen}, queue::{InternalEvent, Queue, StackablePopupOpen}, strings::{self, order}, @@ -64,6 +65,7 @@ pub struct Revlog { repo: RepoPathRef, commit_details: CommitDetailsComponent, list: CommitList, + options: SharedOptions, git_log: AsyncLog, search: LogSearch, git_tags: AsyncTags, @@ -79,14 +81,19 @@ pub struct Revlog { impl Revlog { /// pub fn new(env: &Environment) -> Self { + let list = CommitList::new( + env, + &strings::log_title(&env.key_config), + ); + list.set_show_diff_stats( + env.options.borrow().log_show_diff_stats(), + ); Self { repo: env.repo.clone(), queue: env.queue.clone(), commit_details: CommitDetailsComponent::new(env), - list: CommitList::new( - env, - &strings::log_title(&env.key_config), - ), + list, + options: env.options.clone(), git_log: AsyncLog::new( env.repo.borrow().clone(), &env.sender_git, @@ -118,6 +125,13 @@ impl Revlog { || self.git_local_branches.is_pending() || self.git_remote_branches.is_pending() || self.commit_details.any_work_pending() + || self.list.stats_pending() + } + + pub fn update_diff_stats_option(&self) { + self.list.set_show_diff_stats( + self.options.borrow().log_show_diff_stats(), + ); } const fn is_search_pending(&self) -> bool { @@ -157,6 +171,9 @@ impl Revlog { ) -> Result<()> { if self.visible { match ev { + AsyncGitNotification::CommitStats => { + self.commit_details.update_stats(); + } AsyncGitNotification::CommitFiles | AsyncGitNotification::Log => self.update()?, AsyncGitNotification::CommitFilter => {