A3: offer git's prepared merge message in the commit box

git.mergeMessage reads MERGE_MSG without its comment lines while a merge
is in progress. The Changes window fills an empty box with it once per
merge when conflicts show up, and again on vcs.commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-31 14:25:11 +01:00
parent 95fd9b926f
commit 983319d8a3
7 changed files with 183 additions and 2 deletions

View file

@ -1,5 +1,5 @@
//! Merge commands (M4.8): `git.merge`, `git.mergeAbort`,
//! `git.conflictVersions` and `git.markResolved`, on top of
//! `git.conflictVersions`, `git.markResolved` and `git.mergeMessage`, on top of
//! `lutra_vcs::Repo`'s merge calls.
//!
//! Each runs through [`super::git::start_with`]: a pending outcome, git and
@ -25,6 +25,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(MergeAbort))?;
registry.register(Box::new(ConflictVersionsCommand))?;
registry.register(Box::new(MarkResolved))?;
registry.register(Box::new(MergeMessage))?;
Ok(())
}
@ -112,6 +113,36 @@ impl Command for MergeAbort {
}
}
/// `git.mergeMessage`.
struct MergeMessage;
impl Command for MergeMessage {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.mergeMessage",
label: "Git: Prepared Merge Message",
menu_path: None,
default_shortcut: None,
params: "none; returns { message: string | null }: the message git prepared for the merge in progress (MERGE_MSG without its # comment lines), null when no merge is in progress; for prefilling the commit box",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let _: serde_json::Map<String, Value> = parse(command, params)?;
start_with(
state,
command,
false,
Box::new(|repo| Ok(json!({ "message": repo.merge_message()? }))),
)
}
}
/// Params of `git.conflictVersions`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
@ -217,4 +248,5 @@ pub(crate) const COMMAND_IDS: &[&str] = &[
"git.markResolved",
"git.merge",
"git.mergeAbort",
"git.mergeMessage",
];

View file

@ -147,11 +147,21 @@ fn merge_conflict_versions_resolve_and_abort() {
);
assert_eq!(host.git_changes(), 0);
let prepared = host.run("git.mergeMessage", Value::Null).unwrap();
let text = prepared["message"].as_str().unwrap();
assert!(text.starts_with("Merge branch 'feature'"), "{text}");
assert!(!text.contains('#'), "{text}");
assert_eq!(host.git_changes(), 0);
let again = host.run("git.merge", json!({"branch": "feature"}));
assert!(matches!(again, Err(EngineError::Failed(m)) if m.contains("in progress")));
host.run("git.mergeAbort", Value::Null).unwrap();
assert_eq!(host.git_changes(), 1);
assert_eq!(
host.run("git.mergeMessage", Value::Null).unwrap(),
json!({"message": null})
);
assert_eq!(
std::fs::read_to_string(root.join("a.php")).unwrap(),
"<?php\nmain\n"

View file

@ -12,11 +12,29 @@
//! - [`Repo::mark_resolved`] stages the files (`add -A`), which removes the
//! unmerged entries; a file deleted in the work tree is staged as deleted.
//! - [`Repo::merge_abort`] runs `git merge --abort`.
//! - [`Repo::merge_message`] reads the message git prepared for the merge
//! in progress (`MERGE_MSG`), for the commit box.
use std::io::Read;
use crate::VcsError;
use crate::repo::{Contents, FILE_CAP, Repo, SMALL_CAP, check_name, decode};
use crate::runner::{Call, HOOK_TIMEOUT};
/// The most of `MERGE_MSG` [`Repo::merge_message`] reads.
const MESSAGE_CAP: u64 = 64 * 1024;
/// Removes comment lines (starting with `#`) and surrounding blank lines
/// from a prepared commit message; line endings become `\n`.
fn strip_comments(text: &str) -> String {
text.lines()
.filter(|line| !line.starts_with('#'))
.collect::<Vec<_>>()
.join("\n")
.trim_matches(['\n', ' ', '\t'])
.to_string()
}
/// How a merge ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeResult {
@ -209,6 +227,35 @@ impl Repo {
})
}
/// The message git prepared for the merge in progress: `MERGE_MSG` in
/// the repository directory, without its comment lines (those starting
/// with `#`, git's default comment character, such as the list of
/// conflicts) and without surrounding blank lines.
///
/// A missing or unreadable file means there is no message: the box is
/// only a convenience, and the commit itself reports real failures.
///
/// # Returns
/// `None` when no merge is in progress or git left no message.
///
/// # Errors
/// The runner's errors.
pub fn merge_message(&self) -> Result<Option<String>, VcsError> {
if !self.merging()? {
return Ok(None);
}
let Ok(file) = std::fs::File::open(self.git_dir().join("MERGE_MSG")) else {
return Ok(None);
};
let mut bytes = Vec::new();
if file.take(MESSAGE_CAP).read_to_end(&mut bytes).is_err() {
return Ok(None);
}
let text = String::from_utf8_lossy(&bytes);
let message = strip_comments(&text);
Ok((!message.is_empty()).then_some(message))
}
/// Aborts the merge in progress (`git merge --abort`): the work tree
/// and index go back to the state before the merge.
///
@ -303,6 +350,16 @@ mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn strips_comment_lines_from_a_prepared_message() {
assert_eq!(
strip_comments("Merge branch 'f'\r\n\r\n# Conflicts:\r\n#\ta.php\r\n"),
"Merge branch 'f'"
);
assert_eq!(strip_comments("\nA\n\nB\n#c\n\n"), "A\n\nB");
assert_eq!(strip_comments("# only\n"), "");
}
#[test]
fn reads_check_lines() {
assert_eq!(

View file

@ -127,10 +127,14 @@ fn a_conflict_its_versions_resolving_and_committing() {
init(root);
conflicting(root);
let repo = open(&cli, root);
assert_eq!(repo.merge_message().unwrap(), None);
let outcome = repo.merge("feature").unwrap();
assert_eq!(outcome.result, MergeResult::Conflicts);
assert_eq!(outcome.conflicts, vec!["a.php"]);
assert!(repo.merging().unwrap());
let prepared = repo.merge_message().unwrap().unwrap();
assert!(prepared.starts_with("Merge branch 'feature'"), "{prepared}");
assert!(!prepared.contains('#'), "{prepared}");
let status = repo.status().unwrap();
let file = status.files.iter().find(|f| f.path == "a.php").unwrap();
assert_eq!(file.worktree, FileState::Conflicted);
@ -160,6 +164,7 @@ fn a_conflict_its_versions_resolving_and_committing() {
));
repo.commit("Merge feature", false).unwrap();
assert!(!repo.merging().unwrap());
assert_eq!(repo.merge_message().unwrap(), None);
assert_eq!(git(root, &["rev-list", "--count", "--merges", "HEAD"]), "1");
}