From adf61dd6697b9972abfc70c037843deca8725f62 Mon Sep 17 00:00:00 2001 From: yongming Date: Wed, 2 Oct 2019 14:12:05 +0200 Subject: [PATCH] Add command to only check migration files in a given file --- .../management/commands/lintmigrations.py | 14 ++++++++++++- django_migration_linter/migration_linter.py | 21 ++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/django_migration_linter/management/commands/lintmigrations.py b/django_migration_linter/management/commands/lintmigrations.py index 3ef7dad..1100dfb 100644 --- a/django_migration_linter/management/commands/lintmigrations.py +++ b/django_migration_linter/management/commands/lintmigrations.py @@ -25,6 +25,15 @@ class Command(BaseCommand): "the initial repo commit will be used" ), ) + parser.add_argument( + "--include-migrations-in-file", + metavar="FILE_PATH", + type=str, + nargs="?", + help=( + "if specified, only migrations inside the file " "will be considered", + ), + ) parser.add_argument( "--ignore-name-contains", type=str, @@ -122,7 +131,10 @@ class Command(BaseCommand): only_unapplied_migrations=options["unapplied_migrations"], exclude_migration_tests=options["exclude_migration_tests"], ) - linter.lint_all_migrations(git_commit_id=options["commit_id"]) + linter.lint_all_migrations( + git_commit_id=options["commit_id"], + migrations_file_path=options["include_migrations_in_file"], + ) linter.print_summary() if linter.has_errors: sys.exit(1) diff --git a/django_migration_linter/migration_linter.py b/django_migration_linter/migration_linter.py index 882e9c4..2d333ca 100644 --- a/django_migration_linter/migration_linter.py +++ b/django_migration_linter/migration_linter.py @@ -85,10 +85,12 @@ class MigrationLinter(object): def should_use_cache(self): return self.django_path and not self.no_cache - def lint_all_migrations(self, git_commit_id=None): + def lint_all_migrations(self, git_commit_id=None, migrations_file_path=None): # Collect migrations if git_commit_id: migrations = self._gather_migrations_git(git_commit_id) + elif migrations_file_path: + migrations = self._gather_migrations_from_file(migrations_file_path) else: migrations = self._gather_all_migrations() @@ -248,6 +250,23 @@ class MigrationLinter(object): raise Exception("Error while executing git diff command") return migrations + def _gather_migrations_from_file(self, migrations_file_path): + from django.db.migrations.loader import MIGRATIONS_MODULE_NAME + + migrations = [] + + with open(migrations_file_path, "r") as f: + lines = f.read() + for line in lines: + if ( + re.search(r"/{0}/.*\.py".format(MIGRATIONS_MODULE_NAME), line) + and "__init__" not in line + ): + app_label, name = split_migration_path(line) + migration = self.migration_loader.disk_migrations[app_label, name] + migrations.append(migration) + return migrations + def _gather_all_migrations(self): # Prune Django apps for (app_label, _), migration in self.migration_loader.disk_migrations.items():