I have a deployment setup whereby I push a next.js repo to a git remote I have setup on a server.
I have a post-receive hook setup which will then build the app in a temp folder, before copying it to its permanent folder and starting it with PM2.
# post-receive
#!/bin/sh
# The production directory
TARGET="/var/node-apps/my-app"
# A temporary directory for deployment
TEMP="/var/node-apps/tmp/my-app"
# The Git repo
REPO="/var/git/my-app.git"
# The Git branch
BRANCH="master"
# Deploy the content to the temporary directory
echo ‘post-receive: copy to tmp’
mkdir -p $TEMP
git --work-tree=$TEMP --git-dir=$REPO checkout $BRANCH -f
echo ‘post-receive: checkout branch’
cd $TEMP
echo ‘post-receive: npm install…’
npm install \
&& echo ‘post-receive: building…’ \
&& npm run build \
&& echo ‘post-receive: → done.’
# Replace the production directory
# with the temporary directory
cd /
rm -rf $TARGET
mv $TEMP $TARGET
cd $TARGET
(pm2 delete 'my-app' || true)
pm2 start npm --name 'my-app' -- run start-production -i max
echo ‘post-receive: app started successfully with pm2.’
pm2 save
echo ‘post-receive: pm2 saved.’
This is working great, however if the build fails (for example theres a linting error), the post-receive script continues executing, and will copy the failed build to the permanent directory, and start the app with PM2 (which of course fails, as the build has failed).
If the webpack build fails, I would like the post-receive hook not to continue, and instead echo a warning.
I have tried to handle errors like so:
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
trap 'abort' 1
set -e
[rest of script here]
trap : 0
trap : 1
but this is also not working.