use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
#[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 repo_root: Option<PathBuf>,
pub changed_count: usize,
}
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 = run_git(root, &["status", "--porcelain"]).unwrap_or_default();
let dirty = parse_porcelain_dirty(&porcelain);
let changed_count = porcelain.lines().filter(|l| !l.trim().is_empty()).count();
let (ahead, behind) = match run_git(
root,
&["rev-list", "--left-right", "--count", "HEAD...@{u}"],
) {
Ok(s) => parse_ahead_behind(&s),
Err(_) => (0, 0),
};
let head_oid = run_git(root, &["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
GitStatus {
in_repo: true,
branch,
detached_hash,
dirty,
ahead,
behind,
head_oid,
ignored: Arc::new(query_ignored(root)),
repo_root: Some(repo_root),
changed_count,
}
}
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))
}
fn join_raw(root: &Path, raw: &[u8]) -> PathBuf {
let trimmed = raw.strip_suffix(b"/").unwrap_or(raw);
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
root.join(std::ffi::OsStr::from_bytes(trimmed))
}
#[cfg(not(unix))]
{
root.join(String::from_utf8_lossy(trimmed).as_ref())
}
}
fn git_raw(root: &Path, args: &[&str], stdin_data: Option<&[u8]>) -> Option<Vec<u8>> {
use std::io::Write;
let mut cmd = Command::new("git");
cmd.arg("-C")
.arg(root)
.env("GIT_OPTIONAL_LOCKS", "0")
.args(args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.stdin(if stdin_data.is_some() {
std::process::Stdio::piped()
} else {
std::process::Stdio::null()
});
let mut child = cmd.spawn().ok()?;
let writer = match stdin_data {
Some(data) => {
let mut pipe = child.stdin.take()?;
let data = data.to_vec();
Some(std::thread::spawn(move || {
let _ = pipe.write_all(&data);
}))
}
None => None,
};
let out = child.wait_with_output().ok();
if let Some(w) = writer {
let _ = w.join();
}
Some(out?.stdout)
}
pub fn repo_toplevel(dir: &Path) -> Option<PathBuf> {
run_git(dir, &["rev-parse", "--show-toplevel"])
.ok()
.filter(|s| !s.is_empty())
.map(PathBuf::from)
}
fn run_git(path: &Path, args: &[&str]) -> std::io::Result<String> {
let path_str = path
.to_str()
.ok_or_else(|| std::io::Error::other("non-utf8 workspace path"))?;
let mut cmd = Command::new("git");
cmd.env("GIT_OPTIONAL_LOCKS", "0");
cmd.args(["-C", path_str]).args(args);
let output = cmd.output()?;
if !output.status.success() {
return Err(std::io::Error::other(format!(
"git {:?} failed with code {:?}",
args,
output.status.code()
)));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
fn never_prompt(cmd: &mut Command) {
cmd.env("GIT_TERMINAL_PROMPT", "0")
.stdin(std::process::Stdio::null());
#[cfg(unix)]
detach_from_tty(cmd);
}
#[cfg(unix)]
fn detach_from_tty(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
}
fn run_mutation(root: &Path, args: &[&str]) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&format!("> git {}", args.join(" ")),
);
let mut cmd = Command::new("git");
cmd.args(["-C", path_str]).args(args);
never_prompt(&mut cmd);
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
let msg = if !stdout.is_empty() { stdout } else { stderr };
if !msg.is_empty() {
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&msg,
);
}
Ok(msg)
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
let err = if msg.is_empty() {
let verb = args.first().copied().unwrap_or("git");
format!("git {verb} failed with code {:?}", output.status.code())
} else {
msg
};
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Error,
&err,
);
Err(err)
}
}
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_porcelain_dirty(out: &str) -> bool {
out.lines().any(|l| !l.trim().is_empty())
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChangeEntry {
pub path: String,
pub kind: ChangeKind,
pub additions: usize,
pub deletions: usize,
}
impl Default for ChangeEntry {
fn default() -> Self {
Self {
path: String::new(),
kind: ChangeKind::Modified,
additions: 0,
deletions: 0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChangeKind {
StagedAdded,
StagedModified,
StagedDeleted,
StagedRenamed,
Modified,
Deleted,
Untracked,
Conflicted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChangeSection {
Staged,
Changes,
Untracked,
Conflicts,
}
impl ChangeKind {
pub fn section(self) -> ChangeSection {
match self {
Self::StagedAdded
| Self::StagedModified
| Self::StagedDeleted
| Self::StagedRenamed => ChangeSection::Staged,
Self::Modified | Self::Deleted => ChangeSection::Changes,
Self::Untracked => ChangeSection::Untracked,
Self::Conflicted => ChangeSection::Conflicts,
}
}
pub fn badge(self) -> char {
match self {
Self::StagedAdded => 'A',
Self::StagedModified | Self::Modified => 'M',
Self::StagedDeleted | Self::Deleted => 'D',
Self::StagedRenamed => 'R',
Self::Untracked => 'U',
Self::Conflicted => '!',
}
}
}
pub fn unquote_porcelain_path(raw: &str) -> String {
if !raw.starts_with('"') {
return raw.to_string();
}
let bytes = raw.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i: usize = 1;
while i < bytes.len() {
let b = bytes[i];
if b == b'"' {
break;
}
if b == b'\\' && i + 1 < bytes.len() {
let n = bytes[i + 1];
match n {
b'a' => {
out.push(0x07);
i += 2;
}
b'b' => {
out.push(0x08);
i += 2;
}
b't' => {
out.push(b'\t');
i += 2;
}
b'n' => {
out.push(b'\n');
i += 2;
}
b'v' => {
out.push(0x0B);
i += 2;
}
b'f' => {
out.push(0x0C);
i += 2;
}
b'r' => {
out.push(b'\r');
i += 2;
}
b'"' => {
out.push(b'"');
i += 2;
}
b'\\' => {
out.push(b'\\');
i += 2;
}
b'0'..=b'7' => {
while i + 3 < bytes.len()
&& bytes[i] == b'\\'
&& (b'0'..=b'7').contains(&bytes[i + 1])
&& (b'0'..=b'7').contains(&bytes[i + 2])
&& (b'0'..=b'7').contains(&bytes[i + 3])
{
let val = ((bytes[i + 1] - b'0') as u16) * 64
+ ((bytes[i + 2] - b'0') as u16) * 8
+ ((bytes[i + 3] - b'0') as u16);
out.push(val as u8);
i += 4;
}
}
_ => {
out.push(b'\\');
i += 1;
}
}
} else {
out.push(b);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
pub fn parse_porcelain_changes(out: &str) -> Vec<ChangeEntry> {
let mut entries = Vec::new();
for line in out.lines() {
if line.len() < 3 {
continue;
}
let bytes = line.as_bytes();
let x = bytes[0] as char;
let y = bytes[1] as char;
let path_part = &line[3..];
let path = if let Some((_, dst)) = path_part.split_once(" -> ") {
unquote_porcelain_path(dst)
} else {
unquote_porcelain_path(path_part)
};
let conflict = matches!(
(x, y),
('A', 'A')
| ('D', 'D')
| ('A', 'U')
| ('U', 'A')
| ('D', 'U')
| ('U', 'D')
| ('U', 'U')
);
if conflict {
entries.push(ChangeEntry {
path,
kind: ChangeKind::Conflicted,
..Default::default()
});
continue;
}
if x == '?' && y == '?' {
entries.push(ChangeEntry {
path,
kind: ChangeKind::Untracked,
..Default::default()
});
continue;
}
if x != ' ' && x != '?' {
let kind = match x {
'A' => ChangeKind::StagedAdded,
'M' => ChangeKind::StagedModified,
'D' => ChangeKind::StagedDeleted,
'R' | 'C' => ChangeKind::StagedRenamed,
_ => ChangeKind::StagedModified,
};
entries.push(ChangeEntry {
path: path.clone(),
kind,
..Default::default()
});
}
if y != ' ' && y != '?' {
let kind = match y {
'M' => ChangeKind::Modified,
'D' => ChangeKind::Deleted,
_ => ChangeKind::Modified,
};
entries.push(ChangeEntry {
path,
kind,
..Default::default()
});
}
}
entries
}
pub fn query_changes(root: &Path) -> Vec<ChangeEntry> {
let Some(toplevel) = repo_toplevel(root) else {
return Vec::new();
};
let path_str = match root.to_str() {
Some(s) => s,
None => return Vec::new(),
};
let output = match Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["-C", path_str, "status", "--porcelain"])
.output()
{
Ok(o) if o.status.success() => o,
_ => return Vec::new(),
};
let raw = String::from_utf8_lossy(&output.stdout);
let mut entries = parse_porcelain_changes(&raw);
let staged = numstat_map(path_str, &["diff", "--cached", "--numstat"]);
let unstaged = numstat_map(path_str, &["diff", "--numstat"]);
for entry in &mut entries {
let stats = match entry.kind.section() {
ChangeSection::Staged => staged.get(&entry.path),
ChangeSection::Changes => unstaged.get(&entry.path),
ChangeSection::Untracked => None,
ChangeSection::Conflicts => None,
};
if let Some((a, d)) = stats {
entry.additions = *a;
entry.deletions = *d;
}
}
for entry in &mut entries {
if matches!(entry.kind, ChangeKind::Untracked) {
entry.additions = count_lines_in_file(&toplevel, &entry.path);
}
}
entries
}
pub fn parse_numstat(out: &str) -> std::collections::HashMap<String, (usize, usize)> {
let mut map = std::collections::HashMap::new();
for line in out.lines() {
let mut parts = line.splitn(3, '\t');
let Some(adds) = parts.next() else { continue };
let Some(dels) = parts.next() else { continue };
let Some(path_part) = parts.next() else {
continue;
};
let additions = adds.parse::<usize>().unwrap_or(0);
let deletions = dels.parse::<usize>().unwrap_or(0);
let path = if let Some((_, dst)) = path_part.split_once(" -> ") {
unquote_porcelain_path(dst)
} else {
unquote_porcelain_path(path_part)
};
map.insert(path, (additions, deletions));
}
map
}
fn numstat_map(workdir: &str, args: &[&str]) -> std::collections::HashMap<String, (usize, usize)> {
let output = match Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["-C", workdir])
.args(args)
.output()
{
Ok(o) if o.status.success() => o,
_ => return std::collections::HashMap::new(),
};
parse_numstat(&String::from_utf8_lossy(&output.stdout))
}
fn count_lines_in_file(root: &Path, rel_path: &str) -> usize {
let abs = root.join(rel_path);
let Ok(bytes) = std::fs::read(&abs) else {
return 0;
};
if bytes.is_empty() {
return 0;
}
let mut lines = bytes.iter().filter(|b| **b == b'\n').count();
if !bytes.ends_with(b"\n") {
lines += 1;
}
lines
}
pub fn read_file_at_head(root: &Path, rel_path: &str) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let spec = format!("HEAD:{rel_path}");
let output = Command::new("git")
.args(["-C", path_str, "show", &spec])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if stderr.is_empty() {
format!(
"git show {spec} failed with code {:?}",
output.status.code()
)
} else {
stderr
});
}
String::from_utf8(output.stdout).map_err(|_| format!("{rel_path} at HEAD is not UTF-8"))
}
pub fn read_file_at_rev(root: &Path, rev: &str, rel_path: &str) -> Result<String, String> {
let spec = format!("{rev}:./{rel_path}");
let output = Command::new("git")
.arg("-C")
.arg(root)
.args(["show", &spec])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
}
String::from_utf8(output.stdout).map_err(|_| format!("{rel_path} at {rev} is not UTF-8"))
}
pub fn read_file_at_stage(root: &Path, rel_path: &str, stage: u8) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let spec = format!(":{stage}:{rel_path}");
let output = Command::new("git")
.args(["-C", path_str, "show", &spec])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if stderr.is_empty() {
format!(
"git show {spec} failed with code {:?}",
output.status.code()
)
} else {
stderr
});
}
String::from_utf8(output.stdout)
.map_err(|_| format!("{rel_path} at stage {stage} is not UTF-8"))
}
#[derive(Clone, Copy)]
enum HunkSide {
Old,
New,
}
fn retarget_hunk_starts(patch: &str, side: HunkSide) -> String {
let fix = |line: &str| -> Option<String> {
let rest = line.strip_prefix("@@ -")?;
let (old, rest) = rest.split_once(" +")?;
let (new, tail) = rest.split_once(" @@")?;
let start = |range: &str| range.split(',').next().map(str::to_string);
let count = |range: &str| range.split_once(',').map(|(_, c)| format!(",{c}"));
let pick = match side {
HunkSide::Old => start(old)?,
HunkSide::New => start(new)?,
};
Some(format!(
"@@ -{pick}{} +{pick}{} @@{tail}",
count(old).unwrap_or_default(),
count(new).unwrap_or_default()
))
};
patch
.split('\n')
.map(|l| fix(l).unwrap_or_else(|| l.to_string()))
.collect::<Vec<_>>()
.join("\n")
}
pub fn apply_patch(
root: &Path,
patch: &str,
cached: bool,
reverse: bool,
) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut args: Vec<&str> = vec!["-C", path_str, "apply", "--whitespace=nowarn"];
if cached {
args.push("--cached");
}
if reverse {
args.push("-R");
}
args.push("-");
let retargeted = match (cached, reverse) {
(true, false) => retarget_hunk_starts(patch, HunkSide::Old),
(false, true) => retarget_hunk_starts(patch, HunkSide::New),
_ => patch.to_string(),
};
let patch = retargeted.as_str();
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&format!("> git {} <<patch", args[2..].join(" ")),
);
let mut child = Command::new("git")
.args(&args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
if let Err(e) = stdin.write_all(patch.as_bytes()) {
drop(stdin);
let _ = child.wait();
return Err(format!("failed to feed patch to git apply: {e}"));
}
}
let output = child
.wait_with_output()
.map_err(|e| format!("git apply did not exit cleanly: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
Ok(if !stdout.is_empty() { stdout } else { stderr })
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
let err = if msg.is_empty() {
format!("git apply failed with code {:?}", output.status.code())
} else {
msg
};
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Error,
&err,
);
Err(err)
}
}
pub fn commit_all_tracked(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let output = Command::new("git")
.args(["-C", path_str, "commit", "-am", message])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
let summary = if !stdout.is_empty() { stdout } else { stderr };
Ok(summary)
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git commit failed with code {:?}", output.status.code())
} else {
msg
})
}
}
pub fn push_current_branch(root: &Path) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str, "push"]);
never_prompt(&mut cmd);
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
let summary = if !stderr.is_empty() { stderr } else { stdout };
Ok(summary)
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git push failed with code {:?}", output.status.code())
} else {
msg
})
}
}
pub fn diff_staged(root: &Path) -> Result<String, String> {
diff_text(root, &["diff", "--staged"])
}
pub fn diff_against_branch(root: &Path, branch: &str) -> Result<String, String> {
diff_text(root, &["diff", branch])
}
pub fn diff_previous_commit(root: &Path) -> Result<String, String> {
diff_text(root, &["diff", "HEAD~1"])
}
fn diff_text(root: &Path, args: &[&str]) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str]).args(args);
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git {args:?} failed with code {:?}", output.status.code())
} else {
msg
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileHistoryEntry {
pub short_hash: String,
pub summary: String,
pub author: String,
pub age_secs: i64,
}
pub fn file_history(root: &Path, rel_path: &str, limit: usize) -> Vec<FileHistoryEntry> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.args([
"-C",
path_str,
"log",
"--follow",
&format!("-n{limit}"),
"--format=%h\x1f%s\x1f%an\x1f%ct",
"--",
rel_path,
])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_file_history(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
pub fn parse_file_history(out: &str, now: i64) -> Vec<FileHistoryEntry> {
out.lines()
.filter_map(|line| {
let mut parts = line.split('\x1f');
let short_hash = parts.next()?.to_string();
let summary = parts.next()?.to_string();
let author = parts.next()?.to_string();
let ct: i64 = parts.next()?.trim().parse().ok()?;
if short_hash.is_empty() {
return None;
}
Some(FileHistoryEntry {
short_hash,
summary,
author,
age_secs: now - ct,
})
})
.collect()
}
pub fn show_commit_file_diff(root: &Path, hash: &str, rel_path: &str) -> Result<String, String> {
let has_diff = |raw: &str| raw.lines().any(|l| l.starts_with("diff --git"));
let raw = diff_text(root, &["show", hash, "--", rel_path])?;
if has_diff(&raw) {
return Ok(raw);
}
match path_at_commit(root, hash, rel_path) {
Some(old) if old != rel_path => diff_text(root, &["show", hash, "--", &old]),
_ => Ok(raw),
}
}
fn path_at_commit(root: &Path, hash: &str, rel_path: &str) -> Option<String> {
let out = run_git(
root,
&[
"log",
"--follow",
"-n200",
"--name-only",
"--format=%x1e%H",
"--",
rel_path,
],
)
.ok()?;
out.split('\x1e').find_map(|record| {
let mut lines = record.lines();
let full = lines.next()?.trim();
if hash.is_empty() || !full.starts_with(hash) {
return None;
}
lines
.map(str::trim)
.find(|l| !l.is_empty())
.map(unquote_porcelain_path)
})
}
pub fn show_commit(root: &Path, hash: &str) -> Result<String, String> {
diff_text(root, &["show", "--stat", "--patch", hash])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphCommit {
pub hash: String,
pub short_hash: String,
pub parents: Vec<String>,
pub refs: Vec<String>,
pub summary: String,
pub author: String,
pub age_secs: i64,
}
pub fn commit_graph(root: &Path, limit: usize) -> Vec<GraphCommit> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.args([
"-C",
path_str,
"log",
"--branches",
"--tags",
"HEAD",
"--topo-order",
&format!("-n{limit}"),
"--format=%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct",
])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_commit_graph(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorktreeLane {
pub path: PathBuf,
pub branch: String,
pub base: Option<String>,
}
impl WorktreeLane {
pub fn plan(repo: &Path, name: &str) -> Option<Self> {
let slug = lane_slug(name)?;
let parent = repo.parent()?;
let base = repo.file_name()?.to_string_lossy();
Some(Self {
path: parent.join(format!("{base}-{slug}")),
branch: format!("agent/{slug}"),
base: None,
})
}
}
fn lane_slug(name: &str) -> Option<String> {
let mapped: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
let mut out = String::new();
for part in mapped.split('-').filter(|p| !p.is_empty()) {
if !out.is_empty() {
out.push('-');
}
out.push_str(part);
}
if out.is_empty() {
return None;
}
let capped: String = out.chars().take(60).collect();
let capped = capped.trim_matches('-');
(!capped.is_empty()).then(|| capped.to_string())
}
pub fn lane_removal_block(lane: &Path) -> Option<String> {
let Some(path_str) = lane.to_str() else {
return Some(format!("{} is not a readable path", lane.display()));
};
let output = Command::new("git")
.args(["-C", path_str, "status", "--porcelain", "--ignored"])
.output();
let Ok(output) = output else {
return Some(String::from(
"could not run git to check for uncommitted work",
));
};
if !output.status.success() {
return Some(format!("{path_str} does not look like a git worktree"));
}
let dirty = String::from_utf8_lossy(&output.stdout);
let mut changed = 0usize;
let mut ignored = 0usize;
for line in dirty.lines().filter(|l| !l.trim().is_empty()) {
if line.starts_with("!!") {
ignored += 1;
} else {
changed += 1;
}
}
match (changed, ignored) {
(0, 0) => None,
(0, n) => Some(format!(
"this lane has {n} ignored file{} (build output, local config) that removal would \
delete — clear them by hand first",
if n == 1 { "" } else { "s" }
)),
(1, _) => Some(String::from(
"this lane has 1 file with uncommitted changes — commit or discard it first",
)),
(n, _) => Some(format!(
"this lane has {n} files with uncommitted changes — commit or discard them first"
)),
}
}
fn run_git_mut(dir: &Path, args: &[&str]) -> Result<(), String> {
let Some(dir) = dir.to_str() else {
return Err(String::from("path is not valid UTF-8"));
};
let output = Command::new("git")
.args(["-C", dir])
.args(args)
.output()
.map_err(|e| e.to_string())?;
if output.status.success() {
return Ok(());
}
let err = String::from_utf8_lossy(&output.stderr);
Err(err
.trim()
.lines()
.next()
.unwrap_or("git failed")
.to_string())
}
pub fn add_worktree_lane(repo: &Path, lane: &mut WorktreeLane) -> Result<(), String> {
let Some(path) = lane.path.to_str().map(str::to_owned) else {
return Err(String::from("lane path is not valid UTF-8"));
};
let base = current_branch(repo);
run_git_mut(repo, &["worktree", "add", "-b", &lane.branch, &path])?;
lane.base = base;
Ok(())
}
pub fn current_branch(root: &Path) -> Option<String> {
let out = run_git(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok()?;
let name = out.trim();
(!name.is_empty()).then(|| name.to_string())
}
pub fn remove_worktree_lane(lane: &Path) -> Result<(), String> {
let Some(path) = lane.to_str() else {
return Err(String::from("lane path is not valid UTF-8"));
};
run_git_mut(lane, &["worktree", "remove", path])
}
pub fn pr_worktree_path(repo: &Path, number: u64) -> Option<PathBuf> {
let name = repo.file_name()?.to_str()?;
Some(repo.parent()?.join(format!("{name}-pr-{number}")))
}
pub fn remote_for_slug(repo: &Path, slug: &str) -> String {
let slug = slug.to_ascii_lowercase();
let names = |url: &str| {
let url = url.trim().to_ascii_lowercase();
let url = url.strip_suffix(".git").unwrap_or(&url).to_string();
url.ends_with(&format!("/{slug}")) || url.ends_with(&format!(":{slug}"))
};
run_git(repo, &["remote", "-v"])
.ok()
.and_then(|out| {
out.lines().find_map(|l| {
let mut parts = l.split_whitespace();
let (name, url) = (parts.next()?, parts.next()?);
names(url).then(|| name.to_string())
})
})
.unwrap_or_else(|| format!("https://github.com/{slug}.git"))
}
fn is_worktree_of(repo: &Path, path: &Path) -> bool {
let want = path.canonicalize().ok();
run_git(repo, &["worktree", "list", "--porcelain"]).is_ok_and(|out| {
out.lines()
.filter_map(|l| l.strip_prefix("worktree "))
.any(|w| Path::new(w).canonicalize().ok() == want)
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrWorktree {
pub oid: String,
pub created: bool,
}
pub fn checkout_pr_worktree(
repo: &Path,
remote: &str,
number: u64,
path: &Path,
previous: Option<&str>,
) -> Result<PrWorktree, String> {
let Some(path_s) = path.to_str() else {
return Err(String::from("worktree path is not valid UTF-8"));
};
let Some(repo_s) = repo.to_str() else {
return Err(String::from("repository path is not valid UTF-8"));
};
let mut fetch = Command::new("git");
fetch
.args(["-C", repo_s, "fetch", "--quiet", remote])
.arg(format!("refs/pull/{number}/head"));
never_prompt(&mut fetch);
let fetch = fetch.output().map_err(|e| e.to_string())?;
if !fetch.status.success() {
let err = String::from_utf8_lossy(&fetch.stderr);
return Err(err
.trim()
.lines()
.next()
.unwrap_or("git fetch failed")
.to_string());
}
let oid = run_git(repo, &["rev-parse", "FETCH_HEAD"])
.map_err(|e| e.to_string())?
.trim()
.to_string();
if path.exists() {
if !is_worktree_of(repo, path) {
return Err(format!(
"{path_s} already exists and is not a worktree of this repository"
));
}
let head = worktree_head(path);
if head.as_deref() != Some(oid.as_str()) {
if let Some(why) = lane_removal_block(path) {
return Err(format!("the existing checkout has work in it: {why}"));
}
if previous.is_none() || head.as_deref() != previous {
return Err(format!(
"{path_s} is at a commit review mode did not check out — put that work on a branch, or remove the worktree"
));
}
}
run_git_mut(path, &["checkout", "--quiet", "--detach", &oid])?;
Ok(PrWorktree {
oid,
created: false,
})
} else {
run_git_mut(repo, &["worktree", "add", "--detach", path_s, &oid])?;
Ok(PrWorktree { oid, created: true })
}
}
pub fn worktree_head(path: &Path) -> Option<String> {
run_git(path, &["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
pub fn pr_worktree_keep_reason(path: &Path, checked_out: &str) -> Option<String> {
if let Some(why) = lane_removal_block(path) {
return Some(why);
}
match worktree_head(path) {
Some(head) if head == checked_out => None,
Some(_) => Some(String::from(
"it has commits beyond the pull request's head — put them on a branch first",
)),
None => Some(String::from("git cannot read its HEAD")),
}
}
pub fn branch_history(root: &Path, limit: usize) -> Vec<GraphCommit> {
branch_history_range(root, "HEAD", limit)
}
pub fn branch_history_range(root: &Path, revspec: &str, limit: usize) -> Vec<GraphCommit> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.args([
"-C",
path_str,
"log",
"--first-parent",
revspec,
&format!("-n{limit}"),
"--format=%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct",
])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
parse_commit_graph(&String::from_utf8_lossy(&output.stdout), now)
}
#[derive(Debug, Default)]
pub struct CommitTree {
pub paths: HashSet<PathBuf>,
pub submodules: Vec<PathBuf>,
}
impl CommitTree {
pub fn contains(&self, path: &Path) -> bool {
self.paths.contains(path) || self.submodules.iter().any(|s| path.starts_with(s))
}
}
pub fn tree_paths(root: &Path, rev: &str) -> Option<CommitTree> {
let output = Command::new("git")
.arg("-C")
.arg(root)
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["ls-tree", "-r", "-t", "-z", rev])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let mut tree = CommitTree::default();
for entry in output.stdout.split(|b| *b == 0).filter(|s| !s.is_empty()) {
let Some(tab) = entry.iter().position(|b| *b == b'\t') else {
continue;
};
let path = join_raw(root, &entry[tab + 1..]);
if entry[..tab].split(|b| *b == b' ').nth(1) == Some(b"commit") {
tree.submodules.push(path.clone());
}
tree.paths.insert(path);
}
Some(tree)
}
pub fn parse_commit_graph(out: &str, now: i64) -> Vec<GraphCommit> {
out.lines()
.filter_map(|line| {
let mut parts = line.split('\x1f');
let hash = parts.next()?.to_string();
let short_hash = parts.next()?.to_string();
let parents: Vec<String> = parts
.next()?
.split_whitespace()
.map(str::to_string)
.collect();
let refs: Vec<String> = parts
.next()?
.split(", ")
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
let summary = parts.next()?.to_string();
let author = parts.next()?.to_string();
let ct: i64 = parts.next()?.trim().parse().ok()?;
if hash.is_empty() {
return None;
}
Some(GraphCommit {
hash,
short_hash,
parents,
refs,
summary,
author,
age_secs: (now - ct).max(0),
})
})
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BlameLine {
pub short_hash: String,
pub summary: String,
pub author: String,
pub age_secs: i64,
pub uncommitted: bool,
pub text: Option<String>,
}
pub fn blame(root: &Path, rel_path: &str) -> Vec<BlameLine> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["-C", path_str, "blame", "--line-porcelain", "--", rel_path])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_blame(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
pub fn parse_blame(out: &str, now: i64) -> Vec<BlameLine> {
let mut lines = Vec::new();
let mut hash: Option<String> = None;
let mut author = String::new();
let mut summary = String::new();
let mut author_time: i64 = now;
for raw in out.lines() {
if let Some(rest) = raw.strip_prefix("author ") {
author = rest.to_string();
} else if let Some(rest) = raw.strip_prefix("author-time ") {
author_time = rest.trim().parse().unwrap_or(now);
} else if let Some(rest) = raw.strip_prefix("summary ") {
summary = rest.to_string();
} else if let Some(content) = raw.strip_prefix('\t') {
if let Some(full) = hash.take() {
let uncommitted = full.chars().all(|c| c == '0');
lines.push(BlameLine {
short_hash: full.chars().take(8).collect(),
summary: std::mem::take(&mut summary),
author: std::mem::take(&mut author),
age_secs: now - author_time,
uncommitted,
text: Some(content.to_string()),
});
}
} else if let Some(h) = raw.split(' ').next() {
if h.len() == 40 && h.chars().all(|c| c.is_ascii_hexdigit()) {
hash = Some(h.to_string());
}
}
}
lines
}
pub fn default_branch(root: &Path) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
if let Ok(out) = Command::new("git")
.args([
"-C",
path_str,
"symbolic-ref",
"--short",
"refs/remotes/origin/HEAD",
])
.output()
&& out.status.success()
{
let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
if let Some(short) = raw.strip_prefix("origin/") {
if !short.is_empty() {
return Ok(short.to_string());
}
} else if !raw.is_empty() {
return Ok(raw);
}
}
for candidate in ["main", "master", "develop", "trunk"] {
let out = Command::new("git")
.args([
"-C",
path_str,
"rev-parse",
"--verify",
"--quiet",
candidate,
])
.output();
if let Ok(o) = out
&& o.status.success()
{
return Ok(candidate.to_string());
}
}
Err(
"Could not resolve a default branch (tried origin/HEAD, main, master, develop, trunk)"
.to_string(),
)
}
pub fn stage_path(root: &Path, rel_path: &str) -> Result<(), String> {
stage_paths(root, std::slice::from_ref(&rel_path.to_string()))
}
pub fn stage_paths(root: &Path, rel_paths: &[String]) -> Result<(), String> {
if rel_paths.is_empty() {
return Ok(());
}
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str, "--literal-pathspecs", "add", "--"]);
for p in rel_paths {
cmd.arg(p);
}
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git add failed with code {:?}", output.status.code())
} else {
msg
})
}
}
pub fn unstage_path(root: &Path, rel_path: &str) -> Result<(), String> {
unstage_paths(root, std::slice::from_ref(&rel_path.to_string()))
}
pub fn unstage_paths(root: &Path, rel_paths: &[String]) -> Result<(), String> {
if rel_paths.is_empty() {
return Ok(());
}
let mut args: Vec<&str> = vec!["--literal-pathspecs", "reset", "-q", "HEAD", "--"];
args.extend(rel_paths.iter().map(String::as_str));
run_mutation(root, &args).map(|_| ())
}
pub fn discard_path(
root: &Path,
rel_path: &str,
untracked: bool,
staged: bool,
) -> Result<(), String> {
if untracked {
let abs = root.join(rel_path);
if abs.is_dir() {
run_mutation(
root,
&["--literal-pathspecs", "clean", "-fdq", "--", rel_path],
)
.map(|_| ())
} else {
std::fs::remove_file(&abs)
.map_err(|e| format!("failed to remove {}: {e}", abs.display()))
}
} else {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str, "--literal-pathspecs", "checkout"]);
if staged {
cmd.arg("HEAD");
}
let output = cmd
.args(["--", rel_path])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git checkout failed with code {:?}", output.status.code())
} else {
msg
})
}
}
}
pub fn pull_current_branch(root: &Path) -> Result<String, String> {
run_mutation(root, &["pull"])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BranchInfo {
pub display: String,
pub checkout_name: String,
pub is_current: bool,
pub is_remote: bool,
}
pub fn list_branches(root: &Path) -> Result<Vec<BranchInfo>, String> {
let locals_raw = run_git(
root,
&[
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname:short)%09%(HEAD)",
"refs/heads",
],
)
.map_err(|e| e.to_string())?;
let mut branches: Vec<BranchInfo> = Vec::new();
let mut local_names: std::collections::HashSet<String> = std::collections::HashSet::new();
for line in locals_raw.lines() {
let mut parts = line.split('\t');
let Some(name) = parts.next() else { continue };
if name.is_empty() {
continue;
}
let is_current = parts.next().map(|m| m.trim() == "*").unwrap_or(false);
local_names.insert(name.to_string());
branches.push(BranchInfo {
display: name.to_string(),
checkout_name: name.to_string(),
is_current,
is_remote: false,
});
}
let remotes_raw = run_git(
root,
&[
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname:short)",
"refs/remotes",
],
)
.unwrap_or_default();
for full in remotes_raw.lines() {
if full.is_empty() || full.ends_with("/HEAD") {
continue;
}
let short = full.split_once('/').map(|(_, s)| s).unwrap_or(full);
if local_names.contains(short) {
continue;
}
branches.push(BranchInfo {
display: full.to_string(),
checkout_name: short.to_string(),
is_current: false,
is_remote: true,
});
}
Ok(branches)
}
pub fn checkout_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["switch", name])
}
pub fn create_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["switch", "-c", name])
}
pub fn stash_push(root: &Path) -> Result<String, String> {
run_mutation(root, &["stash", "push"])
}
pub fn stash_pop(root: &Path) -> Result<String, String> {
run_mutation(root, &["stash", "pop"])
}
pub fn fetch_all(root: &Path) -> Result<String, String> {
run_mutation(root, &["fetch", "--all", "--prune"])
}
pub fn clone_dir_name(url: &str) -> Option<String> {
let trimmed = url.trim().trim_end_matches('/');
let seg = trimmed.rsplit(['/', ':']).next()?.trim();
let name = seg.strip_suffix(".git").unwrap_or(seg).trim();
(!name.is_empty()).then(|| name.to_string())
}
pub fn clone_into(parent: &Path, url: &str) -> Result<PathBuf, String> {
let name =
clone_dir_name(url).ok_or_else(|| format!("can't derive a folder name from {url}"))?;
let dest = parent.join(&name);
run_mutation(parent, &["clone", "--", url, &name]).map(|_| dest)
}
pub fn commit_staged(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
run_mutation(root, &["commit", "-m", message])
}
pub fn commit_amend(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
run_mutation(root, &["commit", "--amend", "-m", message])
}
pub fn commit_amend_no_edit(root: &Path) -> Result<String, String> {
run_mutation(root, &["commit", "--amend", "--no-edit"])
}
pub fn stage_all(root: &Path) -> Result<String, String> {
run_mutation(root, &["add", "-A"])
}
pub fn unstage_all(root: &Path) -> Result<String, String> {
run_mutation(root, &["reset", "-q", "HEAD"])
}
pub fn discard_all_tracked(root: &Path) -> Result<String, String> {
run_mutation(root, &["checkout", "--", "."])
}
pub fn pull_rebase(root: &Path) -> Result<String, String> {
run_mutation(root, &["pull", "--rebase"])
}
pub fn push_force(root: &Path) -> Result<String, String> {
run_mutation(root, &["push", "--force-with-lease"])
}
pub fn push_to_remote(root: &Path, remote: &str) -> Result<String, String> {
run_mutation(root, &["push", remote])
}
pub fn publish_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation(root, &["push", "-u", "origin", branch])
}
pub fn create_branch_from(root: &Path, name: &str, base: &str) -> Result<String, String> {
run_mutation(root, &["switch", "-c", name, base])
}
pub fn rename_branch(root: &Path, new_name: &str) -> Result<String, String> {
run_mutation(root, &["branch", "-m", new_name])
}
pub fn delete_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["branch", "-d", name])
}
pub fn merge_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation(root, &["merge", branch])
}
pub fn rebase_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation(root, &["rebase", branch])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteInfo {
pub name: String,
pub url: String,
}
pub fn list_remotes(root: &Path) -> Result<Vec<RemoteInfo>, String> {
let raw = run_git(root, &["remote", "-v"]).map_err(|e| e.to_string())?;
let mut out: Vec<RemoteInfo> = Vec::new();
for line in raw.lines() {
let mut parts = line.split_whitespace();
let (Some(name), Some(url)) = (parts.next(), parts.next()) else {
continue;
};
if out.iter().any(|r| r.name == name) {
continue;
}
out.push(RemoteInfo {
name: name.to_string(),
url: url.to_string(),
});
}
Ok(out)
}
pub fn add_remote(root: &Path, name: &str, url: &str) -> Result<String, String> {
run_mutation(root, &["remote", "add", name, url])
}
pub fn remove_remote(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["remote", "remove", name])
}
pub fn stash_push_untracked(root: &Path) -> Result<String, String> {
run_mutation(root, &["stash", "push", "-u"])
}
pub fn stash_push_staged(root: &Path) -> Result<String, String> {
run_mutation(root, &["stash", "push", "--staged"])
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StashInfo {
pub index: usize,
pub message: String,
}
pub fn list_stashes(root: &Path) -> Result<Vec<StashInfo>, String> {
let raw =
run_git(root, &["stash", "list", "--format=%gd\x1f%gs"]).map_err(|e| e.to_string())?;
let mut out = Vec::new();
for line in raw.lines() {
let mut parts = line.split('\x1f');
let Some(reflog) = parts.next() else { continue };
let message = parts.next().unwrap_or("").to_string();
let index = reflog
.trim_start_matches("stash@{")
.trim_end_matches('}')
.parse::<usize>()
.unwrap_or(out.len());
out.push(StashInfo { index, message });
}
Ok(out)
}
pub fn stash_apply(root: &Path, index: usize) -> Result<String, String> {
run_mutation(root, &["stash", "apply", &format!("stash@{{{index}}}")])
}
pub fn stash_pop_at(root: &Path, index: usize) -> Result<String, String> {
run_mutation(root, &["stash", "pop", &format!("stash@{{{index}}}")])
}
pub fn stash_drop(root: &Path, index: usize) -> Result<String, String> {
run_mutation(root, &["stash", "drop", &format!("stash@{{{index}}}")])
}
pub fn list_tags(root: &Path) -> Result<Vec<String>, String> {
let raw = run_git(root, &["tag", "--sort=-creatordate"]).map_err(|e| e.to_string())?;
Ok(raw
.lines()
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect())
}
pub fn create_tag(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["tag", name])
}
pub fn delete_tag(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["tag", "-d", name])
}
pub fn humanize_age(secs_ago: i64) -> String {
let s = secs_ago.max(0);
if s < 60 {
return format!("{s} seconds ago");
}
let m = s / 60;
if m < 60 {
return format!("{m} minute{} ago", if m == 1 { "" } else { "s" });
}
let h = m / 60;
if h < 24 {
return format!("{h} hour{} ago", if h == 1 { "" } else { "s" });
}
let d = h / 24;
if d < 30 {
return format!("{d} day{} ago", if d == 1 { "" } else { "s" });
}
let mo = d / 30;
if mo < 12 {
return format!("{mo} month{} ago", if mo == 1 { "" } else { "s" });
}
let y = mo / 12;
format!("{y} year{} ago", if y == 1 { "" } else { "s" })
}
fn current_unix_seconds() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
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)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GitRequest {
Status,
StatusAndChanges,
SetRoot(PathBuf),
}
impl GitRequest {
pub fn merge(self, other: Self) -> Self {
use GitRequest::*;
match (self, other) {
(SetRoot(_), _) | (_, SetRoot(_)) => {
unreachable!(
"SetRoot is drained inline before merge; it cannot reach the query merge"
)
}
(StatusAndChanges, _) | (_, StatusAndChanges) => StatusAndChanges,
(Status, Status) => Status,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GitResponse {
Status(GitStatus),
StatusAndChanges(GitStatus, Vec<ChangeEntry>),
}
pub fn git_worker_loop(
initial_root: PathBuf,
rx: std::sync::mpsc::Receiver<GitRequest>,
tx: std::sync::mpsc::Sender<GitResponse>,
) {
let mut root = initial_root;
while let Ok(first) = rx.recv() {
let mut pending: Option<GitRequest> = match first {
GitRequest::SetRoot(p) => {
root = p;
None
}
other => Some(other),
};
while let Ok(newer) = rx.try_recv() {
match newer {
GitRequest::SetRoot(p) => {
root = p;
}
other => {
pending = Some(match pending {
Some(prev) => prev.merge(other),
None => other,
});
}
}
}
let Some(req) = pending else {
continue;
};
let resp = match req {
GitRequest::Status => GitResponse::Status(query(&root)),
GitRequest::StatusAndChanges => {
let s = query(&root);
let c = query_changes(&root);
GitResponse::StatusAndChanges(s, c)
}
GitRequest::SetRoot(_) => unreachable!("SetRoot was drained inline"),
};
if tx.send(resp).is_err() {
return;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn parse_branch_handles_typical_output() {
assert_eq!(parse_branch("main\n".into()), Some("main".to_string()));
assert_eq!(
parse_branch("feature/cool-thing\n".into()),
Some("feature/cool-thing".to_string())
);
}
#[test]
fn parse_branch_treats_empty_as_none() {
assert_eq!(parse_branch(String::new()), None);
assert_eq!(parse_branch(" \n".into()), None);
}
#[test]
fn parse_porcelain_dirty_empty_means_clean() {
assert!(!parse_porcelain_dirty(""));
assert!(!parse_porcelain_dirty("\n"));
assert!(!parse_porcelain_dirty(" "));
}
#[test]
fn parse_porcelain_dirty_any_line_means_dirty() {
assert!(parse_porcelain_dirty(" M src/app.rs\n"));
assert!(parse_porcelain_dirty("?? new.txt\n"));
assert!(parse_porcelain_dirty("MM Cargo.toml\n M src/lib.rs\n"));
}
#[test]
fn parse_ahead_behind_typical() {
assert_eq!(parse_ahead_behind("3\t2"), (3, 2));
assert_eq!(parse_ahead_behind("0\t0"), (0, 0));
assert_eq!(parse_ahead_behind("12\t0\n"), (12, 0));
}
#[test]
fn parse_ahead_behind_falls_back_to_zero_on_garbage() {
assert_eq!(parse_ahead_behind(""), (0, 0));
assert_eq!(parse_ahead_behind("?"), (0, 0));
}
#[test]
fn parse_commit_graph_splits_parents_and_refs() {
let line = format!(
"{h}\x1f{s}\x1f{p1} {p2}\x1fHEAD -> main, tag: v1.0, origin/main\x1ffeat: merge\x1fvitali87\x1f1000",
h = "a".repeat(40),
s = "aaaaaaa",
p1 = "b".repeat(40),
p2 = "c".repeat(40),
);
let commits = parse_commit_graph(&line, 4600);
assert_eq!(commits.len(), 1);
let c = &commits[0];
assert_eq!(c.short_hash, "aaaaaaa");
assert_eq!(c.parents, vec!["b".repeat(40), "c".repeat(40)]);
assert_eq!(
c.refs,
vec![
"HEAD -> main".to_string(),
"tag: v1.0".to_string(),
"origin/main".to_string()
]
);
assert_eq!(c.summary, "feat: merge");
assert_eq!(c.age_secs, 3600);
let root_line = format!(
"{h}\x1fddddddd\x1f\x1f\x1finit\x1ft\x1f1",
h = "d".repeat(40)
);
let commits = parse_commit_graph(&root_line, 1);
assert!(commits[0].parents.is_empty());
assert!(commits[0].refs.is_empty());
}
#[test]
fn commit_graph_of_a_real_merge_lays_out_the_diamond() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().canonicalize().unwrap();
let run = |args: &[&str]| {
let ok = Command::new("git")
.args(["-C", root.to_str().unwrap()])
.args(args)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?} failed");
};
run(&["init", "-q", "-b", "main"]);
run(&["config", "user.email", "t@t"]);
run(&["config", "user.name", "t"]);
std::fs::write(root.join("a.txt"), "1\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "root"]);
run(&["checkout", "-q", "-b", "feature"]);
std::fs::write(root.join("b.txt"), "2\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "feature work"]);
run(&["checkout", "-q", "main"]);
std::fs::write(root.join("c.txt"), "3\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "main work"]);
run(&["merge", "-q", "--no-ff", "-m", "merge feature", "feature"]);
let commits = commit_graph(&root, 50);
assert_eq!(commits.len(), 4, "root, two branches, one merge");
assert_eq!(commits[0].summary, "merge feature");
assert_eq!(commits[0].parents.len(), 2, "the merge has two parents");
assert!(
commits[0].refs.iter().any(|r| r.contains("main")),
"HEAD decoration must survive parsing; got {:?}",
commits[0].refs
);
let rows = crate::widgets::commit_graph::layout_graph(commits);
let rails: Vec<String> = rows
.iter()
.map(|r| r.cells.iter().map(|(ch, _)| *ch).collect())
.collect();
assert_eq!(
rails,
vec!["●╮", "│●", "●│", "●╯"],
"a no-ff merge of one branch must draw the diamond"
);
}
fn repo_with_two_hunks(root: &Path) {
let run = |args: &[&str]| {
let ok = Command::new("git")
.args(["-C", root.to_str().unwrap()])
.args(args)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?} failed");
};
run(&["init", "-q", "-b", "main"]);
run(&["config", "user.email", "t@t"]);
run(&["config", "user.name", "t"]);
let original: String = (1..=20).map(|i| format!("line{i}\n")).collect();
std::fs::write(root.join("f.txt"), original).unwrap();
run(&["add", "f.txt"]);
run(&["commit", "-q", "-m", "init"]);
let mut edited: Vec<String> = (1..=20).map(|i| format!("line{i}")).collect();
edited[1] = "LINE2".into();
edited[17] = "LINE18".into();
std::fs::write(root.join("f.txt"), edited.join("\n") + "\n").unwrap();
}
fn git_stdout(root: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(["-C", root.to_str().unwrap()])
.args(args)
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).to_string()
}
#[test]
fn apply_patch_cached_stages_only_the_given_hunk() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
repo_with_two_hunks(root);
let head = read_file_at_head(root, "f.txt").unwrap();
let work = std::fs::read_to_string(root.join("f.txt")).unwrap();
let diff = crate::widgets::diff::DiffData::build(
std::path::PathBuf::new(),
std::path::PathBuf::new(),
head.lines().map(str::to_string).collect(),
work.lines().map(str::to_string).collect(),
);
let range = diff.hunk_range_at(0).unwrap();
let patch = diff.hunk_patch("f.txt", range);
apply_patch(root, &patch, true, false).unwrap();
let staged = git_stdout(root, &["diff", "--cached"]);
assert!(staged.contains("+LINE2"), "hunk 1 must be staged: {staged}");
assert!(
!staged.contains("LINE18"),
"hunk 2 must NOT be staged: {staged}"
);
let unstaged = git_stdout(root, &["diff"]);
assert!(
unstaged.contains("+LINE18"),
"hunk 2 must stay in the working tree: {unstaged}"
);
apply_patch(root, &patch, true, true).unwrap();
let staged = git_stdout(root, &["diff", "--cached"]);
assert!(
staged.trim().is_empty(),
"reverse cached apply must empty the index diff: {staged}"
);
}
#[test]
fn apply_patch_reverse_reverts_only_the_given_hunk_in_the_working_tree() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
repo_with_two_hunks(root);
let head = read_file_at_head(root, "f.txt").unwrap();
let work = std::fs::read_to_string(root.join("f.txt")).unwrap();
let diff = crate::widgets::diff::DiffData::build(
std::path::PathBuf::new(),
std::path::PathBuf::new(),
head.lines().map(str::to_string).collect(),
work.lines().map(str::to_string).collect(),
);
let range = diff.hunk_range_at(0).unwrap();
let patch = diff.hunk_patch("f.txt", range);
apply_patch(root, &patch, false, true).unwrap();
let after = std::fs::read_to_string(root.join("f.txt")).unwrap();
assert!(after.contains("line2\n"), "hunk 1 must be reverted");
assert!(!after.contains("LINE2"), "hunk 1 edit must be gone");
assert!(after.contains("LINE18"), "hunk 2 must survive the revert");
}
#[test]
fn query_outside_a_git_repo_returns_in_repo_false() {
let tmp = TempDir::new().unwrap();
let s = query(tmp.path());
assert!(!s.in_repo);
assert!(s.branch.is_none());
assert!(!s.dirty);
}
#[test]
fn query_in_a_fresh_repo_finds_branch_and_clean() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let s = query(p);
assert!(s.in_repo);
assert_eq!(s.branch.as_deref(), Some("main"));
assert!(!s.dirty);
}
#[test]
fn query_reports_dirty_after_a_file_appears() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join("hello.txt"), "hi").unwrap();
let s = query(p);
assert!(s.in_repo);
assert!(s.dirty);
}
#[test]
fn query_collects_ignored_files_and_collapsed_dirs() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\nbuild/\n").unwrap();
std::fs::write(p.join("app.log"), "").unwrap();
std::fs::write(p.join("keep.txt"), "").unwrap();
std::fs::create_dir(p.join("build")).unwrap();
std::fs::write(p.join("build/out.txt"), "").unwrap();
let s = query(p);
assert!(s.ignored.contains(&p.join("app.log")));
assert!(
s.ignored.contains(&p.join("build")),
"a fully-ignored directory collapses to one entry, not its contents"
);
assert!(
!s.ignored.contains(&p.join("build/out.txt")),
"children of a collapsed ignored dir are not enumerated"
);
assert!(!s.ignored.contains(&p.join("keep.txt")));
assert!(!s.ignored.contains(&p.join(".gitignore")));
}
#[test]
fn a_directory_git_does_not_ignore_is_not_reported_as_ignored() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\n").unwrap();
std::fs::create_dir(p.join("logs")).unwrap();
std::fs::write(p.join("logs/app.log"), "").unwrap();
let s = query(p);
assert!(
s.ignored.contains(&p.join("logs/app.log")),
"the ignored file itself is still reported"
);
assert!(
!s.ignored.contains(&p.join("logs")),
"no rule matches `logs` itself, so it must not be greyed"
);
}
#[test]
fn git_raw_does_not_deadlock_on_a_payload_past_the_pipe_buffer() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\n").unwrap();
let n = 20_000;
let mut payload = Vec::new();
for i in 0..n {
payload.extend_from_slice(
format!("padded-name-to-widen-the-pipe-payload-{i:06}.log").as_bytes(),
);
payload.push(0);
}
let out =
git_raw(p, &["check-ignore", "-z", "--stdin"], Some(&payload)).unwrap_or_default();
let got = out.split(|b| *b == 0).filter(|s| !s.is_empty()).count();
assert_eq!(
got, n,
"every path must come back instead of stalling on a full pipe"
);
}
#[test]
fn a_filename_with_a_leading_space_is_reported_intact() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\n").unwrap();
std::fs::write(p.join(" leading.log"), "").unwrap();
std::fs::write(p.join("zz.log"), "").unwrap();
let s = query(p);
assert!(
s.ignored.contains(&p.join(" leading.log")),
"the leading space belongs to the filename; got {:?}",
s.ignored
);
assert!(s.ignored.contains(&p.join("zz.log")));
}
#[test]
fn one_paths_ignore_verdict_matches_the_rules() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\nout/\n").unwrap();
assert!(is_ignored(p, &p.join("a.log")));
assert!(
is_ignored(p, &p.join("out/deep/gen.rs")),
"under an ignored dir"
);
assert!(!is_ignored(p, &p.join("src/lib.rs")));
let bare = TempDir::new().unwrap();
assert!(
!is_ignored(bare.path(), &bare.path().join("a.log")),
"no repo"
);
}
#[test]
fn query_outside_a_repo_has_an_empty_ignored_set() {
let tmp = TempDir::new().unwrap();
let s = query(tmp.path());
assert!(s.ignored.is_empty());
}
#[test]
fn diff_previous_commit_shows_the_delta_since_the_last_commit() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(p)
.args(["-c", "user.email=t@t", "-c", "user.name=t"])
.args(args)
.output()
.unwrap();
};
git(&["init", "-q", "-b", "main"]);
std::fs::write(p.join("f.txt"), "one\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "first"]);
std::fs::write(p.join("f.txt"), "two\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "second"]);
let raw = diff_previous_commit(p).unwrap();
assert!(
raw.contains("-one"),
"diff vs previous commit must show the removed line; got: {raw}"
);
assert!(
raw.contains("+two"),
"diff vs previous commit must show the added line; got: {raw}"
);
}
#[test]
fn humanize_seconds_minutes_hours_days() {
assert_eq!(humanize_age(0), "0 seconds ago");
assert_eq!(humanize_age(45), "45 seconds ago");
assert_eq!(humanize_age(60), "1 minute ago");
assert_eq!(humanize_age(120), "2 minutes ago");
assert_eq!(humanize_age(3600), "1 hour ago");
assert_eq!(humanize_age(7200), "2 hours ago");
assert_eq!(humanize_age(86_400), "1 day ago");
assert_eq!(humanize_age(2 * 86_400), "2 days ago");
}
#[test]
fn humanize_clamps_negatives_to_zero() {
assert_eq!(humanize_age(-100), "0 seconds ago");
}
#[test]
fn parse_porcelain_changes_handles_unstaged_modified() {
let entries = parse_porcelain_changes(" M src/app.rs\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::Modified,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_handles_staged_modified() {
let entries = parse_porcelain_changes("M src/app.rs\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::StagedModified,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_emits_two_entries_for_partially_staged() {
let entries = parse_porcelain_changes("MM src/app.rs\n");
assert_eq!(
entries,
vec![
ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::StagedModified,
..Default::default()
},
ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::Modified,
..Default::default()
},
]
);
}
#[test]
fn parse_porcelain_changes_handles_untracked() {
let entries = parse_porcelain_changes("?? scratch.txt\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "scratch.txt".to_string(),
kind: ChangeKind::Untracked,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_handles_rename_takes_destination_path() {
let entries = parse_porcelain_changes("R old.txt -> new.txt\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "new.txt".to_string(),
kind: ChangeKind::StagedRenamed,
..Default::default()
}]
);
}
#[test]
fn unquote_porcelain_path_passes_plain_ascii_paths_through() {
assert_eq!(unquote_porcelain_path("README.md"), "README.md");
assert_eq!(unquote_porcelain_path("src/main.rs"), "src/main.rs");
}
#[test]
fn unquote_porcelain_path_strips_double_quotes_and_unescapes_spaces() {
assert_eq!(
unquote_porcelain_path("\"linked_list copy.py\""),
"linked_list copy.py",
);
}
#[test]
fn unquote_porcelain_path_decodes_c_style_escapes() {
assert_eq!(
unquote_porcelain_path(r#""line\nbreak.txt""#),
"line\nbreak.txt"
);
assert_eq!(
unquote_porcelain_path(r#""quote\"inside.txt""#),
"quote\"inside.txt"
);
assert_eq!(
unquote_porcelain_path(r#""back\\slash.txt""#),
"back\\slash.txt"
);
}
#[test]
fn unquote_porcelain_path_decodes_octal_utf8_sequences() {
assert_eq!(unquote_porcelain_path(r#""f\303\244.txt""#), "fä.txt");
}
#[test]
fn parse_porcelain_changes_de_quotes_paths_with_spaces() {
let entries = parse_porcelain_changes("?? \"linked_list copy.py\"\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "linked_list copy.py".to_string(),
kind: ChangeKind::Untracked,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_handles_conflict() {
let entries = parse_porcelain_changes("UU merge.txt\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "merge.txt".to_string(),
kind: ChangeKind::Conflicted,
..Default::default()
}]
);
}
#[test]
fn parse_numstat_extracts_additions_deletions_per_path() {
let out = "12\t3\tsrc/app.rs\n5\t0\tREADME.md\n-\t-\tassets/logo.png\n";
let map = parse_numstat(out);
assert_eq!(map.get("src/app.rs"), Some(&(12, 3)));
assert_eq!(map.get("README.md"), Some(&(5, 0)));
assert_eq!(map.get("assets/logo.png"), Some(&(0, 0)));
}
#[test]
fn parse_numstat_keys_renames_on_destination_path() {
let out = "2\t1\told.rs -> new.rs\n";
let map = parse_numstat(out);
assert_eq!(map.get("new.rs"), Some(&(2, 1)));
assert!(!map.contains_key("old.rs"));
}
#[test]
fn change_kind_section_groups_correctly() {
assert_eq!(ChangeKind::StagedAdded.section(), ChangeSection::Staged);
assert_eq!(ChangeKind::Modified.section(), ChangeSection::Changes);
assert_eq!(ChangeKind::Untracked.section(), ChangeSection::Untracked);
assert_eq!(ChangeKind::Conflicted.section(), ChangeSection::Conflicts);
}
#[test]
fn commit_all_tracked_rejects_empty_message() {
let tmp = TempDir::new().unwrap();
assert!(commit_all_tracked(tmp.path(), "").is_err());
assert!(commit_all_tracked(tmp.path(), " \n").is_err());
}
#[test]
fn commit_all_tracked_creates_a_commit_in_a_real_repo() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("hello.txt"), "hi").unwrap();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "."])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-m", "init", "--quiet"])
.status();
std::fs::write(p.join("hello.txt"), "hi v2").unwrap();
let summary = commit_all_tracked(p, "second commit").expect("commit should succeed");
assert!(
summary.contains("second commit") || summary.contains("main"),
"summary was: {summary}"
);
assert!(
query_changes(p).is_empty(),
"post-commit working tree should be clean"
);
}
#[test]
fn git_request_merge_collapses_status_and_changes_into_status_and_changes() {
assert_eq!(
GitRequest::Status.merge(GitRequest::Status),
GitRequest::Status,
);
assert_eq!(
GitRequest::Status.merge(GitRequest::StatusAndChanges),
GitRequest::StatusAndChanges,
);
assert_eq!(
GitRequest::StatusAndChanges.merge(GitRequest::Status),
GitRequest::StatusAndChanges,
);
}
#[test]
fn git_worker_loop_processes_a_status_and_changes_request_and_returns_entries() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("untracked.txt"), "x").unwrap();
let (req_tx, req_rx) = std::sync::mpsc::channel::<GitRequest>();
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<GitResponse>();
let root = p.to_path_buf();
let join = std::thread::spawn(move || git_worker_loop(root, req_rx, resp_tx));
req_tx.send(GitRequest::StatusAndChanges).unwrap();
let resp = resp_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("worker must reply within 10s");
match resp {
GitResponse::StatusAndChanges(_, entries) => {
assert_eq!(
entries.len(),
1,
"expected 1 untracked entry, got {entries:?}"
);
assert_eq!(entries[0].kind, ChangeKind::Untracked);
}
other => panic!("expected StatusAndChanges, got {other:?}"),
}
drop(req_tx);
join.join().unwrap();
}
#[test]
fn git_worker_loop_set_root_redirects_subsequent_query_to_the_new_root() {
let tmp_no_repo = TempDir::new().unwrap();
let tmp_repo = TempDir::new().unwrap();
let p_repo = tmp_repo.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p_repo)
.args(["init", "-q", "-b", "feature-x"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p_repo)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p_repo)
.args(["config", "user.name", "a"])
.status();
let (req_tx, req_rx) = std::sync::mpsc::channel::<GitRequest>();
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<GitResponse>();
let initial_root = tmp_no_repo.path().to_path_buf();
let join = std::thread::spawn(move || git_worker_loop(initial_root, req_rx, resp_tx));
req_tx
.send(GitRequest::SetRoot(p_repo.to_path_buf()))
.unwrap();
req_tx.send(GitRequest::Status).unwrap();
let resp = resp_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("worker must reply within 10s after SetRoot+Status");
match resp {
GitResponse::Status(status) => {
assert!(
status.in_repo,
"after SetRoot to a real git repo the next Status must report in_repo=true (the bug was that SetRoot didn't exist, so queries kept hitting the stale root captured at thread spawn)"
);
assert_eq!(status.branch.as_deref(), Some("feature-x"));
}
other => panic!("expected Status, got {other:?}"),
}
drop(req_tx);
join.join().unwrap();
}
#[test]
fn git_worker_loop_coalesces_a_burst_into_one_status_and_changes_response() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
let (req_tx, req_rx) = std::sync::mpsc::channel::<GitRequest>();
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<GitResponse>();
let root = p.to_path_buf();
req_tx.send(GitRequest::Status).unwrap();
req_tx.send(GitRequest::StatusAndChanges).unwrap();
let join = std::thread::spawn(move || git_worker_loop(root, req_rx, resp_tx));
let first = resp_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("worker must reply within 10s");
assert!(
matches!(first, GitResponse::StatusAndChanges(_, _)),
"burst must coalesce into one StatusAndChanges response, got {first:?}",
);
let second = resp_rx.recv_timeout(std::time::Duration::from_millis(200));
assert!(
second.is_err(),
"coalesce must produce exactly one response per burst, got an extra {second:?}",
);
drop(req_tx);
join.join().unwrap();
}
fn sh_git(p: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).into_owned()
}
#[test]
fn staging_a_bracketed_path_stages_only_that_file() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::create_dir(p.join("pages")).unwrap();
std::fs::write(p.join("pages/[id].tsx"), "a").unwrap();
std::fs::write(p.join("pages/i.tsx"), "b").unwrap();
stage_paths(p, &[String::from("pages/[id].tsx")]).unwrap();
let staged = sh_git(p, &["diff", "--cached", "--name-only"]);
assert_eq!(staged.trim(), "pages/[id].tsx");
unstage_paths(p, &[String::from("pages/[id].tsx")]).unwrap();
assert_eq!(sh_git(p, &["diff", "--cached", "--name-only"]).trim(), "");
}
#[test]
fn discarding_a_changes_row_keeps_the_staged_part() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "staged\n").unwrap();
sh_git(p, &["add", "seed.txt"]);
std::fs::write(p.join("seed.txt"), "staged\nunstaged\n").unwrap();
discard_path(p, "seed.txt", false, false).unwrap();
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"staged\n"
);
assert_eq!(
sh_git(p, &["diff", "--cached", "--name-only"]).trim(),
"seed.txt"
);
}
#[test]
fn discarding_an_untracked_folder_keeps_its_ignored_files() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join(".gitignore"), ".env\n").unwrap();
sh_git(p, &["add", ".gitignore"]);
sh_git(p, &["commit", "-qm", "ignore"]);
std::fs::create_dir(p.join("app")).unwrap();
std::fs::write(p.join("app/new.rs"), "x").unwrap();
std::fs::write(p.join("app/.env"), "SECRET=1").unwrap();
discard_path(p, "app/", true, false).unwrap();
assert!(!p.join("app/new.rs").exists());
assert!(
p.join("app/.env").exists(),
"an ignored file is not the discard's to delete"
);
}
#[test]
fn a_single_hunk_stages_and_reverts_at_its_own_lines() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let head: String = (0..12)
.map(|i| if i % 2 == 0 { "a\n" } else { "c\n" })
.collect();
std::fs::write(p.join("f.txt"), &head).unwrap();
sh_git(p, &["add", "f.txt"]);
sh_git(p, &["commit", "-qm", "f"]);
let mut work: Vec<&str> = head.lines().collect();
work.insert(9, "cz");
for _ in 0..3 {
work.insert(0, "top");
}
let work_text = work.join("\n") + "\n";
std::fs::write(p.join("f.txt"), &work_text).unwrap();
let patch = "--- a/f.txt\n+++ b/f.txt\n@@ -9,2 +12,3 @@\n a\n+cz\n c\n";
apply_patch(p, patch, true, false).unwrap();
let staged = sh_git(p, &["show", ":f.txt"]);
let mut want: Vec<&str> = head.lines().collect();
want.insert(9, "cz");
assert_eq!(staged, want.join("\n") + "\n", "staged at HEAD line 9");
sh_git(p, &["reset", "-q"]);
apply_patch(p, patch, false, true).unwrap();
let reverted = std::fs::read_to_string(p.join("f.txt")).unwrap();
let mut want: Vec<&str> = work_text.lines().collect();
want.remove(12);
assert_eq!(
reverted,
want.join("\n") + "\n",
"reverted at working line 12"
);
}
#[test]
fn a_pull_request_head_checks_out_into_a_sibling_worktree() {
let tmp = tempfile::tempdir().unwrap();
let git = |dir: &Path, args: &[&str]| {
let out = Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
let up = tmp.path().join("up");
std::fs::create_dir(&up).unwrap();
init_repo_with_commit(&up);
let pr_commit = |msg: &str| {
std::fs::write(up.join("pr.txt"), msg).unwrap();
git(&up, &["add", "."]);
git(&up, &["commit", "-q", "-m", msg]);
let sha = git(&up, &["rev-parse", "HEAD"]);
git(&up, &["update-ref", "refs/pull/7/head", &sha]);
sha
};
let first = pr_commit("one");
let app = tmp.path().join("app");
git(tmp.path(), &["clone", "-q", up.to_str().unwrap(), "app"]);
git(&app, &["config", "user.email", "a@b"]);
git(&app, &["config", "user.name", "a"]);
let path = pr_worktree_path(&app, 7).unwrap();
assert_eq!(path, tmp.path().join("app-pr-7"));
let remote = remote_for_slug(&app, "o/r");
assert_eq!(remote, "https://github.com/o/r.git", "no remote names o/r");
assert_eq!(
checkout_pr_worktree(&app, "origin", 7, &path, None),
Ok(PrWorktree {
oid: first.clone(),
created: true
})
);
assert_eq!(std::fs::read_to_string(path.join("pr.txt")).unwrap(), "one");
assert_eq!(pr_worktree_keep_reason(&path, &first), None);
let second = pr_commit("two");
let err = checkout_pr_worktree(&app, "origin", 7, &path, None).unwrap_err();
assert!(err.contains("did not check out"), "{err}");
assert_eq!(
checkout_pr_worktree(&app, "origin", 7, &path, Some(&first)),
Ok(PrWorktree {
oid: second.clone(),
created: false
})
);
assert_eq!(std::fs::read_to_string(path.join("pr.txt")).unwrap(), "two");
std::fs::write(path.join("pr.txt"), "edited").unwrap();
assert!(pr_worktree_keep_reason(&path, &second).is_some());
git(&path, &["commit", "-q", "-am", "mine"]);
let why = pr_worktree_keep_reason(&path, &second).expect("a new commit keeps it");
assert!(why.contains("commits"), "{why}");
let mine = git(&path, &["rev-parse", "HEAD"]);
let third = pr_commit("three");
let err = checkout_pr_worktree(&app, "origin", 7, &path, Some(&second)).unwrap_err();
assert!(err.contains("did not check out"), "{err}");
assert_eq!(worktree_head(&path).as_deref(), Some(mine.as_str()));
assert_ne!(mine, third);
let stray = pr_worktree_path(&app, 8).unwrap();
std::fs::create_dir(&stray).unwrap();
let second_pr = git(&up, &["rev-parse", "HEAD"]);
git(&up, &["update-ref", "refs/pull/8/head", &second_pr]);
let err = checkout_pr_worktree(&app, "origin", 8, &stray, None).unwrap_err();
assert!(err.contains("not a worktree"), "{err}");
}
#[test]
fn the_pull_request_remote_is_the_one_naming_the_repository() {
let tmp = tempfile::tempdir().unwrap();
init_repo_with_commit(tmp.path());
for (name, url) in [
("origin", "git@github.com:me/fork.git"),
("upstream", "https://github.com/Owner/Repo"),
] {
let _ = Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(["remote", "add", name, url])
.status();
}
assert_eq!(remote_for_slug(tmp.path(), "owner/repo"), "upstream");
assert_eq!(remote_for_slug(tmp.path(), "me/fork"), "origin");
}
fn init_repo_with_commit(p: &Path) {
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("seed.txt"), "one\ntwo\n").unwrap();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "."])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-m", "init", "--quiet"])
.status();
}
#[test]
fn repo_toplevel_resolves_from_a_subdirectory_and_refuses_outside_a_repo() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let sub = p.join("crates").join("foo");
std::fs::create_dir_all(&sub).unwrap();
let top = repo_toplevel(&sub).expect("a repo subdirectory resolves to its toplevel");
assert_eq!(
top.canonicalize().unwrap(),
p.canonicalize().unwrap(),
"the toplevel is the repo root, not the subdirectory"
);
let outside = TempDir::new().unwrap();
assert_eq!(
repo_toplevel(outside.path()),
None,
"outside a repo there is no toplevel"
);
}
#[test]
fn query_from_a_subdir_carries_the_repo_root_and_counts_untracked_lines() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let sub = p.join("crates").join("foo");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(p.join("notes.txt"), "one\ntwo\nthree\n").unwrap();
let status = query(&sub);
assert!(status.in_repo, "a subdir of a repo is inside the repo");
assert_eq!(
status
.repo_root
.as_ref()
.expect("the status carries the discovered toplevel")
.canonicalize()
.unwrap(),
p.canonicalize().unwrap(),
);
let entries = query_changes(&sub);
let notes = entries
.iter()
.find(|e| e.path == "notes.txt")
.expect("porcelain reports the toplevel file from a subdir workspace");
assert_eq!(
notes.additions, 3,
"untracked line counts must join the porcelain path against the TOPLEVEL"
);
}
#[test]
fn a_lane_name_becomes_a_safe_branch_and_directory() {
let plan = |name: &str| WorktreeLane::plan(Path::new("/repos/croft"), name);
let p = plan("fix the parser").expect("an ordinary name");
assert_eq!(p.branch, "agent/fix-the-parser");
assert_eq!(p.path, PathBuf::from("/repos/croft-fix-the-parser"));
assert!(
!p.path.starts_with("/repos/croft/"),
"a lane must not nest inside its own repo: {}",
p.path.display()
);
for name in [
"a..b", "a b", "a~b", "a^b", "a:b", "a?b", "a*b", "a[b", "a\\b",
] {
let p = plan(name).unwrap_or_else(|| panic!("{name} should still plan"));
assert!(
!p.branch.contains("..")
&& !p.branch.contains(' ')
&& !p.branch.contains(['~', '^', ':', '?', '*', '[', '\\']),
"{name} produced an unsafe branch: {}",
p.branch
);
}
let long = plan(&"parser".repeat(50)).expect("a long name still plans");
let dir = long
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
assert!(dir.len() < 100, "directory name is {} bytes", dir.len());
assert!(!long.branch.ends_with('-'), "branch: {}", long.branch);
for empty in ["", " ", "///", "..."] {
assert!(plan(empty).is_none(), "{empty:?} must not yield a lane");
}
}
#[test]
fn a_dirty_lane_refuses_removal_and_a_clean_one_allows_it() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let side = TempDir::new().unwrap();
let lane = side.path().join("lane-clean");
let git = |args: &[&str]| {
let _ = Command::new("git").args(["-C"]).arg(p).args(args).status();
};
git(&[
"worktree",
"add",
"-q",
"-b",
"lane",
lane.to_str().unwrap(),
]);
assert!(lane.is_dir(), "staging: the worktree exists");
assert_eq!(lane_removal_block(&lane), None, "a clean lane may go");
std::fs::write(lane.join("scratch.txt"), "unsaved").unwrap();
let why = lane_removal_block(&lane).expect("a dirty lane must be refused");
assert!(
why.contains("uncommitted"),
"the refusal must say why: {why}"
);
std::fs::remove_file(lane.join("scratch.txt")).unwrap();
std::fs::write(lane.join(".gitignore"), "*.local\n").unwrap();
let lane_git0 = |args: &[&str]| {
let _ = Command::new("git")
.args(["-C"])
.arg(&lane)
.args(args)
.status();
};
lane_git0(&["add", "-A"]);
lane_git0(&["commit", "-q", "-m", "ignore"]);
std::fs::write(lane.join("secrets.local"), "TOKEN=1").unwrap();
assert!(
plain_status_is_clean(&lane),
"control: plain --porcelain sees nothing, which is the trap"
);
let why = lane_removal_block(&lane).expect("ignored files must refuse");
assert!(
why.contains("ignored"),
"the refusal must name what it is protecting: {why}"
);
std::fs::remove_file(lane.join("secrets.local")).unwrap();
let lane_git = |args: &[&str]| {
let _ = Command::new("git")
.args(["-C"])
.arg(&lane)
.args(args)
.status();
};
lane_git(&["add", "-A"]);
lane_git(&["commit", "-q", "-m", "keep"]);
assert_eq!(
lane_removal_block(&lane),
None,
"a committed lane is clean again"
);
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["worktree", "remove", "--force", lane.to_str().unwrap()])
.status();
let outside = TempDir::new().unwrap();
let why = lane_removal_block(outside.path())
.expect("a directory that is not a worktree must be refused");
assert!(
why.contains("worktree") || why.contains("could not run"),
"the refusal must say what went wrong: {why}"
);
let gone = outside.path().join("no-such-lane");
assert!(
lane_removal_block(&gone).is_some(),
"a missing path must be refused rather than reported clean"
);
}
#[test]
fn branch_history_is_the_current_branch_with_head_first() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let git = |args: &[&str]| {
let _ = Command::new("git").args(["-C"]).arg(p).args(args).status();
};
git(&["checkout", "-q", "-b", "sibling"]);
std::fs::write(p.join("sibling.txt"), "s").unwrap();
git(&["add", "-A"]);
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-q", "-m", "sibling-future"])
.env("GIT_COMMITTER_DATE", "2038-01-01T00:00:00")
.env("GIT_AUTHOR_DATE", "2038-01-01T00:00:00")
.status();
git(&["checkout", "-q", "-"]);
let head = Command::new("git")
.args(["-C"])
.arg(p)
.args(["rev-parse", "HEAD"])
.output()
.expect("rev-parse");
let head = String::from_utf8_lossy(&head.stdout).trim().to_string();
let hist = branch_history(p, 50);
assert!(!hist.is_empty(), "the branch has commits");
assert_eq!(
hist[0].hash, head,
"index 0 must be HEAD, not whatever sorted first across branches"
);
assert!(
hist.iter().all(|c| c.summary != "sibling-future"),
"a sibling branch's commit leaked into the branch history: {:?}",
hist.iter().map(|c| &c.summary).collect::<Vec<_>>()
);
let graph = commit_graph(p, 50);
assert!(
graph.iter().any(|c| c.summary == "sibling-future"),
"control: commit_graph should see every branch"
);
}
#[test]
fn tree_paths_lists_a_commits_files_and_folders_under_the_root() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let git = |args: &[&str]| {
let _ = Command::new("git").args(["-C"]).arg(p).args(args).status();
};
std::fs::create_dir_all(p.join("sub/deep")).unwrap();
std::fs::write(p.join("sub/deep/new.txt"), "n").unwrap();
git(&["add", "-A"]);
git(&["commit", "-q", "-m", "add new"]);
let before = tree_paths(p, "HEAD~1").expect("HEAD~1 lists");
assert!(before.contains(&p.join("seed.txt")));
assert!(!before.contains(&p.join("sub/deep/new.txt")));
assert!(!before.contains(&p.join("sub")));
let head = tree_paths(p, "HEAD").expect("HEAD lists");
assert!(head.contains(&p.join("sub/deep/new.txt")));
assert!(head.contains(&p.join("sub")), "folders are listed too");
assert!(head.contains(&p.join("sub/deep")));
let sub = p.join("sub");
let nested = tree_paths(&sub, "HEAD").expect("subdir lists");
assert!(nested.contains(&sub.join("deep/new.txt")));
assert!(!nested.paths.iter().any(|q| q.ends_with("seed.txt")));
assert!(tree_paths(p, "no-such-rev").is_none());
let head_sha = String::from_utf8(
Command::new("git")
.arg("-C")
.arg(p)
.args(["rev-parse", "HEAD"])
.output()
.unwrap()
.stdout,
)
.unwrap();
let cacheinfo = format!("160000,{},vendored", head_sha.trim());
git(&["update-index", "--add", "--cacheinfo", &cacheinfo]);
git(&["commit", "-q", "-m", "add submodule"]);
let with_sub = tree_paths(p, "HEAD").expect("HEAD lists");
assert_eq!(with_sub.submodules, vec![p.join("vendored")]);
assert!(with_sub.contains(&p.join("vendored/src/lib.rs")));
assert!(!with_sub.contains(&p.join("vendoredx")));
}
fn plain_status_is_clean(lane: &Path) -> bool {
let out = Command::new("git")
.args(["-C"])
.arg(lane)
.args(["status", "--porcelain"])
.output()
.expect("git status");
String::from_utf8_lossy(&out.stdout).trim().is_empty()
}
#[test]
fn a_failed_lane_creation_leaves_the_base_unset() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
run_git_mut(p, &["checkout", "-b", "release-9"]).expect("branch");
let mut first = WorktreeLane::plan(p, "parser work").expect("planned");
add_worktree_lane(p, &mut first).expect("the first lane is created");
assert_eq!(first.base.as_deref(), Some("release-9"), "precondition");
let mut second = WorktreeLane::plan(p, "parser work").expect("planned");
assert!(add_worktree_lane(p, &mut second).is_err(), "precondition");
assert_eq!(
second.base, None,
"a lane git refused to create records no base"
);
remove_worktree_lane(&first.path).expect("cleanup");
}
#[test]
fn a_lane_records_the_branch_it_was_cut_from() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
run_git_mut(p, &["checkout", "-b", "release-42"]).expect("branch");
let mut lane = WorktreeLane::plan(p, "parser work").expect("planned");
assert_eq!(lane.base, None, "plan is pure and reads no git");
add_worktree_lane(p, &mut lane).expect("git worktree add should succeed");
assert_eq!(
lane.base.as_deref(),
Some("release-42"),
"the lane records the branch HEAD was on, not a default"
);
assert_ne!(
lane.base.as_deref(),
Some(lane.branch.as_str()),
"the base is what it forked FROM, never the lane's own branch"
);
remove_worktree_lane(&lane.path).expect("cleanup");
}
#[test]
fn a_lane_is_created_and_removed_through_git() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let mut lane = WorktreeLane::plan(p, "parser work").expect("planned");
assert!(lane.path.starts_with(p.parent().unwrap()), "a sibling");
add_worktree_lane(p, &mut lane).expect("git worktree add should succeed");
assert!(lane.path.is_dir(), "the lane directory exists");
let out = Command::new("git")
.args(["-C"])
.arg(&lane.path)
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.output()
.expect("rev-parse");
assert_eq!(
String::from_utf8_lossy(&out.stdout).trim(),
lane.branch,
"the lane must be on its own branch"
);
assert!(
add_worktree_lane(p, &mut lane).is_err(),
"a duplicate lane must fail rather than adopt the existing one"
);
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["worktree", "lock", lane.path.to_str().unwrap()])
.status();
assert_eq!(
lane_removal_block(&lane.path),
None,
"a locked-but-clean lane has no uncommitted work"
);
assert!(
remove_worktree_lane(&lane.path).is_err(),
"git must refuse a locked worktree, and the caller must hear it"
);
assert!(lane.path.is_dir(), "the refusal left the lane in place");
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["worktree", "unlock", lane.path.to_str().unwrap()])
.status();
remove_worktree_lane(&lane.path).expect("a clean lane removes");
assert!(!lane.path.exists(), "the lane directory is gone");
}
#[test]
fn diff_staged_returns_only_indexed_changes() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "seed.txt"])
.status();
std::fs::write(p.join("untracked.txt"), "z").unwrap();
let out = diff_staged(p).expect("git diff --staged should succeed");
assert!(
out.contains("+three"),
"staged diff must include the +three line that was indexed: {out}"
);
assert!(
!out.contains("untracked.txt"),
"untracked file must NOT appear in staged diff: {out}"
);
}
#[test]
fn default_branch_resolves_main_when_only_local() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let b = default_branch(p).expect("default branch must resolve");
assert_eq!(b, "main", "freshly init -b main repo must resolve to main");
}
#[test]
fn diff_against_branch_shows_working_tree_versus_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
let out = diff_against_branch(p, "main").expect("diff main should succeed");
assert!(
out.contains("+three"),
"diff vs branch must include the new +three line: {out}"
);
}
#[test]
fn a_commit_from_before_a_rename_shows_its_diff_under_the_old_name() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
let o = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
assert!(
o.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
String::from_utf8_lossy(&o.stdout).trim().to_string()
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(p.join("old.txt"), "one\ntwo\nthree\nfour\n").unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "add"]);
std::fs::write(p.join("old.txt"), "one\ntwo\nthree\nFOUR\n").unwrap();
git(&["commit", "-qam", "edit"]);
let edit = git(&["rev-parse", "--short", "HEAD"]);
git(&["mv", "old.txt", "new.txt"]);
git(&["commit", "-qm", "rename"]);
let diff = show_commit_file_diff(p, &edit, "new.txt").unwrap();
assert!(diff.contains("+FOUR"), "{diff}");
}
#[test]
fn parse_file_history_splits_fields_and_computes_age() {
let now = 10_000i64;
let out = "abc123\x1ffix: thing\x1fvitali87\x1f9_996\n\
def456\x1ffeat: thing\x1falice\x1f7600"
.replace('_', "");
let entries = parse_file_history(&out, now);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].short_hash, "abc123");
assert_eq!(entries[0].summary, "fix: thing");
assert_eq!(entries[0].author, "vitali87");
assert_eq!(
entries[0].age_secs, 4,
"now (10000) minus commit time (9996)"
);
assert_eq!(entries[1].age_secs, 2400);
assert!(parse_file_history("oops-no-fields", now).is_empty());
}
#[test]
fn file_history_returns_real_commits_for_a_tracked_file() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let hist = file_history(p, "seed.txt", 10);
assert!(
!hist.is_empty(),
"a committed file must have at least one history entry"
);
}
#[test]
fn parse_blame_groups_porcelain_into_one_entry_per_line() {
let now = 10_000i64;
let out = "\
abcdef0123456789abcdef0123456789abcdef01 1 1 1
author Vitali
author-time 9996
summary fix: the thing
filename seed.txt
\tone
0000000000000000000000000000000000000000 2 2 1
author Not Committed Yet
author-time 9999
summary Version of seed.txt from seed.txt
filename seed.txt
\ttwo
";
let b = parse_blame(out, now);
assert_eq!(b.len(), 2, "one entry per source line");
assert_eq!(b[0].short_hash, "abcdef01");
assert_eq!(b[0].author, "Vitali");
assert_eq!(b[0].summary, "fix: the thing");
assert_eq!(b[0].age_secs, 4, "now (10000) minus author-time (9996)");
assert!(!b[0].uncommitted);
assert!(b[1].uncommitted, "the zero hash marks an uncommitted line");
}
#[test]
fn blame_returns_one_entry_per_committed_line() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let b = blame(p, "seed.txt");
assert_eq!(b.len(), 2, "blame reports every source line");
assert_eq!(
b[0].author, "a",
"committed by init_repo_with_commit's user"
);
assert!(!b[0].uncommitted);
assert!(!b[0].short_hash.is_empty());
}
fn stage(p: &Path, rel: &str) {
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", rel])
.status();
}
fn is_staged(p: &Path, rel: &str) -> bool {
query_changes(p)
.iter()
.any(|e| e.path == rel && e.kind.section() == ChangeSection::Staged)
}
#[test]
fn unstage_path_moves_a_staged_file_back_to_changes() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
stage(p, "seed.txt");
assert!(is_staged(p, "seed.txt"), "precondition: seed.txt is staged");
unstage_path(p, "seed.txt").expect("unstage must succeed");
assert!(
!is_staged(p, "seed.txt"),
"after unstage the modification is back in the working tree, not the index"
);
}
#[test]
fn unstage_paths_is_a_noop_on_an_empty_list() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
assert!(unstage_paths(p, &[]).is_ok());
}
#[test]
fn create_branch_then_list_branches_marks_the_new_current_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_branch(p, "feature/x").expect("create_branch must succeed");
let branches = list_branches(p).expect("list_branches must succeed");
let current: Vec<&BranchInfo> = branches.iter().filter(|b| b.is_current).collect();
assert_eq!(current.len(), 1, "exactly one branch is current");
assert_eq!(current[0].display, "feature/x");
assert!(
branches
.iter()
.any(|b| b.display == "main" && !b.is_current)
);
}
#[test]
fn checkout_branch_switches_back_to_an_existing_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_branch(p, "feature/x").unwrap();
checkout_branch(p, "main").expect("checkout_branch must succeed");
let branch = query(p).branch;
assert_eq!(branch.as_deref(), Some("main"));
}
#[test]
fn stash_push_then_pop_round_trips_a_working_tree_change() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nstashed\n").unwrap();
stash_push(p).expect("stash push must succeed");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\n"
);
stash_pop(p).expect("stash pop must succeed");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\nstashed\n",
"pop restores the stashed edit"
);
}
#[test]
fn clone_dir_name_strips_dot_git_and_path() {
assert_eq!(
clone_dir_name("https://codeberg.org/vitali87/croft.git").as_deref(),
Some("croft")
);
assert_eq!(
clone_dir_name("git@github.com:owner/repo.git").as_deref(),
Some("repo")
);
assert_eq!(
clone_dir_name("https://host/path/thing/").as_deref(),
Some("thing")
);
assert_eq!(clone_dir_name(" ").as_deref(), None);
}
#[test]
fn stage_all_then_unstage_all_round_trips_the_index() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
std::fs::write(p.join("new.txt"), "x").unwrap();
stage_all(p).expect("stage_all");
assert!(is_staged(p, "seed.txt"));
assert!(is_staged(p, "new.txt"), "untracked file is staged by -A");
unstage_all(p).expect("unstage_all");
assert!(!is_staged(p, "seed.txt"));
assert!(!is_staged(p, "new.txt"));
}
#[test]
fn discard_all_tracked_reverts_modifications_but_keeps_untracked() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nDIRTY\n").unwrap();
std::fs::write(p.join("scratch.txt"), "keep me").unwrap();
discard_all_tracked(p).expect("discard_all_tracked");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\n",
"tracked modification is reverted to HEAD"
);
assert!(
p.join("scratch.txt").exists(),
"untracked files survive a tracked-only discard"
);
}
#[test]
fn commit_staged_commits_only_the_index() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nstaged\n").unwrap();
std::fs::write(p.join("other.txt"), "unstaged").unwrap();
stage(p, "seed.txt");
commit_staged(p, "only staged").expect("commit_staged");
assert!(
query_changes(p).iter().any(|e| e.path == "other.txt"),
"an unstaged file must remain a pending change after commit_staged"
);
}
#[test]
fn rename_branch_changes_the_current_branch_name() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
rename_branch(p, "renamed").expect("rename_branch");
assert_eq!(query(p).branch.as_deref(), Some("renamed"));
}
#[test]
fn delete_branch_removes_a_merged_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_branch(p, "throwaway").unwrap();
checkout_branch(p, "main").unwrap();
delete_branch(p, "throwaway").expect("delete_branch");
assert!(
!list_branches(p)
.unwrap()
.iter()
.any(|b| b.display == "throwaway"),
"the deleted branch must be gone"
);
}
#[test]
fn add_then_list_then_remove_remote_round_trips() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
add_remote(p, "upstream", "https://example.com/x.git").expect("add_remote");
let remotes = list_remotes(p).unwrap();
assert!(
remotes
.iter()
.any(|r| r.name == "upstream" && r.url == "https://example.com/x.git")
);
remove_remote(p, "upstream").expect("remove_remote");
assert!(
!list_remotes(p)
.unwrap()
.iter()
.any(|r| r.name == "upstream")
);
}
#[test]
fn create_then_list_then_delete_tag_round_trips() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_tag(p, "v1.0.0").expect("create_tag");
assert!(list_tags(p).unwrap().contains(&"v1.0.0".to_string()));
delete_tag(p, "v1.0.0").expect("delete_tag");
assert!(!list_tags(p).unwrap().contains(&"v1.0.0".to_string()));
}
#[test]
fn stash_list_indexes_newest_first_and_apply_drop_work() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nfirst\n").unwrap();
stash_push(p).expect("first stash");
std::fs::write(p.join("seed.txt"), "one\ntwo\nsecond\n").unwrap();
stash_push(p).expect("second stash");
let stashes = list_stashes(p).unwrap();
assert_eq!(stashes.len(), 2);
assert_eq!(stashes[0].index, 0, "newest stash is stash@{{0}}");
stash_apply(p, 1).expect("stash_apply");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\nfirst\n"
);
assert_eq!(list_stashes(p).unwrap().len(), 2);
stash_drop(p, 0).expect("stash_drop");
assert_eq!(list_stashes(p).unwrap().len(), 1);
}
#[test]
fn pull_on_an_up_to_date_clone_succeeds() {
let upstream = TempDir::new().unwrap();
let up = upstream.path();
init_repo_with_commit(up);
let clone = TempDir::new().unwrap();
let clone_path = clone.path().join("work");
let ok = Command::new("git")
.args(["clone", "-q"])
.arg(up)
.arg(&clone_path)
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "clone of the local upstream must succeed");
let summary = pull_current_branch(&clone_path).expect("pull must succeed");
assert!(
summary.to_lowercase().contains("up to date") || summary.is_empty(),
"an up-to-date pull reports no new work (got: {summary:?})"
);
}
}