如何编辑合并提交的父提交(父提交为合并提交)的Git提交信息?
Hey there, let's break down what's going on and fix this step by step:
First, the issue with git rebase -i D~ is that D is a merge commit (it has two parent commits: A from your working branch, and C from master). By default, D~ points to the first parent of D (which is C, the master branch parent). So when you run that command, Git tries to rebase your working branch onto C, which is why you only see master's commits (E, C, B) in the interactive list—your working branch's D and F aren't included at all.
To edit D's commit message properly, we need to make sure the interactive rebase includes D and preserves the merge structure. Here's how to do it:
Step 1: Stay on your working branch
First, double-check you're on the branch with the ...A-D-F commit chain (let's call it feature for clarity):
git checkout feature
Step 2: Run interactive rebase with merge preservation
Since D is a merge commit, we need the --preserve-merges (short -p) flag to keep your branch's merge history intact. We'll target the parent of D that's on your working branch—this is D^2 (the second parent of D, which is A):
git rebase -i -p D^2
When the interactive rebase editor pops up, you should see entries for commit D (the merge) and commit F (the later merge of D and E).
Step 3: Reword D's commit message
In the editor, find the line for commit D. Change the leading pick to reword (or just r for short), then save and close the editor.
Git will now pause and open a new editor window where you can type your new commit message for D. Make your changes, save, and close.
Step 4: Finish the rebase
Git will automatically resume the rebase process and reapply commit F on top of your updated D. Since none of these commits have been pushed yet, you won't run into any remote conflict issues (as long as you have no uncommitted local changes).
Alternative Approach: Use a Temporary Branch (If Rebase Feels Tricky)
If you want a more straightforward, visual way to do this, try this method:
- Create a temporary branch starting at A (the parent of D on your working branch):
git checkout -b temp A - Re-merge C into this temp branch, using your new commit message:
git merge C --no-commit git commit -m "Your new, improved commit message for D" - Cherry-pick the F commit (the merge of D and E) onto the temp branch:
git cherry-pick F - Update your working branch to point to this updated temp branch:
git checkout feature git reset --hard temp - Clean up the temporary branch:
git branch -D temp
Either way, you'll end up with your working branch having the corrected commit message for D, while keeping your merge history intact.
内容的提问来源于stack exchange,提问作者Charles

