Pleymor
Pleymor

Reputation: 2911

Delete all git branches already pushed

My need

Hi, I'm looking for a command to delete all local branches already pushed to origin.

I especially want to keep all branches with commits not pushed yet to their respective remote branches.

Reason

git prune does a part of the job by clearing branches while the remote is deleted, but as I have many feature branches I would need to keep only the branches which have not been fully pushed to remote, to avoid having a long list of local branches in my repo, restricting them to those actually in works.

Thank you!

Upvotes: 1

Views: 263

Answers (2)

jthill
jthill

Reputation: 60275

git remote update # `git fetch --all` but it allows configurable skipping, see the docs
git for-each-ref refs/heads --format='
        [[ "%(upstream)" != "" ]] &&    # there is an upstream branch
        git merge-base --is-ancestor %(refname) %(upstream) &&  # which has this tip
        echo delete %(refname)
' # | sh # | git update-ref --stdin

Generating commands for the shell is useful and fun -- if you c&p the above it won't actually do anything to your repo, its output is instead the commands to check for whether a branch is in the upstream; delete a # and it'll execute the checks instead of just printing them, try it.

Upvotes: 3

Romain Valeri
Romain Valeri

Reputation: 21938

Although it looks like a blind elephant in regards to the nimble and smart solution suggested by jthill, I share here the brutal approach I tend to use so far for the same need you describe :

# nuke all branches* (which have no unique commit)
git branch -d $(git for-each-ref --format="%(refname:short) refs/heads")

# for "main" branches (I mean permanent, like master), recreate them if needed from remote
git checkout master

This is the one-shot version, but an alias can easily be made from it for convenience.

Note the -d flag which, as opposed to -D, means "soft deletion" and refuses to delete branches with unmerged commits (safecheck ignored by -D).


* here, git might (depending on the state of the current branch) complain about not being able to delete the branch you're on. Not a big deal in direct command mode, but a bit annoying in an alias. Just checkout a mock branch beforehand and delete it afterwards. Since we're nuking everything to be sure, I tend to name the branch from-orbit.

Upvotes: 3

Related Questions