If you squash-merge a branch, you can't delete it in the usual way,
git branch -d, because there is no history of merging into the default branch.
In the figure below, squash-merge the commit on your topic branch, D, and it's merged into your default branch as a new commit, E. Then the git history becomes a child of B, and it loses its relevance to the topic branch.
To delete a topic branch that has lost its merge history, you must forcibly delete with
git branch -D, and you are always worried that you might accidentally delete another branch you are working on.
To solve this problem, I created a tool called gh poi ("poi" means "feel free to throw it away" in Japanese).
gh poi is an extension that runs as a subcommand of the GitHub CLI, which is officially provided by GitHub.
GitHub CLI v2.0.0 (released August 2021) and later versions allow you to develop and install extensions.
By providing it as an extension, you don't need to issue an access token to GitHub for each tool and can use it easily.
As mentioned earlier, squash-merge branches can only be deleted by forcibly delete. Since
gh poi also executes forced deletion internally, it is important to correctly determine the branch to delete.
- Use gh repo view to get the remote repository name
- Use the
gitcommand to get a list of commit hashes for the branches that exist in the current directory
- Use gh api to search for all the pull requests associated with the repository name and commit hash mentioned above
- Determine deletion branches and execute based on search results
The GitHub API is used to check the pull requests associated with the head commit hash in each local branch, and if the status of the pull request is merged, the local work is considered complete and can be deleted. Since it uses the GitHub API, the best feature of it is that it can determine the deletion of any merge method including "Squash and merge".
In some cases, a pull request is closed and a new pull request is created. In this case, there will be multiple pull requests related to the branch, but if there is at least one pull request that has been merged and all other related branches are closed, it is determined that the branch can be deleted.
If there are still open pull requests, they are not included in the deletion list because they may continue to be worked on locally. We can easily run
gh poi at any time to clean up the working environment.
In addition, if there is a forked repository in the first step, it also gets the name of the upstream repository, so it can make the same deletion decision when we merged the pull request to the forked repository. This is useful when contributing to OSS.
I found a few ways to delete squash-merge branches, but I couldn't find a tool that worked with GitHub and could delete them cleanly as expected, so I decided to make my own.
If you are interested in this project, please also register for ⭐️ Star from gh-poi.
Thanks for reading ☕️