1

I have a repo with many remotes setup because we are using the Forking Workflow

I typically clean all the merged branches from the origin repo every quarter. I'm having difficulty figuring out how to clean the merged branches from the individual remotes.

git branch -r --merged <how can i target a specific remote?> |
  grep -v "develop" |
  grep -v "master" |
  grep -v "pr" |
  sed -r 's/(remote1|remote2|remote3|remote4)\///' |
  xargs git push -d origin

The idea here is to list all the merged branches, filter out develop, master, pr and remove origin/, then git push -d

the problem I'm having is I don't know how to target only a specific remote for deletion. Each time I run this command, it lists all the branches from each remote. Then running the command outputs an error

error: unable to delete '<branch-name>': remote ref does not exist
0

2 Answers 2

2

Since the output of git branch -r --merged includes the remote name, you can use grep (etc) to filter by remote. E.g. to see only those branches in the remote1 remote:

git branch -r --merged | grep remote1/

Putting that together with what you have -- and simplifying things a bit -- we get:

git branch -r --merged |
  grep remote1/ |
  grep -vE 'develop|master|pr' |
  sed 's/[^/]*\///' |
  xargs git push -d remote1

If you're getting errors, replace xargs with echo xargs so you can see the generated command line without running it.

Sign up to request clarification or add additional context in comments.

Comments

0

The low-level push can take refspecs from stdin and thus batch up the deletes into a single connection.

Assuming the usual remote-tracking map convention, so remote.origin.fetch = +refs/heads/*:refs/remotes/origin/* and so on, you can

git send-pack $(git config remote.origin.url) --stdin <<EOD
^refs/heads/develop
^refs/heads/master
^refs/heads/pr*
$(git for-each-ref --merged=HEAD \
        --format='+:refs/heads/%(refname:lstrip=3)' \
        refs/remotes/origin/* )
EOD

and you can see what it'll do before doing it by adding a --dry-run option on the send-pack.

3 Comments

thanks but this is not what I want to do. This command deletes develop, master, and pr. Those are the branches I want to avoid. Nice, concise attempt though. I ended up writing a node script and used the Bitbucket rest api
@JeremyFiel It does not delete those refs. Those are exclusion markers on the front.
ah ok.. i misunderstood it. thanks for your attempt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.