Skip to content

Instantly share code, notes, and snippets.

@pilosus
Created May 3, 2024 15:42
Show Gist options
  • Select an option

  • Save pilosus/9d844aacde5ab715f51fcbbd425d7679 to your computer and use it in GitHub Desktop.

Select an option

Save pilosus/9d844aacde5ab715f51fcbbd425d7679 to your computer and use it in GitHub Desktop.
Python script to rename alembic migration files after `file_template` configuration option is changed from default one
"""
Copyright (c) 2024 Vitaly Samigullin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### Rename alembic migration files ###
This Python script renames Alembic migration files that followed
the default naming convention from the `alembic.ini`:
```
[alembic]
script_location = migrations
# 415d16af53f6_test_migrations.py
file_template = %%(rev)s_%%(slug)s
```
to the new file name format:
```
[alembic]
script_location = migrations
# 2024_05_02_1011-415d16af53f6_test_migrations.py
file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
```
Renaming migration files doesn't affect the migration themselves:
https://stackoverflow.com/questions/35672933/does-alembic-care-what-its-migration-files-are-called
So, it's nice to keep things tidy!
"""
import ast
import datetime
import re
import os
import unicodedata
migrations = os.path.dirname("./migrations/versions/")
def slugify(value, length=40):
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s-]', '', value).strip().lower()
result = re.sub('[-\s]+', '_', value)
if length is not None:
return result[:length]
return result
for migration in os.listdir(migrations):
old_file_path = os.path.join(migrations, migration)
if os.path.isdir(old_file_path):
continue
old_file_name_no_ext = migration.rstrip(".py")
with open(old_file_path) as f:
content = f.read()
parsed = ast.parse(content)
docstring = ast.get_docstring(parsed)
message, _, revision, revises, ts = docstring.split("\n")
message_trunc = slugify(value=message, length=40)
revision_id = re.sub('Revision ID: ', '', revision)
if migration == "{}_.py".format(revision_id):
slug = message_trunc
else:
slug = ""
dt_str = re.sub('Create Date: ', '', ts)
dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S.%f')
new_dt_str = dt.strftime("%Y_%m_%d_%H%M")
new_file_name = "{dt}-{old}{slug}.py".format(dt=new_dt_str, old=old_file_name_no_ext, slug=slug)
new_file_path = os.path.join(migrations, new_file_name)
os.rename(old_file_path, new_file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment