Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Caffe1neAdd1ct/a76a10b1dc414f544254292d78078c59 to your computer and use it in GitHub Desktop.
Save Caffe1neAdd1ct/a76a10b1dc414f544254292d78078c59 to your computer and use it in GitHub Desktop.
pre-push-nextjs
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Worktree exists
worktree_created=0
# Check if worktree exists; if not, create it
if [ ! -d "/tmp/hook-build" ]; then
git worktree add /tmp/hook-build HEAD
worktree_created=1
fi
echo "Worktree created: ${worktree_created}"
# Obtain the current branch head
branch="$(git symbolic-ref --short HEAD)"
build_branch="build/${branch}"
echo "Current branch: ${branch}"
echo "Build branch: ${build_branch}"
cd /tmp/hook-build || exit 1
# Switch to the correct commit
git fetch origin
git checkout -B "$build_branch" "$branch" >/dev/null 2>&1 || true
echo "Checked out branch: $(git symbolic-ref --short HEAD)"
if [ $worktree_created -eq 1 ]; then
npm i --silent
fi
changed_files=$(git diff --name-only origin/$branch $build_branch || true)
echo "Changed files: ${changed_files}"
if echo "$changed_files" | grep -q "package.json\|package-lock.json"; then
npm i --silent
fi
npm run build
build_status=$?
echo "Build status: ${build_status}"
git checkout -B "build/main" "$branch" >/dev/null 2>&1 || true
git branch -D "$build_branch" >/dev/null 2>&1 || true
exit $build_status
@Caffe1neAdd1ct
Copy link
Author

Pre push build for nextjs which utilises git worktree to avoid replacing the .next folder with a production build, then requiring a restart of npm run dev.

Improvements could be build/main default branch needed - could use an env but this is to avoid switching back to a branch in-use by the parent worktree repository

The /tmp/ directory should most likely have an environment variable, or use ../SAME_FOLDER_NAME__TMP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment