Bash script to notify Slack channel for merged branches
Repository health becomes an issue for large projects. If you use feature branches, you’ll have a waste of merged-unused-branches. I have prepared a bash script to find these branches and the authors of last commit of those branches. Then I have sent a summary to a channel in Slack. Here is the script (also in gist):
#!/bin/bash -ex
sendSlackMsg(){
curl -X POST --data-urlencode "payload={\"channel\": \"$1\", \"attachments\": [{\"title\":\"Merged branches report:\", \"text\":\"$2\",\"mrkdwn_in\":[\"text\"]}], \"icon_emoji\":\":shipit:\"}" https://hooks.slack.com/services/incoming-webhook-url
}
#user-defined
cd $REPO
git fetch -a --prune
declare -a textArray
git branch -r --merged origin/master | \
awk '{branch=substr($1,8); if(branch!="HEAD" && branch!="master") {print branch}}' | {
while read branch; do
git fetch origin $branch
author=$(git log origin/$branch --format="%an" -n 1)
branchTxt='*'$branch'*, last committer: *'$author'*'
textArray+=("$branchTxt")
done
printf '%s\n' "${textArray[@]}" > branchtmp.out
}
text=$(cat branchtmp.out)
rm branchtmp.out
sendSlackMsg "#engineering" "$text"
Explanation:
git fetch -a --prune
updates local fetched branches, prunes deleted branches.git branch -r --merged origin/master
finds remote branches that are already merged intomaster
.awk
line cuts theorigin/
prefix and filters ourmaster
andHEAD
.- Then in while loop, each merged branch is actually fetched. We’re doing it to
find the author.
git log origin/$branch --format="%an" -n 1
shows the log of last commit, where the format defines that only author name will be displayed. After this process is repeated for each branch, the result is printed out to a temporary file because piped commands are executed in subshell. I couldn’t figure out to use a variable in parent shell. - After text preparing is finished, it’s sent to Slack by webhook integrations (a quick setup can be found here).
Finally, I have setup a cron job to execute this script every morning during weekdays. Here is the expression:
$ crontab -l
0 6 * * 1-5 sh /path/to/listMergedBranches.sh
Finally, every morning at 6 AM (which becomes 9AM in our timezone), a report for merged branches appears on Slack channel.
Result: less branches, cleaner environment.