-
-
Save anapaulagomes/439a9211935046f4fe05660dced38461 to your computer and use it in GitHub Desktop.
Django - Avoid duplicate in migration names before committing changes in Git
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
Pre-commit hook for git written in Python. | |
Check if there is any migration number used more than one in each | |
migrations folder of South or Django >= 1.7. | |
You can install this pre-hook by executing the command: | |
ln -s ./git-pre-commit-hook .git/hooks/pre-commit | |
chmod +x .git/hooks/pre-commit | |
Or by calling the current script or check_migrations_files() in your | |
own file. | |
By Maxime Lorant <[email protected]> Free for any use (BSD) | |
""" | |
import subprocess | |
import sys | |
from collections import Counter, defaultdict | |
def check_migrations_files(): | |
""" Check if migrations names does not clash (e.g. two with the same number) """ | |
# Get migrations files in a list | |
migrations = subprocess.check_output("git ls-files -- $(find . -type d -iname migrations)", shell=True) | |
migrations = migrations.decode().split('\n') | |
by_folders = defaultdict(list) | |
for migration in migrations: | |
# Skip empty lines and __init__ file | |
if '/' in migration: | |
path, filename = migration.rsplit('/', 1) | |
if filename != '__init__.py': | |
# Filename format: xxxx_name_of_the_migration. We keep only `xxxx` | |
number, _ = filename.split('_', 1) | |
by_folders[path].append(number) | |
# For each folder we get the list of items | |
for key, lst in by_folders.items(): | |
duplicated = [x for x, y in Counter(lst).items() if y > 1] | |
# Check if there is any duplicate | |
if duplicated: | |
duplicated_string = ','.join(duplicated) | |
print("At least two migrations has the same number ({}) in \033[1m{}\033[0m." | |
"\nPlease fix this before committing your changes.".format(duplicated_string, key)) | |
sys.exit(-1) | |
if __name__ == "__main__": | |
check_migrations_files() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment