Skip to content

Instantly share code, notes, and snippets.

@dabrady
Created February 21, 2020 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dabrady/4b9e57fb2529ca256dfb506dbb5103b1 to your computer and use it in GitHub Desktop.
Save dabrady/4b9e57fb2529ca256dfb506dbb5103b1 to your computer and use it in GitHub Desktop.
A post-merge Git hook for Ruby on Rails projects which installs dependencies and runs database migrations as needed
# Determine if the project dependencies have changed and install them if needed.
# (See below for an explanation of the `git` command being used here.)
NEW_GEMS=$(git diff-tree --name-only --no-commit-id --diff-filter=M ORIG_HEAD HEAD Gemfile Gemfile.lock)
[ -z "$NEW_GEMS" ] || (echo "Gemfile changed: installing updated dependences..." && bundle install)
# Get a list of new migration files that have been added since you last pulled.
#
# Check out `git help diff-tree` for full details, but the TL;DR is:
# `diff-tree`: show what is different between two project trees (as opposed to
# `diff`, which is more useful for diffing individual commits)
# `-r`: recursively search the diff tree, rather than just the top level
# `--name-only`: output only the paths of the changed files, instead of the diff
# `--no-commit-id`: prevent Git from outputting commit IDs with the filenames
# `--diff-filter=A`: only look for files that have been [A]dded
# `--relative=db/migrate`: restrict our search to the `db/migrate` folder
# `ORIG_HEAD`: a Git variable containing the previous HEAD commit; in this case,
# wherever your local repo was before you pulled from the branch
# `HEAD`: a Git variable containing the current HEAD commit; in this case,
# the HEAD of the branch you just pulled
ADDED_MIGRATION_FILES=$(git diff-tree -r --name-only --no-commit-id --diff-filter=A --relative=db/migrate ORIG_HEAD HEAD)
# If there are any new migrations, run them.
# Otherwise, exit gracefully.
[ -z "$ADDED_MIGRATION_FILES" ] && exit 0
echo "Database structure has changed: running migrations..."
bundle exec rake db:migrate \
&& echo "Database structure successfully updated." \
|| (echo "ERROR: Failed to update local database." && exit 1)
exit 0
@dabrady
Copy link
Author

dabrady commented Feb 21, 2020

The post-merge file goes in your .git/hooks directory within the repo you wish it to apply to. See https://githooks.com/ for more details.

Alternatively/additionally, you can put it in the hooks folder of your Git template directory, and it will be added automatically to the .git folder of every repo you create/clone after that point. See https://git-scm.com/docs/git-init#_template_directory for more details.

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