prune-gh-pages.sh 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/bin/bash
  2. # gh-pages cleanup script: Switches to gh-pages branch, and removes all
  3. # directories that aren't listed as remote branches
  4. function deslash () {
  5. # Recursively build a string of a directory's parents. E.g.,
  6. # deslashed "feature/test/branch" returns feature/test feature
  7. deslashed=$(dirname $1)
  8. if [[ $deslashed =~ .*/.* ]]
  9. then
  10. echo $deslashed $(deslash $deslashed)
  11. else
  12. echo $deslashed
  13. fi
  14. }
  15. repository=origin
  16. if [[ $1 != "" ]]
  17. then
  18. repository=$1
  19. fi
  20. # Cache current branch
  21. current=$(git rev-parse --abbrev-ref HEAD)
  22. # Checkout most recent gh-pages
  23. git fetch --force $repository gh-pages:gh-pages
  24. git checkout gh-pages
  25. git clean -fdx
  26. # Make an array of directories to not delete, from the list of remote branches
  27. branches=$(git ls-remote --refs --quiet $repository | awk '{print $2}' | sed -e 's/refs\/heads\///')
  28. # Add parent directories of branches to the exclusion list (e.g. greenkeeper/)
  29. for branch in $branches; do
  30. if [[ $branch =~ .*/.* ]]; then
  31. branches+=" $(deslash $branch)"
  32. fi
  33. done
  34. # Dedupe all the greenkeepers (or other duplicate parent directories)
  35. branches=$(echo "${branches[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')
  36. # Remove all directories that don't have corresponding branches
  37. # It would be nice if we could exclude everything in .gitignore, but we're
  38. # not on the branch with the .gitignore anymore... so we can't.
  39. find . -type d \
  40. \( \
  41. -path ./.git -o \
  42. -path ./node_modules \
  43. $(printf " -o -path ./%s" $branches) \
  44. \) -prune \
  45. -o -mindepth 1 -type d \
  46. -exec rm -rfv {} \;
  47. # Push
  48. git add -u
  49. git commit -m "Remove stale directories"
  50. git push $repository gh-pages
  51. # Return to where we were
  52. git checkout -f $current
  53. exit