Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #!/usr/bin/env bash
  2. while getopts "d" opt; do
  3. case $opt in
  4. d) dryRunOpt="--dry-run";;
  5. esac
  6. done
  7.  
  8. # prune local "cache" of remote branches first:
  9. git fetch --prune origin
  10.  
  11. # delete merged to HEAD branches:
  12. mergedBranches=$(git branch -r --merged origin/HEAD | grep -v -e "origin/master" -e "origin/develop" -e "->" | cut -d/ -f2-)
  13. if [ -n "${mergedBranches}" ]; then
  14. echo -e "\033[0;32mDeleting merged branches...\033[0m"
  15. echo git push $dryRunOpt --delete origin ${mergedBranches}
  16. fi
  17.  
  18. # delete branches with last (cherry picked) commit older than 5 months:
  19. echo -e "\n\033[0;32mSearching for stale branches...\033[0m"
  20. unameOut="$(uname -s)"
  21. case "${unameOut}" in
  22. Linux*) machine=Linux;;
  23. Darwin*) machine=Mac;;
  24. *) machine="UNKNOWN:${unameOut}"
  25. esac
  26.  
  27. if [ $machine == "Mac" ]; then
  28. staleTimestamp=$(date -v -6m +"%s")
  29. maybeStaleTimestamp=$(date -v -3m +"%s")
  30. else
  31. staleTimestamp=$(date -d "now - 6 months" +"%s")
  32. maybeStaleTimestamp=$(date -d "now - 3 months" +"%s")
  33. fi
  34.  
  35. notMergedBranches=$(git branch -r --no-merged origin/HEAD | grep -v -e "origin/master" -e "origin/develop" -e "->")
  36. branchesToDelete=""
  37. branchesToReview=""
  38.  
  39. for branch in ${notMergedBranches}; do
  40. lastCommitInfo=$(git cherry origin/HEAD ${branch} | grep -v "^-" | cut -d" " -f2 | xargs git show --format="%H|%ct|%cr|%an" --quiet | grep -v "^$(git rev-parse HEAD)" | tail -1)
  41. lastCommitTimestamp=$(echo "${lastCommitInfo}" | cut -d"|" -f2)
  42. if [ -z "${lastCommitTimestamp}" ] || [ ${lastCommitTimestamp} -lt ${staleTimestamp} ]; then
  43. branchesToDelete+=" ${branch#origin/}"
  44. elif [ ${lastCommitTimestamp} -lt ${maybeStaleTimestamp} ]; then
  45. branchesToReview+="${branch#origin/}|${lastCommitInfo}"$'\n'
  46. fi
  47. echo -n .
  48. done
  49. echo # for new line after dots
  50.  
  51. if [ -n "${branchesToDelete}" ]; then
  52. echo -e "\n\033[0;32mDeleting stale branches...\033[0m"
  53. echo git push $dryRunOpt --delete origin ${branchesToDelete}
  54. else
  55. echo -e "\n\033[0;32mNo stale branches...\033[0m"
  56. fi
  57.  
  58. if [ -n "${branchesToReview}" ]; then
  59. echo -e "\n\033[1;33mBranches to review (may be stale):\033[0m"
  60. echo "${branchesToReview}" | sort -t"|" -k5 | awk -F"|" 'NF {print $5 " changed branch \"" $1 "\" in project \"'${PWD##*/}'\" " $4}'
  61. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement