Detailed changes
@@ -2855,6 +2855,7 @@ dependencies = [
"env_logger",
"futures",
"fuzzy",
+ "git2",
"gpui",
"lazy_static",
"log",
@@ -4013,7 +4014,6 @@ dependencies = [
"fsevent",
"futures",
"fuzzy",
- "git2",
"gpui",
"ignore",
"language",
@@ -34,6 +34,7 @@ use gpui::{
WeakViewHandle,
};
use json::json;
+use language::git::{DiffHunk, DiffHunkStatus};
use language::{Bias, DiagnosticSeverity, OffsetUtf16, Selection};
use project::ProjectPath;
use settings::Settings;
@@ -543,6 +544,33 @@ impl EditorElement {
}
}
+ println!("painting from hunks: {:#?}\n", &layout.diff_hunks);
+ for hunk in &layout.diff_hunks {
+ let color = match hunk.status() {
+ DiffHunkStatus::Added => Color::green(),
+ DiffHunkStatus::Modified => Color::blue(),
+ _ => continue,
+ };
+
+ let start_row = hunk.buffer_range.start;
+ let end_row = hunk.buffer_range.end;
+
+ let start_y = start_row as f32 * layout.line_height - (scroll_top % layout.line_height);
+ let end_y = end_row as f32 * layout.line_height - (scroll_top % layout.line_height)
+ + layout.line_height;
+
+ let highlight_origin = bounds.origin() + vec2f(0., start_y);
+ let highlight_size = vec2f(6., end_y - start_y);
+ let highlight_bounds = RectF::new(highlight_origin, highlight_size);
+
+ cx.scene.push_quad(Quad {
+ bounds: highlight_bounds,
+ background: Some(color),
+ border: Border::new(0., Color::transparent_black()),
+ corner_radius: 0.,
+ });
+ }
+
if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
let mut x = bounds.width() - layout.gutter_padding;
let mut y = *row as f32 * layout.position_map.line_height - scroll_top;
@@ -1425,6 +1453,11 @@ impl Element for EditorElement {
let line_number_layouts =
self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
+ let diff_hunks = snapshot
+ .buffer_snapshot
+ .diff_hunks_in_range(start_row..end_row)
+ .collect();
+
let mut max_visible_line_width = 0.0;
let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
for line in &line_layouts {
@@ -1573,6 +1606,7 @@ impl Element for EditorElement {
highlighted_rows,
highlighted_ranges,
line_number_layouts,
+ diff_hunks,
blocks,
selections,
context_menu,
@@ -1710,6 +1744,7 @@ pub struct LayoutState {
highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
context_menu: Option<(DisplayPoint, ElementBox)>,
+ diff_hunks: Vec<DiffHunk<u32>>,
code_actions_indicator: Option<(u32, ElementBox)>,
hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
}
@@ -7,9 +7,10 @@ use collections::{BTreeMap, Bound, HashMap, HashSet};
use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task};
pub use language::Completion;
use language::{
- char_kind, AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind, Chunk,
- DiagnosticEntry, Event, File, IndentSize, Language, OffsetRangeExt, Outline, OutlineItem,
- Selection, ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId,
+ char_kind, git::DiffHunk, AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind,
+ Chunk, DiagnosticEntry, Event, File, IndentSize, Language, OffsetRangeExt, Outline,
+ OutlineItem, Selection, ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _,
+ TransactionId,
};
use smallvec::SmallVec;
use std::{
@@ -2529,6 +2530,15 @@ impl MultiBufferSnapshot {
})
}
+ pub fn diff_hunks_in_range<'a>(
+ &'a self,
+ row_range: Range<u32>,
+ ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
+ self.as_singleton()
+ .into_iter()
+ .flat_map(move |(_, _, buffer)| buffer.diff_hunks_in_range(row_range.clone()))
+ }
+
pub fn range_for_syntax_ancestor<T: ToOffset>(&self, range: Range<T>) -> Option<Range<usize>> {
let range = range.start.to_offset(self)..range.end.to_offset(self);
@@ -51,6 +51,7 @@ smol = "1.2"
tree-sitter = "0.20"
tree-sitter-rust = { version = "*", optional = true }
tree-sitter-typescript = { version = "*", optional = true }
+git2 = "0.15"
[dev-dependencies]
client = { path = "../client", features = ["test-support"] }
@@ -1,3 +1,4 @@
+use crate::git::{BufferDiff, DiffHunk};
pub use crate::{
diagnostic_set::DiagnosticSet,
highlight_map::{HighlightId, HighlightMap},
@@ -48,6 +49,7 @@ pub use lsp::DiagnosticSeverity;
pub struct Buffer {
text: TextBuffer,
head_text: Option<String>,
+ diff: BufferDiff,
file: Option<Arc<dyn File>>,
saved_version: clock::Global,
saved_version_fingerprint: String,
@@ -74,6 +76,7 @@ pub struct Buffer {
pub struct BufferSnapshot {
text: text::BufferSnapshot,
+ git_hunks: Arc<[DiffHunk<Anchor>]>,
pub(crate) syntax: SyntaxSnapshot,
file: Option<Arc<dyn File>>,
diagnostics: DiagnosticSet,
@@ -416,6 +419,11 @@ impl Buffer {
UNIX_EPOCH
};
+ let mut diff = BufferDiff::new();
+ if let Some(head_text) = &head_text {
+ diff.update(head_text, &buffer);
+ }
+
Self {
saved_mtime,
saved_version: buffer.version(),
@@ -424,6 +432,7 @@ impl Buffer {
was_dirty_before_starting_transaction: None,
text: buffer,
head_text,
+ diff,
file,
syntax_map: Mutex::new(SyntaxMap::new()),
parsing_in_background: false,
@@ -453,6 +462,7 @@ impl Buffer {
BufferSnapshot {
text,
syntax,
+ git_hunks: self.diff.hunks(),
file: self.file.clone(),
remote_selections: self.remote_selections.clone(),
diagnostics: self.diagnostics.clone(),
@@ -2145,6 +2155,30 @@ impl BufferSnapshot {
})
}
+ pub fn diff_hunks_in_range<'a>(
+ &'a self,
+ query_row_range: Range<u32>,
+ ) -> impl 'a + Iterator<Item = DiffHunk<u32>> {
+ self.git_hunks.iter().filter_map(move |hunk| {
+ let range = hunk.buffer_range.to_point(&self.text);
+
+ if range.start.row < query_row_range.end && query_row_range.start < range.end.row {
+ let end_row = if range.end.column > 0 {
+ range.end.row + 1
+ } else {
+ range.end.row
+ };
+
+ Some(DiffHunk {
+ buffer_range: range.start.row..end_row,
+ head_range: hunk.head_range.clone(),
+ })
+ } else {
+ None
+ }
+ })
+ }
+
pub fn diagnostics_in_range<'a, T, O>(
&'a self,
search_range: Range<T>,
@@ -2218,6 +2252,7 @@ impl Clone for BufferSnapshot {
fn clone(&self) -> Self {
Self {
text: self.text.clone(),
+ git_hunks: self.git_hunks.clone(),
syntax: self.syntax.clone(),
file: self.file.clone(),
remote_selections: self.remote_selections.clone(),
@@ -0,0 +1,197 @@
+use std::ops::Range;
+use std::sync::Arc;
+
+use sum_tree::Bias;
+use text::{Anchor, Point};
+
+pub use git2 as libgit;
+use libgit::Patch as GitPatch;
+
+#[derive(Debug, Clone, Copy)]
+pub enum DiffHunkStatus {
+ Added,
+ Modified,
+ Removed,
+}
+
+#[derive(Debug)]
+pub struct DiffHunk<T> {
+ pub buffer_range: Range<T>,
+ pub head_range: Range<usize>,
+}
+
+impl DiffHunk<u32> {
+ pub fn status(&self) -> DiffHunkStatus {
+ if self.head_range.is_empty() {
+ DiffHunkStatus::Added
+ } else if self.buffer_range.is_empty() {
+ DiffHunkStatus::Removed
+ } else {
+ DiffHunkStatus::Modified
+ }
+ }
+}
+
+pub struct BufferDiff {
+ hunks: Arc<[DiffHunk<Anchor>]>,
+}
+
+impl BufferDiff {
+ pub fn new() -> BufferDiff {
+ BufferDiff {
+ hunks: Arc::new([]),
+ }
+ }
+
+ pub fn hunks(&self) -> Arc<[DiffHunk<Anchor>]> {
+ self.hunks.clone()
+ }
+
+ pub fn update(&mut self, head: &str, buffer: &text::BufferSnapshot) {
+ let current = buffer.as_rope().to_string().into_bytes();
+ let patch = match GitPatch::from_buffers(head.as_bytes(), None, ¤t, None, None) {
+ Ok(patch) => patch,
+ Err(_) => {
+ //Reset hunks in case of failure to avoid showing a stale (potentially erroneous) diff
+ self.hunks = Arc::new([]);
+ return;
+ }
+ };
+
+ let mut hunks = Vec::new();
+ for index in 0..patch.num_hunks() {
+ let (hunk, _) = match patch.hunk(index) {
+ Ok(it) => it,
+ Err(_) => break,
+ };
+
+ let new_start = hunk.new_start();
+ let new_end = new_start + hunk.new_lines();
+ let start_anchor = buffer.anchor_at(Point::new(new_start, 0), Bias::Left);
+ let end_anchor = buffer.anchor_at(Point::new(new_end, 0), Bias::Left);
+ let buffer_range = start_anchor..end_anchor;
+
+ let old_start = hunk.old_start() as usize;
+ let old_end = old_start + hunk.old_lines() as usize;
+ let head_range = old_start..old_end;
+
+ hunks.push(DiffHunk {
+ buffer_range,
+ head_range,
+ });
+ }
+
+ self.hunks = hunks.into();
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub enum GitDiffEdit {
+ Added(u32),
+ Modified(u32),
+ Removed(u32),
+}
+
+impl GitDiffEdit {
+ pub fn line(self) -> u32 {
+ use GitDiffEdit::*;
+
+ match self {
+ Added(line) | Modified(line) | Removed(line) => line,
+ }
+ }
+}
+
+// struct DiffTracker {
+// track_line_num: u32,
+// edits: Vec<GitDiffEdit>,
+// }
+
+// impl DiffTracker {
+// fn new() -> DiffTracker {
+// DiffTracker {
+// track_line_num: 0,
+// edits: Vec::new(),
+// }
+// }
+
+// fn attempt_finalize_file(&mut self, base_path: &Path) -> Result<()> {
+// let relative = if let Some(relative) = self.last_file_path.clone() {
+// relative
+// } else {
+// return Ok(());
+// };
+
+// let mut path = base_path.to_path_buf();
+// path.push(relative);
+// path = canonicalize(path).map_err(Error::Io)?;
+
+// self.diffs.push(GitFileDiff {
+// path,
+// edits: take(&mut self.edits),
+// });
+
+// Ok(())
+// }
+
+// fn handle_diff_line(
+// &mut self,
+// delta: DiffDelta,
+// line: DiffLine,
+// base_path: &Path,
+// ) -> Result<()> {
+// let path = match (delta.old_file().path(), delta.new_file().path()) {
+// (Some(old), _) => old,
+// (_, Some(new)) => new,
+// (_, _) => return Err(Error::DeltaMissingPath),
+// };
+
+// if self.last_file_path.as_deref() != Some(path) {
+// self.attempt_finalize_file(base_path)?;
+// self.last_file_path = Some(path.to_path_buf());
+// self.track_line_num = 0;
+// }
+
+// match line.origin_value() {
+// DiffLineType::Context => {
+// self.track_line_num = line.new_lineno().ok_or(Error::ContextMissingLineNum)?;
+// }
+
+// DiffLineType::Deletion => {
+// self.track_line_num += 1;
+// self.edits.push(GitDiffEdit::Removed(self.track_line_num));
+// }
+
+// DiffLineType::Addition => {
+// let addition_line_num = line.new_lineno().ok_or(Error::AdditionMissingLineNum)?;
+// self.track_line_num = addition_line_num;
+
+// let mut replaced = false;
+// for rewind_index in (0..self.edits.len()).rev() {
+// let edit = &mut self.edits[rewind_index];
+
+// if let GitDiffEdit::Removed(removed_line_num) = *edit {
+// match removed_line_num.cmp(&addition_line_num) {
+// Ordering::Equal => {
+// *edit = GitDiffEdit::Modified(addition_line_num);
+// replaced = true;
+// break;
+// }
+
+// Ordering::Greater => continue,
+// Ordering::Less => break,
+// }
+// }
+// }
+
+// if !replaced {
+// self.edits.push(GitDiffEdit::Added(addition_line_num));
+// }
+// }
+
+// _ => {}
+// }
+
+// Ok(())
+// }
+// }
@@ -1,5 +1,6 @@
mod buffer;
mod diagnostic_set;
+pub mod git;
mod highlight_map;
mod outline;
pub mod proto;
@@ -52,7 +52,6 @@ smol = "1.2.5"
thiserror = "1.0.29"
toml = "0.5"
rocksdb = "0.18"
-git2 = "0.15"
[dev-dependencies]
client = { path = "../client", features = ["test-support"] }
@@ -1,7 +1,7 @@
use anyhow::{anyhow, Result};
use fsevent::EventStream;
use futures::{future::BoxFuture, Stream, StreamExt};
-use git2::{Repository, RepositoryOpenFlags};
+use language::git::libgit::{Repository, RepositoryOpenFlags};
use language::LineEnding;
use smol::io::{AsyncReadExt, AsyncWriteExt};
use std::{
@@ -4533,8 +4533,8 @@ impl Project {
fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
cx.observe(worktree, |_, _, cx| cx.notify()).detach();
if worktree.read(cx).is_local() {
- cx.subscribe(worktree, |this, worktree, _, cx| {
- this.update_local_worktree_buffers(worktree, cx);
+ cx.subscribe(worktree, |this, worktree, event, cx| match event {
+ worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
})
.detach();
}