use super::*;
pub fn commit(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
refuse_unmerged(root)?;
let flags = if has_staged_changes(root)? {
"-m"
} else {
"-am"
};
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, "commit", flags, message]);
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 !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 unmerged_paths(root: &Path) -> Vec<String> {
let Ok(out) = Command::new("git")
.arg("-C")
.arg(root)
.args(["diff", "--no-relative", "--name-only", "--diff-filter=U", "-z"])
.output()
else {
return Vec::new();
};
let mut paths: Vec<String> = String::from_utf8_lossy(&out.stdout)
.split('\0')
.filter(|p| !p.is_empty())
.map(String::from)
.collect();
paths.dedup();
paths
}
pub fn refuse_unmerged(root: &Path) -> Result<(), String> {
let paths = unmerged_paths(root);
if paths.is_empty() {
return Ok(());
}
let named = first_paths(&paths);
let (n, them) = match paths.len() {
1 => (String::from("1 merge conflict"), "it"),
n => (format!("{n} merge conflicts"), "them"),
};
Err(format!(
"Resolve {n} ({named}) and stage {them} before committing"
))
}
pub(super) fn has_staged_changes(root: &Path) -> Result<bool, String> {
let output = Command::new("git")
.arg("-C")
.arg(root)
.env("GIT_OPTIONAL_LOCKS", "0")
.args([
"diff",
"--cached",
"--quiet",
"--no-relative",
"--ignore-submodules=none",
"--no-ext-diff",
])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
match output.status.code() {
Some(0) => Ok(false),
Some(1) => Ok(true),
code => {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(if stderr.is_empty() {
format!("git diff --cached failed with code {code:?}")
} else {
stderr
})
}
}
}
pub(super) fn first_paths(paths: &[String]) -> String {
let mut named = paths.iter().take(3).cloned().collect::<Vec<_>>().join(", ");
if paths.len() > 3 {
named.push_str(", …");
}
named
}
pub(super) fn refuse_conflict_markers(root: &Path, scope: Option<&[String]>) -> Result<(), String> {
let unmerged = unmerged_paths(root);
if unmerged.is_empty() {
return Ok(());
}
let Some(top) = repo_toplevel(root) else {
return Ok(());
};
let canon = |p: PathBuf| std::fs::canonicalize(&p).unwrap_or(p);
let scope: Option<Vec<PathBuf>> =
scope.map(|paths| paths.iter().map(|p| canon(root.join(p))).collect());
let marked: Vec<String> = unmerged
.into_iter()
.filter(|rel| {
let abs = canon(top.join(rel));
scope
.as_ref()
.is_none_or(|scope| scope.iter().any(|s| abs.starts_with(s)))
&& leftover_conflict_markers(&top, rel)
})
.collect();
if marked.is_empty() {
return Ok(());
}
let (has, them) = if marked.len() == 1 {
("has", "it")
} else {
("have", "them")
};
Err(format!(
"{} still {has} conflict markers: resolve {them} before staging",
first_paths(&marked)
))
}
pub(super) fn leftover_conflict_markers(top: &Path, rel: &str) -> bool {
Command::new("git")
.arg("-C")
.arg(top)
.args(["--literal-pathspecs", "diff", "--check", "--no-color", "--"])
.arg(rel)
.output()
.is_ok_and(|out| String::from_utf8_lossy(&out.stdout).contains("leftover conflict marker"))
}
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 undo_last_commit(root: &Path) -> Result<String, String> {
if let Some(op) = operation_in_progress(root) {
return Err(format!(
"a {op} is in progress; finish or abort it before undoing a commit"
));
}
let message = run_git(root, &["log", "-1", "--format=%B", "HEAD"])
.map_err(|_| String::from("there is no commit to undo"))?;
if run_git(root, &["rev-parse", "--verify", "-q", "HEAD~1"]).is_ok() {
run_mutation(root, &["reset", "--soft", "HEAD~1"])?;
} else {
let raw = run_git(root, &["cat-file", "commit", "HEAD"])
.map_err(|_| String::from("cannot read the last commit"))?;
if raw
.lines()
.take_while(|l| !l.is_empty())
.any(|l| l.starts_with("parent "))
{
return Err(String::from(
"the parent commit is not in this shallow checkout; deepen it before undoing a commit",
));
}
if run_git(root, &["symbolic-ref", "-q", "HEAD"]).is_err() {
return Err(String::from(
"HEAD is detached; check out a branch before undoing its root commit",
));
}
run_mutation(root, &["update-ref", "-d", "HEAD"])?;
}
Ok(message)
}
pub fn head_is_on_upstream(root: &Path) -> bool {
let code = Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("-C")
.arg(root)
.args(["merge-base", "--is-ancestor", "HEAD", "@{u}"])
.output()
.ok()
.and_then(|o| o.status.code());
match code {
Some(0) => true,
Some(1) => false,
_ => run_git(root, &["symbolic-ref", "-q", "HEAD"])
.and_then(|branch| run_git(root, &["for-each-ref", "--format=%(upstream)", &branch]))
.is_ok_and(|upstream| !upstream.is_empty()),
}
}
pub fn cherry_pick(root: &Path, hash: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["cherry-pick", hash])
}
pub fn revert_commit(root: &Path, hash: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["revert", "--no-edit", hash])
}
pub fn checkout_detached(root: &Path, hash: &str) -> Result<String, String> {
run_mutation(root, &["switch", "--detach", hash])
}
pub fn create_tag_at(root: &Path, name: &str, target: &str) -> Result<String, String> {
run_mutation(root, &["tag", name, target])
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResetMode {
Soft,
Mixed,
Hard,
}
impl ResetMode {
pub(super) fn flag(self) -> &'static str {
match self {
ResetMode::Soft => "--soft",
ResetMode::Mixed => "--mixed",
ResetMode::Hard => "--hard",
}
}
}
pub fn reset_to(root: &Path, hash: &str, mode: ResetMode) -> Result<String, String> {
run_mutation(root, &["reset", "-q", mode.flag(), hash])
}
pub fn worktree_fingerprint(root: &Path) -> String {
let head = run_git(root, &["rev-parse", "HEAD"]).unwrap_or_default();
let branch = run_git(root, &["symbolic-ref", "-q", "HEAD"]).unwrap_or_default();
let index = run_git(root, &["ls-files", "-s", "-z"]).unwrap_or_default();
let status = Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("-C")
.arg(root)
.args(["status", "--porcelain=v1", "-z", "--untracked-files=all"])
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
.unwrap_or_default();
let top = repo_toplevel(root).unwrap_or_else(|| root.to_path_buf());
let mut out = format!("{head}\n{branch}\n{index}\n");
for entry in status.split('\0').filter(|e| !e.is_empty()) {
out.push_str(entry);
let path = entry.get(3..).unwrap_or(entry);
if let Ok(meta) = std::fs::metadata(top.join(path)) {
let mtime = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos());
out.push_str(&format!(" {} {mtime}", meta.len()));
}
out.push('\n');
}
out
}