use std::{
cell::OnceCell,
collections::BTreeMap,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{
RepoPath, RepoRoot,
git::{self, Git, MIN_GIT},
model::core_fields,
source::{self, Source},
yaml,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum When {
Commit(String),
WorkingTree,
}
#[derive(Debug, Clone)]
pub(crate) struct Change {
pub(crate) when: When,
pub(crate) time: i64,
pub(crate) before: Option<String>,
pub(crate) after: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Failed;
#[derive(Debug, Clone, Default)]
pub(crate) struct Changes {
pub(crate) document: Vec<Change>,
pub(crate) asset: Vec<Change>,
}
#[derive(Debug)]
pub(crate) struct History {
git: Git,
head: Option<String>,
now: i64,
readable: OnceCell<bool>,
renames: OnceCell<Option<BTreeMap<String, String>>>,
deleted: OnceCell<Option<Vec<RepoPath>>>,
}
impl History {
pub(crate) fn open(root: &RepoRoot) -> History {
let git = Git::new(root.as_path());
let head = git.head();
History {
git,
head,
now: now(),
readable: OnceCell::new(),
renames: OnceCell::new(),
deleted: OnceCell::new(),
}
}
pub(crate) fn head(&self) -> &str {
self.head.as_deref().unwrap_or_default()
}
pub(crate) fn readable(&self) -> bool {
*self.readable.get_or_init(|| {
self.head.is_some()
&& git::version().is_some_and(|v| v >= MIN_GIT)
&& self.git.is_top()
&& self.git.partial().is_none()
&& !self.git.is_shallow()
})
}
pub(crate) fn changes(
&self,
path: &RepoPath,
text: &str,
id: Option<&str>,
asset: Option<&RepoPath>,
) -> Result<Changes, Failed> {
let mut entries = log(&self.git, path)?;
let mut from = None;
if entries.first().is_none_or(|e| e.after.is_none()) {
from = self.moved_from(path, id)?;
entries = match &from {
Some(from) => log(&self.git, from)?,
None => Vec::new(),
};
}
let document = self.document(&entries, from.as_ref().unwrap_or(path), path, text)?;
let asset = match asset {
Some(asset) => {
let before = from
.as_ref()
.and_then(RepoPath::parent)
.and_then(|dir| RepoPath::parse(&format!("{dir}/{}", asset.file_name())));
self.asset(asset, before.as_ref())?
}
None => Vec::new(),
};
Ok(Changes { document, asset })
}
fn document(
&self,
entries: &[Entry],
head_path: &RepoPath,
path: &RepoPath,
text: &str,
) -> Result<Vec<Change>, Failed> {
let texts = self.git.blobs(
entries
.iter()
.flat_map(|e| [e.before.as_deref(), e.after.as_deref()])
.flatten(),
);
let text_of = |oid: &Option<String>| {
oid.as_ref()
.and_then(|o| texts.get(o).cloned().flatten())
.map(|t| t.replace("\r\n", "\n"))
};
let head = entries.first().and_then(|e| e.after.as_ref());
let mut changes = Vec::new();
if head.is_none() || listed(&self.git, path)? {
let before = head.and_then(|_| {
self.git
.run(&[
"cat-file",
"--filters",
&format!("HEAD:{}", head_path.relative()),
])
.and_then(|out| String::from_utf8(out).ok())
.map(|t| t.replace("\r\n", "\n"))
.or_else(|| entries.first().and_then(|e| text_of(&e.after)))
});
changes.push(Change {
when: When::WorkingTree,
time: self.now,
before,
after: Some(text.to_string()),
});
}
changes.extend(commits(entries, text_of));
Ok(changes)
}
fn asset(&self, path: &RepoPath, before: Option<&RepoPath>) -> Result<Vec<Change>, Failed> {
let mut entries = log(&self.git, path)?;
if entries.first().is_none_or(|e| e.after.is_none()) {
entries = match before {
Some(before) => log(&self.git, before)?,
None => Vec::new(),
};
}
let Some(head) = entries.first().and_then(|e| e.after.clone()) else {
return Ok(commits(&entries, |_| None).collect());
};
let mut changes = Vec::new();
let changed = hash(&self.git, path)? != head;
if changed {
changes.push(Change {
when: When::WorkingTree,
time: self.now,
before: None,
after: None,
});
}
changes.extend(commits(&entries, |_| None));
Ok(changes)
}
fn moved_from(&self, path: &RepoPath, id: Option<&str>) -> Result<Option<RepoPath>, Failed> {
let renames = self.renames.get_or_init(|| {
let out = self.git.run(&[
"diff-index",
"--cached",
"-M",
"--raw",
"-z",
"--no-color",
"HEAD",
])?;
Some(
git::raw(&out)
.into_iter()
.filter(|r| r.status.starts_with('R'))
.filter_map(|r| match r.paths.as_slice() {
[from, to] => Some((to.clone(), from.clone())),
_ => None,
})
.collect(),
)
});
let renames = renames.as_ref().ok_or(Failed)?;
if let Some(from) = renames.get(path.relative()) {
return Ok(RepoPath::parse(&format!("/{from}")));
}
let Some(id) = id else {
return Ok(None);
};
let deleted = self.deleted.get_or_init(|| {
let out = self.git.run(&["ls-files", "--deleted", "-z"])?;
Some(
out.split(|b| *b == 0)
.filter_map(|p| RepoPath::parse(&format!("/{}", String::from_utf8_lossy(p))))
.collect(),
)
});
let named: Vec<(RepoPath, String)> = deleted
.as_ref()
.ok_or(Failed)?
.iter()
.filter(|p| p.file_name() == path.file_name())
.cloned()
.map(|p| {
let object = format!("HEAD:{}", p.relative());
(p, object)
})
.collect();
let texts = self.git.blobs(named.iter().map(|(_, o)| o.as_str()));
let mut same = named.into_iter().filter(|(p, object)| {
texts
.get(object)
.cloned()
.flatten()
.is_some_and(|t| id_of(p, &t).as_deref() == Some(id))
});
Ok(match (same.next(), same.next()) {
(Some((from, _)), None) => Some(from),
_ => None,
})
}
}
fn commits<'a>(
entries: &'a [Entry],
text_of: impl Fn(&Option<String>) -> Option<String> + 'a,
) -> impl Iterator<Item = Change> + 'a {
entries
.iter()
.filter(|e| e.before != e.after)
.map(move |e| Change {
when: When::Commit(e.commit.clone()),
time: e.time,
before: text_of(&e.before),
after: text_of(&e.after),
})
}
fn id_of(path: &RepoPath, text: &str) -> Option<String> {
let source = Source::from_text(path.clone(), text);
let (front, line) = source::split(&source).frontmatter?;
core_fields(Some(yaml::parse(front, line).as_ref()), path).id
}
fn listed(git: &Git, path: &RepoPath) -> Result<bool, Failed> {
git.run(&[
"--no-optional-locks",
"status",
"--porcelain",
"-z",
"--untracked-files=all",
"--",
path.relative(),
])
.map(|out| !out.is_empty())
.ok_or(Failed)
}
fn hash(git: &Git, path: &RepoPath) -> Result<String, Failed> {
if !path.to_fs(&RepoRoot::new(git.dir.clone())).exists() {
return Ok(String::new());
}
git.text(&["hash-object", "--", path.relative()])
.ok_or(Failed)
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.and_then(|d| i64::try_from(d.as_secs()).ok())
.unwrap_or(i64::MAX)
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Entry {
commit: String,
time: i64,
before: Option<String>,
after: Option<String>,
}
fn log(git: &Git, path: &RepoPath) -> Result<Vec<Entry>, Failed> {
let out = git
.run(&[
"log",
"-m",
"--first-parent",
"--follow",
"--root",
"--raw",
"--no-abbrev",
"--no-color",
"--no-show-signature",
"-z",
"--format=commit %H %ct",
"HEAD",
"--",
path.relative(),
])
.ok_or(Failed)?;
Ok(entries(&out))
}
fn entries(out: &[u8]) -> Vec<Entry> {
git::raw(out)
.into_iter()
.filter_map(|r| {
let header = r.header?;
let mut parts = header.strip_prefix("commit ")?.split(' ');
let commit = parts.next()?.to_string();
let time = parts.next()?.parse().ok()?;
Some(Entry {
commit,
time,
before: r.before,
after: r.after,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_entries_of_a_log_hold_each_change_with_its_commit() {
let out = b"commit aaa 200\0\n:100644 100644 1111 2222 M\0b/x.md\0\0commit bbb 100\0\n:100644 100644 1111 1111 R100\0a/x.md\0b/x.md\0\0commit ccc 50\0\n:000000 100644 0000 1111 A\0a/x.md\0";
let found = entries(out);
assert_eq!(
found,
[
Entry {
commit: "aaa".into(),
time: 200,
before: Some("1111".into()),
after: Some("2222".into()),
},
Entry {
commit: "bbb".into(),
time: 100,
before: Some("1111".into()),
after: Some("1111".into()),
},
Entry {
commit: "ccc".into(),
time: 50,
before: None,
after: Some("1111".into()),
},
]
);
}
#[test]
fn a_log_without_commits_holds_no_entry() {
let empty = entries(b"");
assert!(empty.is_empty(), "{empty:?}");
let headless = entries(b":100644 100644 1 2 M\0x\0");
assert!(headless.is_empty(), "{headless:?}");
}
}