Sam Shleifer
Sam Shleifer

Reputation: 1866

Delete all local branches that have been squashed and merged

I am working on a fork of a repository. I send pull requests from branches of that fork and they get "Squash and Merged" into the master branch of the upstream repository once they are accepted. How can I automatically find and delete local branches that have already been squashed and merged? Most strategies shown in other solutions rely on determining whether all commits in a branch can be found in master's commit history, but since all my commits are squashed this condition is never met.

More Info

My git remote -v looks like:

origin  [email protected]:sshleifer/transformers_fork.git (fetch)
origin  [email protected]:sshleifer/transformers_fork.git (push)
upstream    [email protected]:huggingface/transformers.git (fetch)
upstream    [email protected]:huggingface/transformers.git (push)

Upvotes: 4

Views: 1155

Answers (2)

ely
ely

Reputation: 77454

If you can persuade the owners of the upstream repository, you could use a workflow where instead of generating pull requests from the fork to some long-lived branch of the upstream, you instead generate pull requests against a short-lived feature branch that has the exact same name as the branch you are pushing, and then separately the administrator can manage a pull request from that feature branch (in the upstream) to the long-lived branch. If this deletes the feature branch upon the squash merge, then you could detect when upstream feature branches are deleted with remote prune.

# My PR to upstream creates a new feature branch
fork:my-feature-branch -> upstream:my-feature-branch

# Upstream deals with merging to long-lived branch
# this operation will delete upstream:my-feature-branch
upstream:my-feature-branch -> upstream:develop

# I synchronize my fork with upstream and observe branches removed
# with remote prune, and either manually or programmatically delete
# the fork: version of those branches.

Upvotes: 0

LeGEC
LeGEC

Reputation: 51890

Through git alone : the short answer is you can't (not with 100% reliability).

Here are some unreliable ways to explore :

  • if the commit messages on master contain the branch name : grep it out ;
  • if the commit messages on master contain a PR name : grep it out, then use Github's api to find what branch is linked to this PR ;
  • if the commit messages on master contain an issue number : grep it out, and match it with your own rule (issue number in branch name ? fix #xyz in some commit message ?) ;
  • if the branches are always merged soon enough, or rebased on master before being squashed + merged, you can try to look if the content (the ^{tree}) in your branch matches the content of a commit on master :
    • git log --first-parent --format="%T" will give you the list of trees on master,
    • git rev-parse branch/name^{tree} will give you the tree for branch branch/name

Upvotes: 4

Related Questions