Created
September 25, 2019 08:20
-
-
Save lgylym/226647522475ac74654a5420296d83b4 to your computer and use it in GitHub Desktop.
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
# This script is used to bulk insert ignore statements to django migration files. | |
# It can be handy after squashing migration files. | |
# Place this file at the root of the project directory when use. | |
# | |
# Example usage: | |
# python manage.py lintmigrations --exclude-apps foobar | grep ERR | python fix_ignores.py | |
import glob | |
import sys | |
NEW_IMPORT = "\n\nimport django_migration_linter as linter\n\n\n" | |
NEW_IGNORE = " operations = [\n linter.IgnoreMigration(),\n" | |
def has_import_fix(content): | |
return NEW_IMPORT in content | |
def has_ignore_fix(content): | |
return NEW_IGNORE in content | |
def get_migration_file_path(input): | |
app, file_name = input.split("...")[0].strip("()").split(",") | |
app = app.strip() | |
migration_file = file_name.strip() | |
partial_path = app + "/migrations/" + migration_file + ".py" | |
files = [f for f in glob.glob("./**/" + partial_path, recursive=True)] | |
if len(files) == 1: | |
return files[0] | |
def fix_file(file_path): | |
content = None | |
with open(file_path, "r") as f: | |
content = f.read() | |
if not has_import_fix(content): | |
content = content.replace("\n\n\n", NEW_IMPORT) | |
if not has_ignore_fix(content): | |
content = content.replace(" operations = [\n", NEW_IGNORE) | |
with open(file_path, "w") as f: | |
f.write(content) | |
for line in sys.stdin: | |
if not line: | |
continue | |
migration_file_path = get_migration_file_path(line) | |
print(f"fixing {migration_file_path}") | |
fix_file(migration_file_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment