use crate::git::{self, Opts};
use anyhow::{anyhow, Result};
use serde::Serialize;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum Head {
Branch {
name: String,
oid: String,
},
Unborn {
name: String,
},
Detached {
oid: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum EntryKind {
Ordinary,
Renamed,
Unmerged,
Untracked,
Ignored,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entry {
pub path: String,
pub orig_path: Option<String>,
pub x: char,
pub y: char,
pub kind: EntryKind,
}
impl Entry {
pub fn staged(&self) -> bool {
matches!(self.kind, EntryKind::Ordinary | EntryKind::Renamed) && self.x != '.'
}
pub fn unstaged(&self) -> bool {
matches!(self.kind, EntryKind::Ordinary | EntryKind::Renamed) && self.y != '.'
}
pub fn conflicted(&self) -> bool {
self.kind == EntryKind::Unmerged
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum InProgress {
Merge,
Rebase,
CherryPick,
Revert,
Am,
Bisect,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BranchInfo {
pub head: Head,
pub upstream: Option<String>,
pub ahead: u32,
pub behind: u32,
pub stash_count: usize,
pub upstream_gone: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct RepoState {
pub branch: BranchInfo,
pub entries: Vec<Entry>,
pub op: Option<InProgress>,
pub git_dir: PathBuf,
pub workdir: PathBuf,
}
pub fn parse_status_v2(z: &[u8]) -> (BranchInfo, Vec<Entry>) {
let mut oid = String::new();
let mut head_name: Option<String> = None;
let mut detached = false;
let mut upstream = None;
let mut ab: Option<(u32, u32)> = None;
let mut stash_count = 0usize;
let mut entries = Vec::new();
let mut records = z.split(|b| *b == 0).filter(|r| !r.is_empty());
while let Some(record) = records.next() {
let text = String::from_utf8_lossy(record);
if let Some(header) = text.strip_prefix("# ") {
let (key, value) = header.split_once(' ').unwrap_or((header, ""));
match key {
"branch.oid" => {
oid = if value == "(initial)" {
String::new()
} else {
value.into()
}
}
"branch.head" if value == "(detached)" => detached = true,
"branch.head" => head_name = Some(value.into()),
"branch.upstream" => upstream = Some(value.to_string()),
"branch.ab" => {
let mut parts = value.split_whitespace();
let mut number = |sign: char| {
parts
.next()
.and_then(|p| p.strip_prefix(sign))
.and_then(|n| n.parse().ok())
.unwrap_or(0)
};
let ahead = number('+');
let behind = number('-');
ab = Some((ahead, behind));
}
"stash" => stash_count = value.trim().parse().unwrap_or(0),
_ => {}
}
continue;
}
let kind_char = text.chars().next().unwrap_or(' ');
let (fields, kind) = match kind_char {
'1' => (8, EntryKind::Ordinary),
'2' => (9, EntryKind::Renamed),
'u' => (10, EntryKind::Unmerged),
'?' => (1, EntryKind::Untracked),
'!' => (1, EntryKind::Ignored),
_ => continue,
};
let parts: Vec<&str> = text.splitn(fields + 1, ' ').collect();
let Some(path) = parts.get(fields) else {
continue;
};
let (x, y) = match kind {
EntryKind::Untracked => ('?', '?'),
EntryKind::Ignored => ('!', '!'),
_ => {
let mut xy = parts.get(1).copied().unwrap_or("..").chars();
(xy.next().unwrap_or('.'), xy.next().unwrap_or('.'))
}
};
let orig_path = if kind == EntryKind::Renamed {
records
.next()
.map(|r| String::from_utf8_lossy(r).into_owned())
} else {
None
};
entries.push(Entry {
path: path.to_string(),
orig_path,
x,
y,
kind,
});
}
let head = match (detached, head_name) {
(true, _) | (false, None) => Head::Detached { oid: oid.clone() },
(false, Some(name)) if oid.is_empty() => Head::Unborn { name },
(false, Some(name)) => Head::Branch { name, oid },
};
let upstream_gone = upstream.is_some() && ab.is_none();
let (ahead, behind) = ab.unwrap_or((0, 0));
(
BranchInfo {
head,
upstream,
ahead,
behind,
stash_count,
upstream_gone,
},
entries,
)
}
pub fn detect_in_progress(git_dir: &Path) -> Option<InProgress> {
if git_dir.join("rebase-merge").is_dir() {
return Some(InProgress::Rebase);
}
let apply = git_dir.join("rebase-apply");
if apply.is_dir() {
return Some(if apply.join("applying").exists() {
InProgress::Am
} else {
InProgress::Rebase
});
}
let markers = [
("MERGE_HEAD", InProgress::Merge),
("CHERRY_PICK_HEAD", InProgress::CherryPick),
("REVERT_HEAD", InProgress::Revert),
("BISECT_LOG", InProgress::Bisect),
];
markers
.into_iter()
.find(|(file, _)| git_dir.join(file).exists())
.map(|(_, op)| op)
}
pub fn in_repo() -> bool {
git::git_raw(&["rev-parse", "--is-inside-work-tree"], &Opts::default())
.is_ok_and(|out| out.ok() && out.text() == "true")
}
pub fn load() -> Result<RepoState> {
let dirs = git::git_ok(
&["rev-parse", "--absolute-git-dir", "--show-toplevel"],
&Opts::default(),
)
.map_err(|_| anyhow!("Not a git repository"))?;
let mut lines = dirs.lines();
let git_dir = PathBuf::from(lines.next().unwrap_or_default());
let workdir = PathBuf::from(lines.next().unwrap_or_default());
let out = git::git_raw(
&["status", "--porcelain=v2", "-z", "--branch", "--show-stash"],
&Opts::default(),
)?;
if !out.ok() {
return Err(anyhow!("{}", out.stderr.trim()));
}
let (branch, entries) = parse_status_v2(&out.stdout);
Ok(RepoState {
branch,
entries,
op: detect_in_progress(&git_dir),
git_dir,
workdir,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
const OID: &str = "1234567890abcdef1234567890abcdef12345678";
fn entry(path: &str, x: char, y: char, kind: EntryKind) -> Entry {
Entry {
path: path.into(),
orig_path: None,
x,
y,
kind,
}
}
#[test]
fn parses_fixtures() {
let ordinary = format!(
"# branch.oid {OID}\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +2 -1\0\
1 .M N... 100644 100644 100644 {OID} {OID} src/a file.rs\0"
);
let rename = format!(
"# branch.oid {OID}\0# branch.head dev\0\
2 R. N... 100644 100644 100644 {OID} {OID} R100 new name.txt\0old.txt\0\
1 A. N... 000000 100644 100644 {OID} {OID} added.txt\0"
);
let unmerged = format!(
"# branch.oid {OID}\0# branch.head main\0\
u UU N... 100644 100644 100644 100644 {OID} {OID} {OID} both.txt\0? new.txt\0! target/\0"
);
let cases: Vec<(&str, Vec<u8>, BranchInfo, Vec<Entry>)> = vec![
(
"ordinary with upstream ahead/behind",
ordinary.into_bytes(),
BranchInfo {
head: Head::Branch {
name: "main".into(),
oid: OID.into(),
},
upstream: Some("origin/main".into()),
ahead: 2,
behind: 1,
stash_count: 0,
upstream_gone: false,
},
vec![entry("src/a file.rs", '.', 'M', EntryKind::Ordinary)],
),
(
"rename and no upstream",
rename.into_bytes(),
BranchInfo {
head: Head::Branch {
name: "dev".into(),
oid: OID.into(),
},
upstream: None,
ahead: 0,
behind: 0,
stash_count: 0,
upstream_gone: false,
},
vec![
Entry {
orig_path: Some("old.txt".into()),
..entry("new name.txt", 'R', '.', EntryKind::Renamed)
},
entry("added.txt", 'A', '.', EntryKind::Ordinary),
],
),
(
"unmerged, untracked, ignored",
unmerged.into_bytes(),
BranchInfo {
head: Head::Branch {
name: "main".into(),
oid: OID.into(),
},
upstream: None,
ahead: 0,
behind: 0,
stash_count: 0,
upstream_gone: false,
},
vec![
entry("both.txt", 'U', 'U', EntryKind::Unmerged),
entry("new.txt", '?', '?', EntryKind::Untracked),
entry("target/", '!', '!', EntryKind::Ignored),
],
),
(
"unborn",
b"# branch.oid (initial)\0# branch.head main\0".to_vec(),
BranchInfo {
head: Head::Unborn {
name: "main".into(),
},
upstream: None,
ahead: 0,
behind: 0,
stash_count: 0,
upstream_gone: false,
},
vec![],
),
(
"detached with stash",
format!("# branch.oid {OID}\0# branch.head (detached)\0# stash 3\0").into_bytes(),
BranchInfo {
head: Head::Detached { oid: OID.into() },
upstream: None,
ahead: 0,
behind: 0,
stash_count: 3,
upstream_gone: false,
},
vec![],
),
(
"gone upstream",
format!(
"# branch.oid {OID}\0# branch.head topic\0# branch.upstream origin/topic\0"
)
.into_bytes(),
BranchInfo {
head: Head::Branch {
name: "topic".into(),
oid: OID.into(),
},
upstream: Some("origin/topic".into()),
ahead: 0,
behind: 0,
stash_count: 0,
upstream_gone: true,
},
vec![],
),
(
"non-UTF8 path is lossy",
b"# branch.oid (initial)\0# branch.head main\0? caf\xe9.txt\0".to_vec(),
BranchInfo {
head: Head::Unborn {
name: "main".into(),
},
upstream: None,
ahead: 0,
behind: 0,
stash_count: 0,
upstream_gone: false,
},
vec![entry("caf\u{fffd}.txt", '?', '?', EntryKind::Untracked)],
),
(
"empty input",
Vec::new(),
BranchInfo {
head: Head::Detached { oid: String::new() },
upstream: None,
ahead: 0,
behind: 0,
stash_count: 0,
upstream_gone: false,
},
vec![],
),
];
for (name, input, branch, entries) in cases {
let (got_branch, got_entries) = parse_status_v2(&input);
assert_eq!(got_branch, branch, "{name}");
assert_eq!(got_entries, entries, "{name}");
}
}
#[test]
fn entry_flags() {
let both = entry("a", 'M', 'M', EntryKind::Ordinary);
assert!(both.staged() && both.unstaged() && !both.conflicted());
let staged = entry("a", 'A', '.', EntryKind::Ordinary);
assert!(staged.staged() && !staged.unstaged());
let conflict = entry("a", 'U', 'U', EntryKind::Unmerged);
assert!(conflict.conflicted() && !conflict.staged() && !conflict.unstaged());
let new = entry("a", '?', '?', EntryKind::Untracked);
assert!(!new.staged() && !new.unstaged() && !new.conflicted());
}
#[test]
fn detects_operations() {
let repo = TempRepo::new(0);
let dir = repo.path().join(".git");
assert_eq!(detect_in_progress(&dir), None);
let checks: [(&str, bool, InProgress); 6] = [
("MERGE_HEAD", false, InProgress::Merge),
("CHERRY_PICK_HEAD", false, InProgress::CherryPick),
("REVERT_HEAD", false, InProgress::Revert),
("BISECT_LOG", false, InProgress::Bisect),
("rebase-merge", true, InProgress::Rebase),
("rebase-apply", true, InProgress::Rebase),
];
for (name, is_dir, op) in checks {
let path = dir.join(name);
if is_dir {
std::fs::create_dir(&path).unwrap();
} else {
std::fs::write(&path, "x").unwrap();
}
assert_eq!(detect_in_progress(&dir), Some(op), "{name}");
if is_dir {
if name == "rebase-apply" {
std::fs::write(path.join("applying"), "").unwrap();
assert_eq!(detect_in_progress(&dir), Some(InProgress::Am));
}
std::fs::remove_dir_all(&path).unwrap();
} else {
std::fs::remove_file(&path).unwrap();
}
}
}
#[test]
fn loads_a_real_repo() {
let repo = TempRepo::new(2).with_remote();
repo.write("f2.txt", "changed\n");
repo.write("new file.txt", "x\n");
repo.git(&["stash", "push", "-m", "keep", "--", "f2.txt"]);
repo.write("f1.txt", "edited\n");
repo.git(&["add", "f1.txt"]);
let state = repo.run(load).unwrap();
assert!(repo.run(in_repo));
let Head::Branch { name, oid } = &state.branch.head else {
panic!("{:?}", state.branch.head)
};
assert_eq!(name, "main");
assert_eq!(oid, &repo.git(&["rev-parse", "HEAD"]));
assert_eq!(state.branch.upstream.as_deref(), Some("origin/main"));
assert_eq!((state.branch.ahead, state.branch.behind), (0, 0));
assert_eq!(state.branch.stash_count, 1);
assert_eq!(state.op, None);
assert!(state.git_dir.ends_with(".git"));
let staged: Vec<&str> = state
.entries
.iter()
.filter(|e| e.staged())
.map(|e| e.path.as_str())
.collect();
assert_eq!(staged, ["f1.txt"]);
assert!(state
.entries
.iter()
.any(|e| e.path == "new file.txt" && e.kind == EntryKind::Untracked));
let outside = TempRepo::outside();
assert!(!outside.run(in_repo));
assert!(outside.run(load).is_err());
}
}