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
Generated
+1
View File
@@ -7159,6 +7159,7 @@ dependencies = [
"gix-worktree", "gix-worktree",
"gix-worktree-state", "gix-worktree-state",
"ignore", "ignore",
"jiff",
"log", "log",
"nostr", "nostr",
"serde", "serde",
+2
View File
@@ -25,6 +25,8 @@ nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
gix = { version = "0.88", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation", "status"] } gix = { version = "0.88", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation", "status"] }
jiff = "0.2"
smol = "2" smol = "2"
futures = "0.3" futures = "0.3"
flume = { version = "0.11.1", default-features = false, features = ["async", "select"] } flume = { version = "0.11.1", default-features = false, features = ["async", "select"] }
+3
View File
@@ -21,5 +21,8 @@ anyhow.workspace = true
futures.workspace = true futures.workspace = true
log.workspace = true log.workspace = true
[dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
[lints] [lints]
workspace = true workspace = true
@@ -1,5 +1,4 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
@@ -305,7 +304,9 @@ impl PullRequestDetailView {
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx)) cx.new(|cx| {
CommitDiffView::new(worktree.clone(), commit_id.clone(), false, window, cx)
})
}, },
window, window,
cx, cx,
+3 -2
View File
@@ -1,5 +1,4 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
@@ -232,7 +231,9 @@ impl NewPullRequestView {
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
cx.new(|cx| CommitDiffView::new(repo_path.clone(), commit_id.clone(), window, cx)) cx.new(|cx| {
CommitDiffView::new(repo_path.clone(), commit_id.clone(), false, window, cx)
})
}, },
window, window,
cx, cx,
+575 -187
View File
@@ -3,54 +3,91 @@ use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Axis, Context, Entity, IntoElement, ParentElement as _, AnyElement, App, AppContext as _, Axis, Context, Entity, EventEmitter, InteractiveElement as _,
Render, ScrollStrategy, SharedString, Styled as _, Task, UniformListScrollHandle, Window, div, IntoElement, ListAlignment, ListState, ParentElement as _, Render, SharedString,
px, uniform_list, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, Window, div,
list, px,
}; };
use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo}; use signed_git::{CommitDiff, FileCommit, FileDiff, Repo};
use ui::badge::{Badge, BadgeVariant}; use ui::avatar::Avatar;
use ui::badge::GroupedBadge;
use ui::button::{Button, ButtonVariant};
use ui::clipboard::ClipboardButton; use ui::clipboard::ClipboardButton;
use ui::common::{StyledExt as _, h_flex, v_flex}; use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole}; use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel; use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState}; use ui::layout::resizable::{Resizable, ResizableState};
use ui::separator::Separator;
use ui::switch::Switch;
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::toggle::Toggle;
use ui::tooltip::Tooltip;
use ui::tree::{Tree, TreeItem}; use ui::tree::{Tree, TreeItem};
use utils::relative_time_secs; use utils::relative_time_secs;
use super::helpers::{DiffRow, diff_rows, render_diff_row}; use super::helpers::{DiffRow, co_authors, diff_rows, render_diff_row, short_id};
use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten}; use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten};
use crate::shared::widgets::empty_state; use crate::shared::widgets::{centered_spinner, empty_state, scroll_overlay};
/// Emitted when the user activates the Download commit button.
pub enum DiffPaneEvent {
DownloadCommit,
}
impl EventEmitter<DiffPaneEvent> for DiffPane {}
/// One virtualized row of the multi-file diff list.
#[derive(Clone)]
enum PaneRow {
Header {
file_index: usize,
gap: bool,
expanded: bool,
},
Note {
message: SharedString,
last: bool,
},
Line {
file_index: usize,
row: DiffRow,
last: bool,
},
}
pub struct DiffPane { pub struct DiffPane {
diff: Option<CommitDiff>, diff: Option<CommitDiff>,
seeds: Vec<TreeItemSeed>, seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>, expanded: HashSet<String>,
rows: Vec<TreeRow>, rows: Vec<TreeRow>,
selected_file: Option<SharedString>,
selected_index: Option<usize>, selected_index: Option<usize>,
/// Rows of the selected file's diff, hunk headers and lines. tree_visible: bool,
diff_rows: Vec<DiffRow>,
scroll_handle: UniformListScrollHandle,
split: Entity<ResizableState>, split: Entity<ResizableState>,
expanded_files: HashSet<String>,
pane_rows: Vec<PaneRow>,
list: ListState,
wrap: bool,
downloadable: bool,
} }
impl DiffPane { impl DiffPane {
pub fn new(cx: &mut Context<Self>) -> Self { pub fn new(cx: &mut Context<Self>) -> Self {
let split = ResizableState::new(cx);
split.update(cx, |split, cx| split.set_sizes([px(260.)], cx));
Self { Self {
diff: None, diff: None,
seeds: Vec::new(), seeds: Vec::new(),
expanded: HashSet::new(), expanded: HashSet::new(),
rows: Vec::new(), rows: Vec::new(),
selected_file: None,
selected_index: None, selected_index: None,
diff_rows: Vec::new(), tree_visible: false,
scroll_handle: UniformListScrollHandle::new(), split,
split: { expanded_files: HashSet::new(),
let split = ResizableState::new(cx); pane_rows: Vec::new(),
split.update(cx, |split, cx| split.set_sizes([px(260.)], cx)); list: ListState::new(0, ListAlignment::Top, px(320.)),
split wrap: false,
}, downloadable: false,
} }
} }
@@ -65,26 +102,16 @@ impl DiffPane {
.map(|file| PathBuf::from(&file.path)) .map(|file| PathBuf::from(&file.path))
.collect(); .collect();
paths.sort(); paths.sort();
self.seeds = build_tree_items(&paths); self.seeds = build_tree_items(&paths);
self.expanded = collect_expanded(&self.seeds); self.expanded = collect_expanded(&self.seeds);
self.rows = flatten(&self.seeds, &self.expanded); self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = None;
let first = diff
.files
.first()
.map(|file| SharedString::from(file.path.as_str()));
self.selected_file = first.clone();
self.selected_index = first
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
self.diff = Some(diff); self.diff = Some(diff);
if let Some(path) = first { self.expanded_files.clear();
self.set_diff_rows(path.as_ref()); self.rebuild_rows();
} else { self.list = ListState::new(self.pane_rows.len(), ListAlignment::Top, px(320.));
self.diff_rows.clear();
}
cx.notify(); cx.notify();
} }
@@ -93,28 +120,129 @@ impl DiffPane {
self.seeds.clear(); self.seeds.clear();
self.expanded.clear(); self.expanded.clear();
self.rows.clear(); self.rows.clear();
self.selected_file = None;
self.selected_index = None; self.selected_index = None;
self.diff_rows.clear(); self.expanded_files.clear();
self.pane_rows.clear();
self.list = ListState::new(0, ListAlignment::Top, px(320.));
cx.notify(); cx.notify();
} }
fn select_file(&mut self, path: &str, cx: &mut Context<Self>) { pub fn set_tree_visible(&mut self, visible: bool, cx: &mut Context<Self>) {
self.selected_file = Some(path.into()); self.tree_visible = visible;
cx.notify();
}
pub fn set_downloadable(&mut self, downloadable: bool, cx: &mut Context<Self>) {
self.downloadable = downloadable;
cx.notify();
}
pub fn toggle_wrap(&mut self, cx: &mut Context<Self>) {
self.wrap = !self.wrap;
self.rebuild_rows();
cx.notify();
}
fn toggle_file(&mut self, path: &str, cx: &mut Context<Self>) {
if !self.expanded_files.remove(path) {
self.expanded_files.insert(path.to_owned());
}
self.rebuild_rows();
cx.notify();
}
fn all_expanded(&self) -> bool {
self.diff.as_ref().is_some_and(|diff| {
!diff.files.is_empty()
&& diff
.files
.iter()
.all(|file| self.expanded_files.contains(&file.path))
})
}
fn toggle_all_files(&mut self, cx: &mut Context<Self>) {
if self.all_expanded() {
self.expanded_files.clear();
} else if let Some(diff) = self.diff.as_ref() {
self.expanded_files = diff.files.iter().map(|file| file.path.clone()).collect();
}
self.rebuild_rows();
cx.notify();
}
fn select_tree_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_index = self.rows.iter().position(|row| row.id == path); self.selected_index = self.rows.iter().position(|row| row.id == path);
self.set_diff_rows(path); if self.expanded_files.insert(path.to_owned()) {
self.rebuild_rows();
}
let header_index = self.pane_rows.iter().position(|row| match row {
PaneRow::Header { file_index, .. } => self
.diff
.as_ref()
.and_then(|diff| diff.files.get(*file_index))
.is_some_and(|file| file.path == path),
_ => false,
});
if let Some(header_index) = header_index {
self.list.scroll_to_reveal_item(header_index);
}
cx.notify(); cx.notify();
} }
fn set_diff_rows(&mut self, path: &str) { fn rebuild_rows(&mut self) {
let Some(diff) = self.diff.as_ref() else { let Some(diff) = self.diff.as_ref() else {
self.pane_rows.clear();
self.list.reset(0);
return; return;
}; };
let Some(file) = diff.files.iter().find(|file| file.path == path) else {
return; let mut pane_rows = Vec::new();
}; for (file_index, file) in diff.files.iter().enumerate() {
self.diff_rows = diff_rows(file); let expanded = self.expanded_files.contains(&file.path);
self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top); pane_rows.push(PaneRow::Header {
file_index,
gap: file_index > 0,
expanded,
});
if !expanded {
continue;
}
if file.binary {
pane_rows.push(PaneRow::Note {
message: SharedString::from("Diff not available"),
last: true,
});
continue;
}
if file.hunks.is_empty() {
pane_rows.push(PaneRow::Note {
message: SharedString::from("No content changes"),
last: true,
});
continue;
}
let rows = diff_rows(file);
let last_row = rows.len().saturating_sub(1);
pane_rows.extend(
rows.into_iter()
.enumerate()
.map(|(row_index, row)| PaneRow::Line {
file_index,
row,
last: row_index == last_row,
}),
);
}
self.pane_rows = pane_rows;
self.list.reset(self.pane_rows.len());
} }
fn toggle_folder(&mut self, id: &str, cx: &mut Context<Self>) { fn toggle_folder(&mut self, id: &str, cx: &mut Context<Self>) {
@@ -123,9 +251,8 @@ impl DiffPane {
} }
self.rows = flatten(&self.seeds, &self.expanded); self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = self self.selected_index = self
.selected_file .selected_index
.as_ref() .and_then(|index| self.rows.get(index).map(|_| index));
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
cx.notify(); cx.notify();
} }
@@ -195,138 +322,298 @@ impl DiffPane {
if expandable { if expandable {
self.toggle_folder(&id, cx); self.toggle_folder(&id, cx);
} else { } else {
self.select_file(&id, cx); self.select_tree_file(&id, cx);
} }
} }
fn render_detail_column(&self, cx: &mut Context<Self>) -> AnyElement { fn render_toolbar(&self, cx: &mut Context<Self>) -> AnyElement {
let view = cx.entity().downgrade();
let (insertions, deletions) = self.diff().map_or((0, 0), |diff| {
(
diff.files.iter().map(|file| file.insertions).sum(),
diff.files.iter().map(|file| file.deletions).sum(),
)
});
let files = self.diff().map_or(0, |diff| diff.files.len());
let all_expanded = self.all_expanded();
h_flex()
.h_12()
.px_2()
.gap_2()
.flex_none()
.border_b_1()
.border_color(cx.theme().colors.border)
.child(
Toggle::new("toggle-tree")
.icon(Icon::named(IconRole::PanelLeft))
.pressed(self.tree_visible)
.accessibility_label("Toggle file tree")
.on_change({
let view = view.clone();
move |pressed, _, cx| {
if let Err(error) =
view.update(cx, |this, cx| this.set_tree_visible(pressed, cx))
{
log::warn!("failed to toggle file tree: {error}");
}
}
}),
)
.when(insertions > 0 || deletions > 0, |this| {
this.child(GroupedBadge::new(
"toolbar-diff-stats",
insertions,
deletions,
))
})
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(format!("{files} changed files")),
)
.child(div().flex_1())
.child(
Switch::new("wrap-lines")
.label("Wrap")
.checked(self.wrap)
.small()
.on_change({
let view = view.clone();
move |checked, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
if checked != this.wrap {
this.toggle_wrap(cx);
}
}) {
log::warn!("failed to toggle wrap: {error}");
}
}
}),
)
.child(
Button::new("expand-all")
.label(if all_expanded { "Collapse" } else { "Expand" })
.icon(Icon::named(IconRole::UnfoldVertical))
.variant(ButtonVariant::Ghost)
.small()
.on_click({
let view = view;
move |_, _, cx| {
if let Err(error) =
view.update(cx, |this, cx| this.toggle_all_files(cx))
{
log::warn!("failed to toggle all diff files: {error}");
}
}
}),
)
.when(self.downloadable, |this| {
this.child(
Button::new("download")
.label("Download")
.icon(Icon::named(IconRole::Download))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Download commit"))
.small()
.on_click(cx.listener(|_, _, _, cx| {
cx.emit(DiffPaneEvent::DownloadCommit);
})),
)
})
.into_any_element()
}
fn render_file_list(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(diff) = self.diff.as_ref() else { let Some(diff) = self.diff.as_ref() else {
return empty_state("No changes"); return empty_state("No changes");
}; };
let Some(path) = self.selected_file.clone() else {
return if diff.files.is_empty() {
empty_state("No files changed")
} else {
empty_state("Select a file")
};
};
let Some(file) = diff.files.iter().find(|file| file.path == path.as_ref()) else {
return empty_state("File not found");
};
self.render_file_diff(file, cx)
}
fn render_file_diff(&self, file: &FileDiff, cx: &App) -> AnyElement { let files = diff.files.clone();
let status_label = match file.status { let pane_rows = self.pane_rows.clone();
DiffStatus::Added => "A", let wrap = self.wrap;
DiffStatus::Modified => "M", let view = cx.entity().downgrade();
DiffStatus::Deleted => "D",
DiffStatus::Renamed => "R",
DiffStatus::Copied => "C",
};
let status_color = match file.status {
DiffStatus::Added => cx.theme().ramps.success.base,
DiffStatus::Modified => cx.theme().ramps.info.base,
DiffStatus::Deleted => cx.theme().ramps.destructive.base,
DiffStatus::Renamed | DiffStatus::Copied => cx.theme().colors.muted_foreground,
};
let title = match &file.old_path {
Some(old) => format!("{old} → {}", file.path),
None => file.path.clone(),
};
let body: AnyElement = if file.binary { div()
empty_state("Diff not available")
} else if file.hunks.is_empty() {
empty_state("No content changes")
} else {
let hunks = file.hunks.clone();
let rows = self.diff_rows.clone();
v_flex()
.size_full()
.relative() .relative()
.flex_1()
.min_h_0()
.h_full()
.debug_selector(|| "commit-diff-files-list".to_owned())
.child( .child(
uniform_list("commit-diff-rows", rows.len(), move |range, _, cx| { list(self.list.clone(), move |ix, _, cx| {
range match pane_rows.get(ix) {
.map(|ix| render_diff_row(&hunks, rows[ix], cx)) Some(row) => render_pane_row(row, &files, &view, wrap, cx),
.collect() None => div().into_any_element(),
}
}) })
.track_scroll(&self.scroll_handle) .size_full()
.size_full(), .p_2(),
) )
.child(crate::shared::widgets::scroll_overlay( .child(scroll_overlay("commit-diff-files", self.list.clone()))
"commit-diff-scroll",
self.scroll_handle.clone(),
))
.into_any_element() .into_any_element()
}
}
fn render_pane_row(
row: &PaneRow,
files: &[FileDiff],
pane: &WeakEntity<DiffPane>,
wrap: bool,
cx: &App,
) -> AnyElement {
let border = cx.theme().colors.border;
let surface = cx.theme().colors.surface;
match row {
PaneRow::Header {
file_index,
gap,
expanded,
} => {
let Some(file) = files.get(*file_index) else {
return div().into_any_element();
};
let path = file.path.clone();
let title = match &file.old_path {
Some(old) => SharedString::from(format!("{old} → {}", file.path)),
None => SharedString::from(file.path.clone()),
}; };
v_flex() div()
.flex_1() .w_full()
.min_w_0() .when(*gap, |this| this.pt_2())
.h_full()
.child( .child(
h_flex() h_flex()
.px_3() .id(("file-header", *file_index))
.h_9() .debug_selector(move || format!("commit-diff-file-card-{file_index}"))
.h_10()
.px_2()
.gap_2() .gap_2()
.bg(surface)
.border_1()
.border_color(border)
.cursor_pointer()
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.when(*expanded, |this| this.rounded_t_lg().border_b_0())
.when(!*expanded, |this| this.rounded_lg())
.child( .child(
div() Icon::named(if *expanded {
.text_xs() IconRole::ChevronDown
.font_medium() } else {
.text_color(status_color) IconRole::ChevronRight
.child(status_label), })
.color(cx.theme().colors.muted_foreground),
) )
.child(div().min_w_0().truncate().text_sm().child(title))
.when(file.insertions > 0 || file.deletions > 0, |this| {
this.child(GroupedBadge::new(
("file-diff-stats", *file_index),
file.insertions,
file.deletions,
))
})
.child(div().flex_1())
.child( .child(
div() Button::new(("view-file", *file_index))
.flex_1() .label("View file")
.min_w_0() .icon(Icon::named(IconRole::Eye))
.text_xs() .variant(ButtonVariant::Ghost)
.font_medium() .small()
.text_ellipsis() .on_click(|_, _, cx| cx.stop_propagation()),
.whitespace_nowrap()
.child(title),
)
.when(!file.binary, |this| {
this.child(
h_flex()
.gap_2()
.text_xs()
.child(
Badge::new("file-insertions", format!("+ {}", file.insertions))
.variant(BadgeVariant::Success),
)
.child(
Badge::new("file-deletions", format!("- {}", file.deletions))
.variant(BadgeVariant::Danger),
),
) )
.on_click({
let pane = pane.clone();
move |_, _, cx| {
if let Err(error) =
pane.update(cx, |this, cx| this.toggle_file(&path, cx))
{
log::warn!("failed to toggle diff file: {error}");
}
}
}), }),
) )
.child(div().flex_1().min_h_0().child(body))
.into_any_element() .into_any_element()
} }
PaneRow::Note { message, last, .. } => div()
.w_full()
.border_x_1()
.border_color(border)
.bg(surface)
.px_3()
.py_2()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.when(*last, |this| this.border_b_1().rounded_b_lg())
.child(message.clone())
.into_any_element(),
PaneRow::Line {
file_index,
row,
last,
} => {
let Some(file) = files.get(*file_index) else {
return div().into_any_element();
};
div()
.w_full()
.border_x_1()
.border_color(border)
.bg(surface)
.when(*last, |this| this.border_b_1().rounded_b_lg())
.child(render_diff_row(&file.hunks, *row, wrap, cx))
.into_any_element()
}
}
} }
impl Render for DiffPane { impl Render for DiffPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let tree = self.render_tree_column(cx); if self.diff.is_none() {
let detail = self.render_detail_column(cx); return empty_state("No changes");
}
let diff = self.diff.as_ref().expect("diff checked above");
if diff.files.is_empty() {
return empty_state("No files changed");
}
let toolbar = self.render_toolbar(cx);
let file_list = self.render_file_list(cx);
let content = if self.tree_visible {
let tree = self.render_tree_column(cx);
h_flex() h_flex()
.size_full() .flex_1()
.min_h_0() .min_h_0()
.bg(cx.theme().colors.background)
.child( .child(
Resizable::new("commit-diff-split", self.split.clone()) Resizable::new("commit-diff-split", self.split.clone())
.axis(Axis::Horizontal) .axis(Axis::Horizontal)
.pane_with_min(tree, px(120.)) .pane_with_min(tree, px(120.))
.pane_with_min(detail, px(240.)) .pane_with_min(file_list, px(240.))
.flex_1() .flex_1()
.min_w_0() .min_w_0()
.h_full(), .h_full(),
) )
.into_any_element()
} else {
div()
.flex_1()
.min_w_0()
.h_full()
.child(file_list)
.into_any_element()
};
v_flex()
.size_full()
.min_h_0()
.bg(cx.theme().colors.background)
.child(toolbar)
.child(content)
.into_any_element()
} }
} }
@@ -338,16 +625,25 @@ pub struct CommitDiffView {
error: Option<SharedString>, error: Option<SharedString>,
pane: Entity<DiffPane>, pane: Entity<DiffPane>,
tasks: Vec<Task<Result<(), anyhow::Error>>>, tasks: Vec<Task<Result<(), anyhow::Error>>>,
_download_subscription: Subscription,
} }
impl CommitDiffView { impl CommitDiffView {
pub fn new( pub fn new(
worktree: PathBuf, worktree: PathBuf,
commit_id: String, commit_id: String,
downloadable: bool,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Self { ) -> Self {
let pane = cx.new(DiffPane::new); let pane = cx.new(|cx| {
let mut pane = DiffPane::new(cx);
pane.set_downloadable(downloadable, cx);
pane
});
let subscription = cx.subscribe(&pane, |this, _, DiffPaneEvent::DownloadCommit, cx| {
this.download_patch(cx);
});
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
window.defer(cx, move |window, cx| { window.defer(cx, move |window, cx| {
@@ -364,11 +660,14 @@ impl CommitDiffView {
description: None, description: None,
author: String::new(), author: String::new(),
time: 0, time: 0,
date_label: String::new(),
parents: Vec::new(),
}, },
loading: true, loading: true,
error: None, error: None,
pane, pane,
tasks: Vec::new(), tasks: Vec::new(),
_download_subscription: subscription,
} }
} }
@@ -424,15 +723,59 @@ impl CommitDiffView {
self.push_task(task); self.push_task(task);
} }
fn download_patch(&mut self, cx: &mut Context<Self>) {
let worktree = self.worktree.clone();
let id = self.commit.id.clone();
let suggested_name = format!("{}.patch", short_id(&id));
let prompt = cx.prompt_for_new_path(&worktree, Some(suggested_name.as_str()));
let task: Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let destination = match prompt.await {
Ok(Ok(Some(path))) => path,
Ok(Ok(None)) => return Ok(()),
Ok(Err(error)) => {
log::warn!("failed to open the commit patch save dialog: {error}");
return Ok(());
}
Err(_) => return Ok(()),
};
let patch = cx
.background_spawn(async move {
Repo::open(&worktree).and_then(|repo| repo.commit_patch(&id))
})
.await;
match patch {
Ok(patch) => {
if let Err(error) = std::fs::write(&destination, patch) {
log::warn!("failed to write commit patch: {error}");
}
}
Err(error) => log::warn!("failed to build commit patch: {error}"),
}
this.update(cx, |_, cx| cx.notify())?;
Ok(())
});
self.push_task(task);
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement { fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let commit = &self.commit; let commit = &self.commit;
let (files, insertions, deletions) = self.pane.read(cx).diff().map_or((0, 0, 0), |diff| { let muted = cx.theme().colors.muted_foreground;
(
diff.files.len(), let row = |label: &'static str, value: AnyElement| -> AnyElement {
diff.files.iter().map(|file| file.insertions).sum(), h_flex()
diff.files.iter().map(|file| file.deletions).sum(), .h_6()
) .gap_2()
}); .text_xs()
.child(div().w_20().flex_none().text_color(muted).child(label))
.child(div().flex_1().min_w_0().child(value))
.into_any_element()
};
v_flex() v_flex()
.flex_none() .flex_none()
@@ -442,56 +785,101 @@ impl CommitDiffView {
.gap_2() .gap_2()
.border_b_1() .border_b_1()
.border_color(cx.theme().colors.border) .border_color(cx.theme().colors.border)
.child(
v_flex()
.child( .child(
div() div()
.text_sm() .min_w_0()
.font_semibold() .font_semibold()
.truncate()
.text_ellipsis() .text_ellipsis()
.whitespace_nowrap() .child(SharedString::from(commit.summary.clone())),
.child(commit.summary.clone()),
)
.child(
h_flex()
.gap_2()
.text_base()
.child(SharedString::from(format!("{} committed", commit.author)))
.child(
h_flex()
.gap_1()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(&commit.id))
.child(ClipboardButton::new("commit-id", &commit.id)),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
),
),
) )
.when_some(commit.description.as_ref(), |this, description| { .when_some(commit.description.as_ref(), |this, description| {
this.child(div().text_base().child(SharedString::from(description))) this.child(
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(description)),
)
}) })
.child( .child(Separator::horizontal())
.child(row(
"Author",
h_flex() h_flex()
.gap_2() .gap_2()
.text_xs() .child(
.child(Badge::new("commit-files", format!("{files} files changed"))) Avatar::new(commit.author.clone())
.when(insertions > 0, |this| { .name(commit.author.clone())
this.child( .small(),
Badge::new("commit-insertions", format!("+ {insertions}")) )
.variant(BadgeVariant::Success), .child(
div()
.truncate()
.child(SharedString::from(commit.author.clone())),
)
.into_any_element(),
))
.children(
commit
.description
.as_ref()
.map_or_else(Vec::new, |description| {
co_authors(description)
.into_iter()
.map(|name| {
row(
"Co-author",
h_flex()
.gap_2()
.child(Avatar::new(name.clone()).name(name.clone()).small())
.child(div().truncate().text_ellipsis().child(name))
.into_any_element(),
) )
}) })
.when(deletions > 0, |this| { .collect::<Vec<_>>()
this.child(
Badge::new("commit-deletions", format!("- {deletions}"))
.variant(BadgeVariant::Danger),
)
}), }),
) )
.child(row(
"Date",
h_flex()
.gap_2()
.child(relative_time_secs(commit.time))
.when(!commit.date_label.is_empty(), |this| {
this.child(
div()
.text_color(muted)
.child(SharedString::from(format!("({})", commit.date_label))),
)
})
.into_any_element(),
))
.child(row(
"Commit",
h_flex()
.gap_2()
.child(
div()
.text_ellipsis()
.truncate()
.child(SharedString::from(commit.id.clone())),
)
.child(ClipboardButton::new("commit-id", &commit.id).xsmall())
.into_any_element(),
))
.children(commit.parents.iter().enumerate().map(|(ix, parent)| {
row(
"Parent",
h_flex()
.gap_2()
.child(
div()
.text_ellipsis()
.truncate()
.child(SharedString::from(parent.clone())),
)
.child(ClipboardButton::new(("commit-parent", ix), parent).xsmall())
.into_any_element(),
)
}))
.into_any_element() .into_any_element()
} }
} }
@@ -509,8 +897,8 @@ impl Panel for CommitDiffView {
impl Render for CommitDiffView { impl Render for CommitDiffView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let body: AnyElement = if self.loading { let body = if self.loading {
crate::shared::widgets::centered_spinner("commit-diff-loading") centered_spinner("commit-diff-loading")
} else if let Some(error) = self.error.clone() { } else if let Some(error) = self.error.clone() {
empty_state(error) empty_state(error)
} else { } else {
+2 -1
View File
@@ -16,6 +16,7 @@ use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem}; use ui::tree::{Tree, TreeItem};
use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash};
use crate::repo::helpers::short_id;
use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten}; use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten};
use crate::shared::widgets::empty_state; use crate::shared::widgets::empty_state;
@@ -367,7 +368,7 @@ impl RepoFilesView {
div() div()
.text_xs() .text_xs()
.font_family(cx.theme().mono_font) .font_family(cx.theme().mono_font)
.child(commit.id.clone()), .child(short_id(&commit.id)),
) )
.child( .child(
div() div()
+37 -7
View File
@@ -39,6 +39,29 @@ pub fn short_id(hex: &str) -> SharedString {
SharedString::from(hex.get(..8).unwrap_or(hex).to_owned()) SharedString::from(hex.get(..8).unwrap_or(hex).to_owned())
} }
/// The co-author names credited in a commit body, deduplicated in order.
pub(super) fn co_authors(description: &str) -> Vec<SharedString> {
let mut names: Vec<SharedString> = Vec::new();
for line in description.lines() {
let trimmed = line.trim();
if !trimmed.to_lowercase().starts_with("co-authored-by:") {
continue;
}
let name = trimmed
.split_once(':')
.map(|(_, value)| value.trim())
.unwrap_or_default()
.split('<')
.next()
.unwrap_or_default()
.trim();
if !name.is_empty() && !names.iter().any(|existing| existing.as_ref() == name) {
names.push(SharedString::from(name.to_owned()));
}
}
names
}
/// Snapshots the worktree and derives the explorer's tree rows and paths. /// Snapshots the worktree and derives the explorer's tree rows and paths.
pub(super) fn snapshot_worktree( pub(super) fn snapshot_worktree(
worktree: PathBuf, worktree: PathBuf,
@@ -295,7 +318,12 @@ pub(super) fn diff_rows(file: &FileDiff) -> Vec<DiffRow> {
rows rows
} }
pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> AnyElement { pub(super) fn render_diff_row(
hunks: &[DiffHunk],
row: DiffRow,
wrap: bool,
cx: &App,
) -> AnyElement {
match row { match row {
DiffRow::Hunk { DiffRow::Hunk {
old_start, old_start,
@@ -318,14 +346,14 @@ pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> Any
))) )))
.into_any_element(), .into_any_element(),
DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) { DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, cx), Some(line) => render_diff_line(line, wrap, cx),
// A stale row index renders as a blank row rather than panicking. // A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(), None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
}, },
} }
} }
fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement { fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement {
let bg = match line.kind { let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)), DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)),
DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)), DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)),
@@ -335,7 +363,8 @@ fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
h_flex() h_flex()
.w_full() .w_full()
.h(px(DIFF_ROW_HEIGHT)) .when(wrap, |row| row.min_h(px(DIFF_ROW_HEIGHT)))
.when(!wrap, |row| row.h(px(DIFF_ROW_HEIGHT)))
.font_family(cx.theme().mono_font) .font_family(cx.theme().mono_font)
.text_xs() .text_xs()
.when_some(bg, |this, bg| this.bg(bg)) .when_some(bg, |this, bg| this.bg(bg))
@@ -361,9 +390,10 @@ fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
div() div()
.flex_1() .flex_1()
.min_w_0() .min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_color(cx.theme().colors.foreground) .text_color(cx.theme().colors.foreground)
.when(!wrap, |content| {
content.overflow_hidden().whitespace_nowrap()
})
.child(line.text.clone()), .child(line.text.clone()),
) )
.into_any_element() .into_any_element()
@@ -400,7 +430,7 @@ pub(crate) fn commit_row(
.font_family(cx.theme().mono_font) .font_family(cx.theme().mono_font)
.text_sm() .text_sm()
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.child(commit.id.clone()), .child(short_id(&commit.id)),
) )
.child( .child(
div() div()
+4 -2
View File
@@ -145,7 +145,9 @@ impl RepoHistoryView {
&workspace, &workspace,
id, id,
move |window, cx| { move |window, cx| {
cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx)) cx.new(|cx| {
CommitDiffView::new(worktree.clone(), commit_id.clone(), true, window, cx)
})
}, },
window, window,
cx, cx,
@@ -227,7 +229,7 @@ impl Render for RepoHistoryView {
let detail = detail.clone(); let detail = detail.clone();
let path = path.clone(); let path = path.clone();
let target = ahead_id.clone(); let target = ahead_id.clone();
let short = commit.id.clone(); let short = super::helpers::short_id(&commit.id);
Button::new(("sync-commit", ix)) Button::new(("sync-commit", ix))
.label("Sync") .label("Sync")
+9 -8
View File
@@ -1,6 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
}; };
@@ -205,8 +206,13 @@ impl Render for Workspace {
.collect(); .collect();
let weak = cx.entity().downgrade(); let weak = cx.entity().downgrade();
let close_weak = weak.clone(); let body = self.active_detail().map(|view| view.view());
v_flex()
.size_full()
.gap_2()
.when(self.details.len() > 1, |this| {
let close_weak = weak.clone();
let tabs = Tabs::new("signed-detail-tabs") let tabs = Tabs::new("signed-detail-tabs")
.variant(TabsVariant::Pill) .variant(TabsVariant::Pill)
.overflow_scroll(true) .overflow_scroll(true)
@@ -230,13 +236,8 @@ impl Render for Workspace {
workspace.close_detail_at(index, cx); workspace.close_detail_at(index, cx);
})); }));
}); });
this.child(tabs)
let body = self.active_detail().map(|view| view.view()); })
v_flex()
.size_full()
.gap_2()
.child(tabs)
.child(div().flex_1().min_h_0().w_full().children(body)) .child(div().flex_1().min_h_0().w_full().children(body))
} }
} }
+1
View File
@@ -12,6 +12,7 @@ serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
log.workspace = true log.workspace = true
anyhow.workspace = true anyhow.workspace = true
jiff.workspace = true
gix = { workspace = true, features = ["revision", "blob-diff"] } gix = { workspace = true, features = ["revision", "blob-diff"] }
gix-worktree = "0.57" gix-worktree = "0.57"
gix-worktree-state = "0.35" gix-worktree-state = "0.35"
+50
View File
@@ -235,3 +235,53 @@ impl ConsumeHunk for HunkCollector<'_> {
/// Marks the end of the unified diff stream. /// Marks the end of the unified diff stream.
fn finish(self) {} 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 description: Option<String>,
pub author: String, pub author: String,
pub time: i64, 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 { 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( pub fn new(
id: String, id: String,
summary: String, summary: String,
description: Option<String>, description: Option<String>,
author: String, author: String,
time: i64, time: i64,
date_label: String,
parents: Vec<String>,
) -> Self { ) -> Self {
Self { Self {
id, id,
@@ -36,6 +43,8 @@ impl FileCommit {
description, description,
author, author,
time, time,
date_label,
parents,
} }
} }
@@ -58,9 +67,10 @@ impl FileCommit {
let author = commit.author().into_anyhow()?; let author = commit.author().into_anyhow()?;
let message = commit.message().into_anyhow()?; let message = commit.message().into_anyhow()?;
let time = author.time().into_anyhow()?;
Ok(FileCommit::new( Ok(FileCommit::new(
commit.id().shorten_or_id().to_string(), commit.id().to_string(),
String::from_utf8_lossy(message.title).trim().to_string(), String::from_utf8_lossy(message.title).trim().to_string(),
if include_description { if include_description {
message message
@@ -71,7 +81,40 @@ impl FileCommit {
None None
}, },
String::from_utf8_lossy(author.name).trim().to_string(), 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 diffy::{Hunk, Line};
use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder}; use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder};
use crate::history::FileCommit; use crate::history::{FileCommit, format_commit_date};
pub struct PatchParser; pub struct PatchParser;
@@ -37,6 +37,10 @@ impl PatchParser {
.into_iter() .into_iter()
.filter(|message| !message.id.is_empty()) .filter(|message| !message.id.is_empty())
.map(|message| { .map(|message| {
let time = message
.header("Date")
.and_then(|value| gix::date::parse(value.trim(), None).ok());
FileCommit::new( FileCommit::new(
message.id.to_string(), message.id.to_string(),
message message
@@ -48,11 +52,9 @@ impl PatchParser {
.header("From") .header("From")
.map(Self::name_from_address) .map(Self::name_from_address)
.unwrap_or_default(), .unwrap_or_default(),
message time.map(|time| time.seconds).unwrap_or(0),
.header("Date") time.map(format_commit_date).unwrap_or_default(),
.and_then(|value| gix::date::parse(value.trim(), None).ok()) Vec::new(),
.map(|time| time.seconds)
.unwrap_or(0),
) )
}) })
.collect() .collect()
+184 -1
View File
@@ -10,7 +10,7 @@ use gix::progress::Discard;
use nostr::prelude::*; use nostr::prelude::*;
use crate::GixResultExt as _; 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::history::{CommitList, FileCommit, MAX_LISTED_COMMITS};
use crate::nip34::{GraspSignals, Nip34Binding, Nip34Json, Nip34Kind}; use crate::nip34::{GraspSignals, Nip34Binding, Nip34Json, Nip34Kind};
use crate::sync::{RefSync, RepoSyncStatus}; use crate::sync::{RefSync, RepoSyncStatus};
@@ -481,6 +481,151 @@ impl Repo {
Self::tree_diff(self, old_tree.as_ref(), &new_tree) 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. /// Diffs the trees of `base` and `tip` directly, files sorted by path.
pub fn range_diff(&self, base: &str, tip: &str) -> Result<CommitDiff> { pub fn range_diff(&self, base: &str, tip: &str) -> Result<CommitDiff> {
let base_tree = self let base_tree = self
@@ -1810,6 +1955,44 @@ mod tests {
assert!(binding_of(&path).is_none()); 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] #[test]
fn nak_exclude_and_state_refs_are_detected() { fn nak_exclude_and_state_refs_are_detected() {
let (_dir, path) = init_repo(); let (_dir, path) = init_repo();
+92
View File
@@ -181,3 +181,95 @@ impl RenderOnce for Badge {
}) })
} }
} }
/// A pill pairing a green additions segment with a red deletions segment.
#[derive(IntoElement)]
#[must_use]
pub struct GroupedBadge {
id: ElementId,
insertions: usize,
deletions: usize,
style: StyleRefinement,
}
impl GroupedBadge {
/// Creates a grouped badge from insertion and deletion counts.
pub fn new<I>(id: I, insertions: usize, deletions: usize) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
insertions,
deletions,
style: StyleRefinement::default(),
}
}
}
impl gpui::Styled for GroupedBadge {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl RenderOnce for GroupedBadge {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let additions = (
theme.ramps.success.base.opacity(0.2),
theme.ramps.success.base,
);
let deletions = (
theme.ramps.destructive.base.opacity(0.2),
theme.ramps.destructive.base,
);
h_flex()
.id(self.id.clone())
.debug_selector({
let id = self.id.clone();
move || format!("{id}")
})
.flex_none()
.text_xs()
.font_medium()
.when(self.insertions > 0, |group| {
group.child(
h_flex()
.justify_center()
.h_5()
.px_1p5()
.bg(additions.0)
.text_color(additions.1)
.debug_selector({
let id = self.id.clone();
move || format!("{id}-additions")
})
.when(self.deletions == 0, |segment| segment.rounded_full())
.when(self.deletions > 0, |segment| segment.rounded_l_full())
.child(SharedString::from(format!("+{}", self.insertions))),
)
})
.when(self.deletions > 0, |group| {
group.child(
h_flex()
.justify_center()
.h_5()
.px_1p5()
.bg(deletions.0)
.text_color(deletions.1)
.debug_selector({
let id = self.id.clone();
move || format!("{id}-deletions")
})
.when(self.insertions == 0, |segment| segment.rounded_full())
.when(self.insertions > 0, |segment| segment.rounded_r_full())
.child(SharedString::from(format!("-{}", self.deletions))),
)
})
.refine_style(&self.style)
}
}
+2 -1
View File
@@ -326,6 +326,8 @@ impl RenderOnce for Button {
h_flex() h_flex()
.id(self.id.clone()) .id(self.id.clone())
.refine_style(&self.style)
.flex_shrink_0()
.when_some(self.debug_selector, |button, selector| { .when_some(self.debug_selector, |button, selector| {
button.debug_selector(move || selector()) button.debug_selector(move || selector())
}) })
@@ -351,7 +353,6 @@ impl RenderOnce for Button {
.border_color(border) .border_color(border)
.when_some(background, |button, background| button.bg(background)) .when_some(background, |button, background| button.bg(background))
.text_color(foreground) .text_color(foreground)
.refine_style(&self.style)
.when_some(a11y_label, |button, label| button.aria_label(label)) .when_some(a11y_label, |button, label| button.aria_label(label))
.child( .child(
h_flex() h_flex()
+6 -2
View File
@@ -133,7 +133,7 @@ impl RenderOnce for Switch {
h_flex() h_flex()
.id(self.id) .id(self.id)
.gap_2() .gap_1()
.control_text(self.size) .control_text(self.size)
.refine_style(&self.style) .refine_style(&self.style)
.role(Role::Switch) .role(Role::Switch)
@@ -179,7 +179,11 @@ impl RenderOnce for Switch {
.left(inset) .left(inset)
.switch_knob(self.size) .switch_knob(self.size)
.rounded(theme.radius.full) .rounded(theme.radius.full)
.bg(colors.primary_foreground) .bg(if self.checked {
colors.primary_foreground
} else {
colors.muted_foreground
})
.with_spring("switch-thumb", anim, move |thumb, offset| { .with_spring("switch-thumb", anim, move |thumb, offset| {
thumb.left(inset + offset) thumb.left(inset + offset)
}), }),
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"> <path d="M12 13.5L11.4697 14.0303C11.7626 14.3232 12.2374 14.3232 12.5303 14.0303L12 13.5ZM8.75 15.5C8.33579 15.5 8 15.8358 8 16.25C8 16.6642 8.33579 17 8.75 17V15.5ZM15.25 17C15.6642 17 16 16.6642 16 16.25C16 15.8358 15.6642 15.5 15.25 15.5V17ZM11.25 7.75V13.5H12.75V7.75H11.25ZM12.5303 14.0303L14.7803 11.7803L13.7197 10.7197L11.4697 12.9697L12.5303 14.0303ZM12.5303 12.9697L10.2803 10.7197L9.21967 11.7803L11.4697 14.0303L12.5303 12.9697ZM8.75 17H15.25V15.5H8.75V17ZM6.75 4.5H17.25V3H6.75V4.5ZM19.5 6.75V17.25H21V6.75H19.5ZM17.25 19.5H6.75V21H17.25V19.5ZM4.5 17.25V6.75H3V17.25H4.5ZM6.75 19.5C5.50736 19.5 4.5 18.4926 4.5 17.25H3C3 19.3211 4.67893 21 6.75 21V19.5ZM19.5 17.25C19.5 18.4926 18.4926 19.5 17.25 19.5V21C19.3211 21 21 19.3211 21 17.25H19.5ZM17.25 4.5C18.4926 4.5 19.5 5.50736 19.5 6.75H21C21 4.67893 19.3211 3 17.25 3V4.5ZM6.75 3C4.67893 3 3 4.67893 3 6.75H4.5C4.5 5.50736 5.50736 4.5 6.75 4.5V3Z" fill="black"/> </svg>

After

Width:  |  Height:  |  Size: 1008 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"> <path d="M15.25 9.75L13 12L15.25 14.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.75 6.75C3.75 5.09315 5.09315 3.75 6.75 3.75H17.25C18.9069 3.75 20.25 5.09315 20.25 6.75V17.25C20.25 18.9069 18.9069 20.25 17.25 20.25H6.75C5.09315 20.25 3.75 18.9069 3.75 17.25V6.75Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M8.25 3.75V20.25" stroke="black" stroke-width="1.5"/> </svg>

After

Width:  |  Height:  |  Size: 543 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"> <path d="M8 18.75L12 14.75L16 18.75" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 5.25L12 9.25L8 5.25" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>

After

Width:  |  Height:  |  Size: 316 B

+6
View File
@@ -59,6 +59,9 @@ pub enum IconRole {
ArrowUp, ArrowUp,
Inbox, Inbox,
Stack, Stack,
PanelLeft,
UnfoldVertical,
Download,
} }
impl IconRole { impl IconRole {
@@ -106,6 +109,9 @@ impl IconRole {
Self::ArrowUp => "arrow-up", Self::ArrowUp => "arrow-up",
Self::Inbox => "inbox", Self::Inbox => "inbox",
Self::Stack => "stack", Self::Stack => "stack",
Self::PanelLeft => "panel-left",
Self::UnfoldVertical => "unfold-vertical",
Self::Download => "download",
} }
} }