feat: redesign commit diff view
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run

This commit is contained in:
2026-11-21 20:41:50 +07:00
parent 7691a5a7e1
commit 81a46abbe5
22 changed files with 1080 additions and 265 deletions
+1
View File
@@ -12,6 +12,7 @@ serde.workspace = true
serde_json.workspace = true
log.workspace = true
anyhow.workspace = true
jiff.workspace = true
gix = { workspace = true, features = ["revision", "blob-diff"] }
gix-worktree = "0.57"
gix-worktree-state = "0.35"
+50
View File
@@ -235,3 +235,53 @@ impl ConsumeHunk for HunkCollector<'_> {
/// Marks the end of the unified diff stream.
fn finish(self) {}
}
/// Collects hunks as unified-diff text for patch export.
pub(crate) struct PatchCollector {
text: String,
}
impl PatchCollector {
pub(crate) fn new() -> Self {
Self {
text: String::new(),
}
}
}
impl ConsumeHunk for PatchCollector {
type Out = String;
fn consume_hunk(
&mut self,
header: HunkHeader,
lines: &[(GixLineKind, &[u8])],
) -> std::io::Result<()> {
self.text.push_str(&format!(
"@@ -{},{} +{},{} @@\n",
header.before_hunk_start,
header.before_hunk_len,
header.after_hunk_start,
header.after_hunk_len,
));
for (kind, content) in lines {
let prefix = match kind {
GixLineKind::Context => ' ',
GixLineKind::Remove => '-',
GixLineKind::Add => '+',
};
// Tokens may already carry the line's newline; emit exactly one.
let content = content.strip_suffix(b"\n").unwrap_or(content);
self.text.push(prefix);
self.text.push_str(&String::from_utf8_lossy(content));
self.text.push('\n');
}
Ok(())
}
fn finish(self) -> String {
self.text
}
}
+46 -3
View File
@@ -19,16 +19,23 @@ pub struct FileCommit {
pub description: Option<String>,
pub author: String,
pub time: i64,
/// Human-readable absolute date in the commit's recorded offset, e.g.
/// "Nov 21, 2026 at 4:40 AM GMT+7"; empty when the date cannot be formatted.
pub date_label: String,
/// Full hex parent ids; empty for patch-parsed commits.
pub parents: Vec<String>,
}
impl FileCommit {
/// Creates a commit entry from its id, message parts, author, and timestamp.
/// Creates a commit entry from its id, message parts, author, timestamp, date label, and parents.
pub fn new(
id: String,
summary: String,
description: Option<String>,
author: String,
time: i64,
date_label: String,
parents: Vec<String>,
) -> Self {
Self {
id,
@@ -36,6 +43,8 @@ impl FileCommit {
description,
author,
time,
date_label,
parents,
}
}
@@ -58,9 +67,10 @@ impl FileCommit {
let author = commit.author().into_anyhow()?;
let message = commit.message().into_anyhow()?;
let time = author.time().into_anyhow()?;
Ok(FileCommit::new(
commit.id().shorten_or_id().to_string(),
commit.id().to_string(),
String::from_utf8_lossy(message.title).trim().to_string(),
if include_description {
message
@@ -71,7 +81,40 @@ impl FileCommit {
None
},
String::from_utf8_lossy(author.name).trim().to_string(),
author.time().into_anyhow()?.seconds,
time.seconds,
format_commit_date(time),
commit.parent_ids().map(|id| id.to_string()).collect(),
))
}
}
/// Formats a gix time as "Nov 21, 2026 at 4:40 AM GMT+7" in the commit's own offset.
pub(crate) fn format_commit_date(time: gix::date::Time) -> String {
let Ok(timestamp) = jiff::Timestamp::from_second(time.seconds) else {
return String::new();
};
let Ok(offset) = jiff::tz::Offset::from_seconds(time.offset) else {
return String::new();
};
let datetime = offset.to_datetime(timestamp);
let label = datetime.strftime("%b %-d, %Y at %-I:%M %p").to_string();
format!("{label} {}", gmt_label(time.offset))
}
/// The GMT offset label for a seconds offset, e.g. "GMT", "GMT+7", "GMT-5:30".
fn gmt_label(offset: i32) -> String {
if offset == 0 {
return "GMT".to_owned();
}
let sign = if offset < 0 { '-' } else { '+' };
let total_minutes = offset.abs() / 60;
let hours = total_minutes / 60;
let minutes = total_minutes % 60;
if minutes == 0 {
format!("GMT{sign}{hours}")
} else {
format!("GMT{sign}{hours}:{minutes:02}")
}
}
+8 -6
View File
@@ -3,7 +3,7 @@ use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet};
use diffy::{Hunk, Line};
use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder};
use crate::history::FileCommit;
use crate::history::{FileCommit, format_commit_date};
pub struct PatchParser;
@@ -37,6 +37,10 @@ impl PatchParser {
.into_iter()
.filter(|message| !message.id.is_empty())
.map(|message| {
let time = message
.header("Date")
.and_then(|value| gix::date::parse(value.trim(), None).ok());
FileCommit::new(
message.id.to_string(),
message
@@ -48,11 +52,9 @@ impl PatchParser {
.header("From")
.map(Self::name_from_address)
.unwrap_or_default(),
message
.header("Date")
.and_then(|value| gix::date::parse(value.trim(), None).ok())
.map(|time| time.seconds)
.unwrap_or(0),
time.map(|time| time.seconds).unwrap_or(0),
time.map(format_commit_date).unwrap_or_default(),
Vec::new(),
)
})
.collect()
+184 -1
View File
@@ -10,7 +10,7 @@ use gix::progress::Discard;
use nostr::prelude::*;
use crate::GixResultExt as _;
use crate::diff::{CommitDiff, DiffStatus, FileDiff, HunkCollector};
use crate::diff::{CommitDiff, DiffStatus, FileDiff, HunkCollector, PatchCollector};
use crate::history::{CommitList, FileCommit, MAX_LISTED_COMMITS};
use crate::nip34::{GraspSignals, Nip34Binding, Nip34Json, Nip34Kind};
use crate::sync::{RefSync, RepoSyncStatus};
@@ -481,6 +481,151 @@ impl Repo {
Self::tree_diff(self, old_tree.as_ref(), &new_tree)
}
/// Produces the unified diff patch text of a commit against its first parent.
pub fn commit_patch(&self, id: &str) -> Result<String> {
use gix::diff::blob::platform::prepare_diff::Operation;
use gix::object::tree::diff::Change;
use gix::objs::tree::EntryKind;
let commit_id = self.inner.rev_parse_single(id.as_bytes())?;
let commit = commit_id.object()?.into_commit();
let new_tree = commit.tree()?;
let old_tree = match commit.parent_ids().next() {
Some(parent) => Some(parent.object()?.into_commit().tree()?),
None => None,
};
let changes = self
.inner
.diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), None)?;
let mut cache = self.inner.diff_resource_cache_for_tree_diff()?;
let mut patch = String::new();
for change in changes {
let attached = Change::from_change_ref(change.to_ref(), &self.inner, &self.inner);
let (path, old_path, status, mode) = match attached {
Change::Addition {
location,
entry_mode,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => {
(location.to_owned(), None, DiffStatus::Added, entry_mode)
}
Change::Deletion {
location,
entry_mode,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => {
(location.to_owned(), None, DiffStatus::Deleted, entry_mode)
}
Change::Modification {
location,
previous_entry_mode,
entry_mode,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit)
&& !matches!(
previous_entry_mode.kind(),
EntryKind::Tree | EntryKind::Commit
) =>
{
(location.to_owned(), None, DiffStatus::Modified, entry_mode)
}
Change::Rewrite {
location,
source_location,
source_entry_mode,
entry_mode,
copy,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit)
&& !matches!(
source_entry_mode.kind(),
EntryKind::Tree | EntryKind::Commit
) =>
{
let status = if copy {
DiffStatus::Copied
} else {
DiffStatus::Renamed
};
(
location.to_owned(),
Some(source_location.to_owned()),
status,
entry_mode,
)
}
_ => continue,
};
let old = String::from_utf8_lossy(old_path.as_ref().unwrap_or(&path)).into_owned();
let new = String::from_utf8_lossy(&path).into_owned();
patch.push_str(&format!("diff --git a/{old} b/{new}\n"));
match status {
DiffStatus::Added => {
patch.push_str(&format!("new file mode {:o}\n", mode.value()));
}
DiffStatus::Deleted => {
patch.push_str(&format!("deleted file mode {:o}\n", mode.value()));
}
DiffStatus::Renamed => {
patch.push_str(&format!("rename from {old}\nrename to {new}\n"));
}
DiffStatus::Copied => {
patch.push_str(&format!("copy from {old}\ncopy to {new}\n"));
}
DiffStatus::Modified => {}
}
if status == DiffStatus::Added {
patch.push_str("--- /dev/null\n");
} else {
patch.push_str(&format!("--- a/{old}\n"));
}
if status == DiffStatus::Deleted {
patch.push_str("+++ /dev/null\n");
} else {
patch.push_str(&format!("+++ b/{new}\n"));
}
let platform = attached.diff(&mut cache)?;
platform
.resource_cache
.options
.skip_internal_diff_if_external_is_configured = true;
let outcome = platform.resource_cache.prepare_diff().into_anyhow()?;
match outcome.operation {
Operation::InternalDiff { algorithm } => {
let input = outcome.interned_input();
let diff = gix::diff::blob::diff_with_slider_heuristics(algorithm, &input);
let text = gix::diff::blob::UnifiedDiff::new(
&diff,
&input,
PatchCollector::new(),
Default::default(),
)
.consume()?;
patch.push_str(&text);
}
Operation::SourceOrDestinationIsBinary => {
patch.push_str(&format!("Binary files a/{old} and b/{new} differ\n"));
}
Operation::ExternalCommand { .. } => {
unreachable!("external diff drivers are disabled")
}
}
}
Ok(patch)
}
/// Diffs the trees of `base` and `tip` directly, files sorted by path.
pub fn range_diff(&self, base: &str, tip: &str) -> Result<CommitDiff> {
let base_tree = self
@@ -1810,6 +1955,44 @@ mod tests {
assert!(binding_of(&path).is_none());
}
#[test]
fn commit_patch_applies_cleanly_to_parent() {
let (dir, path) = init_repo();
git(&path, &["config", "user.name", "Test Author"]);
git(&path, &["config", "user.email", "test@example.com"]);
std::fs::write(path.join("file.txt"), "one\n").expect("write");
git(&path, &["add", "."]);
git(&path, &["commit", "-q", "-m", "first"]);
std::fs::write(path.join("file.txt"), "two\n").expect("write");
std::fs::write(path.join("file2.txt"), "added\n").expect("write");
git(&path, &["add", "."]);
git(&path, &["commit", "-q", "-m", "second"]);
let patch = Repo::open(&path)
.expect("open repo")
.commit_patch("HEAD")
.expect("commit patch");
assert!(patch.contains("diff --git a/file.txt b/file.txt"));
assert!(patch.contains("diff --git a/file2.txt b/file2.txt"));
assert!(patch.contains("--- /dev/null"));
assert!(patch.contains("+added"));
let patch_path = dir.path().join("head.patch");
std::fs::write(&patch_path, &patch).expect("write patch");
git(&path, &["checkout", "-q", "--detach", "HEAD~1"]);
git(
&path,
&["apply", patch_path.to_str().expect("utf8 patch path")],
);
let applied = std::fs::read_to_string(path.join("file.txt")).expect("read");
assert_eq!(applied, "two\n");
assert_eq!(
std::fs::read_to_string(path.join("file2.txt")).expect("read"),
"added\n"
);
}
#[test]
fn nak_exclude_and_state_refs_are_detected() {
let (_dir, path) = init_repo();