Skip to content

Instantly share code, notes, and snippets.

@detour1999
Last active March 13, 2024 17:00
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 detour1999/8e10e35dd2857aba2424e8762ae2dbc8 to your computer and use it in GitHub Desktop.
Save detour1999/8e10e35dd2857aba2424e8762ae2dbc8 to your computer and use it in GitHub Desktop.
git config local branch cleanup
git config --global alias.br-cleanup '!/path/to/git-br-cleanup.sh'
# ANSI color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
REMOTE_NAME="origin"
# Fetch the latest updates from the remote to ensure accuracy
if ! git fetch "$REMOTE_NAME"; then
echo "Failed to fetch updates from $REMOTE_NAME."
exit 1
fi
# Get the default branch name
DEFAULT_BRANCH=$(git remote show "$REMOTE_NAME" | grep 'HEAD branch' | awk '{print $NF}')
if [ -z "$DEFAULT_BRANCH" ]; then
echo -e "${RED}Failed to determine the default branch from $REMOTE_NAME.${NC}"
exit 1
fi
# Check if we are on the default branch
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$current_branch" != "$DEFAULT_BRANCH" ]; then
echo -e "${GREEN}Switching to default branch: $DEFAULT_BRANCH.${NC}"
if ! git checkout "$DEFAULT_BRANCH"; then
echo -e "${RED}Failed to checkout the default branch: $DEFAULT_BRANCH.${NC}"
exit 1
fi
fi
if ! git fetch --prune; then
echo -e "${RED}Failed to fetch and prune.${NC}"
exit 1
fi
local_branches_deleted_on_remote=$(git branch -vv | grep ': gone]' | awk '{print $1}')
if [ -z "$local_branches_deleted_on_remote" ]; then
echo -e "${YELLOW}No local branches that have been deleted on origin.${NC}"
else
echo -e "${BLUE}Deleting local branches that have been removed from the remote...${NC}"
echo "$local_branches_deleted_on_remote" | while read branch; do
echo -e "${RED}Deleting: $branch${NC}"
git branch -d "$branch" 2> /dev/null || true
done
fi
local_merged_branches=$(git branch --merged "$DEFAULT_BRANCH" | grep -v "^\*\| $DEFAULT_BRANCH\$")
if [ -z "$local_merged_branches" ]; then
echo -e "${YELLOW}No local branches that have been merged into $DEFAULT_BRANCH.${NC}"
else
echo -e "${BLUE}Deleting local branches that have been merged into $DEFAULT_BRANCH...${NC}"
echo "$local_merged_branches" | while read branch; do
echo "${RED}Deleting: $branch${NC}"
git branch -d "$branch" 2> /dev/null || true
done
fi
echo -e "${BLUE}=======remaining branches=======${NC}"
git branch | awk '{if ($1 == "*") {print $2 " (current)"} else {print $1}}' | while read branch; do
echo -e "${GREEN}- $branch${NC}"
done
echo -e "${BLUE}=================================${NC}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment