-
Notifications
You must be signed in to change notification settings - Fork 0
72 lines (67 loc) · 2.44 KB
/
clear-branch.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
name: Clear Branch
on:
schedule:
- cron: '0 8 * * *' # Runs every day at 0:00 Beijing Time (8:00 UTC)
push:
branches:
- test
workflow_dispatch:
inputs:
ref:
description: "Why trigger?"
required: true
type: string
jobs:
clear_branch:
runs-on: ubuntu-latest
env:
SKIP_PATTERNS: |
v6*
v5*
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Configure Git
run: |
git config user.name "$GITHUB_ACTOR"
git config user.email "[email protected]"
- name: Delete invalid branches
run: |
git fetch --prune
current_branch=$(git rev-parse --abbrev-ref HEAD)
protected_branches=$(gh api /repos/${{ github.repository }}/branches --paginate --jq '.[] | select(.protected == true) | .name' | tr '\n' ' ')
echo "All protected branch: ${protected_branches}"
# Define the regex patterns to skip branches
IFS=$'\n' read -r -d '' -a skip_patterns <<< "${{ env.SKIP_PATTERNS }}"
for branch in $(git branch -r | sed 's/origin\///'|grep -v origin); do
skip_branch=false
# Check if the branch matches any of the skip patterns
for pattern in "${skip_patterns[@]}"; do
if [[ $branch =~ $pattern ]]; then
echo "Skipping branch matching pattern: $branch"
skip_branch=true
break
fi
done
if $skip_branch; then
continue
fi
if [[ " ${protected_branches[@]} " =~ " ${branch} " ]]; then
echo "Skipping protected branch: $branch"
continue
fi
if [[ "$branch" == "$current_branch" ]]; then
echo "Skipping current branch: $branch"
continue
fi
# Skip branches with submitted PR
last_commit_date=$(git log -1 --format=%ci origin/$branch)
if [[ $(date -d "$last_commit_date" +%s) -lt $(date -d "10 seconds ago" +%s) ]]; then
if ! gh pr list --head $branch --repo https://github.com//${{ github.repository }} | grep $branch; then
echo "Deleting branch: $branch"
git push origin --delete $branch
fi
fi
done
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}