deploy-remote.sh 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. remote="${MAILHUB_DEPLOY_REMOTE:-}"
  4. remote_dir="${MAILHUB_DEPLOY_DIR:-}"
  5. branch="${MAILHUB_DEPLOY_BRANCH:-$(git branch --show-current)}"
  6. git_url="${MAILHUB_DEPLOY_GIT_URL:-$(git remote get-url origin)}"
  7. stash_remote="${MAILHUB_DEPLOY_STASH_REMOTE:-0}"
  8. if [[ -z "${remote}" || -z "${remote_dir}" ]]; then
  9. echo "Set MAILHUB_DEPLOY_REMOTE and MAILHUB_DEPLOY_DIR before deploying." >&2
  10. echo "Example: MAILHUB_DEPLOY_REMOTE=deploy@example.com MAILHUB_DEPLOY_DIR=/opt/mailhub npm run deploy:remote" >&2
  11. exit 1
  12. fi
  13. if [[ -z "${branch}" ]]; then
  14. echo "Unable to detect current git branch." >&2
  15. exit 1
  16. fi
  17. git fetch origin "${branch}"
  18. local_head="$(git rev-parse HEAD)"
  19. remote_head="$(git rev-parse "origin/${branch}")"
  20. if [[ "${local_head}" != "${remote_head}" ]]; then
  21. echo "Local HEAD is not pushed to origin/${branch}." >&2
  22. echo "Commit and push first, then run this deploy script." >&2
  23. exit 1
  24. fi
  25. ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=4 "${remote}" \
  26. 'bash -s' -- "${remote_dir}" "${branch}" "${git_url}" "${stash_remote}" <<'REMOTE'
  27. set -euo pipefail
  28. remote_dir="$1"
  29. branch="$2"
  30. git_url="$3"
  31. stash_remote="$4"
  32. cd "${remote_dir}"
  33. if ! git remote get-url origin >/dev/null 2>&1; then
  34. git remote add origin "${git_url}"
  35. fi
  36. if [[ -n "$(git status --porcelain)" ]]; then
  37. if [[ "${stash_remote}" == "1" ]]; then
  38. git stash push -u -m "pre-deploy-$(date -u +%Y%m%d-%H%M%S)"
  39. else
  40. echo "Remote working tree is dirty. Set MAILHUB_DEPLOY_STASH_REMOTE=1 to stash it before pulling." >&2
  41. git status --short >&2
  42. exit 1
  43. fi
  44. fi
  45. git fetch origin "${branch}"
  46. git checkout "${branch}"
  47. git pull --ff-only origin "${branch}"
  48. docker compose up -d --build
  49. docker compose ps
  50. REMOTE