use std::borrow::Cow;
use std::io::{self, BufRead, BufReader};
use std::process::{Child, ChildStdout, Command, Stdio};
pub const FS: char = '\0';
pub const LINE: u8 = b'\n';
pub const LOG_FORMAT: &str = "--format=%H%x00%h%x00%P%x00%an%x00%at%x00%D%x00%s";
pub const WHO_FORMAT: &str = "--format=%an%x00%ae%x00%at";
const LOG_FIELDS: usize = 7;
pub struct Commit<'a> {
pub hash: &'a str,
pub short: &'a str,
pub parents: &'a str,
pub author: &'a str,
pub timestamp: &'a str,
pub refs: &'a str,
pub subject: &'a str,
}
impl<'a> Commit<'a> {
pub fn parse(rec: &'a str) -> Option<Commit<'a>> {
let mut f = rec.splitn(LOG_FIELDS, FS);
Some(Commit {
hash: f.next()?,
short: f.next()?,
parents: f.next()?,
author: f.next()?,
timestamp: f.next()?,
refs: f.next()?,
subject: f.next()?,
})
}
pub fn parent_iter(&self) -> impl Iterator<Item = &'a str> {
self.parents.split_whitespace()
}
}
pub fn git(args: &[&str]) -> Command {
let mut c = Command::new("git");
c.args(args).stdout(Stdio::piped()).stderr(Stdio::inherit());
c
}
pub fn log_argv(format: &str) -> Vec<String> {
vec![
"log".to_string(),
format.to_string(),
"--encoding=UTF-8".to_string(),
]
}
#[derive(Debug, Clone, Copy)]
pub struct GitExit(pub i32);
impl std::fmt::Display for GitExit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "git exited with status {}", self.0)
}
}
impl std::error::Error for GitExit {}
pub fn git_exit_code(e: &io::Error) -> Option<i32> {
e.get_ref()
.and_then(|inner| inner.downcast_ref::<GitExit>())
.map(|g| g.0)
}
fn spawn_error(e: io::Error) -> io::Error {
if e.kind() == io::ErrorKind::NotFound {
return io::Error::new(
io::ErrorKind::NotFound,
"git was not found on PATH; gitlimes runs git and needs it installed",
);
}
e
}
pub fn capture(args: &[&str]) -> io::Result<String> {
let out = git(args)
.stderr(Stdio::inherit())
.output()
.map_err(spawn_error)?;
if !out.status.success() {
return Err(io::Error::other(GitExit(out.status.code().unwrap_or(1))));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
pub fn probe(args: &[&str]) -> io::Result<Option<String>> {
let out = git(args).stderr(Stdio::null()).output()?;
if !out.status.success() {
return Ok(None);
}
Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned()))
}
pub struct Records {
child: Child,
out: Option<BufReader<ChildStdout>>,
buf: Vec<u8>,
sep: u8,
drained: bool,
}
impl Records {
pub fn spawn_lines(cmd: Command) -> io::Result<Records> {
Records::spawn_framed(cmd, LINE)
}
pub fn spawn_framed(mut cmd: Command, sep: u8) -> io::Result<Records> {
let mut child = cmd.spawn().map_err(spawn_error)?;
let stdout = child.stdout.take().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"the command must be configured with a piped stdout; use repo::git()",
)
})?;
let out = BufReader::with_capacity(64 * 1024, stdout);
Ok(Records {
child,
out: Some(out),
buf: Vec::with_capacity(1024),
sep,
drained: false,
})
}
pub fn next_record(&mut self) -> io::Result<Option<Cow<'_, str>>> {
let Some(out) = self.out.as_mut() else {
return Ok(None);
};
let start;
loop {
self.buf.clear();
if out.read_until(self.sep, &mut self.buf)? == 0 {
self.drained = true;
return Ok(None);
}
if self.buf.last() == Some(&self.sep) {
self.buf.pop();
}
let s = self
.buf
.iter()
.position(|b| !matches!(b, b'\n' | b'\r'))
.unwrap_or(self.buf.len());
if s < self.buf.len() {
start = s;
break;
}
}
Ok(Some(String::from_utf8_lossy(&self.buf[start..])))
}
pub fn finish(mut self) -> io::Result<()> {
drop(self.out.take());
let status = self.child.wait()?;
if self.drained && !status.success() {
return Err(io::Error::other(GitExit(status.code().unwrap_or(1))));
}
Ok(())
}
}
impl Drop for Records {
fn drop(&mut self) {
drop(self.out.take());
let _ = self.child.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_command_without_piped_stdout_errors_rather_than_panicking() {
let mut cmd = Command::new("git");
cmd.arg("--version");
let err = match Records::spawn_lines(cmd) {
Ok(_) => panic!("spawn should reject a command without piped stdout"),
Err(e) => e,
};
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
assert!(err.to_string().contains("piped stdout"));
}
#[test]
fn a_missing_git_says_so_by_name() {
let mut cmd = Command::new("definitely-not-a-real-program-xyz");
cmd.stdout(Stdio::piped());
let err = match Records::spawn_lines(cmd) {
Ok(_) => panic!("that program should not exist"),
Err(e) => e,
};
assert_eq!(err.kind(), io::ErrorKind::NotFound);
assert!(
err.to_string().contains("git was not found on PATH"),
"unhelpful message: {}",
err
);
}
#[test]
fn git_exit_code_round_trips_through_io_error() {
let e = io::Error::other(GitExit(128));
assert_eq!(git_exit_code(&e), Some(128));
assert_eq!(git_exit_code(&io::Error::other("something else")), None);
}
#[test]
fn the_field_separator_is_one_git_cannot_store() {
assert_eq!(FS, '\0');
assert!(LOG_FORMAT.contains("%x00"));
assert!(
!LOG_FORMAT.contains("%x1f") && !LOG_FORMAT.contains("%x1e"),
"the log format must not rely on a byte a commit can carry"
);
}
#[test]
fn a_subject_containing_a_separator_stays_whole() {
let rec = "HASH\u{0}SHORT\u{0}P1 P2\u{0}Alice\u{0}123\u{0}refs\u{0}subject with \u{1f} and \u{1e}";
let c = Commit::parse(rec).expect("parses");
assert_eq!(c.hash, "HASH");
assert_eq!(c.author, "Alice");
assert_eq!(c.subject, "subject with \u{1f} and \u{1e}");
}
#[test]
fn a_truncated_record_is_rejected_rather_than_half_parsed() {
assert!(Commit::parse("HASH\u{0}SHORT\u{0}P1").is_none());
assert!(Commit::parse("").is_none());
}
#[test]
fn abandoning_a_reader_partway_neither_hangs_nor_leaks() {
let mut rec =
Records::spawn_framed(git(&["log", LOG_FORMAT, "--"]), LINE).expect("spawn git log");
assert!(
rec.next_record().expect("read").is_some(),
"this repository has commits"
);
rec.finish().expect("finish must not hang or error");
}
#[test]
fn dropping_a_reader_without_finishing_still_reaps_git() {
let rec =
Records::spawn_framed(git(&["log", LOG_FORMAT, "--"]), LINE).expect("spawn git log");
drop(rec);
}
#[test]
fn nothing_in_this_module_exits_the_process() {
let needle = format!("process{}exit", "::");
let src = include_str!("repo.rs");
let code = src.split("#[cfg(test)]").next().unwrap_or(src);
let offenders: Vec<&str> = code
.lines()
.filter(|l| l.contains(&needle) && !l.trim_start().starts_with("//"))
.collect();
assert!(
offenders.is_empty(),
"the library must not exit the process: {:?}",
offenders
);
}
}