use super::*;
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct GitStatus {
pub in_repo: bool,
pub branch: Option<String>,
pub detached_hash: Option<String>,
pub dirty: bool,
pub ahead: usize,
pub behind: usize,
pub head_oid: Option<String>,
pub ignored: Arc<HashSet<PathBuf>>,
pub decorations: Arc<HashMap<PathBuf, GitDecoration>>,
pub repo_root: Option<PathBuf>,
pub changed_count: usize,
pub prepared_message: Option<String>,
pub operation: Option<RepoOp>,
pub rebasing_branch: Option<String>,
pub upstream: Option<String>,
}
impl GitStatus {
pub fn head_label(&self) -> &str {
match (&self.branch, &self.rebasing_branch, &self.detached_hash) {
(Some(b), _, _) | (None, Some(b), _) => b,
(None, None, Some(h)) => h,
(None, None, None) => "(no head)",
}
}
}
pub fn query(root: &Path) -> GitStatus {
let Some(repo_root) = repo_toplevel(root) else {
return GitStatus::default();
};
let branch = run_git(root, &["symbolic-ref", "--short", "HEAD"])
.ok()
.and_then(parse_branch);
let detached_hash = if branch.is_none() {
run_git(root, &["rev-parse", "--short", "HEAD"])
.ok()
.and_then(parse_branch)
} else {
None
};
let porcelain = git_raw(
root,
&["status", "--porcelain", "-z", "--untracked-files=all"],
None,
)
.unwrap_or_default();
let prefix = run_git(root, &["rev-parse", "--show-prefix"]).unwrap_or_default();
let decorations = parse_decorations(root, &prefix, &porcelain);
let changed_count = porcelain_z_rows(&porcelain);
let dirty = changed_count > 0;
let upstream = branch.as_ref().and_then(|_| {
run_git(root, &["rev-parse", "--symbolic-full-name", "@{u}"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| s.starts_with("refs/"))
});
let (ahead, behind) = match upstream.as_ref().map(|_| {
run_git(
root,
&["rev-list", "--left-right", "--count", "HEAD...@{u}"],
)
}) {
Some(Ok(s)) => parse_ahead_behind(&s),
_ => (0, 0),
};
let head_oid = run_git(root, &["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let prepared = prepared_message(root, &repo_root);
let operation = repo_operation(root);
GitStatus {
in_repo: true,
detached_hash,
dirty,
ahead,
behind,
head_oid,
ignored: Arc::new(query_ignored(root)),
decorations: Arc::new(decorations),
repo_root: Some(repo_root),
changed_count,
prepared_message: prepared,
rebasing_branch: match (&branch, operation) {
(None, Some(RepoOp::Rebase { .. })) => rebasing_branch(root),
_ => None,
},
branch,
operation,
upstream,
}
}
pub(super) fn prepared_message(root: &Path, top: &Path) -> Option<String> {
let paths = run_git(
root,
&[
"rev-parse",
"--git-path",
"MERGE_MSG",
"--git-path",
"SQUASH_MSG",
],
)
.ok()?;
let marker = std::cell::OnceCell::new();
let strip = |text: String| {
without_comments(
&text,
marker.get_or_init(|| comment_marker(root)).as_deref(),
)
};
paths
.lines()
.find_map(|p| strip(std::fs::read_to_string(root.join(p.trim())).ok()?))
.or_else(|| strip(commit_template(root, top)?))
}
pub(super) fn without_comments(text: &str, marker: Option<&str>) -> Option<String> {
let kept: Vec<&str> = text
.lines()
.filter(|l| !marker.is_some_and(|m| l.starts_with(m)))
.map(str::trim_end)
.collect();
let message = kept.join("\n").trim().to_string();
(!message.is_empty()).then_some(message)
}
pub(super) fn comment_marker(root: &Path) -> Option<String> {
let set = run_git(
root,
&["config", "--get-regexp", r"^core\.comment(char|string)$"],
)
.unwrap_or_default();
match set.lines().last().and_then(|l| l.split_once(' ')) {
Some((_, v)) if v.eq_ignore_ascii_case("auto") => None,
Some((_, v)) => Some(v.to_string()),
None => Some(String::from("#")),
}
}
pub(super) fn commit_template(root: &Path, top: &Path) -> Option<String> {
let named = run_git(root, &["config", "--path", "commit.template"]).ok()?;
let named = Path::new(named.trim());
if named.as_os_str().is_empty() {
return None;
}
std::fs::read_to_string(top.join(named)).ok()
}
pub(super) fn query_ignored(root: &Path) -> HashSet<PathBuf> {
let listed = git_raw(
root,
&[
"ls-files",
"-z",
"--others",
"--ignored",
"--directory",
"--exclude-standard",
],
None,
)
.unwrap_or_default();
let mut stdin = Vec::with_capacity(listed.len());
for candidate in listed.split(|b| *b == 0).filter(|s| !s.is_empty()) {
stdin.extend_from_slice(candidate);
stdin.push(0);
}
if stdin.is_empty() {
return HashSet::new();
}
let confirmed =
git_raw(root, &["check-ignore", "-z", "--stdin"], Some(&stdin)).unwrap_or_default();
confirmed
.split(|b| *b == 0)
.filter(|s| !s.is_empty())
.map(|raw| join_raw(root, raw))
.collect()
}
pub fn is_ignored(root: &Path, path: &Path) -> bool {
let mut stdin = path.as_os_str().as_encoded_bytes().to_vec();
stdin.push(0);
git_raw(root, &["check-ignore", "-z", "--stdin"], Some(&stdin))
.is_some_and(|out| out.iter().any(|b| *b != 0))
}
pub fn child_repos(dir: &Path) -> Vec<PathBuf> {
let Ok(rd) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut repos: Vec<PathBuf> = rd
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
.map(|e| e.path())
.filter(|p| p.join(".git").exists())
.collect();
repos.sort();
repos
}
pub fn parse_branch(out: String) -> Option<String> {
let trimmed = out.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
pub fn parse_ahead_behind(out: &str) -> (usize, usize) {
let mut parts = out.split_whitespace();
let a = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
let b = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
(a, b)
}