use anyhow::{Context, Result};
use std::collections::HashSet;
use std::path::Path;
use std::process::Command;
use std::sync::OnceLock;
#[derive(Debug, Clone)]
pub struct GitState {
pub branch: String,
pub commit: String,
pub dirty: bool,
pub dirty_paths: HashSet<String>,
}
pub fn is_git_repo(root: impl AsRef<Path>) -> bool {
root.as_ref().join(".git").exists()
}
pub fn is_git_available() -> bool {
static AVAILABLE: OnceLock<bool> = OnceLock::new();
*AVAILABLE.get_or_init(|| match Command::new("git").arg("--version").output() {
Ok(_) => true,
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
})
}
pub fn get_current_branch(root: impl AsRef<Path>) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(root.as_ref())
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.output()
.context("Failed to execute git rev-parse")?;
if !output.status.success() {
anyhow::bail!(
"git rev-parse failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let branch = String::from_utf8(output.stdout)
.context("Invalid UTF-8 in branch name")?
.trim()
.to_string();
Ok(branch)
}
pub fn read_head_branch(root: impl AsRef<Path>) -> Option<String> {
let mut git_dir = root.as_ref().join(".git");
if git_dir.is_file() {
let text = std::fs::read_to_string(&git_dir).ok()?;
let target = text.strip_prefix("gitdir:")?.trim();
let target = Path::new(target);
git_dir = if target.is_absolute() {
target.to_path_buf()
} else {
root.as_ref().join(target)
};
}
let head = std::fs::read_to_string(git_dir.join("HEAD")).ok()?;
let head = head.trim();
if let Some(reference) = head.strip_prefix("ref:") {
let reference = reference.trim();
let name = reference.strip_prefix("refs/heads/").unwrap_or(reference);
return Some(name.to_string());
}
if !head.is_empty() && head.bytes().all(|b| b.is_ascii_hexdigit()) {
return Some("HEAD".to_string());
}
None
}
pub fn get_current_commit(root: impl AsRef<Path>) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(root.as_ref())
.args(["rev-parse", "HEAD"])
.output()
.context("Failed to execute git rev-parse HEAD")?;
if !output.status.success() {
anyhow::bail!(
"git rev-parse HEAD failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let commit = String::from_utf8(output.stdout)
.context("Invalid UTF-8 in commit SHA")?
.trim()
.to_string();
Ok(commit)
}
pub fn has_uncommitted_changes(root: impl AsRef<Path>) -> Result<bool> {
let output = Command::new("git")
.arg("-C")
.arg(root.as_ref())
.args(["status", "--porcelain"])
.output()
.context("Failed to execute git status")?;
if !output.status.success() {
anyhow::bail!(
"git status failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let has_changes = !output.stdout.is_empty();
Ok(has_changes)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WorktreeChanges {
pub modified: Vec<String>,
pub added: Vec<String>,
pub deleted: Vec<String>,
pub modified_count: usize,
pub added_count: usize,
pub deleted_count: usize,
pub truncated: bool,
}
impl WorktreeChanges {
pub fn is_empty(&self) -> bool {
self.modified_count == 0 && self.added_count == 0 && self.deleted_count == 0
}
pub fn total(&self) -> usize {
self.modified_count + self.added_count + self.deleted_count
}
pub fn any<F: Fn(&str) -> bool>(&self, pred: F) -> bool {
self.modified
.iter()
.chain(&self.added)
.chain(&self.deleted)
.any(|p| pred(p))
}
}
pub const MAX_REPORTED_PATHS: usize = 100;
impl WorktreeChanges {
pub fn push_modified(&mut self, path: &str) {
self.modified_count += 1;
if self.modified.len() < MAX_REPORTED_PATHS {
self.modified.push(path.to_string());
} else {
self.truncated = true;
}
}
pub fn push_added(&mut self, path: &str) {
self.added_count += 1;
if self.added.len() < MAX_REPORTED_PATHS {
self.added.push(path.to_string());
} else {
self.truncated = true;
}
}
pub fn push_deleted(&mut self, path: &str) {
self.deleted_count += 1;
if self.deleted.len() < MAX_REPORTED_PATHS {
self.deleted.push(path.to_string());
} else {
self.truncated = true;
}
}
pub fn sort(&mut self) {
self.modified.sort();
self.added.sort();
self.deleted.sort();
}
}
fn porcelain_records(root: &Path) -> Result<Vec<(u8, u8, String)>> {
porcelain_records_in(root, &[])
}
fn porcelain_records_in(root: &Path, pathspecs: &[&str]) -> Result<Vec<(u8, u8, String)>> {
let mut command = Command::new("git");
if !pathspecs.is_empty() {
command.arg("--literal-pathspecs");
}
command.arg("-C").arg(root).args([
"status",
"--porcelain=v1",
"-z",
"--untracked-files=all",
"--no-renames",
"--ignored=no",
]);
if !pathspecs.is_empty() {
command.arg("--").args(pathspecs);
}
let output = command.output().context("Failed to execute git status")?;
if !output.status.success() {
anyhow::bail!(
"git status failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let mut records = Vec::new();
for record in output.stdout.split(|b| *b == 0) {
if record.len() < 4 {
continue;
}
let text = String::from_utf8_lossy(record);
let (status, path) = text.split_at(3);
let path = path.trim();
if path.is_empty() {
continue;
}
let mut bytes = status.bytes();
let x = bytes.next().unwrap_or(b' ');
let y = bytes.next().unwrap_or(b' ');
records.push((x, y, path.to_string()));
}
Ok(records)
}
pub fn changed_paths(root: impl AsRef<Path>) -> Result<HashSet<String>> {
Ok(porcelain_records(root.as_ref())?
.into_iter()
.map(|(_, _, p)| p)
.collect())
}
pub fn changed_paths_in(root: impl AsRef<Path>, pathspecs: &[&str]) -> Result<HashSet<String>> {
if pathspecs.is_empty() {
return Ok(HashSet::new());
}
Ok(porcelain_records_in(root.as_ref(), pathspecs)?
.into_iter()
.map(|(_, _, p)| p)
.collect())
}
pub fn head_commit_and_branch(root: impl AsRef<Path>) -> Result<(String, String)> {
let output = Command::new("git")
.arg("-C")
.arg(root.as_ref())
.args(["rev-parse", "HEAD", "--abbrev-ref", "HEAD"])
.output()
.context("Failed to execute git rev-parse")?;
if !output.status.success() {
anyhow::bail!(
"git rev-parse failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let text = String::from_utf8(output.stdout).context("Invalid UTF-8 from git rev-parse")?;
let mut lines = text.lines().map(str::trim);
match (lines.next(), lines.next()) {
(Some(commit), Some(branch)) if !commit.is_empty() && !branch.is_empty() => {
Ok((commit.to_string(), branch.to_string()))
}
_ => anyhow::bail!("git rev-parse printed {:?}", text),
}
}
pub fn diff_names(root: impl AsRef<Path>, from: &str, to: &str) -> Result<Vec<String>> {
let output = Command::new("git")
.arg("-C")
.arg(root.as_ref())
.args(["diff", "--name-only", "-z", "--no-renames", from, to])
.output()
.context("Failed to execute git diff")?;
if !output.status.success() {
anyhow::bail!(
"git diff {}..{} failed: {}",
from,
to,
String::from_utf8_lossy(&output.stderr)
);
}
Ok(output
.stdout
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect())
}
pub fn get_worktree_changes<F>(root: impl AsRef<Path>, keep: F) -> Result<WorktreeChanges>
where
F: Fn(&str) -> bool,
{
let mut changes = WorktreeChanges::default();
for (x, y, path) in porcelain_records(root.as_ref())? {
if !keep(&path) {
continue;
}
if x == b'D' || y == b'D' {
changes.push_deleted(&path);
} else if x == b'?' || x == b'A' {
changes.push_added(&path);
} else {
changes.push_modified(&path);
}
}
Ok(changes)
}
pub fn is_ignored(root: impl AsRef<Path>, path: &str) -> Option<bool> {
let root = root.as_ref();
if !is_git_repo(root) || !is_git_available() {
return None;
}
let status = Command::new("git")
.arg("-C")
.arg(root)
.args(["check-ignore", "-q", "--", path])
.status()
.ok()?;
match status.code() {
Some(0) => Some(true),
Some(1) => Some(false),
_ => None,
}
}
pub fn get_git_state(root: impl AsRef<Path>) -> Result<GitState> {
let root = root.as_ref();
if !is_git_repo(root) {
anyhow::bail!("Not a git repository");
}
let branch = get_current_branch(root)?;
let commit = get_current_commit(root)?;
let dirty_paths = changed_paths(root)?;
Ok(GitState {
branch,
commit,
dirty: !dirty_paths.is_empty(),
dirty_paths,
})
}
pub fn get_git_state_optional(root: impl AsRef<Path>) -> Result<Option<GitState>> {
if !is_git_repo(&root) {
return Ok(None);
}
match get_git_state(root) {
Ok(state) => Ok(Some(state)),
Err(e) => {
log::warn!("Failed to get git state: {}", e);
Ok(None)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_git_repo() {
assert!(is_git_repo("."));
assert!(!is_git_repo("/tmp"));
}
#[test]
fn test_get_current_branch() {
let branch = get_current_branch(".").unwrap();
assert!(!branch.is_empty());
log::info!("Current branch: {}", branch);
}
#[test]
fn test_get_current_commit() {
let commit = get_current_commit(".").unwrap();
assert_eq!(commit.len(), 40);
assert!(commit.chars().all(|c| c.is_ascii_hexdigit()));
log::info!("Current commit: {}", commit);
}
#[test]
fn test_has_uncommitted_changes() {
let has_changes = has_uncommitted_changes(".").unwrap();
log::info!("Has uncommitted changes: {}", has_changes);
}
#[test]
fn test_get_git_state() {
let state = get_git_state(".").unwrap();
assert!(!state.branch.is_empty());
assert_eq!(state.commit.len(), 40);
log::info!("Git state: {:?}", state);
}
}