Skip to content

Instantly share code, notes, and snippets.

@pedronauck
Last active October 28, 2023 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedronauck/c97474a411404e6321479ae79b5d70a5 to your computer and use it in GitHub Desktop.
Save pedronauck/c97474a411404e6321479ae79b5d70a5 to your computer and use it in GitHub Desktop.
Functions to remove branchs that was merged but not deleted
#
# filepath ~/.config/fish/functions/del_branch.fish
#
function del_branch --argument name
for name in $argv
# Check if the branch exists locally
set -l local_exists (git rev-parse --verify --quiet $name)
# Check if the branch exists remotely
set -l remote_exists (git ls-remote --heads origin $name)
# If the branch exists locally, delete it
if test -n "$local_exists"
git branch -D $name
# Check if deletion was successful
if test $status -ne 0
echo "Failed to delete local branch $name."
end
else
echo "No local branch named $name."
end
# If the branch exists remotely, delete it
if test -n "$remote_exists"
git push origin --delete $name
# Check if deletion was successful
if test $status -ne 0
echo "Failed to delete remote branch $name."
end
else
echo "No remote branch named $name."
end
end
end
#
# filepath ~/.config/fish/completions/del_branch.fish
#
function __fish_del_branch_complete
# Fetch and list both local and remote branch names, removing 'origin/' prefix from remote branch names
set -l branches (git for-each-ref --format '%(refname:short)' refs/heads refs/remotes | string replace -r '^origin/' '')
# Remove duplicates by converting to a set
set -l unique_branches (echo $branches | tr ' ' '\n' | sort -u)
for branch in $unique_branches
switch $branch
case HEAD
# Skip this entry
case '*'
# Output branch names
echo $branch
end
end
end
complete -f -c del_branch -a '(__fish_del_branch_complete)'
#
# filepath ~/.config/fish/functions/git_prune.fish
#
git fetch --prune --all
set -l deleted_branches (git branch -vv | grep ": gone]" | awk '{print $1}')
if [ (count $deleted_branches) -eq 0 ]
echo "No branches to delete"
else
for branch in $deleted_branches
git branch -D $branch
end
end
@pedronauck
Copy link
Author

How to use it:

del_branch works for multiple branchs

$ del_branch <name_of_the_branch> <name_of_the_branch>

git_prune

$ git_prune

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment