Skip to content

Instantly share code, notes, and snippets.

@CNBorn
Last active January 4, 2017 16:25
Show Gist options
  • Save CNBorn/7c312744b34c9b6e9b853382fe93385f to your computer and use it in GitHub Desktop.
Save CNBorn/7c312744b34c9b6e9b853382fe93385f to your computer and use it in GitHub Desktop.
Bash Script that automatically fix your alembic revision conflicts
#!/bin/bash
set -e
BRANCH_NAME=$(git symbolic-ref -q --short HEAD)
MIGRATION_FILE=$(git diff --name-only $BRANCH_NAME $(git merge-base $BRANCH_NAME integration) | grep migrations)
MIGRATION_FILE_COUNT=$(echo $MIGRATION_FILE | awk '{print NF}')
if [[ $MIGRATION_FILE_COUNT -gt 1 ]]; then
printf '\033[93mcurrent branch $BRANCH_NAME has more than one migration file! exiting. \033[0m\n'
exit 1
fi
ALEMBIC_HEADS=$(alembic -c alembic.ini heads | grep \(head\))
array=(`echo $ALEMBIC_HEADS | sed -e $'s/\ (head)//g'`)
ALEMBIC_HEADS_COUNT=${#array[@]}
if [[ $ALEMBIC_HEADS_COUNT -eq 1 ]]; then
printf "\033[92mNo need to fix alembic head. Have a nice day. \033[0m\n"
exit 0
fi
if [[ $ALEMBIC_HEADS_COUNT -gt 2 ]]; then
printf "\033[31mToo many heads to deal with, wish you luck! \033[0m\n"
exit 1
fi
MIGRATION_FILE_REVISION=$(cat "$MIGRATION_FILE" | grep "revision = \'")
if [[ $MIGRATION_FILE_REVISION == *"${array[0]}"* ]]
then
MY_REVISION=$(echo ${array[0]})
LATEST_REVISION=$(echo ${array[1]})
else
MY_REVISION=$(echo ${array[1]})
LATEST_REVISION=$(echo ${array[0]})
fi
echo Changing $MY_REVISION \'s down revision to $LATEST_REVISION
# Get the Previous Revision in my Migration File
MIGRATION_FILE_DOWN_REVISION=$(cat "$MIGRATION_FILE" | grep "down_revision = \'" | sed -e $"s/down_revision\ =//g" | sed -e $"s/'//g" | xargs)
# Change the File!
# Sed command usage for Mac OS X only
sed -i "" -e "s/$MIGRATION_FILE_DOWN_REVISION/$LATEST_REVISION/g" $MIGRATION_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment