add-subtree.sh 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/bin/bash
  2. set -e
  3. bash .utils/.check-workdir.sh
  4. if [ "$1" = "" ] || [ "$2" = "" ]; then
  5. echo "Usage 1: <path> <repo url> <branch> [subdir]"
  6. echo "Usage 2: <path> <repo url>/tree/<branch>[/subdir]"
  7. exit
  8. fi
  9. path="${1%/}"
  10. repo="${2%/}"
  11. if [ "$3" = "" ]; then
  12. read repo branch subdir <<< "$(sed -E "s|(https?://[^/]+)/([^/]+)/([^/]+)/(tree\|blob)/([^/]+)/?(.*)|\1/\2/\3 \5 \6|" <<< "${repo}")"
  13. else
  14. branch="${3}"
  15. subdir="${4%/}"
  16. fi
  17. gitsubtree="${path}/.gitsubtree"
  18. prevremotedir=""
  19. if [ -e "${gitsubtree}" ]; then
  20. echo "Subtree already exists, adding new remote to it."
  21. prevremotedir="$(mktemp -d /tmp/gitsubtree-XXXXXXXX)"
  22. # To use 2 remotes for subtree we need to remove current one, add new one, then merge
  23. mv -T "${path}" "${prevremotedir}"
  24. git add "${path}"
  25. git commit -m "Add new remote for ${path}"
  26. fi
  27. if [ "${subdir}" = "" ]; then
  28. subdir="/"
  29. git subtree add -P "${path}" "${repo}" "${branch}" -m "Add ${path} from ${repo}"
  30. else
  31. bash .utils/.subtree-subdir-helper.sh "${path}" "${repo}" "${branch}" "${subdir}" add
  32. fi
  33. if [ "${prevremotedir}" != "" ]; then
  34. if [ -e "${path}/.subtree-cache" ]; then
  35. # Backup subtree cache
  36. cp -rT "${path}/.subtree-cache" "${prevremotedir}/.subtree-cache"
  37. fi
  38. rm -r "${path}"
  39. mv -T "${prevremotedir}" "${path}"
  40. fi
  41. if [ -e "${gitsubtree}" ]; then
  42. # Add new remote at the top
  43. echo "${repo} ${branch} ${subdir}" | cat - "${gitsubtree}" > "${gitsubtree}.new"
  44. mv "${gitsubtree}.new" "${gitsubtree}"
  45. else
  46. echo "${repo} ${branch} ${subdir}" > "${gitsubtree}"
  47. fi
  48. git add "${gitsubtree}"
  49. git commit --amend --no-edit
  50. if [ "${prevremotedir}" != "" ]; then
  51. prevremotedir=""
  52. echo "Added new remote for existing subtree, you must solve conflicts manually..."
  53. fi