-
Notifications
You must be signed in to change notification settings - Fork 39
79 lines (67 loc) · 3.01 KB
/
pruneBranchesByPatterns.yaml
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
73
74
75
76
77
78
79
name: Prune Branches by Patterns
on:
# Trigger the workflow every Monday at 23:00 UTC
# Monday to Tuesday at 00:00 ETC
schedule:
- cron: '0 22 * * 1'
jobs:
delete_merged_branches:
runs-on: ubuntu-latest
steps:
- name: Authorize Mikroe Actions App
uses: actions/create-github-app-token@v1
id: app-token
with:
app-id: ${{ vars.MIKROE_ACTIONS }}
private-key: ${{ secrets.MIKROE_ACTIONS_KEY_AUTHORIZE }}
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Ensure the full history is fetched to check merged branches.
- name: Add GitHub Actions credentials
run: |
git config user.name github-actions
git config user.email [email protected]
- name: List and delete merged feature branches
id: run_script
run: |
# set -x ## Use for debug
# Define the path to the patterns file and log file
pattern_file=".github/workflows/branch_patterns/delete_patterns.txt"
deleted_branches_file="deleted_branches.txt"
# Ensure the file exists
if [ ! -f "$pattern_file" ]; then
echo "Pattern file $pattern_file not found!"
exit 1
fi
# Initialize the log file
echo "Deleted branches on $(date):" > "$deleted_branches_file"
# Read patterns from the file, sanitize for CRLF endings, and iterate over each pattern
deleted_count=0 # Counter to track deleted branches
while IFS= read -r pattern || [[ -n "$pattern" ]]; do
# Remove any \r (CR) characters from the pattern (handles CRLF line endings)
pattern=$(echo "$pattern" | tr -d '\r')
echo "Checking pattern: origin/${pattern}"
# Find branches that match the pattern
branches_to_delete=($(git branch -r --merged | grep "origin/${pattern}" | grep -v 'main' | grep -v 'master' | sed 's/origin\///'))
# Check if any branches were found for the pattern
if [ ${#branches_to_delete[@]} -eq 0 ]; then
echo "No branches to delete for pattern: $pattern"
else
# Delete each branch found for the pattern
for branch in "${branches_to_delete[@]}"; do
echo "Deleting branch $branch"
git push origin --delete "$branch"
echo "$branch" >> "$deleted_branches_file" # Log deleted branches
deleted_count=$((deleted_count+1)) # Increment the deleted branches counter
done
fi
done < "$pattern_file"
echo "deleted_count=$deleted_count" >> $GITHUB_OUTPUT
# Upload the artifact (deleted_branches.txt file)
- name: Upload deleted branches log as artifact
if: steps.run_script.outputs.deleted_count != '0' # Only upload if there were deletions
uses: actions/upload-artifact@v4
with:
name: deleted-branches-log
path: deleted_branches.txt