Skip to content

Instantly share code, notes, and snippets.

@domhnall
Last active November 30, 2022 17:02
Show Gist options
  • Save domhnall/c75069295b2d149bf1ca to your computer and use it in GitHub Desktop.
Save domhnall/c75069295b2d149bf1ca to your computer and use it in GitHub Desktop.
Git pre-commit hook for Rails to highlight route changes
#!/bin/sh
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty
if [ "$skiprouteswarning" != "true" ] && test $(git diff --name-only HEAD | grep "config/routes" | wc -l) -gt 0
then
# Cache the altered filenames
ALTERED_ROUTES_FILES=`git diff --name-only HEAD | grep "config/routes"`
# Display holding message
cat <<EOF
######### APPLICATION ROUTES HAVE BEEN ALTERED #########
________________________________________________________
Review to ensure NO UNNEEDED ROUTES have been added.
Houl yer whisht. Analysing route changes for review ...
EOF
# Build a temp working directory
NEW_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
WORKING_DIR=/tmp/routes_${NEW_UUID}
mkdir -p ${WORKING_DIR}/config/routes
# Capture the new routes config
bundle exec rake routes > ${WORKING_DIR}/new_routes.txt
bundle exec rake traceroute | sed '/Unreachable action methods/,$d' > ${WORKING_DIR}/new_traceroute.txt
# Capture the old routes config
for file in $ALTERED_ROUTES_FILES
do
cp ${file} ${WORKING_DIR}/${file}
git checkout $against -- ${file}
done
bundle exec rake routes > ${WORKING_DIR}/old_routes.txt
bundle exec rake traceroute | sed '/Unreachable action methods/,$d' > ${WORKING_DIR}/old_traceroute.txt
# Calculate the diff
ROUTES=`diff ${WORKING_DIR}/new_routes.txt ${WORKING_DIR}/old_routes.txt`
TRACEROUTE=`diff ${WORKING_DIR}/new_traceroute.txt ${WORKING_DIR}/old_traceroute.txt`
# Reset files as nature intended
for file in $ALTERED_ROUTES_FILES
do
cp ${WORKING_DIR}/${file} ${file}
git add ${file}
done
# Delete working directory
rm -rf ${WORKING_DIR}
# Output findings
cat <<EOF
### ROUTE CHANGES ###
_____________________
${ROUTES}
_____________________
### NEW UNUSED ROUTES ###
_________________________
${TRACEROUTE}
_________________________
Know what you are doing? Disable check using:
> git config hooks.skiprouteswarning true
EOF
# Check if user wants to proceed
echo -n "Proceed with commit (Y) or cancel?\n"
read YN
case $YN in
Y | y | Yes | YES | yes ) echo "OK, you are happy. Let's commit"; exit 0;;
* ) echo "I'll take that as a no. Abandoning commit!"; exit 1;;
esac
fi
![Analytics](https://ga-beacon.appspot.com/UA-58463126-2/gist/domhnall/c75069295b2d149bf1ca?pixel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment