DEV Community

Jeremy Friesen for The DEV Team

Posted on • Originally published at takeonrules.com on

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

Enter fullscreen mode Exit fullscreen mode

The Source Code

Discussion (5)

Collapse
riocantre profile image
Rio Cantre

How can you upload such a long screenshot?! 🤔

Collapse
jeremyf profile image
Jeremy Friesen Author

I'm not quite understanding your comment.

Collapse
riocantre profile image
Rio Cantre

Let me rephrase, the code block seems different from what I used to. It looks cool.

Thread Thread
jeremyf profile image
Jeremy Friesen Author

I used a Liquid tag embed for the Github Gist.

Thread Thread
riocantre profile image
Rio Cantre

Okay 😲