subtree-subdir-helper.sh 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 / -)-${branch}"
  18. fetch="_fetch-${temp}"
  19. split="_split-${temp}-$(tr / - <<< "${subdir}")"
  20. git fetch --no-tags "${repo}" "${branch}:${fetch}"
  21. mkdir -p "${path}/.subtree-cache"
  22. cache="${path}/.subtree-cache/${split}"
  23. hash="$(git rev-parse ${fetch})"
  24. skip=false
  25. if [ -f "${cache}" ]; then
  26. if [ "$(<${cache})" = "${hash}" ]; then
  27. skip=true
  28. fi
  29. fi
  30. ok=true
  31. if ! $skip; then
  32. git checkout "${fetch}"
  33. exec {capture}>&1
  34. result="$(git subtree split -P "${subdir}" -b "${split}" 2>&1 | tee /proc/self/fd/$capture)"
  35. if grep "is not an ancestor of commit" <<< "$result" > /dev/null; then
  36. echo "Resetting split branch..."
  37. git branch -D "${split}"
  38. git subtree split -P "${subdir}" -b "${split}"
  39. fi
  40. if grep "^fatal: " <<< "$result" > /dev/null; then
  41. ok=false
  42. fi
  43. git checkout "${prev}"
  44. if $ok; then
  45. git subtree "${action}" -P "${path}" "${split}" -m "${action^} ${path} from ${repo}"
  46. fi
  47. fi
  48. if $ok; then
  49. echo "${hash}" > "${cache}"
  50. fi