Skip to content
Draft
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
11 changes: 11 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,17 @@ pub struct StyleConfig {
pub branch: StyleConfigEntry,
pub remote: StyleConfigEntry,
pub tag: StyleConfigEntry,

#[serde(default)]
pub blame: BlameStyleConfig,
}

#[derive(Default, Debug, Deserialize)]
pub struct BlameStyleConfig {
#[serde(default)]
pub line_num: StyleConfigEntry,
#[serde(default)]
pub code_line: StyleConfigEntry,
}

#[derive(Default, Debug, Deserialize)]
Expand Down
4 changes: 4 additions & 0 deletions src/default_config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ branch = { fg = "green" }
remote = { fg = "red" }
tag = { fg = "yellow" }

blame.line_num = { mods = "DIM" }
blame.code_line = { mods = "DIM" }

[bindings]
root.quit = ["q", "esc"]
root.refresh = ["g"]
Expand All @@ -121,6 +124,7 @@ root.unstage = ["u"]
root.apply = ["a"]
root.reverse = ["v"]
root.copy_hash = ["y"]
root.blame = ["B"]

picker.next = ["down", "ctrl+n", "tab"]
picker.previous = ["up", "ctrl+p", "backtab"]
Expand Down
2 changes: 2 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub enum Error {
GetBranchName(git2::Error),
BaseCommitOid,
UpstreamCommitOid,
GitBlame(io::Error),
}

impl std::error::Error for Error {}
Expand Down Expand Up @@ -164,6 +165,7 @@ impl Display for Error {
Error::UpstreamCommitOid => {
f.write_str("Could not resolve OID of upstream branch commit")
}
Error::GitBlame(e) => f.write_fmt(format_args!("Git blame error: {e}")),
}
}
}
Expand Down
93 changes: 93 additions & 0 deletions src/git/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,99 @@ pub(crate) fn does_branch_exist(repo: &git2::Repository, name: &str) -> Res<bool
}
}

#[derive(Debug, Clone)]
pub(crate) struct BlameLine {
pub commit_hash: String,
pub short_hash: String,
pub author: String,
pub time_str: String,
pub summary: String,
pub line_num: u32,
pub content: String,
}

pub(crate) fn blame(repo: &Repository, file_path: &str, commit: Option<&str>) -> Res<Vec<BlameLine>> {
let dir = repo.workdir().expect("Bare repos unhandled");

let mut args = vec!["blame", "--line-porcelain"];
let commit_owned;
if let Some(c) = commit {
commit_owned = c.to_string();
args.push(commit_owned.as_str());
}
args.extend_from_slice(&["--", file_path]);

let output = Command::new("git")
.current_dir(dir)
.args(&args)
.output()
.map_err(Error::GitBlame)?;

if !output.status.success() {
return Ok(vec![]);
}

let text = String::from_utf8_lossy(&output.stdout).into_owned();
Ok(parse_blame_porcelain(&text))
}

fn parse_blame_porcelain(text: &str) -> Vec<BlameLine> {
let mut lines = text.lines();
let mut result = Vec::new();

while let Some(header) = lines.next() {
let parts: Vec<&str> = header.splitn(4, ' ').collect();
if parts.len() < 3 || parts[0].len() < 8 {
continue;
}

let commit_hash = parts[0].to_string();
let short_hash = commit_hash[..8].to_string();
let line_num: u32 = parts[2].parse().unwrap_or(0);

let mut author = String::new();
let mut author_time: i64 = 0;
let mut summary = String::new();
let mut content = String::new();

loop {
match lines.next() {
Some(line) if line.starts_with('\t') => {
content = line[1..].to_string();
break;
}
Some(line) if line.starts_with("author ") => {
author = line["author ".len()..].to_string();
}
Some(line) if line.starts_with("author-time ") => {
author_time = line["author-time ".len()..].parse().unwrap_or(0);
}
Some(line) if line.starts_with("summary ") => {
summary = line["summary ".len()..].to_string();
}
Some(_) => {}
None => break,
}
}

let time_str = chrono::DateTime::from_timestamp(author_time, 0)
.map(|t| t.format("%Y-%m-%d %H:%M").to_string())
.unwrap_or_default();

result.push(BlameLine {
commit_hash,
short_hash,
author,
time_str,
summary,
line_num,
content,
});
}

result
}

pub(crate) fn restore_index(file: &Path) -> Command {
let mut cmd = Command::new("git");
cmd.args(["restore", "--staged"]);
Expand Down
37 changes: 37 additions & 0 deletions src/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,43 @@ pub(crate) fn iter_syntax_highlights<'a>(
.peekable()
}

pub(crate) fn highlight_blame_file(
config: &Config,
file_path: &str,
content: String,
) -> BlameHighlights {
let mut highlights_iter =
iter_syntax_highlights(&config.style.syntax_highlight, file_path, content.clone());

let mut result = BlameHighlights {
spans: vec![],
line_index: vec![],
};

for (line_range, _) in line_range_iterator(&content) {
let start = result.spans.len();
collect_line_highlights(&mut highlights_iter, &line_range, &mut result.spans);
result.line_index.push(start..result.spans.len());
}

result
}

#[derive(Debug, Clone)]
pub struct BlameHighlights {
spans: Vec<(Range<usize>, Style)>,
line_index: Vec<Range<usize>>,
}

impl BlameHighlights {
pub fn get_line_highlights(&self, line: usize) -> &[(Range<usize>, Style)] {
if line >= self.line_index.len() {
return &[];
}
&self.spans[self.line_index[line].clone()]
}
}

pub(crate) fn fill_gaps<T: Clone + Default>(
full_range: Range<usize>,
ranges: impl Iterator<Item = (Range<usize>, T)>,
Expand Down
28 changes: 27 additions & 1 deletion src/item_data.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{ops::Range, path::PathBuf, rc::Rc};

use crate::{Res, error::Error, git::diff::Diff};
use crate::{Res, error::Error, git::diff::Diff, highlight::BlameHighlights};

#[derive(Clone, Debug)]
pub(crate) enum ItemData {
Expand Down Expand Up @@ -43,6 +43,27 @@ pub(crate) enum ItemData {
Header(SectionHeader),
BranchStatus(String, u32, u32),
Error(String),
BlameHeader {
commit_hash: String,
short_hash: String,
author: String,
time_str: String,
summary: String,
file_path: String,
},
BlameCodeLine {
blame_file: Rc<BlameFile>,
line_i: usize,
line_num: u32,
content: String,
commit_hash: String,
file_path: String,
},
}

#[derive(Debug)]
pub(crate) struct BlameFile {
pub highlights: BlameHighlights,
}

impl ItemData {
Expand Down Expand Up @@ -72,6 +93,10 @@ impl ItemData {
.cloned()
.map(Rev::Ref)
.or_else(|| Some(Rev::Commit(oid.to_owned()))),
ItemData::BlameHeader { commit_hash, .. }
| ItemData::BlameCodeLine { commit_hash, .. } => {
Some(Rev::Commit(commit_hash.clone()))
}
_ => None,
}
}
Expand Down Expand Up @@ -157,4 +182,5 @@ pub(crate) enum SectionHeader {
StagedChanges(usize),
UnstagedChanges(usize),
UntrackedFiles(usize),
Blame(String, String),
}
36 changes: 36 additions & 0 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::item_data::Ref;
use crate::item_data::SectionHeader;
use git2::Oid;
use git2::Repository;
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::text::Span;
use regex::Regex;
Expand Down Expand Up @@ -153,6 +154,9 @@ impl Item {
SectionHeader::StagedChanges(count) => format!("Staged changes ({count})"),
SectionHeader::UnstagedChanges(count) => format!("Unstaged changes ({count})"),
SectionHeader::UntrackedFiles(count) => format!("Untracked files ({count})"),
SectionHeader::Blame(file, commit) => {
format!("Blame {file} @ {commit}")
}
};

Line::styled(content, &config.style.section_header)
Expand All @@ -173,6 +177,38 @@ impl Item {
Line::raw(content)
}
ItemData::Error(err) => Line::raw(err),
ItemData::BlameHeader {
short_hash,
summary,
..
} => Line::from(vec![
Span::styled(format!("{:<8}", short_hash), &config.style.hash),
Span::raw(" "),
Span::raw(summary.clone()),
]),
ItemData::BlameCodeLine {
blame_file,
line_i,
line_num,
content,
..
} => {
let mut spans = vec![Span::styled(
format!("{:>4} ", line_num),
&config.style.blame.line_num,
)];

for (range, style) in blame_file.highlights.get_line_highlights(line_i) {
if !range.is_empty() && range.end <= content.len() {
spans.push(Span::styled(
content[range.clone()].replace('\t', " "),
*style,
));
}
}

Line::from(spans).style(Style::from(&config.style.blame.code_line))
}
}
}
}
Expand Down
57 changes: 57 additions & 0 deletions src/ops/blame.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use super::OpTrait;
use crate::{Action, app::State, error::Error, item_data::ItemData, screen};
use std::{rc::Rc, sync::Arc};

pub(crate) struct Blame;
impl OpTrait for Blame {
fn get_action(&self, target: &ItemData) -> Option<Action> {
match target {
ItemData::Delta { diff, file_i } => {
let file_path = diff.file_diffs[*file_i]
.header
.new_file
.fmt(&diff.text)
.to_string();
open_blame(file_path, None)
}
ItemData::BlameHeader {
commit_hash,
file_path,
..
}
| ItemData::BlameCodeLine {
commit_hash,
file_path,
..
} => {
let parent = format!("{}^", commit_hash);
open_blame(file_path.clone(), Some(parent))
}
_ => None,
}
}

fn is_target_op(&self) -> bool {
true
}

fn display(&self, _state: &State) -> String {
"Blame".into()
}
}

fn open_blame(file_path: String, commit: Option<String>) -> Option<Action> {
Some(Rc::new(move |app, term| {
app.state.screens.push(
screen::blame::create(
Arc::clone(&app.state.config),
Rc::clone(&app.state.repo),
term.size().map_err(Error::Term)?,
file_path.clone(),
commit.clone(),
)
.expect("Couldn't create blame screen"),
);
Ok(())
}))
}
3 changes: 3 additions & 0 deletions src/ops/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
use std::{fmt::Display, rc::Rc};

pub(crate) mod apply;
pub(crate) mod blame;
pub(crate) mod branch;
pub(crate) mod cherry_pick;
pub(crate) mod commit;
Expand Down Expand Up @@ -110,6 +111,7 @@ pub(crate) enum Op {
Apply,
Reverse,
CopyHash,
Blame,

ToggleSection,
MoveUp,
Expand Down Expand Up @@ -203,6 +205,7 @@ impl Op {
Op::Apply => Box::new(apply::Apply),
Op::Reverse => Box::new(reverse::Reverse),
Op::CopyHash => Box::new(copy_hash::CopyHash),
Op::Blame => Box::new(blame::Blame),

Op::AddRemote => Box::new(remote::AddRemote),
Op::RemoveRemote => Box::new(remote::RemoveRemote),
Expand Down
2 changes: 2 additions & 0 deletions src/ops/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ impl OpTrait for Show {
kind: Ref::Head(oid),
..
} => goto_show_screen(oid.clone()),
ItemData::BlameHeader { commit_hash, .. }
| ItemData::BlameCodeLine { commit_hash, .. } => goto_show_screen(commit_hash.clone()),
ItemData::Untracked(u) => editor(u.as_path(), None),
ItemData::Delta { diff, file_i } => {
let file_path = &diff.file_diffs[*file_i].header.new_file;
Expand Down
Loading
Loading