Ticket #27926: migrations_reset.py

File migrations_reset.py, 2.3 KB (added by Pascal Briet, 8 years ago)
Line 
1
2replaces_statements = {}
3
4for app in APPS:
5 app_migrations_path = os.path.join(DJANGO_PATH, app, "migrations")
6 if not os.path.exists(app_migrations_path):
7 # No migration for this app
8 continue
9
10 # Listing migration files, and removing them
11 migration_files = []
12 for f in os.listdir(app_migrations_path):
13 filepath = os.path.join(app_migrations_path, f)
14 if f.endswith('.py') and '__init__' not in f:
15 migration_files.append(f)
16 os.unlink(filepath)
17
18 if len(migration_files) == 0:
19 continue
20
21 # Generating "replaces" statement
22 replace_statement = " replaces = ["
23 for i, f in enumerate(sorted(migration_files)):
24
25 migration_name = f[:-3] # Removing .py from name
26
27 replace_statement += "('%s', '%s'), " % (app, migration_name)
28
29 replaces_statements[app] = replace_statement + "]"
30
31# Calling makemigrations
32os.chdir(DJANGO_PATH)
33call(["python", "manage.py", "makemigrations"])
34
35
36reset_migration_names = "0001_initial_reset_%s" % timezone.now().strftime("%Y%m%d%H%M%S")
37
38for app in APPS:
39 app_migrations_path = os.path.join(DJANGO_PATH, app, "migrations")
40 if not os.path.exists(app_migrations_path):
41 # No migration for this app
42 continue
43
44 # Looking for freshly generated 0001_initial.py file
45 for f in os.listdir(app_migrations_path):
46 filepath = os.path.join(app_migrations_path, f)
47 if f == "0001_initial.py":
48
49 # Reading file
50 with open(filepath) as migration_file:
51 content = migration_file.read()
52
53 # Removing file
54 os.unlink(filepath)
55
56 # Writing a new initial migrations (initial_reset)
57 content = content.split('\n')
58 new_content = []
59 for i, line in enumerate(content):
60 # Rename '0001_initial' to new migration name
61 line = line.replace("0001_initial", reset_migration_names)
62 new_content.append(line)
63 # Add 'replaces' statement
64 if line.startswith("class Migration"):
65 new_content.append(replaces_codes[app])
66
67 with open(os.path.join(app_migrations_path, reset_migration_names + ".py"), "w") as migration_file:
68 migration_file.write('\n'.join(new_content))
Back to Top