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 @@ -60,7 +60,8 @@ There are two crates.
- `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. `diff.rs` also pairs the lines a change removed and
added, and finds the words that changed between them, for the lines on screen.
added, to show them side by side, 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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ GitCraft is young. This is what it does today; [ROADMAP.md](ROADMAP.md) has what
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.
new argument is easy to spot. "Side by side" puts the old version on the left and the new one on
the right, each changed line facing the line that replaced it; you stage or discard lines from
either side the same way, and the choice stays for the next diff and the next run.
- **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 @@ -48,10 +48,11 @@ drive it the way a user does, and keeps every benchmark as fast as before.
- [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
- [x] Better diffs, part 2: the old and the new version side by side

## Next

1. **Better diffs, part 2**: side by side, syntax colouring, images.
1. **Better diffs, part 3**: 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
120 changes: 85 additions & 35 deletions crates/app/src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::theme;

const LINE: f32 = 18.0;
const NUMBER: f32 = 44.0;
const FONT: FontId = FontId::monospace(12.5);

/// What can be done with lines of the file.
fn verbs(source: &Source) -> &'static [&'static str] {
Expand Down Expand Up @@ -71,11 +72,17 @@ fn line_text(
job
}

/// Where egui keeps whether diffs show the old and the new version side by side: that is how the
/// view looks, like a folded section, so it stays with the view and lasts between runs.
const SIDE_BY_SIDE: &str = "side by side";

/// 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);
let picked = |h, l| file.lines.contains(&(h, l));
let lines = theme::count(file.lines.len(), "line");
let id = egui::Id::unique(SIDE_BY_SIDE);
let mut side_by_side = ui.data_mut(|d| d.get_persisted(id)).unwrap_or(false);
ui.horizontal(|ui| {
ui.strong(file.source.path());
ui.weak(match file.source {
Expand All @@ -88,6 +95,10 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
if alone && (ui.button("Close").clicked() || ui.input(|i| i.key_pressed(Key::Escape))) {
actions.push(Action::CloseFile);
}
if ui.add(egui::Button::selectable(side_by_side, "Side by side")).clicked() {
side_by_side = !side_by_side;
ui.data_mut(|d| d.insert_persisted(id, side_by_side));
}
for verb in verbs {
if !file.lines.is_empty() && ui.button(format!("{verb} {lines}")).clicked() {
actions.push(act(file, verb, &lines, &picked));
Expand All @@ -108,27 +119,34 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
);
return;
}
let rows: Vec<(usize, Option<usize>)> = file
// A hunk's header, then its lines: one per row, or side by side the old and the new version's.
let rows: Vec<(usize, Option<[Option<usize>; 2]>)> = file
.diff
.hunks
.iter()
.enumerate()
.flat_map(|(h, hunk)| std::iter::once((h, None)).chain((0..hunk.lines.len()).map(move |l| (h, Some(l)))))
.flat_map(|(h, hunk)| {
let lines = if side_by_side {
hunk.side_by_side()
} else {
(0..hunk.lines.len()).map(|l| [Some(l), None]).collect()
};
std::iter::once((h, None)).chain(lines.into_iter().map(move |cells| (h, Some(cells))))
})
.collect();
let font = FontId::monospace(12.5);
ui.spacing_mut().item_spacing.y = 0.0;
egui::ScrollArea::both().auto_shrink(false).show_rows(ui, LINE, rows.len(), |ui, range| {
for &(h, line) in &rows[range] {
for &(h, cells) in &rows[range] {
let hunk = &file.diff.hunks[h];
let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), LINE), Sense::click());
let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), LINE), Sense::hover());
let painter = ui.painter_at(rect);
let Some(l) = line else {
let Some(cells) = cells else {
painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
painter.text(
rect.left_center() + Vec2::X * 8.0,
Align2::LEFT_CENTER,
&hunk.header,
font.clone(),
FONT,
Color32::GRAY,
);
for (verb, x) in verbs.iter().zip([110.0, 220.0]) {
Expand All @@ -139,35 +157,67 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
}
continue;
};
let line = &hunk.lines[l];
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();
let at = |x: f32| rect.left_center() + Vec2::X * x;
painter.text(at(NUMBER - 6.0), Align2::RIGHT_CENTER, number(line.old), font.clone(), Color32::DARK_GRAY);
painter.text(
at(2.0 * NUMBER - 6.0),
Align2::RIGHT_CENTER,
number(line.new),
font.clone(),
Color32::DARK_GRAY,
);
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));
let [old, new] = cells;
if !side_by_side {
line(ui, rect, file, (h, old.expect("a line on each row")), None, actions);
continue;
}
let (left, right) = rect.split_left_right_at_fraction(0.5);
for (side, (rect, l)) in [(left, old), (right, new)].into_iter().enumerate() {
match l {
Some(l) => line(ui, rect, file, (h, l), Some(side), actions),
None => {
painter.rect_filled(rect, 0.0, ui.visuals().faint_bg_color);
}
}
}
painter.vline(rect.center().x, rect.y_range(), ui.visuals().widgets.noninteractive.bg_stroke);
}
});
}

/// Draws line `l` of hunk `h` in `rect`, after its numbers in the old and the new version, or
/// side by side only the one of its `side` (0 is old, 1 is new). A click picks or unpicks a
/// changed line for staging.
fn line(
ui: &mut Ui,
rect: Rect,
file: &OpenFile,
(h, l): (usize, usize),
side: Option<usize>,
actions: &mut Vec<Action>,
) {
let hunk = &file.diff.hunks[h];
let line = &hunk.lines[l];
let numbers = [line.old, line.new];
let numbers = side.map_or(&numbers[..], |side| &numbers[side..=side]);
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, " "),
};
let painter = ui.painter_at(rect);
painter.rect_filled(rect, 0.0, if file.lines.contains(&(h, l)) { theme::PICKED } else { background });
let at = |x: f32| rect.left_center() + Vec2::X * x;
let mut x = 0.0;
for n in numbers {
x += NUMBER;
let n = n.map(|n| n.to_string()).unwrap_or_default();
painter.text(at(x - 6.0), Align2::RIGHT_CENTER, n, FONT, Color32::DARK_GRAY);
}
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(x + 6.0) - Vec2::Y * galley.size().y / 2.0, galley, color);
let changed = matches!(line.kind, LineKind::Added | LineKind::Removed);
if changed
&& !verbs(&file.source).is_empty()
&& ui.interact(rect, egui::Id::unique(("diff line", h, l)), Sense::click()).clicked()
{
actions.push(Action::ToggleLine(h, l));
}
}
70 changes: 70 additions & 0 deletions crates/app/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,76 @@ fn a_changed_line_marks_the_words_that_changed() {
assert_eq!(painted_on(&harness, theme::ADDED_WORD), ["amount"]);
}

/// Where the lines on screen that hold `text` are painted, top to bottom.
fn painted_at(harness: &Harness<'_, App>, text: &str) -> Vec<egui::Pos2> {
let shapes = harness.output().shapes.iter();
shapes
.filter_map(|clipped| match &clipped.shape {
egui::Shape::Text(shape) if shape.galley.job.text.contains(text) => Some(shape.pos),
_ => None,
})
.collect()
}

/// Whether two coordinates on screen are the same, to the pixel.
fn same(a: f32, b: f32) -> bool {
(a - b).abs() < 1.0
}

/// Clicks with the mouse at `at`.
fn click_at(harness: &mut Harness<'_, App>, at: egui::Pos2) {
harness.hover_at(at);
harness.drag_at(at);
harness.drop_at(at);
settle(harness);
}

#[test]
fn a_diff_side_by_side_puts_old_and_new_next_to_each_other_to_stage_from() {
let (_dir, git) = repo();
fs::write(git.dir().join("file.txt"), "let total = price * count;\nkeep\n").unwrap();
git.run(&["commit", "-qam", "Total"]).unwrap();
fs::write(git.dir().join("file.txt"), "let total = price * amount;\nkeep\nnew line\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);
let [old] = painted_at(&harness, "- let")[..] else { panic!("no old line") };
let [new] = painted_at(&harness, "+ let")[..] else { panic!("no new line") };
assert!(same(old.x, new.x) && old.y < new.y, "one under the other at first");

harness.get_by_label("Side by side").click();
settle(&mut harness);
let [old] = painted_at(&harness, "- let")[..] else { panic!("no old line") };
let [new] = painted_at(&harness, "+ let")[..] else { panic!("no new line") };
assert!(same(old.y, new.y) && old.x < new.x, "the old line faces the new one");
let [extra] = painted_at(&harness, "+ new line")[..] else { panic!("no added line") };
assert!(same(extra.x, new.x) && extra.y > new.y, "a line that pairs with none is on its own side");
let [left, right] = painted_at(&harness, " keep")[..] else { panic!("not on both sides") };
assert!(same(left.y, right.y) && same(left.x, old.x) && same(right.x, new.x));
assert_eq!(painted_on(&harness, theme::REMOVED_WORD), ["count"]);
assert_eq!(painted_on(&harness, theme::ADDED_WORD), ["amount"]);

// Either side's line can be picked.
click_at(&mut harness, old);
click_at(&mut harness, new);
harness.get_by_label("Stage 2 lines").click();
settle(&mut harness);
assert_eq!(git.run(&["show", ":file.txt"]).unwrap(), "let total = price * amount;\nkeep\n");

// The next diff, of what is still unstaged, is side by side too, until it is turned off.
harness.get_by_label("Close").click();
settle(&mut harness);
harness.get_all_by_label("file.txt").next().unwrap().click();
settle(&mut harness);
let [_, keep] = painted_at(&harness, " keep")[..] else { panic!("not side by side") };
assert!(keep.x > old.x);
harness.get_by_label("Side by side").click();
settle(&mut harness);
assert_eq!(painted_at(&harness, " keep").len(), 1);
}

#[test]
fn discard_single_lines_and_hunks() {
let (_dir, git) = repo();
Expand Down
51 changes: 48 additions & 3 deletions crates/core/src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ impl Hunk {
let [old, new] = if line.kind == LineKind::Removed { [line, pair] } else { [pair, line] };
Some([&old.text, &new.text])
}

/// The lines side by side, as rows of a line of the old version and one of the new: a line
/// that did not change is on both sides, a removed line faces the added line it pairs with,
/// and a line that pairs with none has nothing beside it.
pub fn side_by_side(&self) -> Vec<[Option<usize>; 2]> {
let mut rows = Vec::new();
let mut kind = LineKind::Context;
for (l, line) in self.lines.iter().enumerate() {
// That a line has no newline at its end shows on that line's side.
if line.kind != LineKind::NoNewline {
kind = line.kind;
}
match kind {
LineKind::Context | LineKind::NoNewline => rows.push([Some(l); 2]),
LineKind::Removed => rows.push([Some(l), line.pair]),
LineKind::Added if line.pair.is_none() => rows.push([None, Some(l)]),
// On the row of the removed line.
LineKind::Added => {}
}
}
rows
}
}

/// The diff of one file.
Expand Down Expand Up @@ -348,6 +370,10 @@ index 3333333..4444444 100644
Binary files a/img.png and b/img.png differ
";

/// Blocks with more added lines than removed and the other way around.
const MORE: &str =
"diff --git a/f b/f\n@@ -1,3 +1,4 @@\n-a\n-b\n+A\n+B\n+C\n x\n-y\n\\ No newline at end of file\n+Y\n";

#[test]
fn parses_files_hunks_and_line_numbers() {
let files = FileDiff::parse(DIFF);
Expand Down Expand Up @@ -378,9 +404,28 @@ Binary files a/img.png and b/img.png differ
};
// "-two" and "+TWO" replace each other, "+extra" and "-four" stand alone.
assert_eq!(pairs(DIFF), [None, Some(2), Some(1), None, None, None, None]);
let more =
"diff --git a/f b/f\n@@ -1,3 +1,4 @@\n-a\n-b\n+A\n+B\n+C\n x\n-y\n\\ No newline at end of file\n+Y\n";
assert_eq!(pairs(more), [Some(2), Some(3), Some(0), Some(1), None, None, Some(8), None, Some(6)]);
assert_eq!(pairs(MORE), [Some(2), Some(3), Some(0), Some(1), None, None, Some(8), None, Some(6)]);
}

#[test]
fn side_by_side_a_removed_line_faces_the_added_line_it_pairs_with() {
let rows = |diff: &str| FileDiff::parse(diff)[0].hunks[0].side_by_side();
// "-four" has no newline at its end, on its own side.
assert_eq!(
rows(DIFF),
[[Some(0); 2], [Some(1), Some(2)], [None, Some(3)], [Some(4); 2], [Some(5), None], [Some(6), None]]
);
assert_eq!(
rows(MORE),
[
[Some(0), Some(2)],
[Some(1), Some(3)],
[None, Some(4)],
[Some(5); 2],
[Some(6), Some(8)],
[Some(7), None]
]
);
}

const NONE: [Vec<String>; 2] = [Vec::new(), Vec::new()];
Expand Down
Loading