Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
118 changes: 118 additions & 0 deletions asyncgit/src/commit_stats.rs
Original file line number Diff line number Diff line change
@@ -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<CommitId>,
/// One result per commit. `None` means statistics were unavailable.
pub results: Vec<(CommitId, Option<CommitStats>)>,
}

impl AsyncCommitStatsJob {
/// Create a batch for use with `AsyncSingleJob`.
pub const fn new(repo: RepoPath, commits: Vec<CommitId>) -> Self {
Self {
repo,
commits,
results: Vec::new(),
}
}
}

impl AsyncJob for AsyncCommitStatsJob {
type Notification = AsyncGitNotification;
type Progress = ();

fn run(
&mut self,
_params: RunParams<Self::Notification, Self::Progress>,
) -> Result<Self::Notification> {
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)]
);
}
}
4 changes: 4 additions & 0 deletions asyncgit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ mod blame;
mod branches;
pub mod cached;
mod commit_files;
mod commit_stats;
mod diff;
mod error;
mod fetch_job;
Expand All @@ -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,
Expand Down Expand Up @@ -108,6 +110,8 @@ pub enum AsyncGitNotification {
FileLog,
///
CommitFiles,
/// A batch of commit statistics is ready.
CommitStats,
///
Tags,
///
Expand Down
230 changes: 230 additions & 0 deletions asyncgit/src/sync/commit_stats.rs
Original file line number Diff line number Diff line change
@@ -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<CommitStats> {
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::<Vec<_>>(),
)
.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 <a@b> 1 +0000\ncommitter A <a@b> 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 <a@b> 1 +0000\ncommitter A <a@b> 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"
);
}
}
}
2 changes: 2 additions & 0 deletions asyncgit/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
};
Expand Down
Loading