Skip to content

This website's pre-commit hook

Posted on:January 16, 2024

This is the pre-commit hook I use on this website. I use this hook to automate updating and building the latest Resume PDF. If you’re curious why I generate my resume, you can read about why I do this here if you’re interested. After accidentally forgetting to build the PDF a couple times, I figured there’s an easy way to ensure this happens automatically. You should never “just remember” to do things that robots can do for you.

The solution is to just use a git pre-commit hook which provides a nice interface to running some shell commands during certain lifecycle hooks.

#!/bin/bash

# This script just ensures we update our skills.mdx page anytime we make a change.
# If there's any changes, it also rebuilds the resume PDF.

# Check if we need to update the 'Last Updated' part
actually_updated_at=$(git log -1 --pretty="format:%cd" --date=format:"%B %Y" src/pages/skills.mdx)
says_updated_at=$(cat src/pages/skills.mdx | grep --color=never 'Last Updated' | sed -n 's/.*Last Updated: \([A-Za-z]*\) \([0-9]*\).*/\1 \2/p')
if [ "$actually_updated_at" != "$says_updated_at" ]; then
  echo "Updating 'Last Updated' blurb from '$says_updated_at' to '$actually_updated_at'"
  # Taken from: https://stackoverflow.com/a/22084103/6535053
  sed -i.bak "s/${says_updated_at}/${actually_updated_at}/g" src/pages/skills.mdx
  rm src/pages/skills.mdx.bak # Remove the backup file
  git add src/pages/skills.mdx
else
  echo "No updated needed for 'Last Updated' blurb. It's already set to '$actually_updated_at'"
fi

# Check if we need to rebuild the resume PDF
need_rebuild=$(git diff --name-only HEAD | grep --color=never 'src/pages/skills.mdx')
if [ -n "$need_rebuild" ]; then
  kill_astro=0
  astro_pid=$(ps aux | grep 'astro dev' | grep -v grep | awk '{print $2}')
  echo "astro_pid: $astro_pid"
  if [ ! -n "$astro_pid" ]; then
    echo "Starting Astro"
    yarn astro dev &
    astro_pid=$!
    sleep 5
    # We kill astro because we started it programmatically
    kill_astro=1
  fi

  node buildResumePdf.js

  if [ $kill_astro -eq 1 ]; then
    echo "Killing Astro"
    kill $astro_pid
  fi

  git add public/assets/adam_taylor_resume_latest.pdf
else
  echo "No need to rebuild the resume PDF. No changes to src/pages/skills.mdx."
fi

# Run prettier and add modified files to staging
# From: https://prettier.io/docs/en/precommit.html#option-5-shell-script
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0

# Prettify all selected files
echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write

# Add back the modified/prettified files to staging
echo "$FILES" | xargs git add

exit 0

I mostly write this because I’ve had to write a pre-commit file from scratch like 5 times in the past week, so I suppose it’s been top-of-mind recently.


Thanks for reading! If you enjoyed this, you may also enjoy following me on twitter!