Ruby Script to Find Local Branches with Deleted Remotes

Pivoting from One Strategy to Another

In the Forem codebase we use a Squash and Merge. Prior to joining Forem, I was accustomed to the Create a Merge Commit strategy.

With the Create a Merge Commit strategy, I have a script to Prune Branches. That script tidied up branches that git understood to have been merged into the “main” branch.

However, that script doesn’t work with the Squash and Merge strategy. So I needed to come up with something different. (And please if you are aware of something else that’s part of git let me know).

Scripting the Cleanup

At the bottom of this post is that code. With that code I can do the following: cd /path/to/repo; local-branches-with-missing-remote

That command will print to STDOUT the list of local branches whose tracking branch is now gone; likely because I merged a pull request which automatically deletes the branch on Github.
Whenever I push up a branch, I always use git push --set-upstream to create the tracking branch connection.

Then, when I want to tidy up my local branches, I can run the following: cd /path/to/repo; local-branches-with-missing-remote | xargs git remote -D.

This helps keep my local branch list nice and tidy, which is super important to me as I’ve been issuing lots of tiny pull requests to do some minor refactors to the Forem codebase.

A future me might write an alias to shorten this verbose command title and xargs add-on, but not today.

Sidebar on XARGS

I’m using Unix’s xargs command to take each line of output and run the git remote -D command on that.

The xargs command is analogous to the anonymous function of a block in Ruby.

# `local-branches-with-missing-remote` "piped" into
["branch-1", "branch-2", "branch-3"].each do |line|
  # `xargs git remote -D`
  exec("git remote -D #{line}")
end

The Source Code

26