use crate::{
git::{self, Opts},
input,
model::Config,
policy,
repo_state::{self, Entry, Head, InProgress, RepoState},
safety, screen, ui,
};
use anyhow::{bail, Result};
use std::collections::BTreeSet;
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Finish {
Continue,
Skip,
Abort,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
Ours,
Theirs,
}
pub fn conflict_kind(x: char, y: char) -> &'static str {
match (x, y) {
('U', 'U') => "both sides changed it",
('A', 'A') => "both sides added it",
('D', 'U') => "deleted here, changed by the incoming side",
('U', 'D') => "changed here, deleted by the incoming side",
('A', 'U') => "added here only",
('U', 'A') => "added by the incoming side only",
('D', 'D') => "deleted on both sides",
_ => "conflicted",
}
}
pub fn is_delete_kind(x: char, y: char) -> bool {
!matches!((x, y), ('U', 'U') | ('A', 'A'))
}
pub fn has_conflict_markers(bytes: &[u8]) -> bool {
fn marker(line: &[u8], mark: &[u8]) -> bool {
line.strip_prefix(mark)
.is_some_and(|rest| rest.is_empty() || rest[0] == b' ')
}
bytes.split(|b| *b == b'\n').any(|line| {
let line = line.strip_suffix(b"\r").unwrap_or(line);
line == b"======="
|| marker(line, b"<<<<<<<")
|| marker(line, b">>>>>>>")
|| marker(line, b"|||||||")
})
}
pub fn continue_args(op: InProgress, action: Finish) -> Option<Vec<&'static str>> {
let flag = match action {
Finish::Continue => "--continue",
Finish::Skip => "--skip",
Finish::Abort => "--abort",
};
let command = match op {
InProgress::Merge => {
return match action {
Finish::Continue => Some(vec!["commit", "--no-edit"]),
Finish::Abort => Some(vec!["merge", "--abort"]),
Finish::Skip => None,
}
}
InProgress::Bisect => return None,
InProgress::Rebase => "rebase",
InProgress::CherryPick => "cherry-pick",
InProgress::Revert => "revert",
InProgress::Am => "am",
};
Some(vec![command, flag])
}
fn read_trimmed(git_dir: &Path, rel: &str) -> Option<String> {
std::fs::read_to_string(git_dir.join(rel))
.ok()
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
}
fn short(oid: &str) -> String {
oid.chars().take(7).collect()
}
pub fn merge_branch(message: &str) -> Option<String> {
let first = message.lines().next()?;
let start = first.find('\'')? + 1;
let len = first[start..].find('\'')?;
Some(first[start..start + len].to_string()).filter(|name| !name.is_empty())
}
fn rebase_dir(git_dir: &Path) -> &'static str {
if git_dir.join("rebase-merge").is_dir() {
"rebase-merge"
} else {
"rebase-apply"
}
}
fn step(git_dir: &Path, dir: &str, num: &str, end: &str, noun: &str) -> String {
let number = |file: &str| {
read_trimmed(git_dir, &format!("{dir}/{file}")).and_then(|t| t.parse::<u32>().ok())
};
match (number(num), number(end)) {
(Some(n), Some(m)) => format!(", {noun} {n} of {m}"),
_ => String::new(),
}
}
pub fn describe_op(op: InProgress, git_dir: &Path) -> String {
match op {
InProgress::Rebase => {
let dir = rebase_dir(git_dir);
let branch = read_trimmed(git_dir, &format!("{dir}/head-name"))
.filter(|head| head != "detached HEAD")
.map(|head| {
head.strip_prefix("refs/heads/")
.unwrap_or(&head)
.to_string()
})
.unwrap_or_else(|| "a detached HEAD".into());
let onto = read_trimmed(git_dir, &format!("{dir}/onto"))
.map(|oid| short(&oid))
.unwrap_or_else(|| "its new base".into());
let (num, end) = if dir == "rebase-merge" {
("msgnum", "end")
} else {
("next", "last")
};
format!(
"Rebasing {branch} onto {onto}{}",
step(git_dir, dir, num, end, "step")
)
}
InProgress::Merge => {
match read_trimmed(git_dir, "MERGE_MSG").and_then(|m| merge_branch(&m)) {
Some(branch) => format!("Merging {branch}"),
None => "Merging (a merge is in progress)".into(),
}
}
InProgress::CherryPick => match read_trimmed(git_dir, "CHERRY_PICK_HEAD") {
Some(oid) => format!("Cherry-picking {}", short(&oid)),
None => "Cherry-picking a commit".into(),
},
InProgress::Revert => match read_trimmed(git_dir, "REVERT_HEAD") {
Some(oid) => format!("Reverting {}", short(&oid)),
None => "Reverting a commit".into(),
},
InProgress::Am => format!(
"Applying patches (git am){}",
step(git_dir, "rebase-apply", "next", "last", "patch")
),
InProgress::Bisect => "A bisect is running".into(),
}
}
fn incoming_name(op: InProgress, git_dir: &Path) -> String {
let oid = |file: &str| read_trimmed(git_dir, file).map(|oid| short(&oid));
match op {
InProgress::Merge => read_trimmed(git_dir, "MERGE_MSG").and_then(|m| merge_branch(&m)),
InProgress::Rebase => oid("REBASE_HEAD").or_else(|| oid("rebase-merge/stopped-sha")),
InProgress::CherryPick => oid("CHERRY_PICK_HEAD"),
InProgress::Revert => oid("REVERT_HEAD"),
InProgress::Am | InProgress::Bisect => None,
}
.unwrap_or_default()
}
pub fn side_keys(op: Option<InProgress>) -> [&'static str; 2] {
match op {
Some(InProgress::Rebase) => ["keep upstream", "keep my change"],
Some(InProgress::Merge) => ["keep mine", "keep theirs"],
Some(InProgress::CherryPick) => ["keep current", "keep picked"],
Some(InProgress::Revert) => ["keep current", "keep revert"],
Some(InProgress::Am) => ["keep current", "keep patch"],
None | Some(InProgress::Bisect) => ["keep current", "keep stashed"],
}
}
pub fn side_titles(op: Option<InProgress>, current: &str, incoming: &str) -> [String; 2] {
let named = |text: &str, name: &str| {
if name.is_empty() {
text.to_string()
} else {
format!("{text} ({name})")
}
};
match op {
Some(InProgress::Rebase) => [
named("Keep upstream", current),
named("Keep my change", incoming),
],
Some(InProgress::Merge) => [
"Keep mine (current branch)".into(),
named("Keep theirs", incoming),
],
Some(InProgress::CherryPick) => [
named("Keep current branch", current),
named("Keep the picked commit", incoming),
],
Some(InProgress::Revert) => [
named("Keep current branch", current),
named("Keep the revert", incoming),
],
Some(InProgress::Am) => [
named("Keep current branch", current),
"Keep the patch".into(),
],
None | Some(InProgress::Bisect) => [
"Keep the current version".into(),
"Keep the stashed version".into(),
],
}
}
fn op_noun(op: InProgress) -> &'static str {
match op {
InProgress::Merge => "merge",
InProgress::Rebase => "rebase",
InProgress::CherryPick => "cherry-pick",
InProgress::Revert => "revert",
InProgress::Am => "patch series (git am)",
InProgress::Bisect => "bisect",
}
}
pub fn continue_blockers(conflicted: &[String], with_markers: &[String]) -> Vec<String> {
let mut out = Vec::new();
if !conflicted.is_empty() {
out.push(format!(
"{} file(s) still conflicted: {}",
conflicted.len(),
conflicted.join(", ")
));
}
if !with_markers.is_empty() {
out.push(format!(
"Conflict markers are still in: {} (mark them resolved again to confirm)",
with_markers.join(", ")
));
}
out
}
fn spec(path: &str) -> String {
format!(":(top,literal){path}")
}
fn run_ok(args: &[&str]) -> Result<String> {
git::git_ok(args, &Opts::default())
}
pub fn take_side(path: &str, side: Side) -> Result<Vec<String>> {
let flag = match side {
Side::Ours => "--ours",
Side::Theirs => "--theirs",
};
let p = spec(path);
let out = git::git_raw(&["checkout", flag, "--", &p], &Opts::default())?;
if out.ok() {
run_ok(&["add", "-A", "--", &p])?;
return Ok(vec![
format!("git checkout {flag} -- {path}"),
format!("git add -- {path}"),
]);
}
if out.stderr.contains("does not have") {
return delete_file(path);
}
bail!("{}", out.stderr.trim())
}
pub fn keep_file(path: &str) -> Result<Vec<String>> {
run_ok(&["add", "-A", "--", &spec(path)])?;
Ok(vec![format!("git add -- {path}")])
}
pub fn delete_file(path: &str) -> Result<Vec<String>> {
run_ok(&["rm", "-q", "--ignore-unmatch", "--", &spec(path)])?;
Ok(vec![format!("git rm -- {path}")])
}
pub fn has_manual_edits(current: Option<&[u8]>, delete_kind: bool, stages: &[Vec<u8>]) -> bool {
let Some(current) = current else {
return false;
};
if !delete_kind && has_conflict_markers(current) {
return false;
}
let norm = |bytes: &[u8]| {
bytes
.iter()
.copied()
.filter(|b| *b != b'\r')
.collect::<Vec<u8>>()
};
let current = norm(current);
!stages.iter().any(|stage| norm(stage) == current)
}
pub fn edited_by_user(workdir: &Path, path: &str, delete_kind: bool) -> bool {
let current = std::fs::read(workdir.join(path)).ok();
let mut stages = Vec::new();
let markers = current.as_deref().is_some_and(has_conflict_markers);
if delete_kind || !markers {
for stage in [1, 2, 3] {
if let Ok(out) = git::git_raw(&["show", &format!(":{stage}:{path}")], &Opts::default())
{
if out.ok() {
stages.push(out.stdout);
}
}
}
}
has_manual_edits(current.as_deref(), delete_kind, &stages)
}
pub fn parse_marker_check(output: &str) -> Vec<String> {
let mut paths: Vec<String> = Vec::new();
for line in output.lines() {
let Some((head, _)) = line.split_once(": leftover conflict marker") else {
continue;
};
let path = head.rsplit_once(':').map_or(head, |(path, _line)| path);
if !paths.iter().any(|known| known == path) {
paths.push(path.to_string());
}
}
paths
}
pub fn staged_marker_files() -> Result<Vec<String>> {
let out = git::git_raw(&["diff", "--cached", "--check"], &Opts::default())?;
Ok(parse_marker_check(&String::from_utf8_lossy(&out.stdout)))
}
pub fn skip_op(op: InProgress) -> Result<(git::Out, String)> {
let backup = safety::backup("skip", "HEAD")?;
let out = finish(op, Finish::Skip)?;
Ok((out, backup))
}
fn run_mergetool(workdir: &Path, path: &str) -> Result<std::process::ExitStatus> {
Ok(std::process::Command::new("git")
.args(["mergetool", "--no-prompt", "--", path])
.current_dir(workdir)
.env("GIT_LITERAL_PATHSPECS", "1")
.env_remove("GIT_TERMINAL_PROMPT")
.status()?)
}
pub fn finish(op: InProgress, action: Finish) -> Result<git::Out> {
let Some(args) = continue_args(op, action) else {
bail!("A {} cannot be finished that way here", op_noun(op));
};
git::git_raw(&args, &Opts::default())
}
fn files_with_markers(
workdir: &Path,
watched: &BTreeSet<String>,
confirmed: &BTreeSet<String>,
) -> Vec<String> {
watched
.iter()
.filter(|path| !confirmed.contains(*path))
.filter(|path| {
std::fs::read(workdir.join(path)).is_ok_and(|bytes| has_conflict_markers(&bytes))
})
.cloned()
.collect()
}
pub fn continue_op(watched: &BTreeSet<String>, confirmed: &BTreeSet<String>) -> Result<git::Out> {
let state = repo_state::load()?;
let Some(op) = state.op else {
bail!("Nothing is in progress, so there is nothing to continue.");
};
let conflicted: Vec<String> = state
.entries
.iter()
.filter(|e| e.conflicted())
.map(|e| e.path.clone())
.collect();
let markers = files_with_markers(&state.workdir, watched, confirmed);
let blockers = continue_blockers(&conflicted, &markers);
if !blockers.is_empty() {
bail!("{}", blockers.join("\n"));
}
finish(op, Finish::Continue)
}
pub fn abort_op(op: InProgress) -> Result<String> {
let backup = safety::backup("abort", "HEAD")?;
let out = finish(op, Finish::Abort)?;
if !out.ok() {
bail!("{}\n(backup kept at {backup})", out.stderr.trim());
}
Ok(backup)
}
fn onto_name(git_dir: &Path) -> Option<String> {
let oid = read_trimmed(git_dir, &format!("{}/onto", rebase_dir(git_dir)))?;
let refs = run_ok(&[
"for-each-ref",
"--points-at",
&oid,
"--format=%(refname:short)",
"refs/heads",
"refs/remotes",
])
.ok()?;
refs.lines()
.find(|name| !name.ends_with("/HEAD"))
.map(str::to_string)
}
fn merge_tool_set() -> bool {
run_ok(&["config", "merge.tool"]).is_ok_and(|tool| !tool.trim().is_empty())
}
fn edit_file(path: &Path) -> Result<()> {
let editor = std::env::var("VISUAL")
.or_else(|_| std::env::var("EDITOR"))
.unwrap_or_else(|_| {
if cfg!(windows) {
"notepad".into()
} else {
"vi".into()
}
});
let mut parts = input::split_command(&editor).into_iter();
let Some(program) = parts.next() else {
bail!("The editor command ($VISUAL / $EDITOR) is empty");
};
let args: Vec<String> = parts.collect();
let status = ui::suspended(|| Ok(input::run_editor(&program, &args, path)?))?;
if !status.success() {
bail!("The editor exited with {status}");
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Act {
Side(Side),
Keep,
Delete,
Edit,
Mark,
Diff,
Tool,
Finish(Finish),
Refresh,
}
struct View {
op: Option<InProgress>,
title: String,
sides: [String; 2],
keys: [&'static str; 2],
tool: bool,
}
impl View {
fn new(state: &RepoState) -> View {
let branch = match &state.branch.head {
Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
Head::Detached { oid } => short(oid),
};
let op = state.op;
let (title, current, incoming) = match op {
Some(op) => {
let mut title = describe_op(op, &state.git_dir);
let mut current = branch;
if op == InProgress::Rebase {
let onto = read_trimmed(
&state.git_dir,
&format!("{}/onto", rebase_dir(&state.git_dir)),
);
current = onto.as_deref().map(short).unwrap_or_default();
if let Some(name) = onto_name(&state.git_dir) {
if !current.is_empty() {
title = title.replacen(¤t, &name, 1);
}
current = name;
}
}
(title, current, incoming_name(op, &state.git_dir))
}
None => (
"Conflicts with nothing in progress".to_string(),
branch,
String::new(),
),
};
View {
op,
title,
sides: side_titles(op, ¤t, &incoming),
keys: side_keys(op),
tool: merge_tool_set(),
}
}
fn can_skip(&self) -> bool {
matches!(
self.op,
Some(InProgress::Rebase | InProgress::CherryPick | InProgress::Revert | InProgress::Am)
)
}
}
#[derive(Default)]
struct Session {
watched: BTreeSet<String>,
confirmed: BTreeSet<String>,
status: Option<String>,
index: usize,
}
pub fn run(config: &mut Config) -> Result<()> {
let mut session = Session::default();
loop {
let state = repo_state::load()?;
let conflicted: Vec<&Entry> = state.entries.iter().filter(|e| e.conflicted()).collect();
session
.watched
.extend(conflicted.iter().map(|e| e.path.clone()));
match state.op {
Some(InProgress::Bisect) => {
return ui::notice(
"Conflicts",
&[
"A bisect is running. That is not a conflict, so it is not finished here."
.into(),
screen::muted(
"Finish it with `git bisect reset` (or the mode that started it).",
),
],
)
}
None if conflicted.is_empty() => return nothing_to_resolve(config),
_ => {}
}
let view = View::new(&state);
let header = header(config, &view, conflicted.len(), session.status.take());
let mut rows: Vec<String> = conflicted
.iter()
.map(|e| {
format!(
"{} {}",
e.path,
screen::muted(format!("({})", conflict_kind(e.x, e.y)))
)
})
.collect();
if let Some(op) = view.op {
rows.push(screen::accent(format!(
"> Finish: continue, skip or abort the {}",
op_noun(op)
)));
}
let keys = keys(&view, &conflicted);
let choice = ui::action_list("Conflicts", &header, &rows, &keys, &mut session.index)?;
let (act, entry) = match choice {
ui::Choice::Back => return Ok(()),
ui::Choice::Open(i) => match menu(&view, conflicted.get(i).copied())? {
Some(act) => (act, conflicted.get(i).copied()),
None => continue,
},
ui::Choice::Action(key, i) => match key_act(key) {
Some(act) => (act, conflicted.get(i).copied()),
None => continue,
},
};
if act_on(config, &mut session, &state, &view, entry, act)? {
return Ok(());
}
}
}
fn header(cfg: &Config, view: &View, left: usize, status: Option<String>) -> Vec<String> {
let mut lines = vec![screen::accent(&view.title)];
if view.op.is_none() {
lines.push(screen::warning(
"Probably from `git stash pop` / `stash apply`. Stash conflicts have no abort:",
));
lines.push(screen::muted(
"fix each file, mark it resolved, then run `git reset` to unstage; drop the stash in Stash mode.",
));
}
lines.push(if left > 0 {
screen::warning(format!("! {left} file(s) still conflicted"))
} else {
screen::success("All conflicts resolved: press C to continue")
});
lines.extend(ui::explain(
cfg,
&[
"Each file below has parts from both sides. Keep one side, or edit the file and mark it resolved.",
"When no file is left, continue to finish; abort puts everything back as it was before.",
],
));
if let Some(status) = status {
lines.push(status);
}
lines
}
fn keys(view: &View, conflicted: &[&Entry]) -> Vec<ui::Key> {
let key = |key: char, label: &'static str| ui::Key { key, label };
let mut keys = Vec::new();
if !conflicted.is_empty() {
keys.extend([key('o', view.keys[0]), key('t', view.keys[1])]);
if conflicted.iter().any(|e| is_delete_kind(e.x, e.y)) {
keys.extend([key('k', "keep file"), key('x', "delete file")]);
}
keys.extend([
key('e', "edit"),
key('m', "mark resolved"),
key('d', "diff"),
]);
if view.tool {
keys.push(key('g', "merge tool"));
}
}
if view.op.is_some() {
keys.push(key('C', "continue"));
if view.can_skip() {
keys.push(key('n', "skip commit"));
}
keys.push(key('A', "abort"));
}
keys.push(key('r', "refresh"));
keys
}
fn key_act(key: char) -> Option<Act> {
Some(match key {
'o' => Act::Side(Side::Ours),
't' => Act::Side(Side::Theirs),
'k' => Act::Keep,
'x' => Act::Delete,
'e' => Act::Edit,
'm' => Act::Mark,
'd' => Act::Diff,
'g' => Act::Tool,
'C' => Act::Finish(Finish::Continue),
'n' => Act::Finish(Finish::Skip),
'A' => Act::Finish(Finish::Abort),
'r' => Act::Refresh,
_ => return None,
})
}
fn menu(view: &View, entry: Option<&Entry>) -> Result<Option<Act>> {
let mut options: Vec<(String, Act)> = Vec::new();
let mut context = Vec::new();
if let Some(e) = entry {
context.push(format!(
"{} {}",
screen::accent(&e.path),
screen::muted(conflict_kind(e.x, e.y))
));
if is_delete_kind(e.x, e.y) {
options.push(("Keep the file (git add)".into(), Act::Keep));
options.push(("Delete the file (git rm)".into(), Act::Delete));
} else {
options.push((view.sides[0].clone(), Act::Side(Side::Ours)));
options.push((view.sides[1].clone(), Act::Side(Side::Theirs)));
}
options.push(("Edit in your editor".into(), Act::Edit));
options.push(("Mark resolved".into(), Act::Mark));
options.push(("Show the diff".into(), Act::Diff));
if view.tool {
options.push(("Open the merge tool".into(), Act::Tool));
}
}
if let Some(op) = view.op {
let noun = op_noun(op);
options.push((
format!("Continue the {noun}"),
Act::Finish(Finish::Continue),
));
if view.can_skip() {
options.push(("Skip this commit".into(), Act::Finish(Finish::Skip)));
}
options.push((format!("Abort the {noun}"), Act::Finish(Finish::Abort)));
}
options.push(("Refresh".into(), Act::Refresh));
let labels: Vec<&str> = options.iter().map(|(label, _)| label.as_str()).collect();
Ok(ui::choose("Conflicts", &context, &labels)?
.and_then(|i| options.get(i).map(|(_, act)| *act)))
}
fn done(commands: &[String], what: String) -> String {
format!(
"{} {}",
screen::success(format!("ok: {what}")),
screen::muted(format!("($ {})", commands.join("; ")))
)
}
fn act_on(
cfg: &mut Config,
s: &mut Session,
state: &RepoState,
view: &View,
entry: Option<&Entry>,
act: Act,
) -> Result<bool> {
if let Act::Finish(action) = act {
return finish_flow(cfg, s, view, action);
}
if act == Act::Refresh {
return Ok(false);
}
let Some(e) = entry else {
s.status = Some(screen::warning("Pick a file first."));
return Ok(false);
};
let path = e.path.as_str();
let full = state.workdir.join(path);
match act {
Act::Side(side) => {
let (title, flag) = match side {
Side::Ours => (&view.sides[0], "--ours"),
Side::Theirs => (&view.sides[1], "--theirs"),
};
let command = format!("git checkout {flag} -- {path} && git add -- {path}");
let edited = edited_by_user(&state.workdir, path, is_delete_kind(e.x, e.y));
let go = if edited {
let what =
format!("{title} for {path}? Your manual edits in this file will be replaced.");
let verdict = policy::check(cfg, &policy::Op::DiscardUnstaged);
ui::gate(cfg, &verdict, &what, &command)?
} else {
ui::confirm_action(
cfg,
&format!("{title} for {path}? Edits in this file are replaced."),
&command,
)?
};
if go {
s.status = Some(match take_side(path, side) {
Ok(cmds) => done(&cmds, format!("{title}: {path}")),
Err(error) => screen::danger(format!("x {error}")),
});
}
}
Act::Keep | Act::Delete if !is_delete_kind(e.x, e.y) => {
s.status = Some(screen::warning(
"Both sides have this file: keep one side (o/t) or edit it, then mark it resolved.",
));
}
Act::Keep => s.status = Some(result(keep_file(path), format!("kept {path}"))),
Act::Delete => {
if ui::confirm_action(
cfg,
&format!("Delete {path} to resolve the conflict?"),
&format!("git rm -- {path}"),
)? {
s.status = Some(result(delete_file(path), format!("deleted {path}")));
}
}
Act::Edit => {
if let Err(error) = edit_file(&full) {
s.status = Some(screen::danger(format!("x {error}")));
return Ok(false);
}
let markers = std::fs::read(&full).is_ok_and(|b| has_conflict_markers(&b));
if markers {
s.status = Some(screen::warning(format!(
"! {path} still has conflict markers"
)));
} else if ui::confirm_action(
cfg,
&format!("No conflict markers left in {path}. Mark it resolved?"),
&format!("git add -- {path}"),
)? {
s.status = Some(result(keep_file(path), format!("resolved {path}")));
}
}
Act::Mark => {
let markers = std::fs::read(&full).is_ok_and(|b| has_conflict_markers(&b));
if markers
&& !ui::confirm_action(
cfg,
&format!("Warning: {path} still contains conflict markers (<<<<<<< / ======= / >>>>>>>). Mark it resolved anyway?"),
&format!("git add -- {path}"),
)?
{
return Ok(false);
}
if markers {
s.confirmed.insert(path.to_string());
}
s.status = Some(result(keep_file(path), format!("resolved {path}")));
}
Act::Diff => {
let out = git::git_raw(&["diff", "--", &spec(path)], &Opts::default())?;
let lines: Vec<String> = out.text().lines().map(str::to_string).collect();
if lines.is_empty() {
s.status = Some(screen::muted("No diff to show for this file."));
} else {
ui::diff_view(&format!("Diff: {path}"), &lines, &[])?;
}
}
Act::Tool => {
let status = ui::suspended(|| run_mergetool(&state.workdir, path))?;
s.status = Some(if status.success() {
screen::success(format!(
"ok: merge tool finished for {path} ($ git mergetool --no-prompt -- {path})"
))
} else {
screen::danger(format!("x merge tool for {path} ended with {status}"))
});
}
Act::Finish(_) | Act::Refresh => {}
}
Ok(false)
}
fn result(outcome: Result<Vec<String>>, what: String) -> String {
match outcome {
Ok(cmds) => done(&cmds, what),
Err(error) => screen::danger(format!("x {error}")),
}
}
fn finish_flow(cfg: &mut Config, s: &mut Session, view: &View, action: Finish) -> Result<bool> {
let Some(op) = view.op else {
s.status = Some(screen::warning(
"Nothing is in progress (stash conflict): fix the files, then `git reset`; drop the stash in Stash mode.",
));
return Ok(false);
};
let noun = op_noun(op);
let Some(args) = continue_args(op, action) else {
s.status = Some(screen::warning(format!("A {noun} has no skip.")));
return Ok(false);
};
let command = format!("git {}", args.join(" "));
match action {
Finish::Abort => {
let verdict = policy::check(cfg, &policy::Op::Abort);
let what = format!("Abort the {noun}? Everything goes back to how it was before it started; resolutions so far are lost.");
if !ui::gate(cfg, &verdict, &what, &command)? {
return Ok(false);
}
let backup = ui::git_job("Aborting...", || abort_op(op));
let mut lines = match backup {
Ok(backup) => vec![
screen::success(format!("The {noun} was aborted.")),
format!("{} {}", screen::muted("Command:"), screen::accent(&command)),
format!("{} {backup}", screen::muted("Backup of where you were:")),
],
Err(error) => vec![screen::danger(format!("Could not abort: {error}"))],
};
lines.extend(ui::explain(
cfg,
&["`git reset --hard <backup ref>` brings the abandoned state back."],
));
ui::notice("Abort", &lines)?;
Ok(true)
}
Finish::Continue | Finish::Skip => {
if action == Finish::Continue {
let verdict = policy::check(cfg, &policy::Op::CreatesCommit);
if !ui::gate(cfg, &verdict, &format!("Continue the {noun}?"), &command)? {
return Ok(false);
}
let staged: Vec<String> = staged_marker_files()
.unwrap_or_default()
.into_iter()
.filter(|path| !s.confirmed.contains(path))
.collect();
if !staged.is_empty() {
let context = vec![
screen::danger("Staged files still contain conflict markers:"),
staged.join(", "),
];
if !input::confirm(&context, "Continue anyway and commit the markers?", false)?
{
return Ok(false);
}
}
} else {
let verdict = policy::check(cfg, &policy::Op::Abort);
let what = "Skip this commit? Its changes and your resolutions for it are thrown away (a backup of HEAD is kept first).";
if !ui::gate(cfg, &verdict, what, &command)? {
return Ok(false);
}
}
let (watched, confirmed) = (&s.watched, &s.confirmed);
let outcome = ui::git_job("Working...", || match action {
Finish::Continue => continue_op(watched, confirmed).map(|out| (out, None)),
_ => skip_op(op).map(|(out, backup)| (out, Some(backup))),
});
let (out, backup) = match outcome {
Ok(done) => done,
Err(error) => {
let lines: Vec<String> =
error.to_string().lines().map(screen::warning).collect();
ui::notice("Cannot continue yet", &lines)?;
return Ok(false);
}
};
if let Some(backup) = &backup {
let lines = [
screen::success("The commit was skipped."),
format!("{} {}", screen::muted("Command:"), screen::accent(&command)),
format!("{} {backup}", screen::muted("Backup of where you were:")),
];
ui::notice("Skipped", &lines)?;
}
let after = repo_state::load()?;
match after.op {
None => finished(cfg, s, op, &command),
Some(next) => {
let conflicts = after.entries.iter().any(|e| e.conflicted());
if out.ok() || conflicts {
let now = describe_op(next, &after.git_dir);
s.status = Some(if conflicts {
screen::warning(format!("! Stopped again with conflicts: {now}"))
} else {
screen::success(format!("ok: {command}. Now: {now}"))
});
} else {
let mut lines = vec![screen::danger(format!("$ {command} failed:"))];
lines.extend(out.stderr.lines().map(str::to_string));
ui::notice("Not finished", &lines)?;
}
Ok(false)
}
}
}
}
}
fn settled(state: &RepoState) -> bool {
state.op.is_none() && !state.entries.iter().any(|e| e.conflicted())
}
fn finished(cfg: &mut Config, s: &mut Session, op: InProgress, command: &str) -> Result<bool> {
let noun = op_noun(op);
let mut lines = vec![
screen::success(format!("The {noun} is finished.")),
format!("{} {}", screen::muted("Command:"), screen::accent(command)),
String::new(),
];
lines.push(if op == InProgress::Rebase {
"Next step: push with Sync. The branch was rewritten, so if it was already pushed Sync uses --force-with-lease (it refuses if someone else pushed meanwhile).".into()
} else {
"Next step: push the new commit(s) with Sync.".into()
});
if ui::choose("Done", &lines, &["Open Sync", "Back"])? == Some(0) {
crate::modes::open("sync", cfg)?;
}
let after = repo_state::load()?;
if settled(&after) {
return Ok(true);
}
s.status = Some(screen::warning(match after.op {
Some(next) => format!(
"! New conflicts to resolve: {}",
describe_op(next, &after.git_dir)
),
None => "! New conflicts to resolve".to_string(),
}));
Ok(false)
}
fn nothing_to_resolve(cfg: &Config) -> Result<()> {
let mut lines = vec![
screen::success("Nothing to resolve."),
"No merge, rebase, cherry-pick, revert or patch series is in progress, and no file is conflicted.".into(),
String::new(),
screen::muted("Next step: when a merge or rebase (Sync, Branch) stops with conflicts, come back here."),
];
lines.extend(ui::explain(
cfg,
&["A conflict happens when two changes touch the same lines; git then asks you to pick."],
));
ui::notice("Conflicts", &lines)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn conflict_kind_table() {
let table = [
('U', 'U', "both sides changed it"),
('A', 'A', "both sides added it"),
('D', 'U', "deleted here, changed by the incoming side"),
('U', 'D', "changed here, deleted by the incoming side"),
('A', 'U', "added here only"),
('U', 'A', "added by the incoming side only"),
('D', 'D', "deleted on both sides"),
('M', '.', "conflicted"),
];
for (x, y, want) in table {
assert_eq!(conflict_kind(x, y), want, "{x}{y}");
assert!(!want.contains("ours") && !want.contains("theirs"));
}
assert!(!is_delete_kind('U', 'U') && !is_delete_kind('A', 'A'));
assert!(is_delete_kind('D', 'U') && is_delete_kind('U', 'D') && is_delete_kind('D', 'D'));
}
#[test]
fn markers_detection() {
assert!(has_conflict_markers(
b"a\n<<<<<<< HEAD\nx\n=======\ny\n>>>>>>> feature\n"
));
assert!(has_conflict_markers(b"a\r\n<<<<<<< HEAD\r\nx\r\n"));
assert!(has_conflict_markers(b"x\r\n=======\r\ny"));
assert!(has_conflict_markers(b">>>>>>> theirs"));
assert!(!has_conflict_markers(b""));
assert!(!has_conflict_markers(
b"text <<<<<<< HEAD in the middle\nand ======= too\n"
));
assert!(!has_conflict_markers(b"<<<<<<<<< nine\n========\n"));
assert!(!has_conflict_markers(
" ünïcode\r\n <<<<<<< indented\r\n".as_bytes()
));
}
#[test]
fn continue_args_table() {
use Finish::*;
use InProgress::*;
let table: [(InProgress, Finish, Option<Vec<&str>>); 12] = [
(Merge, Continue, Some(vec!["commit", "--no-edit"])),
(Merge, Skip, None),
(Merge, Abort, Some(vec!["merge", "--abort"])),
(Rebase, Continue, Some(vec!["rebase", "--continue"])),
(Rebase, Skip, Some(vec!["rebase", "--skip"])),
(Rebase, Abort, Some(vec!["rebase", "--abort"])),
(CherryPick, Skip, Some(vec!["cherry-pick", "--skip"])),
(Revert, Abort, Some(vec!["revert", "--abort"])),
(Revert, Continue, Some(vec!["revert", "--continue"])),
(Am, Continue, Some(vec!["am", "--continue"])),
(Am, Skip, Some(vec!["am", "--skip"])),
(Bisect, Abort, None),
];
for (op, action, want) in table {
assert_eq!(continue_args(op, action), want, "{op:?} {action:?}");
}
}
#[test]
fn describe_op_from_files() {
let tmp = TempRepo::outside();
let dir = tmp.path();
let write = |rel: &str, text: &str| {
let path = dir.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
assert_eq!(
describe_op(InProgress::Rebase, dir),
"Rebasing a detached HEAD onto its new base"
);
write("rebase-apply/head-name", "refs/heads/topic\n");
write("rebase-apply/next", "2\n");
write("rebase-apply/last", "5\n");
assert_eq!(
describe_op(InProgress::Rebase, dir),
"Rebasing topic onto its new base, step 2 of 5"
);
assert_eq!(
describe_op(InProgress::Am, dir),
"Applying patches (git am), patch 2 of 5"
);
write("rebase-merge/head-name", "refs/heads/feature\r\n");
write(
"rebase-merge/onto",
"0123456789abcdef0123456789abcdef01234567\n",
);
write("rebase-merge/msgnum", "3\n");
write("rebase-merge/end", "7\n");
assert_eq!(
describe_op(InProgress::Rebase, dir),
"Rebasing feature onto 0123456, step 3 of 7"
);
assert_eq!(
describe_op(InProgress::Merge, dir),
"Merging (a merge is in progress)"
);
write(
"MERGE_MSG",
"Merge branch 'feature/x' into main\n\n# Conflicts:\n",
);
assert_eq!(describe_op(InProgress::Merge, dir), "Merging feature/x");
write("CHERRY_PICK_HEAD", "abcdef1234567890\n");
assert_eq!(
describe_op(InProgress::CherryPick, dir),
"Cherry-picking abcdef1"
);
write("REVERT_HEAD", "fedcba9876543210\n");
assert_eq!(describe_op(InProgress::Revert, dir), "Reverting fedcba9");
assert_eq!(
merge_branch("Merge remote-tracking branch 'origin/dev'"),
Some("origin/dev".into())
);
assert_eq!(merge_branch("no quotes"), None);
assert_eq!(merge_branch(""), None);
}
#[test]
fn side_labels_follow_the_operation() {
let [ours, theirs] = side_titles(Some(InProgress::Rebase), "main", "abc1234");
assert_eq!(ours, "Keep upstream (main)");
assert_eq!(theirs, "Keep my change (abc1234)");
let [ours, theirs] = side_titles(Some(InProgress::Merge), "main", "feature");
assert_eq!(ours, "Keep mine (current branch)");
assert_eq!(theirs, "Keep theirs (feature)");
assert_eq!(
side_keys(Some(InProgress::Rebase)),
["keep upstream", "keep my change"]
);
assert_eq!(side_titles(None, "main", "")[1], "Keep the stashed version");
assert_eq!(continue_blockers(&[], &[]), Vec::<String>::new());
assert_eq!(continue_blockers(&["a".into()], &["b".into()]).len(), 2);
}
#[test]
fn split_command_keeps_quoted_windows_paths() {
use crate::input::split_command;
assert_eq!(
split_command(r#""C:\Program Files\Microsoft VS Code\code.exe" --wait"#),
vec![r"C:\Program Files\Microsoft VS Code\code.exe", "--wait"]
);
assert_eq!(split_command(" vim -n "), vec!["vim", "-n"]);
assert!(split_command(" ").is_empty());
assert_eq!(
split_command(r"C:\Users\O'Brien\vim.exe -f"),
vec![r"C:\Users\O'Brien\vim.exe", "-f"]
);
}
#[test]
fn parse_marker_check_lists_unique_paths() {
let out = "a.txt:1: leftover conflict marker\na.txt:5: leftover conflict marker\nb.txt:2: trailing whitespace.\n+x \nsub/c d.txt:9: leftover conflict marker\n";
assert_eq!(parse_marker_check(out), vec!["a.txt", "sub/c d.txt"]);
assert!(parse_marker_check("").is_empty());
}
#[test]
fn manual_edit_decision_table() {
let marked = b"<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs\n";
assert!(!has_manual_edits(None, false, &[]));
assert!(!has_manual_edits(Some(marked), false, &[]));
assert!(has_manual_edits(Some(b"resolved\n"), false, &[]));
let stage = b"main\n".to_vec();
assert!(!has_manual_edits(
Some(b"main\r\n"),
true,
std::slice::from_ref(&stage)
));
assert!(has_manual_edits(Some(b"mine\n"), true, &[stage]));
}
fn conflict_repo() -> TempRepo {
let repo = TempRepo::new(1);
repo.write("a.txt", "base\n");
repo.git(&["add", "a.txt"]);
repo.git(&["commit", "-q", "-m", "base"]);
repo.git(&["checkout", "-q", "-b", "feature"]);
repo.write("a.txt", "feature\n");
repo.git(&["commit", "-q", "-am", "feature change"]);
repo.git(&["checkout", "-q", "main"]);
repo.write("a.txt", "main\n");
repo.git(&["commit", "-q", "-am", "main change"]);
repo
}
fn start(args: &[&str]) {
let out = git::git_raw(args, &Opts::default()).unwrap();
assert!(!out.ok(), "expected a conflict from {args:?}");
}
fn read(repo: &TempRepo, rel: &str) -> String {
std::fs::read_to_string(repo.path().join(rel))
.unwrap()
.replace('\r', "")
}
#[test]
fn merge_keep_theirs_then_continue() {
let repo = conflict_repo();
repo.run(|| {
start(&["merge", "feature"]);
let state = repo_state::load().unwrap();
assert_eq!(state.op, Some(InProgress::Merge));
assert_eq!(
describe_op(InProgress::Merge, &state.git_dir),
"Merging feature"
);
let watched: BTreeSet<String> = ["a.txt".to_string()].into();
let err = continue_op(&watched, &BTreeSet::new())
.unwrap_err()
.to_string();
assert!(err.contains("still conflicted"), "{err}");
take_side("a.txt", Side::Theirs).unwrap();
keep_file("a.txt").unwrap();
let out = continue_op(&watched, &BTreeSet::new()).unwrap();
assert!(out.ok(), "{}", out.stderr);
assert_eq!(repo_state::load().unwrap().op, None);
});
assert_eq!(read(&repo, "a.txt"), "feature\n");
assert_eq!(
repo.git(&["rev-list", "--parents", "-n1", "HEAD"])
.split(' ')
.count(),
3
);
}
#[test]
fn continue_refused_while_markers_remain() {
let repo = conflict_repo();
repo.run(|| {
start(&["merge", "feature"]);
keep_file("a.txt").unwrap(); let watched: BTreeSet<String> = ["a.txt".to_string()].into();
let err = continue_op(&watched, &BTreeSet::new())
.unwrap_err()
.to_string();
assert!(err.contains("markers"), "{err}");
let confirmed = watched.clone();
assert!(continue_op(&watched, &confirmed).unwrap().ok());
});
}
#[test]
fn rebase_uses_swapped_labels_and_finishes() {
let repo = conflict_repo();
repo.git(&["checkout", "-q", "feature"]);
repo.run(|| {
start(&["rebase", "main"]);
let state = repo_state::load().unwrap();
assert_eq!(state.op, Some(InProgress::Rebase));
let view = View::new(&state);
assert!(
view.title.starts_with("Rebasing feature onto main"),
"{}",
view.title
);
assert!(
view.sides[0].starts_with("Keep upstream (main)"),
"{}",
view.sides[0]
);
assert!(
view.sides[1].starts_with("Keep my change"),
"{}",
view.sides[1]
);
take_side("a.txt", Side::Theirs).unwrap();
let out = continue_op(&["a.txt".to_string()].into(), &BTreeSet::new()).unwrap();
assert!(out.ok(), "{}", out.stderr);
assert_eq!(repo_state::load().unwrap().op, None);
});
assert_eq!(read(&repo, "a.txt"), "feature\n");
assert_eq!(
repo.git(&["rev-parse", "HEAD~1"]),
repo.git(&["rev-parse", "main"])
);
}
#[test]
fn abort_restores_head_and_keeps_a_backup() {
let repo = conflict_repo();
let before = repo.git(&["rev-parse", "HEAD"]);
let backup = repo.run(|| {
start(&["merge", "feature"]);
abort_op(InProgress::Merge).unwrap()
});
assert!(backup.starts_with("refs/gct/backup/"), "{backup}");
assert_eq!(repo.git(&["rev-parse", "HEAD"]), before);
assert!(!repo.git(&["for-each-ref", "refs/gct/backup/"]).is_empty());
assert_eq!(read(&repo, "a.txt"), "main\n");
}
fn delete_modify_repo() -> TempRepo {
let repo = TempRepo::new(1);
repo.write("a.txt", "base\n");
repo.git(&["add", "a.txt"]);
repo.git(&["commit", "-q", "-m", "base"]);
repo.git(&["checkout", "-q", "-b", "feature"]);
repo.git(&["rm", "-q", "a.txt"]);
repo.git(&["commit", "-q", "-m", "delete a"]);
repo.git(&["checkout", "-q", "main"]);
repo.write("a.txt", "main\n");
repo.git(&["commit", "-q", "-am", "main change"]);
repo
}
#[test]
fn delete_modify_resolves_both_ways() {
for keep in [true, false] {
let repo = delete_modify_repo();
repo.run(|| {
start(&["merge", "feature"]);
let state = repo_state::load().unwrap();
let entry = state.entries.iter().find(|e| e.conflicted()).unwrap();
assert_eq!((entry.x, entry.y), ('U', 'D'));
assert!(is_delete_kind(entry.x, entry.y));
if keep {
keep_file("a.txt").unwrap();
} else {
assert_eq!(
take_side("a.txt", Side::Theirs).unwrap(),
vec!["git rm -- a.txt"]
);
}
assert!(continue_op(&BTreeSet::new(), &BTreeSet::new())
.unwrap()
.ok());
});
assert_eq!(repo.path().join("a.txt").exists(), keep);
let tracked = repo.git(&["ls-files", "a.txt"]);
assert_eq!(tracked.is_empty(), !keep);
}
}
#[test]
fn staged_markers_are_found_even_when_not_watched() {
let repo = conflict_repo();
repo.run(|| {
start(&["merge", "feature"]);
assert!(staged_marker_files().unwrap().is_empty());
keep_file("a.txt").unwrap();
assert_eq!(staged_marker_files().unwrap(), vec!["a.txt"]);
});
}
#[test]
fn edited_by_user_detects_manual_resolution() {
let repo = conflict_repo();
repo.run(|| {
start(&["merge", "feature"]);
let workdir = repo_state::load().unwrap().workdir;
assert!(!edited_by_user(&workdir, "a.txt", false));
std::fs::write(workdir.join("a.txt"), "mine\n").unwrap();
assert!(edited_by_user(&workdir, "a.txt", false));
});
let repo = delete_modify_repo();
repo.run(|| {
start(&["merge", "feature"]);
let workdir = repo_state::load().unwrap().workdir;
assert!(!edited_by_user(&workdir, "a.txt", true));
std::fs::write(workdir.join("a.txt"), "mine\n").unwrap();
assert!(edited_by_user(&workdir, "a.txt", true));
});
}
#[test]
fn binary_conflict_counts_as_edited_only_when_it_matches_no_side() {
let repo = TempRepo::new(1);
let bytes = |tag: u8| vec![0u8, 1, 2, tag, 0, 255];
let write = |data: &[u8]| std::fs::write(repo.path().join("b.bin"), data).unwrap();
write(&bytes(0));
repo.git(&["add", "b.bin"]);
repo.git(&["commit", "-q", "-m", "base"]);
repo.git(&["checkout", "-q", "-b", "feature"]);
write(&bytes(1));
repo.git(&["commit", "-q", "-am", "feature"]);
repo.git(&["checkout", "-q", "main"]);
write(&bytes(2));
repo.git(&["commit", "-q", "-am", "main"]);
repo.run(|| {
start(&["merge", "feature"]);
let workdir = repo_state::load().unwrap().workdir;
assert!(
!edited_by_user(&workdir, "b.bin", false),
"untouched (ours) is not an edit"
);
for (tag, edited) in [(0, false), (1, false), (2, false), (9, true)] {
std::fs::write(workdir.join("b.bin"), bytes(tag)).unwrap();
assert_eq!(
edited_by_user(&workdir, "b.bin", false),
edited,
"content {tag}"
);
}
});
assert!(has_manual_edits(Some(b"x"), false, &[b"y".to_vec()]));
assert!(!has_manual_edits(Some(b"y"), false, &[b"y".to_vec()]));
}
#[test]
fn settled_only_when_nothing_is_left() {
let repo = conflict_repo();
repo.run(|| {
assert!(settled(&repo_state::load().unwrap()));
start(&["merge", "feature"]);
assert!(!settled(&repo_state::load().unwrap()));
take_side("a.txt", Side::Ours).unwrap();
assert!(!settled(&repo_state::load().unwrap()), "still merging");
assert!(continue_op(&BTreeSet::new(), &BTreeSet::new())
.unwrap()
.ok());
assert!(settled(&repo_state::load().unwrap()));
});
repo.git(&["checkout", "-q", "-b", "other"]);
repo.write("a.txt", "other\n");
repo.git(&["commit", "-q", "-am", "other change"]);
repo.git(&["checkout", "-q", "main"]);
repo.write("a.txt", "main again\n");
repo.git(&["commit", "-q", "-am", "main again"]);
repo.run(|| {
start(&["merge", "other"]);
assert!(!settled(&repo_state::load().unwrap()));
});
}
#[test]
fn skip_keeps_a_backup_and_drops_the_commit() {
let repo = conflict_repo();
repo.git(&["checkout", "-q", "feature"]);
let backup = repo.run(|| {
start(&["rebase", "main"]);
let (out, backup) = skip_op(InProgress::Rebase).unwrap();
assert!(out.ok(), "{}", out.stderr);
assert_eq!(repo_state::load().unwrap().op, None);
backup
});
assert!(backup.starts_with("refs/gct/backup/"), "{backup}");
assert!(backup.ends_with("-skip"), "{backup}");
assert_eq!(
repo.git(&["rev-parse", "HEAD"]),
repo.git(&["rev-parse", "main"])
);
assert!(!repo.git(&["for-each-ref", "refs/gct/backup/"]).is_empty());
}
#[test]
fn delete_file_removes_and_stages() {
let repo = TempRepo::new(2);
repo.run(|| {
assert_eq!(delete_file("f1.txt").unwrap(), vec!["git rm -- f1.txt"]);
delete_file("never-existed.txt").unwrap();
});
assert!(!repo.path().join("f1.txt").exists());
assert!(repo.git(&["status", "--porcelain"]).contains("D f1.txt"));
}
}