Created
March 8, 2022 22:54
-
-
Save dcragusa/c1519cef08ce7599ad81c3425d774de3 to your computer and use it in GitHub Desktop.
A script to rename the last migration in the core migrations directory, also updating the max_migration file from django-linear-migrations.
This file contains 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
import os | |
import sys | |
REPO_DIR = os.environ.get("REPO_LOCATION", None) | |
MIGRATIONS_DIR = os.path.join(REPO_DIR, 'core', 'migrations') | |
MAX_MIGRATION = os.path.join(MIGRATIONS_DIR, 'max_migration.txt') | |
def get_migration_number(migration: str) -> str: | |
"""Return the number part of a migration name.""" | |
number, _ = migration.split('_', maxsplit=1) | |
return number | |
def get_latest_migration() -> str: | |
"""Gets latest migration.""" | |
develop_migrations = sorted([ | |
f for f in os.listdir(MIGRATIONS_DIR) | |
if 'py' in f # only python files | |
and '__' not in f # exclude __init__ | |
]) | |
return develop_migrations[-1] | |
def update_max_migration(new_filename: str): | |
"""Update the max_migration file with the latest migration name.""" | |
new_name_no_ext = os.path.splitext(new_filename)[0] | |
print(f'Setting max_migration to {new_name_no_ext}') | |
with open(MAX_MIGRATION, 'w') as f: | |
f.write(new_name_no_ext + '\n') | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: | |
print('Run with the new desired migration name.') | |
last_migration_name = get_latest_migration() | |
last_migration_number = get_migration_number(last_migration_name) | |
last_migration_filename = os.path.join(MIGRATIONS_DIR, last_migration_name) | |
new_name = f'{last_migration_number}_{sys.argv[1]}.py' | |
new_filename = os.path.join(MIGRATIONS_DIR, new_name) | |
print(f'Renaming {last_migration_name} to {new_name}') | |
os.rename(last_migration_filename, new_filename) | |
update_max_migration(new_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A script intended to reduce the tedium involved when making migrations and renaming them to something useful.
Run this script after making a migration with the new desired name, e.g. rename_migration.py test. This will rename the migration and also update the max_migration file for you.