解决Git合并冲突并暂存方案后,如何获取原始冲突diff?
Hey there! Great call sticking to the convention of including original conflict diffs in your commit messages—it’s super helpful for future developers to audit merge decisions. The manual workflow you’re using (saving to conflict_log then copying) definitely has room for improvement, especially the risk of forgetting to save the log or fumbling through copy-paste. Let’s fix that with some smoother approaches:
1. Auto-include conflict diffs with a Git hook
Git hooks let you automate steps during the commit process. A prepare-commit-msg hook can automatically add the conflict diff to your commit message right when you run git commit, no manual steps needed.
Here’s how to set it up:
- Create a file named
prepare-commit-msgin your repo’s.git/hooks/directory - Paste this script and make it executable with
chmod +x .git/hooks/prepare-commit-msg:#!/bin/bash # Only run for merge commits where conflicts were resolved if [ -f "$GIT_DIR/MERGE_HEAD" ]; then # Add a clear header and the conflict diff to the commit message echo -e "\n\n=== Original Merge Conflict Diff ===" >> "$1" # Only show unmerged (conflicting) files git diff --diff-filter=U >> "$1" fi
Next time you resolve merge conflicts and run git commit, the conflict diff will be appended to your commit message automatically. You can still edit the message before finalizing the commit.
2. One-line command to skip manual copy-paste
If hooks feel too heavy, you can combine your steps into a single command that saves the diff and opens the commit editor in one go:
git diff --diff-filter=U | tee conflict_log && git commit -e -m "Resolve merge conflicts" -F conflict_log
tee conflict_logsaves the diff to the file and outputs it to the console (so you can verify it)-eopens the commit editor so you can tweak the message before committing-F conflict_logpopulates the editor with the diff content right away
3. Wrap it in a Git alias for even faster access
To avoid typing that long command every time, add a custom alias to your .gitconfig:
[alias] commit-conflict = !git diff --diff-filter=U | tee conflict_log && git commit -e -m "Resolve merge conflicts" -F conflict_log
Now you just need to run git commit-conflict after resolving conflicts—done in one step, no chance to forget saving the log.
A quick note: Using --diff-filter=U ensures you only capture the actual conflicting lines, not other changes in your working directory. This keeps your commit messages clean and focused on the merge resolution context.
内容的提问来源于stack exchange,提问作者Chris Beck

