Skip to content

Instantly share code, notes, and snippets.

@FeroxTL
Last active August 6, 2017 10:42
Show Gist options
  • Save FeroxTL/03557f06adc3068241e9c69570a75797 to your computer and use it in GitHub Desktop.
Save FeroxTL/03557f06adc3068241e9c69570a75797 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import re
import sys
import subprocess
from collections import defaultdict
MIGRATION_REGEX = r'.+\/(?P<app>.+)\/migrations\/(?P<num>\d{4})_.+.py'
fn, previous_head, current_head, is_branch = sys.argv
if not is_branch == '1' or previous_head == current_head:
sys.exit(0)
revert_map, run_map = {}, {}
diff = defaultdict(list)
output = subprocess.check_output(
'git --no-pager diff --name-status %s %s ' % (
previous_head, current_head), shell=True)
for i in output.decode().split('\n'):
if not i:
continue
op, fname = i.split('\t')
diff[op].append(fname)
for path in diff.get('D', []):
match = re.match(MIGRATION_REGEX, path)
if match:
data = match.groupdict()
if data['app'] not in revert_map or int(data['num']) < int(revert_map[data['app']]):
revert_map[data['app']] = data['num']
for path in diff.get('A', []):
match = re.match(MIGRATION_REGEX, path)
if match:
data = match.groupdict()
if data['app'] not in run_map or int(data['num']) > int(run_map[data['app']]):
run_map[data['app']] = data['num']
if revert_map:
print('\nATTENTION!!!\n'
'You have deleted migrations in this branch.\n'
'You may need to return to the previous one and revert those:')
for key, value in revert_map.items():
value = int(value) - 1
if value == 0:
value = 'zero'
print('./manage.py migrate {} {:0>4}'.format(key, value))
if run_map:
print('You have new migrations in this branch:')
for key, value in run_map.items():
print('./manage.py migrate {} {}'.format(key, value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment