use std::io;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};
use crumbkit_process::{Capture, Outcome, OverLimit, RunOptions, Status};
use starmap::Spec;
#[cfg(test)]
mod tests;
const SMALL: usize = 64 * 1024;
const DEADLINE: Duration = Duration::from_secs(30);
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct At {
pub(crate) commit: String,
pub(crate) entry: Entry,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Entry {
Missing,
NotFile,
TooLarge,
File(Vec<u8>),
}
#[derive(Debug)]
pub(crate) enum GitError {
NoRepository,
NotFound,
Failed(io::Error),
}
pub(crate) fn read_at(dir: &Path, revision: &str, name: &str) -> Result<At, GitError> {
if revision.starts_with('-') {
return Err(GitError::NotFound);
}
let deadline = Instant::now() + DEADLINE;
let run = |args: &[&str], limit: usize| git(dir, args, limit, deadline);
let found = run(&["rev-parse", "--git-dir"], SMALL).map_err(GitError::Failed)?;
if !found.success {
return Err(GitError::NoRepository);
}
let commit = format!("{revision}^{{commit}}");
let verified =
run(&["rev-parse", "--verify", "--quiet", &commit], SMALL).map_err(GitError::Failed)?;
if !verified.success {
return Err(GitError::NotFound);
}
let commit = String::from_utf8_lossy(&verified.stdout).trim().to_owned();
let listed = checked(
"git ls-tree",
run(
&[
"--literal-pathspecs",
"ls-tree",
"-l",
"-z",
&commit,
"--",
name,
],
SMALL,
),
)?;
let entry = match tree_entry(&listed.stdout) {
None => Entry::Missing,
Some(entry) if !matches!(entry.mode, "100644" | "100755") => Entry::NotFile,
Some(entry) if entry.size.is_none_or(|size| size > Spec::MAX_BYTES) => Entry::TooLarge,
Some(entry) => {
let read = checked(
"git cat-file",
run(&["cat-file", "blob", entry.id], Spec::MAX_BYTES),
)?;
Entry::File(read.stdout)
}
};
Ok(At { commit, entry })
}
#[derive(Debug)]
struct Ran {
success: bool,
stdout: Vec<u8>,
stderr: Vec<u8>,
}
fn git(dir: &Path, args: &[&str], limit: usize, deadline: Instant) -> io::Result<Ran> {
#[expect(
clippy::disallowed_methods,
reason = "crates/starmap-cli/src/git.rs is the module that starts git"
)]
let mut command = Command::new("git");
command
.args(args)
.current_dir(dir)
.env("GIT_NO_LAZY_FETCH", "1")
.env("GIT_TERMINAL_PROMPT", "0");
let options = RunOptions::new()
.stdout(Capture::Whole {
limit,
over: OverLimit::Stop,
})
.stderr(Capture::Tail { limit: SMALL })
.deadline(deadline);
let finished = crumbkit_process::run(command, &options).map_err(io::Error::other)?;
let success = ended(finished.outcome(), finished.stdout().over_limit(), limit)?;
let (stdout, stderr) = finished.into_output();
Ok(Ran {
success,
stdout: stdout.into_bytes(),
stderr: stderr.into_bytes(),
})
}
fn ended(outcome: Outcome, over_limit: bool, limit: usize) -> io::Result<bool> {
match outcome {
Outcome::TimedOut => Err(io::Error::other(format!(
"git did not finish within {} seconds",
DEADLINE.as_secs()
))),
_ if over_limit => Err(io::Error::other(format!(
"git printed more than {limit} bytes"
))),
Outcome::Stopped(_) => Err(io::Error::other(format!(
"git printed more than {limit} bytes"
))),
Outcome::Ended(Status::Code(code)) => Ok(code == 0),
_ => Err(io::Error::other("git was ended by a signal")),
}
}
fn checked(command: &str, run: io::Result<Ran>) -> Result<Ran, GitError> {
let output = run.map_err(GitError::Failed)?;
if output.success {
return Ok(output);
}
let printed = String::from_utf8_lossy(&output.stderr);
let printed = printed.trim();
let message = if printed.is_empty() {
format!("{command} failed")
} else {
format!("{command} failed: {printed}")
};
Err(GitError::Failed(io::Error::other(message)))
}
#[derive(Debug, PartialEq, Eq)]
struct TreeEntry<'a> {
mode: &'a str,
id: &'a str,
size: Option<usize>,
}
fn tree_entry(listed: &[u8]) -> Option<TreeEntry<'_>> {
let line = listed.split(|&byte| byte == 0).next()?;
let head = line.split(|&byte| byte == b'\t').next()?;
let head = std::str::from_utf8(head).ok()?;
let mut words = head.split_whitespace();
let (mode, _kind, id, size) = (words.next()?, words.next()?, words.next()?, words.next()?);
Some(TreeEntry {
mode,
id,
size: size.parse().ok(),
})
}