use std::io;
use std::path::Path;
use std::process::{Command, Output, Stdio};
use starmap::Spec;
#[cfg(test)]
mod tests;
#[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 found = git(dir, &["rev-parse", "--git-dir"]).map_err(GitError::Failed)?;
if !found.status.success() {
return Err(GitError::NoRepository);
}
let commit = format!("{revision}^{{commit}}");
let verified =
git(dir, &["rev-parse", "--verify", "--quiet", &commit]).map_err(GitError::Failed)?;
if !verified.status.success() {
return Err(GitError::NotFound);
}
let commit = String::from_utf8_lossy(&verified.stdout).trim().to_owned();
let listed = checked(
"git ls-tree",
git(
dir,
&[
"--literal-pathspecs",
"ls-tree",
"-l",
"-z",
&commit,
"--",
name,
],
),
)?;
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", git(dir, &["cat-file", "blob", entry.id]))?;
Entry::File(read.stdout)
}
};
Ok(At { commit, entry })
}
fn git(dir: &Path, args: &[&str]) -> io::Result<Output> {
#[expect(
clippy::disallowed_methods,
reason = "crates/starmap-cli/src/git.rs is the module that starts git"
)]
let output = Command::new("git")
.args(args)
.current_dir(dir)
.env("GIT_NO_LAZY_FETCH", "1")
.env("GIT_TERMINAL_PROMPT", "0")
.stdin(Stdio::null())
.output();
output
}
fn checked(command: &str, run: io::Result<Output>) -> Result<Output, GitError> {
let output = run.map_err(GitError::Failed)?;
if output.status.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(),
})
}