Skip to content

Commit ac1cbc7

Browse files
Fix migration path. (#128)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 8b0c252 commit ac1cbc7

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

migration_fixer/management/commands/makemigrations.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
"""
44

55
import os
6-
import pathlib
76
from functools import partial
87

98
from django.apps import apps
@@ -17,6 +16,7 @@
1716
from migration_fixer.utils import (
1817
fix_numbered_migration,
1918
get_filename,
19+
get_migration_module_path,
2020
migration_sorter,
2121
no_translations,
2222
sibling_nodes,
@@ -178,12 +178,7 @@ def handle(self, *app_labels, **options):
178178
for app_label in conflicts:
179179
conflict = conflicts[app_label]
180180
migration_module, _ = loader.migrations_module(app_label)
181-
migration_absolute_path = os.path.join(
182-
*migration_module.split(".")
183-
)
184-
migration_path = pathlib.Path(
185-
os.path.join(settings.BASE_DIR, migration_absolute_path)
186-
)
181+
migration_path = get_migration_module_path(migration_module)
187182

188183
with migration_path:
189184
if self.verbosity >= 2:
@@ -200,9 +195,9 @@ def handle(self, *app_labels, **options):
200195
diff.b_path
201196
for diff in diff_index
202197
if (
203-
migration_absolute_path
198+
str(migration_path)
204199
in getattr(diff.a_blob, "abspath", "")
205-
or migration_absolute_path
200+
or str(migration_path)
206201
in getattr(diff.b_blob, "abspath", "")
207202
)
208203
]

migration_fixer/utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import re
3+
from importlib import import_module
34
from itertools import count
45
from pathlib import Path
56
from typing import Callable, List, Optional
@@ -127,6 +128,20 @@ def get_filename(path: str) -> str:
127128
return os.path.splitext(os.path.basename(path))[0]
128129

129130

131+
def get_migration_module_path(migration_module_path: str) -> Path:
132+
try:
133+
migration_module = import_module(migration_module_path)
134+
except ImportError as e:
135+
if "bad magic number" in str(e):
136+
raise ImportError(
137+
f"Couldn't import {migration_module_path} as it appears to be a stale .pyc file."
138+
) from e
139+
else:
140+
raise
141+
142+
return Path(os.path.dirname(os.path.abspath(migration_module.__file__)))
143+
144+
130145
def sibling_nodes(graph: MigrationGraph, app_name: Optional[str] = None) -> List[str]:
131146
"""
132147
Return all sibling nodes that have the same parent

0 commit comments

Comments
 (0)