subtree-subdir-helper.sh 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/bin/bash
  2. set -e
  3. if [ "$(git rev-parse --show-prefix)" != "" ]; then
  4. echo "Must be in root of git repo!"
  5. exit
  6. fi
  7. if [ "${1}" = "" ] || [ "${2}" = "" ] || [ "${3}" = "" ] || [ "${4}" = "" ] || [ "${5}" = "" ]; then
  8. echo "Usage: <path> <repo url> <branch> <subdir> <action>"
  9. exit
  10. fi
  11. path="${1}"
  12. repo="${2}"
  13. branch="${3}"
  14. subdir="${4}"
  15. action="${5}"
  16. prev="$(git branch --show-current)"
  17. temp="$(rev <<< "${repo%/}" | cut -d/ -f1,2 | rev | tr / -)-$(tr / - <<< "${branch}")"
  18. fetch="_fetch-${temp}"
  19. split="_split-${temp}-$(tr / - <<< "${subdir}")"
  20. git fetch --no-tags "${repo}" "${branch}:${fetch}"
  21. cache="${path}/.subtree-cache/${split}"
  22. hash="$(git rev-parse ${fetch})"
  23. skip=false
  24. if [ -f "${cache}" ]; then
  25. if git diff --quiet "$(<${cache})" "${hash}" -- "${subdir}"; then
  26. skip=true
  27. fi
  28. fi
  29. ok=true
  30. if $skip; then
  31. echo "No updates, skipping expensive subtree split."
  32. else
  33. git checkout "${fetch}"
  34. exec {capture}>&1
  35. result="$(git subtree split -P "${subdir}" -b "${split}" 2>&1 | tee /proc/self/fd/$capture)"
  36. if grep "is not an ancestor of commit" <<< "$result" > /dev/null; then
  37. echo "Resetting split branch..."
  38. git branch -D "${split}"
  39. git subtree split -P "${subdir}" -b "${split}"
  40. fi
  41. if grep "^fatal: " <<< "$result" > /dev/null; then
  42. ok=false
  43. fi
  44. git checkout "${prev}"
  45. if $ok; then
  46. git subtree "${action}" -P "${path}" "${split}" -m "${action^} ${path} from ${repo}"
  47. fi
  48. fi
  49. if $ok; then
  50. mkdir -p "${path}/.subtree-cache"
  51. echo "${hash}" > "${cache}"
  52. fi