Skip to content

Commit

Permalink
feat: support deleting merged preview branches
Browse files Browse the repository at this point in the history
  • Loading branch information
Oreoxmt committed Jul 10, 2024
1 parent ad36c1d commit 8b48d20
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/prune_branches.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Prune merged preview branches

on:
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:

prune_branches:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout current repo
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Run prune_branches script
run: |
BRANCHES=($(git branch -r | sed 's/^[[:space:]]*origin\///'))
if [ ${#BRANCHES[@]} -gt 0 ]; then
./prune_merged_preview_branches.sh "${BRANCHES[@]}"
else
echo "No branches to prune."
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
60 changes: 60 additions & 0 deletions prune_merged_preview_branches.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/bin/bash

set -e

check_prerequisites() {
# Verify if jq is installed and GITHUB_TOKEN is set.
which jq &>/dev/null || (echo "Error: jq is required but not installed. You can download and install jq from <https://stedolan.github.io/jq/download/>." && exit 1)

test -n "$GITHUB_TOKEN" || (echo "Error: GITHUB_TOKEN (repo scope) is required but not set." && exit 1)
}

# Select appropriate versions of find and sed depending on the operating system.
FIND=$(which gfind || which find)
SED=$(which gsed || which sed)

# Get the directory of this script.
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
cd "$SCRIPT_DIR"

check_prerequisites

# Check if arguments are passed
if [ "$#" -eq 0 ]; then
BRANCHES=($(git branch --list | sed 's/^[*[:space:]]*//'))
else
BRANCHES=("$@")
fi

PRUNE_BRANCHES=()

for branch in "${BRANCHES[@]}"
do
echo "$branch"
# Trim leading spaces and the '*' symbol
branch="${branch#\* }"
branch="${branch# }"

# Check if the branch starts with "preview"
if [[ $branch == preview* ]]; then
repo_owner=$(echo "$branch" | cut -d'/' -f2)
repo_name=$(echo "$branch" | cut -d'/' -f3)
pr_number=$(echo "$branch" | cut -d'/' -f4)
is_merged=$(curl -fsSL -H "Authorization: token $GITHUB_TOKEN" \
"https://api.github.com/repos/$repo_owner/$repo_name/pulls/$pr_number" |
jq -r '.merged_at')
if [ -z "$is_merged" ] || [ "$is_merged" = "null" ]; then
echo "$branch This PR is not merged, skip."
else
PRUNE_BRANCHES+=("$branch")
echo "$branch This PR is merged, continue."
fi
fi
done

# Loop through each branch in the array
for delete_branch in "${PRUNE_BRANCHES[@]}"
do
echo "Deleting branch: $delete_branch"
git push origin --delete $delete_branch
done

0 comments on commit 8b48d20

Please sign in to comment.