use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum FileStatus {
Ignored,
Untracked,
Staged,
Modified,
Conflict,
}
#[derive(Debug, Default, PartialEq)]
pub struct GitInfo {
pub branch: String,
entries: HashMap<PathBuf, FileStatus>,
folders: HashMap<PathBuf, FileStatus>,
}
impl GitInfo {
pub fn parse(output: &str, top: &Path) -> Self {
let mut info = Self::default();
let mut fields = output.split('\0');
while let Some(field) = fields.next() {
if let Some(branch) = field.strip_prefix("## ") {
info.branch = parse_branch(branch);
continue;
}
let (Some(code), Some(path)) = (field.get(..2), field.get(3..)) else {
continue;
};
let mut letters = code.chars();
let (index, tree) = (letters.next().unwrap_or(' '), letters.next().unwrap_or(' '));
if index == 'R' || index == 'C' {
fields.next();
}
let status = match (index, tree) {
('?', '?') => FileStatus::Untracked,
('!', '!') => FileStatus::Ignored,
('U', _) | (_, 'U') | ('A', 'A') | ('D', 'D') => FileStatus::Conflict,
(_, ' ') => FileStatus::Staged,
_ => FileStatus::Modified,
};
let path = top.join(path.trim_end_matches('/'));
if status != FileStatus::Ignored {
for folder in path.ancestors().skip(1).take_while(|folder| folder.starts_with(top))
{
let summary = info.folders.entry(folder.to_path_buf()).or_insert(status);
*summary = status.max(*summary);
}
}
info.entries.insert(path, status);
}
info
}
pub fn status_of(&self, path: &Path) -> Option<FileStatus> {
if let Some(status) = self.entries.get(path).or(self.folders.get(path)) {
return Some(*status);
}
path.ancestors()
.skip(1)
.find_map(|folder| self.entries.get(folder))
.filter(|status| matches!(status, FileStatus::Untracked | FileStatus::Ignored))
.copied()
}
}
fn parse_branch(line: &str) -> String {
let line = line.strip_prefix("No commits yet on ").unwrap_or(line);
if line.starts_with("HEAD (no branch)") {
return "detached".into();
}
let name = line.split("...").next().unwrap_or(line);
name.split(' ').next().unwrap_or(name).to_string()
}
fn run(dir: &Path, args: &[&str]) -> Option<String> {
let output = Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.ok()?;
output
.status
.success()
.then(|| String::from_utf8_lossy(&output.stdout).into_owned())
}
pub fn load(dir: &Path) -> Option<GitInfo> {
let top = run(dir, &["rev-parse", "--show-toplevel"])?;
let status = run(
dir,
&["status", "--porcelain=v1", "-z", "--branch", "--ignored"],
)?;
Some(GitInfo::parse(&status, Path::new(top.trim_end())))
}
pub fn list_files(dir: &Path) -> Option<Vec<String>> {
let output = run(
dir,
&["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
)?;
Some(
output
.split('\0')
.filter(|path| !path.is_empty())
.map(String::from)
.collect(),
)
}
pub fn committed_lines(path: &Path) -> Option<Vec<String>> {
let name = path.file_name()?.to_str()?;
let text = run(path.parent()?, &["show", &format!("HEAD:./{name}")])?;
Some(text.lines().map(String::from).collect())
}