I'm trying to write a pre-commit hook to my Django project that checks for missing migrations. That is, it ensures all changes are reflected in a migrations file.
One way to implement this is to PASS the pre-commit hook if the makemigrations
command returns no changes.
$ ./manage.py makemigrations --dry-run
No changes detected
And to FAIL the pre-commit hook if it returns something:
$ ./manage.py makemigrations --dry-run
Migrations for 'myapp':
myapp/migrations/0003_auto_20201213_2233.py
- Alter field type on event
How can I write this pre-commit hook? Is there a better approach than using makemigrations
? This is what I have so far but it always passes (I think I need to parse the response):
repos:
- repo: local
hooks:
- id: pre-commit-django-migrations
name: Check django migrations
entry: ./manage.py makemigrations --dry-run
language: system
types: [python]
pass_filenames: false
Django keeps track of applied migrations in the Django migrations table. Django migrations consist of plain Python files containing a Migration class. Django knows which changes to perform from the operations list in the Migration classes. Django compares your models to a project state it builds from the migrations.
The goal of pre-commit hooks is to improve the quality of commits. This is achieved by making sure your commits meet some (formal) requirements, e.g: that they comply to a certain coding style (with the hook style-files ). that you commit derivatives such as README.md or .
If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook.
From Django makemigrations
documentation
--check
Makes makemigrations exit with a non-zero status when model changes without migrations are detected.
So you can use --check
instead
entry: python manage.py makemigrations --check
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With