问题
I'd like to automate cleaning of remote branches. I want to be able to check to see if a branch has been merged into master already. Originally, my plan was to use git merge-base to see the last common commit.
However, it turns out that we squash all of our branches as we merge them into master. As this creates a new commit hash, I'm unable to find the common commits between master and my branches.
How might I go about determining if a branch has been merged if we've squashed them all when merging?
Thanks in advance!
回答1:
Here's one approach:
- Use the GitHub API to get the HEAD SHA for all merged pull requests.
- Match these SHAs against local branches.
If a local branch's HEAD has corresponds to that of a PR that's been merged, then you can safely delete it. This will work regardless of how the PR was merged (full merge, fast foward, squash and merge).
I implemented this approach in a delete-squashed-branches script. Here's what usage looks like:
(master) $ git branch
delete-merged-prs
fixup
unmerged-branch
* master
(master) $ delete-squashed-branches
Finding local branches which were merged onto origin/master via GitHub...
warning: deleting branch 'delete-merged-prs' that has been merged to
'refs/remotes/origin/delete-merged-prs', but not yet merged to HEAD.
Deleted branch delete-merged-prs (was 325a42b).
warning: deleting branch 'fixup' that has been merged to
'refs/remotes/origin/fixup', but not yet merged to HEAD.
Deleted branch fixup (was e54f54b).
(master) $ git branch
unmerged-branch
* master
(The warnings can be ignored since the branches were merged onto master via Squash & Merge.)
Caveats:
- You'll need to
pip install pygithub
to use the script. - It will look for local branches that were merged onto
origin/(current branch)
. So you'll want to run it onmaster
,develop
or whatever branch you work off of. - If you have multiple long-lived branches, this approach won't work very well.
回答2:
You could do an experimental merge and check whether it introduces any changes, like so:
git checkout -b foo-merge-test-branch master
git merge --squash foo
if [ -n "$(git status --porcelain)" ]; then
echo "foo has not been merged";
else
echo "foo is already merged";
fi
git reset --hard && git checkout master && git branch -d foo-merge-test-branch
This will only work if none of the files changed in the original git merge --squash foo
have seen further conflicting changes on master
since then.
来源:https://stackoverflow.com/questions/27260574/checking-if-a-git-branch-has-been-merged-into-master-when-squashed