git.sh 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env bash
  2. source "${BASH_SOURCE%/*}/common.sh"
  3. ensure_pwd
  4. ROOT_FOLDER="${PWD}"
  5. # Get a static hash based on the repo url
  6. function get_hash() {
  7. url="${1}"
  8. echo -n "${url}" | sha256sum | awk '{print $1}'
  9. }
  10. if [ -z ${1+x} ]; then
  11. command=""
  12. else
  13. command="$1"
  14. fi
  15. # Clone a repo
  16. if [[ "$command" = "clone" ]]; then
  17. repo="$2"
  18. repo_hash=$(get_hash "${repo}")
  19. write_log "Cloning ${repo} to ${ROOT_FOLDER}/repos/${repo_hash}"
  20. repo_dir="${ROOT_FOLDER}/repos/${repo_hash}"
  21. if [ -d "${repo_dir}" ]; then
  22. write_log "Repo already exists"
  23. exit 0
  24. fi
  25. write_log "Cloning ${repo} to ${repo_dir}"
  26. if ! git clone "${repo}" "${repo_dir}"; then
  27. write_log "Failed to clone repo"
  28. exit 1
  29. fi
  30. write_log "Done"
  31. exit 0
  32. fi
  33. # Update a repo
  34. if [[ "$command" = "update" ]]; then
  35. repo="$2"
  36. repo_hash=$(get_hash "${repo}")
  37. repo_dir="${ROOT_FOLDER}/repos/${repo_hash}"
  38. git config --global --add safe.directory "${repo_dir}"
  39. if [ ! -d "${repo_dir}" ]; then
  40. write_log "Repo does not exist"
  41. exit 1
  42. fi
  43. write_log "Updating ${repo} in ${repo_hash}"
  44. cd "${repo_dir}" || exit
  45. if ! git pull origin "$(git rev-parse --abbrev-ref HEAD)"; then
  46. cd "${ROOT_FOLDER}" || exit
  47. write_log "Failed to update repo"
  48. exit 1
  49. fi
  50. cd "${ROOT_FOLDER}" || exit
  51. write_log "Done"
  52. exit 0
  53. fi
  54. if [[ "$command" = "get_hash" ]]; then
  55. repo="$2"
  56. get_hash "${repo}"
  57. exit
  58. fi