Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre-commit hook to check django migrations

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
like image 421
Johnny Metz Avatar asked Dec 14 '20 06:12

Johnny Metz


People also ask

How does Django keep track of migrations?

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.

Why use pre-commit hook?

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 .

How do I manually run a pre-commit hook?

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.


1 Answers

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
like image 116
iklinac Avatar answered Sep 26 '22 02:09

iklinac