Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ There are two crates.
working without code of our own.
- `status.rs` and `diff.rs` parse `git status --porcelain=v2`, what commits changed (also to one
file, through its renames), who last changed each line of a file, and unified diffs, and build
the patches for staging single lines.
the patches for staging single lines. `diff.rs` also pairs the lines a change removed and
added, and finds the words that changed between them, for the lines on screen.
- `conflict.rs` splits a conflicted file at the markers git wrote into it, and puts it back
together with ours, theirs or both for each conflict.
- `watch.rs` watches the working tree and the refs, and says when something changed that git
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ GitCraft is young. This is what it does today; [ROADMAP.md](ROADMAP.md) has what
that name comes first, so typing its name takes you there. Large histories are searched as you
type, without the window waiting.
- **Commits**: message, author, parents and the files they changed, with the diff of each file.
- **Diffs**: in a line that changed, the words that changed stand out, so a renamed variable or a
new argument is easy to spot.
- **File history**: right-click a file, in a commit or in your changes, for every commit that
changed it, newest first, also from before it was renamed. Pick one to see its diff of the file,
with the commit beside it. Following a file through a large history happens in the background.
Expand Down
3 changes: 2 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ drive it the way a user does, and keeps every benchmark as fast as before.
- [x] Search the graph by message, author or SHA, and jump to any branch or tag by its name
- [x] File history: the commits that changed a file, followed through renames, each with its diff
- [x] Blame: who last changed each line of a file, and in which commit
- [x] Better diffs, part 1: the words that changed within a line stand out

## Next

1. **Better diffs**: side by side, word-level changes, syntax colouring, images.
1. **Better diffs, part 2**: side by side, syntax colouring, images.
2. **Keyboard**: shortcuts for everything, and a command palette.
3. **Settings**: light and dark theme, font size, date format, default pull mode.
4. **Graph polish**: resizable columns, compact lanes, author avatars (optional, never by default
Expand Down
62 changes: 54 additions & 8 deletions crates/app/src/diff.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
//! The diff of one file, with staging and discarding of hunks and single lines.
//! The diff of one file, with the words that changed within its lines, and staging and
//! discarding of hunks and single lines.

use std::ops::Range;

use eframe::egui::cache::{ComputerMut, FrameCache};
use eframe::egui::text::{LayoutJob, TextFormat};
use eframe::egui::{self, Align2, Color32, FontId, Key, Rect, RichText, Sense, Ui, Vec2};
use gitcraft_core::diff::{LineKind, Source};
use gitcraft_core::diff::{self, LineKind, Source};
use gitcraft_core::git::Op;

use crate::app::{Action, Confirm, OpenFile};
Expand Down Expand Up @@ -31,6 +36,41 @@ fn act(file: &OpenFile, verb: &'static str, what: &str, selected: &dyn Fn(usize,
Action::Run(Op::ApplyToIndex { patch, reverse })
}

/// Finds the words that changed between a removed and an added line, once while they are on screen.
#[derive(Debug, Default)]
struct Words;

impl ComputerMut<[&str; 2], [Vec<Range<usize>>; 2]> for Words {
fn compute(&mut self, [old, new]: [&str; 2]) -> [Vec<Range<usize>>; 2] {
diff::words(old, new)
}
}

/// A line's text after its `marker`, with its `words` that changed on the `background`.
fn line_text(
marker: &str,
text: &str,
words: &[Range<usize>],
background: Color32,
font: &FontId,
color: Color32,
) -> LayoutJob {
let mut job = LayoutJob::default();
let mut add = |text: &str, background| {
job.append(text, 0.0, TextFormat { font_id: font.clone(), color, background, ..TextFormat::default() });
};
add(marker, Color32::TRANSPARENT);
let mut at = 0;
// A word can end in the carriage return that is not shown.
for word in words.iter().filter(|word| word.start < text.len()) {
add(&text[at..word.start], Color32::TRANSPARENT);
at = word.end.min(text.len());
add(&text[word.start..at], background);
}
add(&text[at..], Color32::TRANSPARENT);
job
}

/// Shows the open file, with a way to close it when it fills the centre `alone`.
pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>) {
let verbs = verbs(&file.source);
Expand Down Expand Up @@ -100,10 +140,10 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
continue;
};
let line = &hunk.lines[l];
let (background, marker) = match line.kind {
LineKind::Added => (theme::ADDED, "+"),
LineKind::Removed => (theme::REMOVED, "-"),
LineKind::Context | LineKind::NoNewline => (Color32::TRANSPARENT, " "),
let (background, word, marker) = match line.kind {
LineKind::Added => (theme::ADDED, theme::ADDED_WORD, "+ "),
LineKind::Removed => (theme::REMOVED, theme::REMOVED_WORD, "- "),
LineKind::Context | LineKind::NoNewline => (Color32::TRANSPARENT, Color32::TRANSPARENT, " "),
};
painter.rect_filled(rect, 0.0, if picked(h, l) { theme::PICKED } else { background });
let number = |n: Option<u32>| n.map(|n| n.to_string()).unwrap_or_default();
Expand All @@ -116,8 +156,14 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
font.clone(),
Color32::DARK_GRAY,
);
let text = format!("{marker} {}", line.text.trim_end_matches('\r'));
painter.text(at(2.0 * NUMBER + 6.0), Align2::LEFT_CENTER, text, font.clone(), ui.visuals().text_color());
let color = ui.visuals().text_color();
let words = hunk.pair(l).map_or_else(Vec::new, |pair| {
let side = usize::from(line.kind == LineKind::Added);
ui.memory_mut(|m| m.caches.cache::<FrameCache<_, Words>>().get(pair)[side].clone())
});
let job = line_text(marker, line.text.trim_end_matches('\r'), &words, word, &font, color);
let galley = painter.layout_job(job);
painter.galley(at(2.0 * NUMBER + 6.0) - Vec2::Y * galley.size().y / 2.0, galley, color);
let changed = matches!(line.kind, LineKind::Added | LineKind::Removed);
if !verbs.is_empty() && changed && response.clicked() {
actions.push(Action::ToggleLine(h, l));
Expand Down
31 changes: 31 additions & 0 deletions crates/app/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use tempfile::TempDir;

use crate::app::{Action, Selection};
use crate::start::percent;
use crate::theme;
use crate::ui::{App, KEYS};

/// A repository with one commit, with the tester's own git config kept out of the way.
Expand Down Expand Up @@ -316,6 +317,36 @@ fn discarding_an_open_untracked_file_deletes_it_and_closes_it() {
assert_eq!(ws.error, None);
}

/// The parts of the text on screen that are painted on `background`.
fn painted_on(harness: &Harness<'_, App>, background: egui::Color32) -> Vec<String> {
let jobs = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape {
egui::Shape::Text(text) => Some(&text.galley.job),
_ => None,
});
jobs.flat_map(|job| {
let marked = job.sections.iter().filter(|section| section.format.background == background);
marked.map(|section| job.text[section.byte_range.start.0..section.byte_range.end.0].to_owned())
})
.collect()
}

#[test]
fn a_changed_line_marks_the_words_that_changed() {
let (_dir, git) = repo();
fs::write(git.dir().join("file.txt"), "let total = price * count;\nkeep\nold line\n").unwrap();
git.run(&["commit", "-qam", "Total"]).unwrap();
fs::write(git.dir().join("file.txt"), "let total = price * amount;\nkeep\nsomething else\n").unwrap();
let mut harness = app(Some(git.dir()));
harness.get_by_label("Uncommitted changes").click();
settle(&mut harness);
harness.get_by_label("file.txt").click();
settle(&mut harness);

// Only the word that changed stands out; a line rewritten as a whole has nothing to point at.
assert_eq!(painted_on(&harness, theme::REMOVED_WORD), ["count"]);
assert_eq!(painted_on(&harness, theme::ADDED_WORD), ["amount"]);
}

#[test]
fn discard_single_lines_and_hunks() {
let (_dir, git) = repo();
Expand Down
4 changes: 4 additions & 0 deletions crates/app/src/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ const LANES: [Color32; 10] = [
pub const ADDED: Color32 = Color32::from_rgb(0x1d, 0x3b, 0x2c);
/// The background of a removed line.
pub const REMOVED: Color32 = Color32::from_rgb(0x45, 0x22, 0x27);
/// The background of the words that changed in an added line.
pub const ADDED_WORD: Color32 = Color32::from_rgb(0x2c, 0x63, 0x45);
/// The background of the words that changed in a removed line.
pub const REMOVED_WORD: Color32 = Color32::from_rgb(0x74, 0x30, 0x39);
/// The background of a conflict without a pick.
pub const CONFLICT: Color32 = Color32::from_rgb(0x4a, 0x38, 0x1c);
/// The background of a line picked for staging.
Expand Down
Loading
Loading