#!/usr/bin/env bash # git push deploys a Laravel Go app (exe.dev/deploy/laravel-go): # build the pushed commit in ~/build (npm run build, go build), copy the # binary and public/ into a new ~/releases directory, run its migrations, # switch ~/app to it, restart, and check /up. # If anything fails, the push is rejected and the running release stays. # Run by hand with Not deploying: only pushes to $branch deploy."; exit 0 elif [ "$new" = 0000000000000000000000000000000000000000 ]; then echo "-----> Refusing to delete $branch, the deployed branch."; exit 1 fi exec 9>.deploy.lock && flock 9 # one deploy at a time rev=$(git --git-dir=app.git rev-parse --short "$new") prev=$(readlink app || true) release=$HOME/releases/$(date -u +%Y%m%d-%H%M%S)-$rev deployed= trap '[ -n "$deployed" ] || failed' EXIT failed() { live=$(readlink "$HOME/app" || true) [ "$live" = "$release" ] || rm -rf "$release" echo "-----> Deploy failed.${live:+ Still running ${live##*-}.}" } switch_to() { ln -sfn "$1" "$HOME/app.next" && mv -T "$HOME/app.next" "$HOME/app" && sudo systemctl restart app app-worker } echo "-----> Building $(git --git-dir=app.git log -1 --format='%h %s' "$new")" # Go caches compiled packages in ~/.cache/go-build and modules in ~/go, # so only what changed recompiles, even in a fresh ~/build. rm -rf build && mkdir build git --git-dir=app.git archive "$new" | tar -x -C build ln -s "$HOME/app.env" build/.env # for VITE_* settings in the frontend build unset $(git rev-parse --local-env-vars) GIT_QUARANTINE_PATH cd build if [ -f package.json ]; then npm ci --no-audit --no-fund --loglevel=error npm run build fi # A release is the binary, with its migrations and views built in, and # public/, which holds the Vite build. mkdir -p "$release" "$HOME"/data/storage/{app/public,app/private,framework/sessions,logs} go build -trimpath -o "$release/app" . cp -a public "$release/" [ ! -d bootstrap/ssr ] || cp -a --parents bootstrap/ssr "$release/" ln -s "$HOME/app.env" "$release/.env" ln -s "$HOME/data/storage" "$release/storage" cd "$release" ./app migrate --force echo "-----> Switching to $rev" host=$(sed -n 's|^APP_URL=https\{0,1\}://\([^/]*\).*|\1|p' "$HOME/app.env") code=000 if switch_to "$release"; then for _ in $(seq 20); do code=$(curl -s -o /dev/null -w '%{http_code}' -m 5 -H "Host: $host" http://127.0.0.1:8000/up || true) [ "$code" = 000 ] || break; sleep 0.5 done fi if [ "$code" != 200 ]; then echo "-----> $rev answers /up with HTTP $code. Its errors: journalctl -u app" if [ -z "$prev" ] || [ ! -d "$prev" ]; then deployed=1; echo "-----> Nothing to roll back to; $rev stays live."; exit 0 fi echo "-----> Rolling back to ${prev##*-}" switch_to "$prev" echo "-----> Migrations $rev ran, if any, stay applied." exit 1 fi deployed=1 cd "$HOME" && ls -1d releases/*/ | head -n -3 | xargs -r rm -rf # keep three echo "-----> Deployed $rev to https://$host/"