Skip to content

Instantly share code, notes, and snippets.

@amcaplan
Last active March 12, 2018 16:03
Show Gist options
  • Save amcaplan/df0c6f69b271435a119f8b045bd33cc0 to your computer and use it in GitHub Desktop.
Save amcaplan/df0c6f69b271435a119f8b045bd33cc0 to your computer and use it in GitHub Desktop.
Fill in ActiveRecord Migration Rails Versions by shell script (tested on Mac OS X)
# Instructions
#
# 1. Backup your repo somewhere!
# 2. Make sure `git stash list` is empty - that'll help debugging in case things go wrong.
# 3. Make sure `git status` shows that you've made no changes; that'll break things right away.
# 4. Copy and paste the code below.
# 5. Run the `update_timestamps` function and LET IT FINISH!
# 6. Check the results, make sure they look reasonable, and commit!
#
# P.S. I take no responsibility for your use of the script; I recommend understanding what it does before running it.
function versionize() {
local FILE=$1
local COMMIT=$(git log -n 1 --pretty=format:%H -- $FILE)
# Find the correct version of Rails for that migration
git checkout --quiet $COMMIT
local RAILS_VERSION=$(grep "^ rails " Gemfile.lock | egrep -o "[0-9].[0-9]+")
# Substitute if necessary and create a stash if a substitution happens
sed -i '' "s|.*Migration$|&[$RAILS_VERSION]|" $FILE
git diff --quiet && return 1
git stash --quiet && return 0
}
function update_timestamps() {
local COUNTER=0
local ORIG_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Creating stashes for up to $(ls -d -1 db/migrate/* | wc -l | egrep -o "[0-9]+") migrations..."
for filename in $(ls -d -1 db/migrate/*); do
versionize $filename && ((COUNTER++))
# Go back to the tip to find the appropriate commit for the migration file
git checkout --quiet $ORIG_BRANCH
done
echo "${COUNTER} stashes created. Applying stashes..."
until [ $COUNTER -lt 1 ]; do
((COUNTER--))
git stash pop --quiet
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment