A hard to remember git 'command'

Disclaimer: I found that somehow on the internet, in the pre-AI area.
All credits go to the original author(s). (Proably reddit)

A git 'one-liner'

Can you guess what this does?

git checkout -q main && git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do mergeBase=$(git merge-base main $branch) && [[ $(git cherry main $(git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _)) == "-"* ]] && echo "$branch is merged into main and can be deleted"; done

Hm, could you guess it?

Step by step guide

Now let’s use some AI to break it down

  • git checkout -q main
    Quietly switch to the main branch.

  • git for-each-ref refs/heads/ "--format=%(refname:short)"
    List all local branch names.

  • while read branch; do …​ done
    Loop through each local branch.

  • mergeBase=$(git merge-base main $branch)
    Find the common ancestor of main and the current branch.

  • git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _
    Create a synthetic commit using the branch’s tree and the merge base as parent.

  • git cherry main <commit>
    Check if the synthetic commit is already in main.

  • [[ …​ == "-"* ]]
    If the output starts with -, it means the commit is already in main.

  • echo "$branch is merged into main and can be deleted"
    Output the branch name if it’s considered fully merged.

Why would I ever need this?

I like clean git histories, and squash merges are a great way to achieve that.
But it can be difficult to track which local branches have already been merged into main.

This command chain helps to identify local branches that can be safely deleted when they were squashed into main.

Is there a better way?

If you know one, please let me know. I would love to hear about it! git branch --merged did not work for me in the scenario described above.