Skip to content

Instantly share code, notes, and snippets.

@Martin91
Created December 22, 2020 03:02
Show Gist options
  • Save Martin91/d77a738fc9fa4c95edcd26e429f539a6 to your computer and use it in GitHub Desktop.
Save Martin91/d77a738fc9fa4c95edcd26e429f539a6 to your computer and use it in GitHub Desktop.

Revisions

  1. Martin91 created this gist Dec 22, 2020.
    64 changes: 64 additions & 0 deletions .git_scripts_check_branchs.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    #!/bin/zsh

    specialBranches=("master" "uat" "test" "release")

    echo "\u001b[31mScanning released local branches...\n--------------------------------------------------------\u001b[0m"
    releasedLocalBranches=()
    for branch in $(git branch)
    do
    git show-ref -s --heads $branch | xargs git branch --contains | grep master > /dev/null
    if [[ $? -eq 0 && ! " ${specialBranches[@]} " =~ " ${branch} " ]]; then
    echo $branch
    releasedLocalBranches+=($branch)
    fi
    done

    echo "Need to delete these branches? [Y/N]: "
    read choice

    if [ "$choice" = "Y" ]; then
    currentBranch=$(git branch --show-current)
    if [ ! $currentBranch = "master" ]; then
    echo "\u001b[31mERR: To delete local branches, you should checkout to master branch firstly, instead of $currentBranch!\u001b[0m"
    exit 255
    fi
    echo "\u001b[31mATTENTION: Deleting local branches...\n--------------------------------------------------------\u001b[0m"
    for branch in "${releasedLocalBranches[@]}"
    do
    git branch -d $branch
    done
    fi

    # Delete remote branches
    echo "Need to scan remote branches? [Y/N]: "
    read choice
    if [ "$choice" != "Y" ]; then
    echo "Goodbye~"
    exit 0
    fi

    echo "\u001b[31mScanning released remote branches...\n--------------------------------------------------------\u001b[0m"
    releasedRemoteBranches=()
    for ref refName in $(git ls-remote --heads)
    do
    refName="$(echo $refName | sed 's/refs\/heads\///g')"
    git branch -r --contains $ref | grep master > /dev/null
    if [[ $? -eq 0 && ! " ${specialBranches[@]} " =~ " ${branch} " ]]; then
    echo $refName
    releasedRemoteBranches+=($refName)
    fi
    done

    # Delete remote branches
    echo "Need to delete these remote branches? [Y/N]: "
    read choice

    if [ "$choice" = "Y" ]; then
    for branch in "${releasedRemoteBranches[@]}"
    do
    echo "git push origin :$branch"
    # git push origin ":$branch"
    done
    fi

    echo "\u001b[31mGoodBye~\u001b[0m"