use super::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileHistoryEntry {
pub short_hash: String,
pub summary: String,
pub author: String,
pub age_secs: i64,
}
pub(super) fn file_cwd(root: &Path, rel_path: &str) -> (PathBuf, String) {
let abs = root.join(rel_path);
match (abs.parent(), abs.file_name().and_then(|n| n.to_str())) {
(Some(dir), Some(name)) if dir.is_dir() => (dir.to_path_buf(), name.to_string()),
_ => (root.to_path_buf(), rel_path.to_string()),
}
}
pub(super) fn repo_top_and_path(root: &Path, rel_path: &str) -> (PathBuf, String) {
let (dir, name) = file_cwd(root, rel_path);
let out = run_git(&dir, &["rev-parse", "--show-toplevel", "--show-prefix"]);
let mut lines = out.as_deref().unwrap_or_default().lines();
match lines.next() {
Some(top) if !top.is_empty() => {
let prefix = lines.next().unwrap_or_default();
(PathBuf::from(top), format!("{prefix}{name}"))
}
_ => (root.to_path_buf(), rel_path.to_string()),
}
}
pub fn file_history(root: &Path, rel_path: &str, limit: usize) -> Vec<FileHistoryEntry> {
let (dir, name) = file_cwd(root, rel_path);
let Some(path_str) = dir.to_str() else {
return Vec::new();
};
let output = Git::new()
.at(path_str)
.args([
"log",
"--follow",
&format!("-n{limit}"),
"--format=%h\x1f%s\x1f%an\x1f%ct",
"--",
&name,
])
.into_command()
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_file_history(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
pub fn parse_file_history(out: &str, now: i64) -> Vec<FileHistoryEntry> {
out.lines()
.filter_map(|line| {
let mut parts = line.split('\x1f');
let short_hash = parts.next()?.to_string();
let summary = parts.next()?.to_string();
let author = parts.next()?.to_string();
let ct: i64 = parts.next()?.trim().parse().ok()?;
if short_hash.is_empty() {
return None;
}
Some(FileHistoryEntry {
short_hash,
summary,
author,
age_secs: now - ct,
})
})
.collect()
}
pub fn show_commit_file_diff(root: &Path, hash: &str, rel_path: &str) -> Result<String, String> {
let (top, path) = repo_top_and_path(root, rel_path);
let (root, rel_path) = (top.as_path(), path.as_str());
if path_filter(root, rel_path).is_some() {
return filtered_commit_file_diff(root, hash, rel_path);
}
let has_diff = |raw: &str| raw.lines().any(|l| l.starts_with("diff --git"));
let raw = diff_text(root, &["show", hash, "--", rel_path])?;
if has_diff(&raw) {
return Ok(raw);
}
match path_at_commit(root, hash, rel_path) {
Some(old) if old != rel_path => diff_text(root, &["show", hash, "--", &old]),
_ => Ok(raw),
}
}
pub fn follow_names(root: &Path, rel_path: &str, limit: usize) -> Vec<(String, String)> {
let Ok(out) = run_git(
root,
&[
"log",
"--follow",
"--first-parent",
&format!("-n{limit}"),
"--name-only",
"--relative",
"--format=%x1e%H",
"--",
rel_path,
],
) else {
return Vec::new();
};
out.split('\x1e')
.filter_map(|record| {
let mut lines = record.lines();
let hash = lines.next()?.trim();
let path = lines.map(str::trim).find(|l| !l.is_empty())?;
(!hash.is_empty()).then(|| (hash.to_string(), unquote_porcelain_path(path)))
})
.collect()
}
pub(super) fn filtered_commit_file_diff(
root: &Path,
hash: &str,
rel_path: &str,
) -> Result<String, String> {
let name = match read_file_at_rev(root, hash, rel_path) {
Ok(_) => rel_path.to_string(),
Err(_) => path_at_commit(root, hash, rel_path).unwrap_or_else(|| rel_path.to_string()),
};
let new = read_file_at_rev(root, hash, &name)?;
let old = read_file_at_rev(root, &format!("{hash}^"), &name).unwrap_or_default();
let body = similar::TextDiff::from_lines(&old, &new)
.unified_diff()
.header(&format!("a/{name}"), &format!("b/{name}"))
.to_string();
let header = diff_text(root, &["show", "-s", hash])?;
Ok(format!("{header}\ndiff --git a/{name} b/{name}\n{body}"))
}
pub(super) fn path_at_commit(root: &Path, hash: &str, rel_path: &str) -> Option<String> {
let out = run_git(
root,
&[
"log",
"--follow",
"-n200",
"--name-only",
"--format=%x1e%H",
"--",
rel_path,
],
)
.ok()?;
out.split('\x1e').find_map(|record| {
let mut lines = record.lines();
let full = lines.next()?.trim();
if hash.is_empty() || !full.starts_with(hash) {
return None;
}
lines
.map(str::trim)
.find(|l| !l.is_empty())
.map(unquote_porcelain_path)
})
}
pub fn show_commit(root: &Path, hash: &str) -> Result<String, String> {
diff_text(root, &["show", "--stat", "--patch", hash])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphCommit {
pub hash: String,
pub short_hash: String,
pub parents: Vec<String>,
pub refs: Vec<String>,
pub summary: String,
pub author: String,
pub age_secs: i64,
}
pub fn commit_graph(root: &Path, limit: usize) -> Vec<GraphCommit> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Git::new()
.at(path_str)
.args([
"log",
"--branches",
"--tags",
"HEAD",
"--topo-order",
&format!("-n{limit}"),
"--format=%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct",
])
.into_command()
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_commit_graph(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
pub fn branch_history(root: &Path, limit: usize) -> Vec<GraphCommit> {
branch_history_range(root, "HEAD", limit)
}
pub fn branch_history_range(root: &Path, revspec: &str, limit: usize) -> Vec<GraphCommit> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Git::new()
.at(path_str)
.args([
"log",
"--first-parent",
revspec,
&format!("-n{limit}"),
"--format=%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct",
])
.into_command()
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
parse_commit_graph(&String::from_utf8_lossy(&output.stdout), now)
}
#[derive(Debug, Default)]
pub struct CommitTree {
pub paths: HashSet<PathBuf>,
pub submodules: Vec<PathBuf>,
}
impl CommitTree {
pub fn contains(&self, path: &Path) -> bool {
self.paths.contains(path) || self.submodules.iter().any(|s| path.starts_with(s))
}
}
pub fn tree_paths(root: &Path, rev: &str) -> Option<CommitTree> {
let output = Git::new()
.at(root)
.without_optional_locks()
.args(["ls-tree", "-r", "-t", "-z", rev])
.into_command()
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let mut tree = CommitTree::default();
for entry in output.stdout.split(|b| *b == 0).filter(|s| !s.is_empty()) {
let Some(tab) = entry.iter().position(|b| *b == b'\t') else {
continue;
};
let path = join_raw(root, &entry[tab + 1..]);
if entry[..tab].split(|b| *b == b' ').nth(1) == Some(b"commit") {
tree.submodules.push(path.clone());
}
tree.paths.insert(path);
}
Some(tree)
}
pub fn parse_commit_graph(out: &str, now: i64) -> Vec<GraphCommit> {
out.lines()
.filter_map(|line| {
let mut parts = line.split('\x1f');
let hash = parts.next()?.to_string();
let short_hash = parts.next()?.to_string();
let parents: Vec<String> = parts
.next()?
.split_whitespace()
.map(str::to_string)
.collect();
let refs: Vec<String> = parts
.next()?
.split(", ")
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
let summary = parts.next()?.to_string();
let author = parts.next()?.to_string();
let ct: i64 = parts.next()?.trim().parse().ok()?;
if hash.is_empty() {
return None;
}
Some(GraphCommit {
hash,
short_hash,
parents,
refs,
summary,
author,
age_secs: (now - ct).max(0),
})
})
.collect()
}
pub fn commit_message(root: &Path, hash: &str) -> Result<String, String> {
run_git(root, &["log", "-1", "--format=%B", hash])
.map(|m| m.trim().to_string())
.map_err(|e| e.to_string())
}
pub fn commit_card(dir: &Path, hash: &str) -> Result<String, String> {
let format = "--format=%an <%ae>%n%ad (%ar)%ncommit %h%n%n%B";
run_git(dir, &["log", "-1", "--no-show-signature", format, hash]).map_err(|e| e.to_string())
}
pub fn humanize_age(secs_ago: i64) -> String {
let s = secs_ago.max(0);
if s < 60 {
return format!("{s} seconds ago");
}
let m = s / 60;
if m < 60 {
return format!("{m} minute{} ago", if m == 1 { "" } else { "s" });
}
let h = m / 60;
if h < 24 {
return format!("{h} hour{} ago", if h == 1 { "" } else { "s" });
}
let d = h / 24;
if d < 30 {
return format!("{d} day{} ago", if d == 1 { "" } else { "s" });
}
let mo = d / 30;
if mo < 12 {
return format!("{mo} month{} ago", if mo == 1 { "" } else { "s" });
}
let y = mo / 12;
format!("{y} year{} ago", if y == 1 { "" } else { "s" })
}
pub(super) fn current_unix_seconds() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub type RailCell = (char, usize);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphRow {
pub commit: GraphCommit,
pub cells: Vec<RailCell>,
}
pub fn layout_graph(commits: Vec<GraphCommit>) -> Vec<GraphRow> {
let mut lanes: Vec<Option<String>> = Vec::new();
let mut rows = Vec::with_capacity(commits.len());
for c in commits {
let node_lane = match lanes
.iter()
.position(|l| l.as_deref() == Some(c.hash.as_str()))
{
Some(i) => i,
None => match lanes.iter().position(|l| l.is_none()) {
Some(i) => i,
None => {
lanes.push(None);
lanes.len() - 1
}
},
};
let closing: Vec<usize> = lanes
.iter()
.enumerate()
.filter(|(i, l)| *i != node_lane && l.as_deref() == Some(c.hash.as_str()))
.map(|(i, _)| i)
.collect();
let before: Vec<bool> = lanes.iter().map(|l| l.is_some()).collect();
lanes[node_lane] = c.parents.first().cloned();
for &i in &closing {
lanes[i] = None;
}
let mut opening: Vec<usize> = Vec::new();
for p in c.parents.iter().skip(1) {
match lanes.iter().position(|l| l.as_deref() == Some(p.as_str())) {
Some(i) => opening.push(i),
None => {
let i = match lanes.iter().position(|l| l.is_none()) {
Some(free) if free > node_lane => free,
_ => {
lanes.push(None);
lanes.len() - 1
}
};
lanes[i] = Some(p.clone());
opening.push(i);
}
}
}
let width = lanes.len().max(before.len());
let mut span_min = node_lane;
let mut span_max = node_lane;
for &i in closing.iter().chain(opening.iter()) {
span_min = span_min.min(i);
span_max = span_max.max(i);
}
let mut cells: Vec<RailCell> = Vec::with_capacity(width);
for i in 0..width {
let before_occ = before.get(i).copied().unwrap_or(false);
let after_occ = lanes.get(i).is_some_and(|l| l.is_some());
let ch = if i == node_lane {
'●'
} else if closing.contains(&i) {
if i > node_lane { '╯' } else { '╰' }
} else if opening.contains(&i) {
if before_occ {
if i > node_lane { '┤' } else { '├' }
} else if i > node_lane {
'╮'
} else {
'╭'
}
} else if before_occ && after_occ {
if i > span_min && i < span_max {
'┼'
} else {
'│'
}
} else if i > span_min && i < span_max {
'─'
} else {
' '
};
cells.push((ch, i));
}
while cells.last().is_some_and(|(ch, _)| *ch == ' ') {
cells.pop();
}
rows.push(GraphRow { commit: c, cells });
while lanes.last().is_some_and(|l| l.is_none()) {
lanes.pop();
}
}
rows
}
#[cfg(test)]
mod graph_tests {
use super::*;
fn commit(hash: &str, parents: &[&str]) -> GraphCommit {
GraphCommit {
hash: hash.to_string(),
short_hash: hash.chars().take(7).collect(),
parents: parents.iter().map(|p| p.to_string()).collect(),
refs: Vec::new(),
summary: format!("commit {hash}"),
author: "vitali87".to_string(),
age_secs: 3600,
}
}
fn rails(rows: &[GraphRow]) -> Vec<String> {
rows.iter()
.map(|r| r.cells.iter().map(|(ch, _)| *ch).collect())
.collect()
}
#[test]
fn linear_history_is_a_single_node_column() {
let rows = layout_graph(vec![
commit("c", &["b"]),
commit("b", &["a"]),
commit("a", &[]),
]);
assert_eq!(rails(&rows), vec!["●", "●", "●"]);
assert!(rows.iter().all(|r| r.cells[0].1 == 0));
}
#[test]
fn merge_opens_a_lane_and_the_branch_point_closes_it() {
let rows = layout_graph(vec![
commit("m", &["a", "b"]),
commit("a", &["r"]),
commit("b", &["r"]),
commit("r", &[]),
]);
assert_eq!(
rails(&rows),
vec![
"●╮", "●│", "│●", "●╯", ]
);
assert_eq!(rows[0].cells[1].1, 1);
assert_eq!(rows[2].cells[1].1, 1);
assert_eq!(rows[3].cells[1].1, 1);
}
#[test]
fn second_branch_tip_gets_its_own_lane_without_a_merge() {
let rows = layout_graph(vec![
commit("t", &["a"]),
commit("u", &["a"]),
commit("a", &[]),
]);
assert_eq!(rails(&rows), vec!["●", "│●", "●╯"]);
}
#[test]
fn pass_through_lane_crosses_a_long_connector() {
let rows = layout_graph(vec![
commit("m", &["a", "c"]),
commit("x", &["b"]),
commit("c", &["y"]),
commit("a", &["z1"]),
commit("b", &["z2"]),
commit("y", &["z3"]),
]);
assert_eq!(rows[0].cells[0].0, '●');
assert!(
rows[0].cells.iter().any(|(ch, _)| *ch == '╮'),
"the merge's second parent must open a rail; got {:?}",
rails(&rows)
);
}
#[test]
fn merge_into_an_expected_lane_junctions_instead_of_opening() {
let rows = layout_graph(vec![
commit("x", &["b"]),
commit("m", &["a", "b"]),
commit("b", &[]),
]);
assert_eq!(
rails(&rows),
vec![
"●", "├●", "●│", ]
);
}
}