forked from mmmaly/chcemvediet
-
Notifications
You must be signed in to change notification settings - Fork 4
/
migrate-checkout.sh
executable file
·78 lines (70 loc) · 2.21 KB
/
migrate-checkout.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/bash -e
#
# Utility to auto-migrate with checkout. After checkout, all migrations that are not present in the
# new branch are unapplied and all migrations that were not present in the old branch are
# reapplied. So jumping between branches should keep the database structure compatible with code.
#
# WARNING: Unapplying migrations may delete data! The script is NOT to be used in production
# environment.
#
# Usage: ./checkout-and-migrate.sh <branch>
#
old_branch="$(git symbolic-ref --short HEAD)"
new_branch="$1"
# Inspect migrations in the old branch
declare -a old_migrations
app=""
while read line; do
if [[ "$line" == "[X] "* ]]; then
migration="${line#"[X] "}"
old_migrations+=("$app:$migration")
elif [[ "$line" == "[ ] "* ]]; then
true # Skip unapplied migrations
else
app="$line"
fi
done < <(env/bin/python manage.py migrate --list)
# Check out the new branch
git checkout "$new_branch"
# Inspect migrations in the new branch
declare -a new_migrations
app=""
while read line; do
if [[ "$line" == "[X] "* ]]; then
migration="${line#"[X] "}"
new_migrations+=("$app:$migration")
elif [[ "$line" == "[ ] "* ]]; then
true # Skip unapplied migrations
else
app="$line"
fi
done < <(env/bin/python manage.py migrate --list)
# Return back to the old branch
git checkout "$old_branch"
# Find last common migrations
declare -A common_migrations
declare -A last_migrations
for migration in "${old_migrations[@]}"; do
app="${migration%:*}"
name="${migration#*:}"
common_migrations["$app"]="zero"
last_migrations["$app"]="$name"
done
for migration in "${old_migrations[@]}"; do
if [[ " ${new_migrations[*]} " == *" $migration "* ]]; then
app="${migration%:*}"
name="${migration#*:}"
common_migrations["$app"]="$name"
fi
done
# Revert to last common migrations (unless the last common migration is the very last migration).
for app in "${!common_migrations[@]}"; do
name="${common_migrations[$app]}"
last="${last_migrations[$app]}"
if [[ "$name" != "$last" ]]; then
env/bin/python manage.py migrate "$app" "$name"
fi
done
# Finally, check out the new branch again and run migrations in the new branch.
git checkout "$new_branch"
env/bin/python manage.py migrate