Skip to content

Prune Branches by Patterns #14

Prune Branches by Patterns

Prune Branches by Patterns #14

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 github-actions@github.com
- 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