add-subtree.sh 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. rm -r "${path}"
  35. mv -T "${prevremotedir}" "${path}"
  36. fi
  37. # Add new remote at the top
  38. echo "${repo} ${branch} ${subdir}" | cat - "${gitsubtree}" 2> /dev/null > "${gitsubtree}.new"
  39. mv "${gitsubtree}.new" "${gitsubtree}"
  40. git add "${gitsubtree}"
  41. git commit --amend --no-edit
  42. if [ "${prevremotedir}" != "" ]; then
  43. prevremotedir=""
  44. echo "Added new remote for existing subtree, you must solve conflicts manually..."
  45. fi