简体   繁体   中英

How delete a local branch after merging it through a pull request? git-flow, bitbucket, sourcetree

My environment in local:

  • Git connecting with Bitbucket
  • Sourcetree with git-flow

Steps

  1. I create a feature x in Sourcetree then I add the code.
  2. I do a commit including the option to create a pull request and push the changes to feature x branch in remote .
  3. In pull request I select the option for Close {branch} after the pull request is merged .
  4. Within Bitbucket a member team approves the pull request then merges it into the develop branch.
  5. I pull the new changes to my local develop branch.

NOTE It's important to review the code through pull request before merging it into develop , so the question is:

Is there any way to delete automatically the feature x branch in my local after made a pull in develop ?

*I tried with a fetch but it does not work.

One simple, non-automated way to handle this is to periodically run a branch cleaning command in your local repo, like

# to be executed with your "main" stable branch checked out
git branch -d $(git branch --merged)

It'll delete every already merged local branch (ie those which do NOT have "not yet merged" commits). So all these branches which have been merged through pull requests will be deleted, but not the few ones that have recent (not reviewed/not merged) commits.

Note : if your policy is to squash commits upon pull request, this won't be a suitable solution, since your local branches still have the original (pre-squash) commits, so they won't be viewed as merged and won't be deleted.

Similar question is already asked elsewhere and there are various useful answers. The point is to find all remote branches marked as 'gone' and then delete them locally.

Short answer

This just lists all local branches to delete:

git branch -vv | grep ': gone]' | grep -v "\\*" | awk '{ print $1; }'

To delete them, just add git branch -D :

git branch -vv | grep ': gone]' | grep -v "\\*" | awk '{ print $1; }' | xargs -r git branch -D

Note: You should be already on master and have fetched your local repo. You can run it before:

git checkout master && git fetch -p && git branch -vv | grep ': gone]' | grep -v "\\*" | awk '{ print $1; }' | xargs -r git branch -D

Alias

And you can create your own alias for it:

git config --global alias.delete-gone-branches "! git branch -vv | grep ': gone]' | grep -v \\"*\\" | awk '{ print \\$1; }' | xargs -r git branch -D"

And then run just git delete-gone-branches .

Sources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM