add-subtree.sh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 ! git diff --quiet || ! git diff --cached --quiet || ! git merge HEAD &> /dev/null; then
  8. echo "Workdir must be clean!"
  9. exit
  10. fi
  11. if [ "$1" = "" ] || [ "$2" = "" ]; then
  12. echo "Usage 1: <path> <repo url> <branch> [subdir]"
  13. echo "Usage 2: <path> <repo url>/tree/<branch>[/subdir]"
  14. exit
  15. fi
  16. path="${1%/}"
  17. repo="${2%/}"
  18. if [ "$3" = "" ]; then
  19. read repo branch subdir <<< "$(sed -E "s|(https?://[^/]+)/([^/]+)/([^/]+)/(tree\|blob)/([^/]+)/?(.*)|\1/\2/\3 \5 \6|" <<< "${repo}")"
  20. else
  21. branch="${3}"
  22. subdir="${4%/}"
  23. fi
  24. gitsubtree="${path}/.gitsubtree"
  25. prevremotedir=""
  26. if [ -e "${gitsubtree}" ]; then
  27. echo "Subtree already exists, adding new remote to it."
  28. prevremotedir="$(mktemp -d /tmp/gitsubtree-XXXXXXXX)"
  29. mv -T "${path}" "${prevremotedir}"
  30. git add "${path}"
  31. git commit -m "Add new remote for ${path}"
  32. fi
  33. if [ "${subdir}" = "" ]; then
  34. subdir="/"
  35. git subtree add -P "${path}" "${repo}" "${branch}" -m "Add ${path} from ${repo}"
  36. else
  37. bash .utils/.subtree-subdir-helper.sh "${path}" "${repo}" "${branch}" "${subdir}" add
  38. fi
  39. if [ "${prevremotedir}" != "" ]; then
  40. rm -r "${path}"
  41. mv -T "${prevremotedir}" "${path}"
  42. fi
  43. echo "${repo} ${branch} ${subdir}" >> "${gitsubtree}"
  44. git add "${gitsubtree}"
  45. git commit --amend --no-edit
  46. if [ "${prevremotedir}" != "" ]; then
  47. prevremotedir=""
  48. echo "Added new remote for existing subtree, you must solve conflicts manually..."
  49. fi