use anyhow::{Context, Result, bail};
use std::io::{BufRead, BufReader, Read};
use std::process::{Command, Stdio};
use crate::record::{Record, parse_note};
pub const NOTES_REF: &str = "refs/notes/tak";
const REMOTE_REF: &str = "refs/notes/tak-remote";
const FETCH_REFSPEC: &str = "+refs/notes/tak:refs/notes/tak-remote";
const PUSH_REFSPEC: &str = "refs/notes/tak:refs/notes/tak";
const USER_FETCH_REFSPEC: &str = "+refs/notes/tak:refs/notes/tak";
const PUSH_ATTEMPTS: u32 = 5;
fn git(args: &[&str]) -> Result<String> {
let out = Command::new("git")
.args(args)
.output()
.with_context(|| format!("failed to run `git {}`", args.join(" ")))?;
if !out.status.success() {
bail!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
}
fn identity_args() -> Vec<&'static str> {
let configured = |key: &str| {
Command::new("git")
.args(["config", "--get", key])
.output()
.map(|o| o.status.success())
.unwrap_or(false)
};
let mut args = Vec::new();
if !configured("user.name") {
args.extend_from_slice(&["-c", "user.name=tak"]);
}
if !configured("user.email") {
args.extend_from_slice(&["-c", "user.email=tak@localhost"]);
}
args
}
fn git_committing(args: &[&str]) -> Result<String> {
let mut full = identity_args();
full.extend_from_slice(args);
git(&full)
}
fn git_ok(args: &[&str]) -> Result<(bool, String)> {
let out = Command::new("git")
.args(args)
.output()
.with_context(|| format!("failed to run `git {}`", args.join(" ")))?;
let text = if out.status.success() {
String::from_utf8_lossy(&out.stdout).trim_end().to_string()
} else {
String::from_utf8_lossy(&out.stderr).trim_end().to_string()
};
Ok((out.status.success(), text))
}
pub fn fetch(remote: &str) -> Result<bool> {
let (ok, _) = git_ok(&["fetch", "--quiet", "--depth", "1", remote, FETCH_REFSPEC])?;
if !ok {
return Ok(false);
}
absorb_remote()?;
Ok(true)
}
fn absorb_remote() -> Result<()> {
let (has_local, _) = git_ok(&["rev-parse", "--verify", "--quiet", NOTES_REF])?;
if !has_local {
git(&["update-ref", NOTES_REF, REMOTE_REF])?;
return Ok(());
}
git_committing(&[
"notes",
"--ref",
NOTES_REF,
"merge",
"-s",
"cat_sort_uniq",
REMOTE_REF,
])?;
Ok(())
}
pub fn read(remote: Option<&str>, commit: &str) -> Result<Vec<Record>> {
if let Some(r) = remote {
let _ = fetch(r);
}
let (ok, body) = git_ok(&["notes", "--ref", NOTES_REF, "show", commit])?;
if !ok {
return Ok(vec![]);
}
Ok(parse_note(&body))
}
pub fn append(commit: &str, records: &[Record]) -> Result<()> {
if records.is_empty() {
return Ok(());
}
let mut lines: Vec<String> = Vec::new();
let (ok, existing) = git_ok(&["notes", "--ref", NOTES_REF, "show", commit])?;
if ok {
lines.extend(existing.lines().map(str::to_string));
}
for r in records {
lines.push(r.to_line()?);
}
lines.sort();
lines.dedup();
git_committing(&[
"notes",
"--ref",
NOTES_REF,
"add",
"-f",
"-m",
&lines.join("\n"),
commit,
])?;
Ok(())
}
pub fn push(remote: &str) -> Result<()> {
for attempt in 1..=PUSH_ATTEMPTS {
let (ok, err) = git_ok(&["push", "--quiet", remote, PUSH_REFSPEC])?;
if ok {
return Ok(());
}
if attempt == PUSH_ATTEMPTS {
bail!("could not push {NOTES_REF} after {PUSH_ATTEMPTS} attempts: {err}");
}
git(&["fetch", "--quiet", remote, FETCH_REFSPEC])?;
absorb_remote()?;
}
unreachable!()
}
pub fn rev_parse(rev: &str) -> Result<String> {
git(&["rev-parse", &format!("{rev}^{{commit}}")])
}
pub fn prefix() -> Result<String> {
git(&["rev-parse", "--show-prefix"])
}
pub fn file_at(commit: &str, path: &str) -> Result<Option<String>> {
let mut at = path.to_string();
for _ in 0..=MAX_LINKS {
let entry = git(&[
"--literal-pathspecs",
"ls-tree",
"-z",
"--full-tree",
commit,
"--",
&at,
])?;
let Some((meta, _)) = entry.split_once('\t') else {
if at == path {
return Ok(None);
}
bail!("{path} at {commit} is a symlink to {at}, which does not exist there");
};
let blob = format!("{commit}:{at}");
match meta.split(' ').next() {
Some("100644" | "100755") => return git(&["cat-file", "blob", &blob]).map(Some),
Some("120000") => {
let target = git(&["cat-file", "blob", &blob])?;
at = resolve_link(&at, &target).with_context(|| {
format!(
"{path} at {commit} is a symlink to {target}, which is outside \
the repository"
)
})?;
}
_ => bail!("{at} at {commit} is not a regular file"),
}
}
bail!("{path} at {commit} goes through more than {MAX_LINKS} symlinks")
}
const MAX_LINKS: usize = 8;
fn resolve_link(link: &str, target: &str) -> Option<String> {
if target.starts_with('/') || target.starts_with('\\') {
return None;
}
let mut parts: Vec<&str> = link.split('/').collect();
parts.pop();
for part in target.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop()?;
}
name => parts.push(name),
}
}
(!parts.is_empty()).then(|| parts.join("/"))
}
pub fn rev_list(rev: &str, n: usize) -> Result<Vec<String>> {
let n = n.to_string();
let out = git(&["rev-list", "--first-parent", "-n", &n, rev])?;
Ok(out.lines().map(str::to_string).collect())
}
pub fn trailers(base: &str, head: &str, key: &str, first_parent: bool) -> Result<String> {
let format = format!("--format=%H%x00%(trailers:key={key},valueonly,unfold,separator=%x00)");
let range = format!("{base}..{head}");
let mut args = vec!["log", "--no-show-signature"];
if first_parent {
args.push("--first-parent");
}
args.extend([format.as_str(), "--end-of-options", &range, "--"]);
git(&args)
}
#[derive(Debug, Clone)]
pub struct Logged {
pub sha: String,
pub date: String,
pub subject: String,
pub records: Vec<Record>,
}
const LOG_FIELDS: usize = 4;
pub fn log(rev: &str, max: Option<usize>) -> Result<Vec<Logged>> {
walk(rev, max, |_| false)
}
pub fn log_until(rev: &str, done: impl FnMut(&Logged) -> bool) -> Result<Vec<Logged>> {
walk(rev, None, done)
}
fn walk(rev: &str, max: Option<usize>, done: impl FnMut(&Logged) -> bool) -> Result<Vec<Logged>> {
let notes = format!("--notes={NOTES_REF}");
let limit = max.map(|n| format!("--max-count={n}"));
let mut args = vec![
"log",
"-z",
"--first-parent",
"--no-show-signature",
"--no-notes",
¬es,
"--format=%H%x00%cI%x00%s%x00%N",
];
if let Some(limit) = &limit {
args.push(limit);
}
args.extend(["--end-of-options", rev, "--"]);
let what = || format!("`git {}`", args.join(" "));
let mut child = Command::new("git")
.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("failed to run {}", what()))?;
let mut stderr = child.stderr.take().expect("stderr is piped");
let errors = std::thread::spawn(move || {
let mut text = String::new();
let _ = stderr.read_to_string(&mut text);
text
});
let read = read_log(
BufReader::new(child.stdout.take().expect("stdout is piped")),
done,
);
let stopped = matches!(read, Ok((_, true)));
if stopped || read.is_err() {
let _ = child.kill();
}
let status = child
.wait()
.with_context(|| format!("failed to wait for {}", what()))?;
let (logged, _) = read.with_context(|| format!("failed to read {}", what()))?;
if !stopped && !status.success() {
let errors = errors.join().unwrap_or_default();
bail!("{} failed: {}", what(), errors.trim());
}
Ok(logged)
}
fn read_log(
mut out: impl BufRead,
mut done: impl FnMut(&Logged) -> bool,
) -> std::io::Result<(Vec<Logged>, bool)> {
let mut logged = Vec::new();
let mut fields: Vec<String> = Vec::with_capacity(LOG_FIELDS);
let mut buf = Vec::new();
loop {
buf.clear();
if out.read_until(0, &mut buf)? == 0 {
return Ok((logged, false));
}
if buf.last() == Some(&0) {
buf.pop();
}
fields.push(String::from_utf8_lossy(&buf).into_owned());
if fields.len() < LOG_FIELDS {
continue;
}
let entry = parse_entry(&fields);
fields.clear();
if let Some(c) = entry {
let last = done(&c);
logged.push(c);
if last {
return Ok((logged, true));
}
}
}
}
fn parse_entry(fields: &[String]) -> Option<Logged> {
let [sha, date, subject, note] = fields else {
return None;
};
if sha.is_empty() || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
Some(Logged {
sha: sha.clone(),
date: date.clone(),
subject: subject.clone(),
records: parse_note(note),
})
}
pub fn is_shallow_boundary(sha: &str) -> bool {
let Ok(path) = git(&["rev-parse", "--git-path", "shallow"]) else {
return false;
};
std::fs::read_to_string(path).is_ok_and(|grafts| grafts.lines().any(|l| l.trim() == sha))
}
pub fn install_refspec(remote: &str) -> Result<()> {
let key = format!("remote.{remote}.fetch");
let (_, existing) = git_ok(&["config", "--get-all", &key])?;
if existing.lines().any(|l| l.trim() == USER_FETCH_REFSPEC) {
return Ok(());
}
git(&["config", "--add", &key, USER_FETCH_REFSPEC])?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const LINE: &str =
r#"{"bench":"a","metrics":{"instructions":5.0},"runner":"r","tool":"self","ts":"t","v":1}"#;
#[test]
fn a_link_resolves_inside_the_tree_or_not_at_all() {
let cases = [
("tak.toml", "config/tak.toml", Some("config/tak.toml")),
(
"a/b/tak.toml",
"../shared/./tak.toml",
Some("a/shared/tak.toml"),
),
("a/tak.toml", "../tak.base.toml", Some("tak.base.toml")),
("a/tak.toml", "../../etc/tak.toml", None),
("tak.toml", "/etc/tak.toml", None),
("tak.toml", ".", None),
];
for (link, target, want) in cases {
assert_eq!(
resolve_link(link, target).as_deref(),
want,
"{link} -> {target}"
);
}
}
#[test]
fn a_log_parses_noted_and_unnoted_commits() {
let out = format!(
"aaa\u{0}2026-01-02T00:00:00+00:00\u{0}second\u{0}{LINE}\n\u{0}\
bbb\u{0}2026-01-01T00:00:00+00:00\u{0}first\u{0}\u{0}"
);
let log = read_log(out.as_bytes(), |_| false).unwrap().0;
assert_eq!(log.len(), 2);
assert_eq!(log[0].sha, "aaa");
assert_eq!(log[0].subject, "second");
assert_eq!(log[0].records.len(), 1);
assert_eq!(log[1].sha, "bbb");
assert!(log[1].records.is_empty());
}
#[test]
fn a_control_character_in_a_subject_stays_in_the_subject() {
let out = format!("aaa\u{0}2026-01-02T00:00:00+00:00\u{0}odd \u{1e} one\u{0}{LINE}\n\u{0}");
let log = read_log(out.as_bytes(), |_| false).unwrap().0;
assert_eq!(log.len(), 1);
assert_eq!(log[0].subject, "odd \u{1e} one");
assert_eq!(log[0].records.len(), 1);
}
#[test]
fn a_log_stops_reading_at_the_commit_that_satisfies_it() {
struct Poisoned;
impl Read for Poisoned {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("read past the stop"))
}
}
let head = format!(
"aaa\u{0}2026-01-02T00:00:00+00:00\u{0}second\u{0}\u{0}\
bbb\u{0}2026-01-01T00:00:00+00:00\u{0}first\u{0}{LINE}\n\u{0}"
);
let out = BufReader::with_capacity(1, head.as_bytes().chain(Poisoned));
let (log, stopped) = read_log(out, |c| !c.records.is_empty()).unwrap();
assert!(stopped);
assert_eq!(log.len(), 2);
assert_eq!(log[1].sha, "bbb");
let out = BufReader::new(head.as_bytes().chain(Poisoned));
assert!(read_log(out, |_| false).is_err());
}
}