Skip to content

Commit 260d5a6

Browse files
refactor(diff): clean up summarize_diff_for_temporary_commit()
1 parent 1eb0f7e commit 260d5a6

File tree

1 file changed

+23
-34
lines changed

1 file changed

+23
-34
lines changed

git-branchless-lib/src/git/diff.rs

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -39,52 +39,41 @@ pub fn summarize_diff_for_temporary_commit(diff: &Diff) -> eyre::Result<String>
3939
// this returns something like `1 file changed, 1 deletion(-)`
4040
// diff.short_stats()
4141

42-
// this returns something like `test2.txt (-1)` or `2 files (+1/-2)`
42+
// this builds something like `test2.txt (-1)` or `2 files (+1/-2)`
4343
let stats = diff.inner.stats()?;
44-
let prefix = if stats.files_changed() == 1 {
45-
let mut prefix = None;
46-
// returning false terminates iteration, but that also returns Err, so
47-
// catch and ignore it
44+
let filename_or_count = if stats.files_changed() == 1 {
45+
let mut filename = None;
46+
47+
// returning false in the closure terminates iteration, but that also
48+
// returns an Err, so catch and ignore it
4849
let _ = diff.inner.foreach(
4950
&mut |delta: git2::DiffDelta, _| {
50-
if let Some(path) = delta.old_file().path() {
51-
// prefix = Some(format!("{}", path.file_name().unwrap().to_string_lossy()));
52-
prefix = Some(format!("{}", path.display()));
53-
} else if let Some(path) = delta.new_file().path() {
54-
prefix = Some(format!("{}", path.display()));
55-
}
56-
51+
let relevant_path = delta
52+
.old_file()
53+
.path()
54+
.or(delta.new_file().path())
55+
.unwrap_or_else(|| unreachable!("diff should have contained at least 1 file"));
56+
filename = Some(format!("{}", relevant_path.display()));
5757
false
5858
},
5959
None,
6060
None,
6161
None,
6262
);
63-
prefix
63+
64+
filename.unwrap_or_else(|| unreachable!("file name should have been initialized"))
6465
} else {
65-
Some(format!("{} files", stats.files_changed()))
66+
format!("{} files", stats.files_changed())
6667
};
6768

68-
let i = stats.insertions();
69-
let d = stats.deletions();
70-
Ok(format!(
71-
"{prefix} ({i}{slash}{d})",
72-
prefix = prefix.unwrap(),
73-
i = if i > 0 {
74-
format!("+{i}")
75-
} else {
76-
String::new()
77-
},
78-
slash = if i > 0 && d > 0 { "/" } else { "" },
79-
d = if d > 0 {
80-
format!("-{d}")
81-
} else {
82-
String::new()
83-
}
84-
))
85-
// stats.files_changed()
86-
// stats.insertions()
87-
// stats.deletions()
69+
let ins_del = match (stats.insertions(), stats.deletions()) {
70+
(0, 0) => unreachable!("empty diff"),
71+
(i, 0) => format!("+{i}"),
72+
(0, d) => format!("-{d}"),
73+
(i, d) => format!("+{i}/-{d}"),
74+
};
75+
76+
Ok(format!("{filename_or_count} ({ins_del})"))
8877
}
8978

9079
/// Calculate the diff between the index and the working copy.

0 commit comments

Comments
 (0)