From 983319d8a3fb858b4c736d1fa500e2713c25def5 Mon Sep 17 00:00:00 2001 From: danny Date: Sat, 31 Oct 2026 14:25:11 +0100 Subject: [PATCH] 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 --- crates/engine/src/cmd/git_merge.rs | 34 +++++++++++++- crates/engine/tests/git_merge.rs | 10 +++++ crates/vcs/src/merge.rs | 57 ++++++++++++++++++++++++ crates/vcs/tests/merge.rs | 5 +++ docs/architecture.md | 2 +- ui/src/components/vcs/changes/changes.ts | 46 +++++++++++++++++++ ui/tests/vcs/ChangesToolWindow.test.ts | 31 +++++++++++++ 7 files changed, 183 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/git_merge.rs b/crates/engine/src/cmd/git_merge.rs index 72cd646..9962453 100644 --- a/crates/engine/src/cmd/git_merge.rs +++ b/crates/engine/src/cmd/git_merge.rs @@ -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 { + let command = self.spec().id; + let _: serde_json::Map = 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", ]; diff --git a/crates/engine/tests/git_merge.rs b/crates/engine/tests/git_merge.rs index b2ab00e..b8e66c9 100644 --- a/crates/engine/tests/git_merge.rs +++ b/crates/engine/tests/git_merge.rs @@ -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(), " String { + text.lines() + .filter(|line| !line.starts_with('#')) + .collect::>() + .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, 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!( diff --git a/crates/vcs/tests/merge.rs b/crates/vcs/tests/merge.rs index 50d5a97..8bc236c 100644 --- a/crates/vcs/tests/merge.rs +++ b/crates/vcs/tests/merge.rs @@ -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"); } diff --git a/docs/architecture.md b/docs/architecture.md index 11378ac..44243d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -709,7 +709,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat ### Merge conflicts (M4.8) - **Backend (`crates/vcs/src/merge.rs`, an `impl Repo` append):** `merge(branch)` runs `git merge --no-edit --no-progress --end-of-options ` (fast-forward when possible, hooks run, 120 s) under the mutation lock (`Repo::lock`, now `pub(crate)`); it refuses while `MERGE_HEAD` exists or the index has unmerged entries. A merge that stops on conflicts is not an error: the conflicted paths come from `ls-files -u -z`. Success compares HEAD before and after (merged or up to date); a failure without unmerged entries or `MERGE_HEAD` is git's refusal (local changes would be overwritten, unknown branch). `merge_abort()` is `git merge --abort`. `conflict_versions(path)` reads the stages `:1:` (base), `:2:` (ours), `:3:` (theirs) with one `cat-file --batch-check` and the blobs as stored, through M4.1's `decode` (binary, over 32 MiB, missing per side). `mark_resolved(paths)` is `stage` (`add -A`, so a file deleted on disk is staged as deleted). `merging()` and `unmerged()` are public. The `--batch-check` and `ls-files -u` parsers are property-tested. -- **Commands (`crates/engine/src/cmd/git_merge.rs`, through `git::start_with`):** `git.merge {branch}` → `{result: "merged"|"upToDate"|"conflicts", conflicts: [path]}`; `git.mergeAbort` → `{}`; `git.conflictVersions {path}` → `{base?, ours: string|null, theirs: string|null, binary, tooLarge}` (`base` absent when the file was added on both sides, a side `null` when deleted there, all texts `null` when binary or too large); `git.markResolved {paths}` → `{}`. Merge, abort and mark resolved send `gitChanged`. +- **Commands (`crates/engine/src/cmd/git_merge.rs`, through `git::start_with`):** `git.merge {branch}` → `{result: "merged"|"upToDate"|"conflicts", conflicts: [path]}`; `git.mergeAbort` → `{}`; `git.conflictVersions {path}` → `{base?, ours: string|null, theirs: string|null, binary, tooLarge}` (`base` absent when the file was added on both sides, a side `null` when deleted there, all texts `null` when binary or too large); `git.markResolved {paths}` → `{}`; `git.mergeMessage` → `{message: string|null}` (git's prepared `MERGE_MSG` without `#` comment lines, null outside a merge; the Changes window offers it in an empty commit box once per merge and on `vcs.commit`). Merge, abort and mark resolved send `gitChanged`. - **Three-way line merge (`ui/src/components/vcs/merge/diff3.ts`):** texts become lines that keep their `\n`; each distinct line is encoded as one BMP character so `@codemirror/merge`'s character `diff` (2 s limit) gives line changes. The changes of ours and theirs against the base are grouped where they overlap or touch on the base (as git does): one side changed takes it, both changed alike takes it once, else a conflict. Without a base every difference of ours and theirs is a conflict. The result starts with every non-conflicting change applied and the base's lines in each conflict. - **Dialog (`MergeDialog.vue`, store `merge.ts`, editors `resolveView.ts`):** an exclusive modal. UI commands (menu Git, no default shortcuts): `vcs.merge {branch?}` lists the other branches with a filter (or merges the given one) after `flushDirty()`, toasts the outcome and opens the conflicts list on conflicts; `vcs.resolveConflicts {path?}` shows the conflicted files (from the shared status store) or one file's resolve view; `vcs.abortMerge` asks first, then runs `git.mergeAbort` (git's refusal stays in the dialog). The Changes window opens a conflicted row through `vcs.resolveConflicts {path}`. With no conflicts left the list offers Commit (`vcs.commit`). - **Resolve view:** three CodeMirror editors, ours (read-only), the result (editable), theirs (read-only), with the file's language. A state field maps each chunk's range in the result through edits; a chunk is open while its text is still the base's, taken from a side while it equals that side, edited otherwise, so undo reopens it without bookkeeping. » / « buttons in the side gutters accept a chunk; the toolbar has previous/next conflict (wrapping, scrolling all three), accept left/right for the current chunk, accept all left/right and a counter. Apply (enabled once no chunk is open) writes the result into the file's engine buffer (so its line ending, the journal and an open tab stay right), saves it and runs `git.markResolved`. A file deleted on one side offers to keep the other side's version; binary and too large files can only be marked resolved as they are on disk. Colours: `--lt-vcs-conflicted` for open chunks, `--lt-vcs-modified` for taken ones and non-conflicting changes. Escape closes, except in a changed resolve view. diff --git a/ui/src/components/vcs/changes/changes.ts b/ui/src/components/vcs/changes/changes.ts index 6fe34b1..02e85c3 100644 --- a/ui/src/components/vcs/changes/changes.ts +++ b/ui/src/components/vcs/changes/changes.ts @@ -19,6 +19,10 @@ * - **Amend:** checking Amend with an empty box fills it with the last * commit's message (`git.lastMessage`); clearing Amend again empties a * box that still holds exactly that text. + * - **Merge message:** while a merge waits on conflicts, an empty box + * (without Amend) offers the message git prepared (`git.mergeMessage`), + * once per merge: when the status first shows conflicted files, and + * again on `vcs.commit` if the box is empty then. * - **Untrusted input:** the status comes from the engine and, through it, * from git; malformed entries are dropped and the count capped * ({@link MAX_FILES}). @@ -236,6 +240,44 @@ export const useChangesStore = defineStore("changes", () => { void onAmend(on); }); + /** Whether the prepared merge message was offered for the merge in progress. */ + let mergeOffered = false; + + /** + * Fills an empty box (without Amend) with the message git prepared for + * the merge in progress. A failed call or no merge leaves the box as it + * is; no merge also ends the current offer. + */ + async function offerMergeMessage(): Promise { + if (amend.value || message.value.trim() !== "") { + return; + } + const result = await runWaiting("git.mergeMessage"); + if (!result.ok) { + return; + } + const value = result.value; + const text = + typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.message === "string" + ? value.message + : null; + if (text === null) { + mergeOffered = false; + return; + } + mergeOffered = true; + if (!amend.value && message.value.trim() === "") { + message.value = text; + } + } + + watch(status, (s) => { + const conflicted = (s?.files ?? []).some((f) => f.index === "conflicted" || f.worktree === "conflicted"); + if (conflicted && !mergeOffered) { + void offerMergeMessage(); + } + }); + /** * Runs a mutating git command, toasting its failure. * @@ -343,6 +385,7 @@ export const useChangesStore = defineStore("changes", () => { params: { hash: hash.slice(0, SHORT_HASH), summary }, }); prefilled = null; + mergeOffered = false; message.value = ""; amend.value = false; await refresh(); @@ -383,6 +426,9 @@ export const useChangesStore = defineStore("changes", () => { open(); focusPending.value = true; focusRequest.value += 1; + if (phase.value === "ready") { + void offerMergeMessage(); + } } /** Hides the tool window; the status and the message stay. */ diff --git a/ui/tests/vcs/ChangesToolWindow.test.ts b/ui/tests/vcs/ChangesToolWindow.test.ts index 0936a02..b8cbc10 100644 --- a/ui/tests/vcs/ChangesToolWindow.test.ts +++ b/ui/tests/vcs/ChangesToolWindow.test.ts @@ -49,6 +49,8 @@ let listeners: ((event: { payload: unknown }) => void)[]; let gitStatus: unknown; /** Errors to throw, by command id. */ let failures: Record; +/** What `git.mergeMessage` answers. */ +let mergeMessage: string | null; /** What `file.saveAll` answers. */ let saveAll: unknown; /** Pinia of the current test. */ @@ -118,6 +120,7 @@ beforeEach(() => { mounted = []; failures = {}; gitStatus = sampleStatus(); + mergeMessage = null; saveAll = { saved: [], failed: [], skipped: [] }; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); @@ -145,6 +148,8 @@ beforeEach(() => { return Promise.resolve(gitStatus); case "git.lastMessage": return Promise.resolve({ message: "Last subject\n\nLast body" }); + case "git.mergeMessage": + return Promise.resolve({ message: mergeMessage }); case "git.commit": return Promise.resolve({ commit: "fedcba9876543210", summary: String(args.params.message).split("\n")[0] }); case "file.saveAll": @@ -338,6 +343,32 @@ describe("the Changes store", () => { expect(callsOf("git.lastMessage")).toHaveLength(1); }); + it("offers git's prepared merge message once while a merge has conflicts", async () => { + const changes = useChangesStore(pinia); + await changes.refresh(); + expect(callsOf("git.mergeMessage")).toHaveLength(0); + mergeMessage = "Merge branch 'feature'"; + gitStatus = { + ...sampleStatus(), + files: [{ path: "a.php", index: "conflicted", worktree: "conflicted" }], + }; + await changes.refresh(); + await flushPromises(); + expect(callsOf("git.mergeMessage")).toHaveLength(1); + expect(changes.message).toBe("Merge branch 'feature'"); + changes.message = ""; + await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true }); + expect(callsOf("git.mergeMessage")).toHaveLength(1); + expect(changes.message).toBe(""); + changes.focusMessage(); + await flushPromises(); + expect(changes.message).toBe("Merge branch 'feature'"); + changes.message = "mine"; + changes.focusMessage(); + await flushPromises(); + expect(changes.message).toBe("mine"); + }); + it("keeps the message when git refuses the commit", async () => { const changes = useChangesStore(pinia); await changes.refresh();