受保护master分支如何通过Pull Request撤销merge commit?能否从feature branch操作?
Alright, let's tackle your Git questions since you're operating in an environment where master can only be modified via Pull Requests. I'll break this down clearly for you:
The safest way to undo a merge commit on master (without rewriting shared history) is using git revert—this creates a new commit that undoes all changes from the merge. Here's how to do it via PR:
- First, fetch the latest master locally:
git checkout master git pull origin master - Find the hash of the merge commit you want to revert. Use
git log --onelineto list commits; merge commits will look likeabc1234 Merge branch 'feature/your-branch'. - Run the revert command, specifying the "first parent" (this tells Git to keep master's original history and undo the merge's changes):
git revert -m 1 <merge-commit-hash>Note:
-m 1refers to the parent branch that was master before the merge. If you're unsure which parent to use, check the merge commit details withgit show <merge-commit-hash>. - Commit the revert (Git will auto-generate a message, but you can customize it):
git commit -m "Revert merge commit <merge-commit-hash> to undo unwanted changes" - Create a new branch for the revert and push it to remote:
git checkout -b revert-merge-unwanted-change git push origin revert-merge-unwanted-change - Finally, open a Pull Request from this revert branch to master. Once approved and merged, the merge commit's changes will be undone on master.
Short answer: You shouldn't use an existing feature branch to undo the merge directly, and you don't need to push changes directly to master either. Here's why:
- If you try to create a branch from the merge commit and use
git resetto "erase" the merge, you'll rewrite master's history. Pushing this would requiregit push -f, which is extremely risky for a shared master branch—it breaks other collaborators' local repos and is likely blocked in your PR-only environment. - The correct approach is the
git revertmethod I outlined above. By creating a new revert branch and opening a PR, you're following your team's workflow (no direct pushes to master) while safely undoing the merge without rewriting history. - Even if you wanted to reuse an existing feature branch, you'd still need to cherry-pick or apply the revert changes to it, which is unnecessary when creating a dedicated revert branch is simpler and cleaner.
To sum up: Stick with the revert + PR workflow. It's compliant with your environment's rules and avoids the pitfalls of rewriting shared Git history.
内容的提问来源于stack exchange,提问作者u123

