diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a423990..b2dfb4f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,7 +58,8 @@ There are two crates. first); cloning and creating a repository are the two functions next to it. Using `git` itself keeps hooks, credentials, signing and config 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) and unified diffs, and build the patches for staging single lines. + file, through its renames), who last changed each line of a file, and unified diffs, and build + the patches for staging single lines. - `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 @@ -82,8 +83,9 @@ Its tests run against real repositories made with `git` in a temporary folder in the meantime runs next. The tab on screen also reloads by itself when its watcher saw a change. - `start.rs` (open, clone and create), `ui.rs` (tabs and toolbar), `graph.rs`, `sidebar.rs`, `details.rs`, - `diff.rs`, `history.rs` (a file's history), `merge.rs` (a conflicted file) and `rebase.rs` (an - interactive rebase) draw the views, and `theme.rs` has the colours. + `diff.rs`, `history.rs` (a file's history), `blame.rs` (who last changed each line), + `merge.rs` (a conflicted file) and `rebase.rs` (an interactive rebase) draw the views, and + `theme.rs` has the colours. The app's tests (`crates/app/src/tests.rs`) drive the whole window the way a user does, through the accessibility tree with [egui_kittest](https://crates.io/crates/egui_kittest). That also keeps diff --git a/README.md b/README.md index 278059e..aebbfc8 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,10 @@ GitCraft is young. This is what it does today; [ROADMAP.md](ROADMAP.md) has what - **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. +- **Blame**: right-click a file for who last changed each line, and in which commit, beside the + lines. From your changes it is the file as it is now, with the lines you have not committed yet, + and it keeps up as you edit; from a commit it is the file in that commit. Click a line to see + its commit and every other line it changed. - **Staging**: stage or unstage files, whole hunks or single lines, then commit or amend. - **Discard**: throw away the changes to a file, a hunk or single lines, after you confirm. - **Branches and tags**: create, check out, merge, rebase, delete, from the sidebar or a right click. diff --git a/ROADMAP.md b/ROADMAP.md index f42a69b..ec70ea2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -46,16 +46,16 @@ drive it the way a user does, and keeps every benchmark as fast as before. another name or URL, or remove it - [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 ## Next -1. **Blame**: who last changed each line of a file, and in which commit. -2. **Better diffs**: side by side, word-level changes, syntax colouring, images. -3. **Keyboard**: shortcuts for everything, and a command palette. -4. **Settings**: light and dark theme, font size, date format, default pull mode. -5. **Graph polish**: resizable columns, compact lanes, author avatars (optional, never by default +1. **Better diffs**: side by side, word-level changes, 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 over the network). -6. **Packaging**: installers with the icon for Windows (MSI), macOS (.app in a .dmg) and Linux +5. **Packaging**: installers with the icon for Windows (MSI), macOS (.app in a .dmg) and Linux (AppImage, .deb, Flatpak), signed where the platform expects it. ## After 1.0 diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 08ee34b..7062593 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -47,6 +47,13 @@ pub enum Action { }, /// Show the diff of the file in a commit of its history, by row, and the commit beside it. Visit(usize), + /// Show who last changed each line of a file instead of the graph. + Blame { + /// The commit whose file it is, or `None` for the file in the working tree. + at: Option, + /// The file. + path: String, + }, /// Back to the graph. CloseFile, /// Pick or unpick a line of the open diff for staging. @@ -222,6 +229,39 @@ impl Merge { /// Each commit that changed a file, newest first, with what it did to it. type Changes = Vec<(ObjectId, FileChange)>; +/// Each line of a file, with the commit that last changed it. +type Lines = Vec<(ObjectId, String)>; + +/// Something being read in the background for the centre, if it is: what was read, or what went +/// wrong. +type Reading = Option>>; + +/// Runs `read` on a thread of its own, and wakes the window once it is done. +fn read_in_background( + ctx: &egui::Context, + read: impl FnOnce() -> Result + Send + 'static, +) -> Receiver> { + let (send, reading) = mpsc::channel(); + let ctx = ctx.clone(); + std::thread::spawn(move || { + // Sending fails only when what it was read for was closed in the meantime. + let _ = send.send(read().map_err(|error| error.to_string())); + ctx.request_repaint(); + }); + reading +} + +/// What was read in the background, once it is there. +fn take(reading: &mut Reading) -> Option> { + let read = match reading.as_ref()?.try_recv() { + Err(TryRecvError::Empty) => return None, + Ok(read) => read, + Err(TryRecvError::Disconnected) => Err("Reading stopped unexpectedly".to_owned()), + }; + *reading = None; + Some(read) +} + /// The history of a file in the centre: the commits that changed it, above the diff of the one /// picked. It is read in the background, because following a file through a large history takes /// a while. @@ -234,7 +274,7 @@ pub struct FileHistory { /// Each commit that changed the file. pub commits: Changes, /// The history being read, if it is. - pub reading: Option>>, + pub reading: Reading, } impl FileHistory { @@ -246,14 +286,31 @@ impl FileHistory { /// Reads the history, in the background. fn read(&mut self, ctx: &egui::Context, git: &Git) { - let (send, reading) = mpsc::channel(); - let (git, ctx, at, path) = (git.clone(), ctx.clone(), self.at.clone(), self.path.clone()); - std::thread::spawn(move || { - // Sending fails only when the history was closed in the meantime. - let _ = send.send(status::file_history(&git, &at, &path).map_err(|error| error.to_string())); - ctx.request_repaint(); - }); - self.reading = Some(reading); + let (git, at, path) = (git.clone(), self.at.clone(), self.path.clone()); + self.reading = Some(read_in_background(ctx, move || status::file_history(&git, &at, &path))); + } +} + +/// Who last changed each line of a file, in the centre. It is read in the background, because +/// git goes back through the history of the file for it. +#[derive(Debug)] +pub struct Blame { + /// The file. + pub path: String, + /// The commit whose file it is, or `None` for the file in the working tree, which is read + /// again after every change. + pub at: Option, + /// Each line, with the commit that last changed it; the null id when it is not committed. + pub lines: Lines, + /// The blame being read, if it is. + pub reading: Reading, +} + +impl Blame { + /// Reads the blame, in the background. + fn read(&mut self, ctx: &egui::Context, git: &Git) { + let (git, at, path) = (git.clone(), self.at.clone(), self.path.clone()); + self.reading = Some(read_in_background(ctx, move || status::blame(&git, at.as_deref(), &path))); } } @@ -385,6 +442,8 @@ pub struct Workspace { pub plan: Option, /// The history of a file in the centre, if any. pub history: Option, + /// Who last changed each line of a file, in the centre, if anyone. + pub blame: Option, /// The commit summary being written. pub summary: String, /// The rest of the commit message. @@ -427,6 +486,7 @@ impl Workspace { merge: None, plan: None, history: None, + blame: None, summary: String::new(), description: String::new(), amend: false, @@ -509,19 +569,23 @@ impl Workspace { } Action::Next(down) => self.reveal_row(ctx, self.search.next(self.selected_commit(), down)), Action::Open(source) => { - self.history = None; + (self.history, self.blame) = (None, None); self.open(source); } Action::History { at, path } => { - let mut history = FileHistory { path, at, commits: Vec::new(), reading: None }; + self.close_centre(); + let history = self.history.insert(FileHistory { path, at, commits: Vec::new(), reading: None }); history.read(ctx, &self.repo.git); - (self.open_file, self.merge, self.plan, self.history) = (None, None, None, Some(history)); } Action::Visit(row) => self.visit(ctx, row), + Action::Blame { at, path } => { + self.close_centre(); + self.blame.insert(Blame { path, at, lines: Vec::new(), reading: None }).read(ctx, &self.repo.git); + } Action::Resolve(path) => match Conflicts::read(&self.repo.git, &path) { Ok(conflicts) => { - (self.merge, self.open_file, self.plan, self.history) = - (Some(Merge::new(path, conflicts)), None, None, None); + self.close_centre(); + self.merge = Some(Merge::new(path, conflicts)); } Err(error) => self.error = Some(error.to_string()), }, @@ -543,28 +607,12 @@ impl Workspace { self.apply(ctx, Action::Shift(from, to)); } } - Action::Step(row, step) => { - let Some(plan) = &mut self.plan else { return }; - let id = plan.steps[row].1; - // A new message starts from the one it has. - if step == Step::Reword && !plan.messages.contains_key(&id) { - match self.commits.get(&self.repo, id) { - Ok(commit) => { - plan.messages.insert(id, commit.message.trim_end().to_owned()); - } - Err(error) => { - self.error = Some(error.to_string()); - return; - } - } - } - plan.steps[row].0 = step; - } + Action::Step(row, step) => self.step(row, step), Action::Shift(from, to) => self.plan.iter_mut().for_each(|plan| { let step = plan.steps.remove(from); plan.steps.insert(to, step); }), - Action::CloseFile => (self.open_file, self.merge, self.plan, self.history) = (None, None, None, None), + Action::CloseFile => self.close_centre(), Action::ToggleLine(hunk, line) => { if let Some(file) = &mut self.open_file && !file.lines.remove(&(hunk, line)) @@ -590,6 +638,30 @@ impl Workspace { } } + /// Sets what the rebase does with the commit in `row` of the plan. + fn step(&mut self, row: usize, step: Step) { + let Some(plan) = &mut self.plan else { return }; + let id = plan.steps[row].1; + // A new message starts from the one it has. + if step == Step::Reword && !plan.messages.contains_key(&id) { + match self.commits.get(&self.repo, id) { + Ok(commit) => { + plan.messages.insert(id, commit.message.trim_end().to_owned()); + } + Err(error) => { + self.error = Some(error.to_string()); + return; + } + } + } + plan.steps[row].0 = step; + } + + /// Back to the graph in the centre. + fn close_centre(&mut self) { + (self.open_file, self.merge, self.plan, self.history, self.blame) = (None, None, None, None, None); + } + /// Shows the diff of a file in the centre. fn open(&mut self, source: Source) { match diff::read(&self.repo.git, &source) { @@ -610,22 +682,28 @@ impl Workspace { self.open(source); } - /// Takes in the history of the file in the centre once it is read, and shows the diff of its - /// newest commit when none is open. - fn take_history(&mut self, ctx: &egui::Context) { - let Some(history) = &mut self.history else { return }; - let read = match history.reading.as_ref().map(Receiver::try_recv) { - None | Some(Err(TryRecvError::Empty)) => return, - Some(Ok(read)) => read, - Some(Err(TryRecvError::Disconnected)) => Err("Reading the history stopped unexpectedly".to_owned()), - }; - history.reading = None; - match read { - Ok(commits) => history.commits = commits, - Err(error) => self.error = Some(error), + /// Takes in the history or the blame of the file in the centre once it is read. A history + /// shows the diff of its newest commit when none is open; a blame that failed, as when the + /// file is gone, closes. + fn take_reading(&mut self, ctx: &egui::Context) { + if let Some(history) = &mut self.history + && let Some(read) = take(&mut history.reading) + { + match read { + Ok(commits) => history.commits = commits, + Err(error) => self.error = Some(error), + } + if self.open_file.is_none() && !history.commits.is_empty() { + self.visit(ctx, 0); + } } - if self.open_file.is_none() && !history.commits.is_empty() { - self.visit(ctx, 0); + if let Some(blame) = &mut self.blame + && let Some(read) = take(&mut blame.reading) + { + match read { + Ok(lines) => blame.lines = lines, + Err(error) => (self.blame, self.error) = (None, Some(error)), + } } } @@ -634,7 +712,7 @@ impl Workspace { match self.repo.git.rebase_plan(&onto) { Ok(listed) if listed.is_empty() => self.error = Some(format!("Nothing to rebase onto {onto:.7}")), Ok(listed) => { - (self.open_file, self.merge, self.history) = (None, None, None); + self.close_centre(); return Some(self.plan.insert(Plan::new(onto, listed))); } Err(error) => self.error = Some(error.to_string()), @@ -748,7 +826,7 @@ impl Workspace { /// Takes in the result of the background job, once it is there, and starts the next. pub fn poll(&mut self, ctx: &egui::Context) { - self.take_history(ctx); + self.take_reading(ctx); let Some(job) = &self.job else { return }; let (failed, snapshot, watch) = match job.outcome.try_recv() { Err(TryRecvError::Empty) => return, @@ -782,6 +860,10 @@ impl Workspace { history.read(ctx, &self.repo.git); } } + // Any change may be to the file in the working tree, or to the commits behind it. + if let Some(blame) = self.blame.as_mut().filter(|blame| blame.at.is_none()) { + blame.read(ctx, &self.repo.git); + } self.snapshot = snapshot; } Some(Err(error)) => self.error = Some(error.to_string()), diff --git a/crates/app/src/blame.rs b/crates/app/src/blame.rs new file mode 100644 index 0000000..e43d98d --- /dev/null +++ b/crates/app/src/blame.rs @@ -0,0 +1,87 @@ +//! Who last changed each line of a file: beside each run of lines the commit that changed them +//! last, and a click on a line shows that commit. + +use eframe::egui::{self, Align2, Color32, FontId, Key, Rect, RichText, Role, Sense, Stroke, Ui, Vec2, WidgetInfo}; + +use crate::app::{Action, Selection, Workspace}; +use crate::graph::put; +use crate::theme; + +const LINE: f32 = 18.0; +/// The width of the commit beside the lines. +const GUTTER: f32 = 400.0; + +/// Shows the blame of the workspace. +pub fn show(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { + let Workspace { blame: Some(blame), commits, repo, selection, .. } = ws else { return }; + ui.horizontal(|ui| { + ui.strong(format!("Blame of {}", blame.path)); + ui.weak(blame.at.as_ref().map_or_else(|| "in the working tree".to_owned(), |at| format!("at {at:.7}"))); + if blame.reading.is_some() { + ui.spinner(); + } else { + ui.weak(theme::count(blame.lines.len(), "line")); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Close").clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + actions.push(Action::CloseFile); + } + }); + }); + ui.separator(); + let (font, now) = (FontId::monospace(12.5), theme::now()); + ui.spacing_mut().item_spacing.y = 0.0; + egui::ScrollArea::vertical().auto_shrink(false).show_rows(ui, LINE, blame.lines.len(), |ui, rows| { + let top = ui.clip_rect().top(); + for row in rows { + let (id, text) = &blame.lines[row]; + let text = text.trim_end_matches('\r'); + let (summary, author, when) = if id.is_null() { + ("Not committed yet".to_owned(), String::new(), String::new()) + } else { + match commits.get(repo, *id) { + Ok(commit) => (commit.summary().to_owned(), commit.author.clone(), theme::when(commit.time, now)), + Err(error) => (error.to_string(), String::new(), String::new()), + } + }; + let line = if id.is_null() { Selection::Wip } else { Selection::Commit(*id) }; + let picked = *selection == Some(line); + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), LINE), Sense::click()); + let gutter = Rect::from_min_size(rect.min, Vec2::new(GUTTER, LINE)); + let painter = ui.painter_at(rect); + if picked { + painter.rect_filled(rect, 0.0, ui.visuals().selection.bg_fill); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, ui.visuals().widgets.hovered.weak_bg_fill); + } else { + painter.rect_filled(gutter, 0.0, ui.visuals().extreme_bg_color); + } + // The commit goes beside the first line of each run of lines it changed, below a line, + // and beside the top line wholly in sight, so that it stays in sight. + let run = row == 0 || blame.lines[row - 1].0 != *id; + if run { + let edge = ui.visuals().widgets.noninteractive.bg_stroke.color; + painter.hline(rect.x_range(), rect.top(), Stroke::new(1.0, edge)); + } + if run || (top..top + LINE).contains(&rect.top()) { + let column = |left: f32, right: f32| { + Rect::from_x_y_ranges(gutter.left() + left..=gutter.right() - right, rect.y_range()) + }; + if !id.is_null() { + put(ui, column(8.0, GUTTER - 64.0), RichText::new(&id.to_string()[..7]).monospace().weak()); + } + put(ui, column(72.0, 192.0), summary.as_str()); + put(ui, column(GUTTER - 184.0, 92.0), RichText::new(author).weak()); + put(ui, column(GUTTER - 84.0, 8.0), RichText::new(when).weak()); + } + let at = |x: f32| gutter.right_center() + Vec2::X * x; + painter.text(at(44.0), Align2::RIGHT_CENTER, (row + 1).to_string(), font.clone(), Color32::DARK_GRAY); + painter.text(at(56.0), Align2::LEFT_CENTER, text, font.clone(), ui.visuals().text_color()); + let name = format!("Line {}: {text} ({summary})", row + 1); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, picked, &name)); + if response.clicked() { + actions.push(Action::Reveal(line)); + } + } + }); +} diff --git a/crates/app/src/details.rs b/crates/app/src/details.rs index 3e0bc39..1fdf0eb 100644 --- a/crates/app/src/details.rs +++ b/crates/app/src/details.rs @@ -38,14 +38,20 @@ fn file(ui: &mut Ui, change: Change, path: &str, open: bool, buttons: impl FnOnc .inner } -/// The right-click menu of a file: its history from the commit `at` back, if it has one. -fn file_menu(file: &Response, at: Option<&str>, path: &str, actions: &mut Vec) { +/// The right-click menu of a file, as `change` left it in the commit `at`, if it has a history: +/// its history from there back, and who last changed each line while the file is there. From +/// `HEAD`, which the uncommitted changes go from, the blame is of the file in the working tree. +fn file_menu(file: &Response, at: Option<&str>, path: &str, change: Change, actions: &mut Vec) { let Some(at) = at else { return }; file.context_menu(|ui| { if ui.button("File history").clicked() { actions.push(Action::History { at: at.to_owned(), path: path.to_owned() }); ui.close(); } + if change != Change::Deleted && ui.button("Blame").clicked() { + actions.push(Action::Blame { at: (at != "HEAD").then(|| at.to_owned()), path: path.to_owned() }); + ui.close(); + } }); } @@ -121,7 +127,7 @@ fn changes(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { actions.push(Action::Confirm(discard(change, path))); } }); - file_menu(&response, head.filter(|_| change != Change::Untracked), path, actions); + file_menu(&response, head.filter(|_| change != Change::Untracked), path, change, actions); if let Change::Conflicted { ours, theirs } = change { let sides = underway.map(|u| [("Ours", "HEAD", ours), ("Theirs", u.theirs, theirs)]); ui.horizontal(|ui| { @@ -154,7 +160,7 @@ fn changes(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { actions.push(Action::Run(Op::Unstage(vec![path.into()]))); } }); - file_menu(&response, head, path, actions); + file_menu(&response, head, path, change, actions); if response.clicked() { actions.push(Action::Open(source)); } @@ -230,7 +236,7 @@ fn commit(ui: &mut Ui, ws: &mut Workspace, id: ObjectId, actions: &mut Vec) -> bool { + harness.state().workspace().unwrap().blame.as_ref().is_some_and(|blame| blame.reading.is_none()) +} + +#[test] +fn blame_tells_which_commit_last_changed_each_line() { + let (_dir, git) = repo(); + let change = |text: &str, message: &str| { + fs::write(git.dir().join("file.txt"), text).unwrap(); + git.apply(&Op::Stage(vec!["file.txt".into()])).unwrap(); + git.apply(&Op::Commit { message: message.into(), amend: false }).unwrap(); + }; + change("one\ntwo\nthree\n", "Count to three"); + git.run(&["config", "user.name", "Otto"]).unwrap(); + change("one\nTWO\nthree\n", "Shout two"); + fs::write(git.dir().join("file.txt"), "one\nTWO\nthree\nfour\n").unwrap(); + let mut harness = app(Some(git.dir())); + + // From the uncommitted changes, it is the file in the working tree. + harness.get_by_label("Uncommitted changes").click(); + settle(&mut harness); + menu(&mut harness, "file.txt", &["Blame"]); + wait_until(&mut harness, "the blame", blame_read); + harness.run(); + for label in ["Blame of file.txt", "in the working tree", "4 lines", "Line 1: one (Count to three)"] { + harness.get_by_label(label); + } + harness.get_by_label("Line 3: three (Count to three)"); + harness.get_by_label("Line 4: four (Not committed yet)"); + + // A line shows the commit that changed it, and the other lines it changed. + harness.get_by_label("Line 2: TWO (Shout two)").click(); + settle(&mut harness); + assert!(picked(&harness, "Line 2: TWO (Shout two)")); + assert!(!picked(&harness, "Line 1: one (Count to three)")); + harness.get_by_label("Otto "); + let ws = harness.state().workspace().unwrap(); + assert_eq!(ws.selection, Some(Selection::Commit(ws.snapshot.history.ids[0]))); + + // What changes outside shows up, before and after it is committed. + fs::write(git.dir().join("file.txt"), "one\nTWO\nthree\nfour\nfive\n").unwrap(); + wait_until(&mut harness, "the new line", |h| h.query_by_label("Line 5: five (Not committed yet)").is_some()); + change("one\nTWO\nthree\nfour\nfive\n", "Count on"); + wait_until(&mut harness, "the new commit", |h| h.query_by_label("Line 5: five (Count on)").is_some()); + harness.key_press(Key::Escape); + settle(&mut harness); + assert!(harness.state().workspace().unwrap().blame.is_none()); + + // From a commit, it is the file in that commit. + harness.get_by_role_and_label(Role::Button, "Count to three").click(); + settle(&mut harness); + menu(&mut harness, "file.txt", &["Blame"]); + wait_until(&mut harness, "the blame", blame_read); + harness.run(); + harness.get_by_label(&format!("at {}", &rev(&git, "HEAD~2")[..7])); + harness.get_by_label("Line 2: two (Count to three)"); + harness.get_by_label("Close").click(); + settle(&mut harness); + + // A file a commit deleted has a history, but no lines to blame. + git.apply(&Op::Remove(vec!["file.txt".into()])).unwrap(); + git.apply(&Op::Commit { message: "Delete the file".into(), amend: false }).unwrap(); + wait_until(&mut harness, "the commit", |h| h.query_by_role_and_label(Role::Button, "Delete the file").is_some()); + harness.get_by_role_and_label(Role::Button, "Delete the file").click(); + settle(&mut harness); + harness.get_by_label("file.txt").click_secondary(); + wait_until(&mut harness, "the menu", |h| h.query_by_label("File history").is_some()); + assert!(harness.query_by_label("Blame").is_none()); +} + #[test] fn the_changed_files_stay_in_reach_below_a_long_commit_message() { let (_dir, git) = repo(); diff --git a/crates/app/src/ui.rs b/crates/app/src/ui.rs index db79353..c12fa7f 100644 --- a/crates/app/src/ui.rs +++ b/crates/app/src/ui.rs @@ -11,7 +11,7 @@ use gitcraft_core::status::Change; use crate::app::{Action, Confirm, Prompt, Selection, Workspace}; use crate::start::Start; -use crate::{details, diff, graph, history, merge, rebase, sidebar, theme}; +use crate::{blame, details, diff, graph, history, merge, rebase, sidebar, theme}; const RECENT: usize = 10; @@ -212,6 +212,8 @@ fn workspace(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { rebase::show(ui, ws, actions); } else if ws.history.is_some() { history::show(ui, ws, actions); + } else if ws.blame.is_some() { + blame::show(ui, ws, actions); } else if let Some(file) = &ws.open_file { diff::show(ui, file, true, actions); } else { diff --git a/crates/core/src/status.rs b/crates/core/src/status.rs index 9a7405c..2cd3b65 100644 --- a/crates/core/src/status.rs +++ b/crates/core/src/status.rs @@ -1,4 +1,5 @@ -//! What changed: in the working tree (`git status`), in a commit, and to a file over time. +//! What changed: in the working tree (`git status`), in a commit, and to a file over time, down to +//! who last changed each line. use crate::git::Git; use crate::{Error, ObjectId, Result}; @@ -191,6 +192,29 @@ pub fn file_history(git: &Git, at: &str, path: &str) -> Result, path: &str) -> Result> { + parse_blame(&git.run(&[&["blame", "--porcelain"][..], at.as_slice(), &["--", path]].concat())?) +} + +/// Parses `git blame --porcelain`: for each line a header that starts with the commit, the first +/// time a commit comes up lines about it, and then the line itself after a tab. +pub fn parse_blame(output: &str) -> Result> { + let mut lines = Vec::new(); + let mut commit = None; + for line in output.split_terminator('\n') { + let bad = || Error::Parse(line.to_owned()); + if let Some(text) = line.strip_prefix('\t') { + lines.push((commit.take().ok_or_else(bad)?, text.to_owned())); + } else if commit.is_none() { + let sha = line.split(' ').next().unwrap_or_default(); + commit = Some(ObjectId::from_hex(sha.as_bytes()).map_err(|_| bad())?); + } + } + Ok(lines) +} + /// Parses `--name-status -z`. pub fn parse_name_status(output: &str) -> Result> { let mut fields = output.split('\0').filter(|f| !f.is_empty()); @@ -265,6 +289,8 @@ mod tests { assert!(Status::parse("u UU N... 100644\0").is_err()); assert!(Status::parse("# branch.ab +x -1\0").is_err()); assert!(parse_name_status("Z\0path\0").is_err()); + assert!(parse_blame("\tno header\n").is_err()); + assert!(parse_blame("not-a-sha 1 1 1\n\tline\n").is_err()); } #[test] @@ -279,4 +305,32 @@ mod tests { ] ); } + + #[test] + fn parses_blame() { + let one = "1".repeat(40); + let two = "2".repeat(40); + let output = [ + &format!("{one} 1 1 2"), + "author Tess Ter", + "summary First", + "filename a.txt", + "\tfirst line", + &format!("{one} 2 2"), + "\t\tindented, with a tab\r", + &format!("{two} 1 3 1"), + "author Other", + "summary\tlooks like a line", + "previous 1111111111111111111111111111111111111111 a.txt", + "filename a.txt", + "\t", + "", + ] + .join("\n"); + let [one, two] = [one, two].map(|sha| ObjectId::from_hex(sha.as_bytes()).unwrap()); + assert_eq!( + parse_blame(&output).unwrap(), + [(one, "first line".into()), (one, "\tindented, with a tab\r".into()), (two, String::new())] + ); + } } diff --git a/crates/core/tests/repo.rs b/crates/core/tests/repo.rs index f03d478..98c8f9f 100644 --- a/crates/core/tests/repo.rs +++ b/crates/core/tests/repo.rs @@ -273,6 +273,29 @@ fn the_history_of_a_file_follows_it_through_renames() { assert_eq!(history(&renamed), [renamed_entry, first_entry]); } +#[test] +fn blame_tells_which_commit_last_changed_each_line() { + let (_dir, git) = repo(); + let first = commit(&git, "old.txt", "one\ntwo\nthree\n", "Count"); + git.run(&["mv", "old.txt", "new.txt"]).unwrap(); + let second = commit(&git, "new.txt", "one\nTWO\nthree\n", "Rename and shout"); + write(&git, "new.txt", "one\nTWO\nthree\nfour\n"); + + let blame = |at: Option<&str>, path: &str| { + let lines = status::blame(&git, at, path).unwrap(); + lines.into_iter().map(|(id, text)| (id.to_string(), text)).collect::>() + }; + let line = |sha: &str, text: &str| (sha.to_owned(), text.to_owned()); + let committed = [line(&first, "one"), line(&second, "TWO"), line(&first, "three")]; + // Through the rename. + assert_eq!(blame(Some("HEAD"), "new.txt"), committed); + // In the working tree, a line not committed yet has no commit. + assert_eq!(blame(None, "new.txt"), [&committed[..], &[line(&"0".repeat(40), "four")]].concat()); + // In an older commit, as it was there. + assert_eq!(blame(Some(&first), "old.txt"), [line(&first, "one"), line(&first, "two"), line(&first, "three")]); + assert!(status::blame(&git, Some(&first), "new.txt").is_err(), "the file is not in that commit"); +} + #[test] fn commit_amend_branch_and_checkout() { let (_dir, git) = repo();