From 55ca02351c5e8c662f7f9e09a8ce93a4f69233c5 Mon Sep 17 00:00:00 2001 From: Julia Date: Thu, 1 Sep 2022 17:22:12 -0400 Subject: [PATCH] Start painting some sort of hunk info, it's wrong but it's close Co-Authored-By: Max Brunsfeld --- Cargo.lock | 2 +- crates/editor/src/element.rs | 35 ++++++ crates/editor/src/multi_buffer.rs | 16 ++- crates/language/Cargo.toml | 1 + crates/language/src/buffer.rs | 35 ++++++ crates/language/src/git.rs | 197 ++++++++++++++++++++++++++++++ crates/language/src/language.rs | 1 + crates/project/Cargo.toml | 1 - crates/project/src/fs.rs | 2 +- crates/project/src/project.rs | 4 +- 10 files changed, 286 insertions(+), 8 deletions(-) create mode 100644 crates/language/src/git.rs diff --git a/Cargo.lock b/Cargo.lock index 31f5f30f38..2872d83a94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index 1e1ab83063..357f15432b 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -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, Color)>, selections: Vec<(ReplicaId, Vec)>, context_menu: Option<(DisplayPoint, ElementBox)>, + diff_hunks: Vec>, code_actions_indicator: Option<(u32, ElementBox)>, hover_popovers: Option<(DisplayPoint, Vec)>, } diff --git a/crates/editor/src/multi_buffer.rs b/crates/editor/src/multi_buffer.rs index 4ee9526a67..91de32bac9 100644 --- a/crates/editor/src/multi_buffer.rs +++ b/crates/editor/src/multi_buffer.rs @@ -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, + ) -> impl 'a + Iterator> { + self.as_singleton() + .into_iter() + .flat_map(move |(_, _, buffer)| buffer.diff_hunks_in_range(row_range.clone())) + } + pub fn range_for_syntax_ancestor(&self, range: Range) -> Option> { let range = range.start.to_offset(self)..range.end.to_offset(self); diff --git a/crates/language/Cargo.toml b/crates/language/Cargo.toml index 6e9f368e77..6d347f3595 100644 --- a/crates/language/Cargo.toml +++ b/crates/language/Cargo.toml @@ -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"] } diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs index ca86f9c172..ad3d8978ad 100644 --- a/crates/language/src/buffer.rs +++ b/crates/language/src/buffer.rs @@ -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, + diff: BufferDiff, file: Option>, 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]>, pub(crate) syntax: SyntaxSnapshot, file: Option>, 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, + ) -> impl 'a + Iterator> { + 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, @@ -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(), diff --git a/crates/language/src/git.rs b/crates/language/src/git.rs new file mode 100644 index 0000000000..5445396918 --- /dev/null +++ b/crates/language/src/git.rs @@ -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 { + pub buffer_range: Range, + pub head_range: Range, +} + +impl DiffHunk { + 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]>, +} + +impl BufferDiff { + pub fn new() -> BufferDiff { + BufferDiff { + hunks: Arc::new([]), + } + } + + pub fn hunks(&self) -> Arc<[DiffHunk]> { + 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, +// } + +// 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(()) +// } +// } diff --git a/crates/language/src/language.rs b/crates/language/src/language.rs index 780f6e75b5..8e2fe601e7 100644 --- a/crates/language/src/language.rs +++ b/crates/language/src/language.rs @@ -1,5 +1,6 @@ mod buffer; mod diagnostic_set; +pub mod git; mod highlight_map; mod outline; pub mod proto; diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml index 4e7ff2d471..a4ea6f2286 100644 --- a/crates/project/Cargo.toml +++ b/crates/project/Cargo.toml @@ -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"] } diff --git a/crates/project/src/fs.rs b/crates/project/src/fs.rs index 68d07c891c..a983df0f4b 100644 --- a/crates/project/src/fs.rs +++ b/crates/project/src/fs.rs @@ -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::{ diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index 6841c561d0..8fa1fe9622 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -4533,8 +4533,8 @@ impl Project { fn add_worktree(&mut self, worktree: &ModelHandle, cx: &mut ModelContext) { 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(); }