Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git: Add possibility to open specific line in a diff using the CLI (#45499)
victor80a1add64b77
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex 565f97ff230..82bec80e04d 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -202,6 +202,13 @@ fn parse_path_with_position(argument_str: &str) -> anyhow::Result<String> {.map(|path_with_pos| path_with_pos.to_string(&|path| path.to_string_lossy().into_owned()))}+/// Returns whether a `--diff` argument refers to an existing path, allowing a+/// trailing `:line:column` suffix (parsed later by the Zed side, matching how+/// regular `zed path:line:column` arguments are handled).+fn diff_path_exists(diff_path: &str) -> bool {+ Path::new(diff_path).exists() || PathWithPosition::parse_str(diff_path).path.exists()+}+fn expand_directory_diff_pairs(diff_pairs: Vec<[String; 2]>,) -> anyhow::Result<(Vec<[String; 2]>, Vec<TempDir>)> {@@ -642,7 +649,7 @@ fn run() -> Result<()> {let right = parse_path_with_position(&path[1])?;for diff_path in [&left, &right] {anyhow::ensure!(- Path::new(diff_path).exists(),+ diff_path_exists(diff_path),"--diff path does not exist: {diff_path}");}diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rsindex a5045a07f63..318495c07b3 100644--- a/crates/editor/src/editor_tests.rs+++ b/crates/editor/src/editor_tests.rs@@ -26636,6 +26636,57 @@ async fn test_diff_base_change_with_expanded_diff_hunks();}+#[gpui::test]+async fn test_go_to_singleton_buffer_point_with_expanded_deleted_hunks(+ executor: BackgroundExecutor,+ cx: &mut TestAppContext,+) {+ init_test(cx, |_| {});++ let mut cx = EditorTestContext::new(cx).await;++ let diff_base = r#"+ removed line 1+ removed line 2+ line 1+ line 2+ line 3+ "#+ .unindent();++ cx.set_state(+ &r#"+ ˇline 1+ line 2+ line 3+ "#+ .unindent(),+ );++ cx.set_head_text(&diff_base);+ executor.run_until_parked();++ cx.update_editor(|editor, window, cx| {+ editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);+ });+ executor.run_until_parked();++ cx.update_editor(|editor, window, cx| {+ editor.go_to_singleton_buffer_point(Point::new(2, 0), window, cx);+ });++ cx.assert_state_with_diff(+ r#"+ - removed line 1+ - removed line 2+ line 1+ line 2+ ˇline 3+ "#+ .unindent(),+ );+}+#[gpui::test]async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut TestAppContext) {init_test(cx, |_| {});diff --git a/crates/editor/src/navigation.rs b/crates/editor/src/navigation.rsindex 29447dd2f3e..3d4b42a3054 100644--- a/crates/editor/src/navigation.rs+++ b/crates/editor/src/navigation.rs@@ -2455,10 +2455,15 @@ impl Editor {cx: &mut Context<Self>,) {let multibuffer = self.buffer().read(cx);- if !multibuffer.is_singleton() {+ let Some(buffer) = multibuffer.as_singleton() else {+ return;+ };+ let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {+ return;+ };+ let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {return;};- let anchor_range = range.to_anchors(&multibuffer.snapshot(cx));self.change_selections(SelectionEffects::scroll(Autoscroll::for_go_to_definition(self.cursor_top_offset(cx),@@ -2467,7 +2472,7 @@ impl Editor {.nav_history(record_nav_history),window,cx,- |s| s.select_anchor_ranges([anchor_range]),+ |s| s.select_anchor_ranges([start..end]),);}diff --git a/crates/git_ui/src/file_diff_view.rs b/crates/git_ui/src/file_diff_view.rsindex 321b7f2a29b..a9c6b5878d8 100644--- a/crates/git_ui/src/file_diff_view.rs+++ b/crates/git_ui/src/file_diff_view.rs@@ -11,7 +11,7 @@ use gpui::{AnyElement, App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle,Focusable, Font, IntoElement, Render, Task, WeakEntity, Window,};-use language::{Buffer, HighlightedText};+use language::{Buffer, HighlightedText, Point};use project::{Project, ProjectPath};use settings::Settings;use std::{@@ -44,6 +44,7 @@ impl FileDiffView {pub fn open(old_path: PathBuf,new_path: PathBuf,+ target_position: Option<Point>,workspace: WeakEntity<Workspace>,window: &mut Window,cx: &mut App,@@ -78,6 +79,23 @@ impl FileDiffView {pane.add_item(Box::new(diff_view.clone()), true, true, None, window, cx);});+ if let Some(target_position) = target_position {+ let (new_buffer, rhs_editor) = {+ let diff_view = diff_view.read(cx);+ (+ diff_view.new_buffer.clone(),+ diff_view.editor.read(cx).rhs_editor().clone(),+ )+ };+ let point = new_buffer+ .read(cx)+ .snapshot()+ .point_from_external_input(target_position.row, target_position.column);+ rhs_editor.update(cx, |editor, cx| {+ editor.go_to_singleton_buffer_point(point, window, cx);+ });+ }+diff_view})})@@ -437,6 +455,7 @@ mod tests {FileDiffView::open(path!("/test/old_file.txt").into(),path!("/test/new_file.txt").into(),+ None,workspace.weak_handle(),window,cx,@@ -586,6 +605,7 @@ mod tests {FileDiffView::open(path!("/test/old_file.rs").into(),path!("/test/new_file.rs").into(),+ None,workspace.weak_handle(),window,cx,@@ -656,6 +676,7 @@ mod tests {FileDiffView::open(PathBuf::from(path!("/test/old_file.txt")),PathBuf::from(path!("/test/new_file.txt")),+ None,workspace.weak_handle(),window,cx,diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rsindex 61773c75178..6722fee9eca 100644--- a/crates/project_panel/src/project_panel.rs+++ b/crates/project_panel/src/project_panel.rs@@ -3804,8 +3804,15 @@ impl ProjectPanel {if let Some((file_path1, file_path2)) = selected_files {self.workspace.update(cx, |workspace, cx| {- FileDiffView::open(file_path1, file_path2, workspace.weak_handle(), window, cx)- .detach_and_log_err(cx);+ FileDiffView::open(+ file_path1,+ file_path2,+ None,+ workspace.weak_handle(),+ window,+ cx,+ )+ .detach_and_log_err(cx);}).ok();}diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rsindex d59e80a35d2..b5bc3652f61 100644--- a/crates/zed/src/zed/open_listener.rs+++ b/crates/zed/src/zed/open_listener.rs@@ -486,9 +486,20 @@ pub async fn open_paths_with_positions(.await?;if diff_all && !diff_paths.is_empty() {+ let mut diff_pairs = Vec::with_capacity(diff_paths.len());+ for diff_pair in diff_paths {+ let parsed = derive_paths_with_position(app_state.fs.as_ref(), diff_pair).await;+ let (Some(old_parsed), Some(new_parsed)) = (parsed.first(), parsed.get(1)) else {+ continue;+ };+ diff_pairs.push([+ old_parsed.path.to_string_lossy().into_owned(),+ new_parsed.path.to_string_lossy().into_owned(),+ ]);+ }if let Ok(diff_view) = multi_workspace.update(cx, |multi_workspace, window, cx| {multi_workspace.workspace().update(cx, |workspace, cx| {- MultiDiffView::open(diff_paths.to_vec(), workspace, window, cx)+ MultiDiffView::open(diff_pairs, workspace, window, cx)})}) {if let Some(diff_view) = diff_view.await.log_err() {@@ -499,16 +510,20 @@ pub async fn open_paths_with_positions(let workspace_weak = multi_workspace.read_with(cx, |multi_workspace, _cx| {multi_workspace.workspace().downgrade()})?;- let canonicalize = async |raw: &str| {+ let canonicalize = async |parsed: &PathWithPosition| {app_state.fs- .canonicalize(Path::new(raw))+ .canonicalize(&parsed.path).await- .with_context(|| format!("opening --diff path {raw:?}"))+ .with_context(|| format!("opening --diff path {:?}", parsed.path))};for diff_pair in diff_paths {+ let parsed = derive_paths_with_position(app_state.fs.as_ref(), diff_pair).await;+ let (Some(old_parsed), Some(new_parsed)) = (parsed.first(), parsed.get(1)) else {+ continue;+ };let (old_path, new_path) =- match futures::join!(canonicalize(&diff_pair[0]), canonicalize(&diff_pair[1])) {+ match futures::join!(canonicalize(old_parsed), canonicalize(new_parsed)) {(Ok(old), Ok(new)) => (old, new),(old, new) => {for result in [old, new] {@@ -519,8 +534,21 @@ pub async fn open_paths_with_positions(continue;}};+ let target_position = new_parsed.row.map(|row| {+ language::Point::new(+ row.saturating_sub(1),+ new_parsed.column.unwrap_or(0).saturating_sub(1),+ )+ });if let Ok(diff_view) = multi_workspace.update(cx, |_multi_workspace, window, cx| {- FileDiffView::open(old_path, new_path, workspace_weak.clone(), window, cx)+ FileDiffView::open(+ old_path,+ new_path,+ target_position,+ workspace_weak.clone(),+ window,+ cx,+ )}) {if let Some(diff_view) = diff_view.await.log_err() {items.push(Some(Ok(Box::new(diff_view))))