|
| 1 | +from django.conf import settings |
| 2 | +from django.core.files.storage import storages |
| 3 | +from django.db import migrations |
| 4 | +from urllib.parse import urlparse |
| 5 | + |
| 6 | +from extras.storage import ScriptFileSystemStorage |
| 7 | + |
| 8 | + |
| 9 | +def normalize(url): |
| 10 | + parsed_url = urlparse(url) |
| 11 | + if not parsed_url.path.endswith('/'): |
| 12 | + return url + '/' |
| 13 | + return url |
| 14 | + |
| 15 | + |
| 16 | +def fix_script_paths(apps, schema_editor): |
| 17 | + """ |
| 18 | + Fix script paths for scripts that had incorrect path from NB 4.3. |
| 19 | + """ |
| 20 | + storage = storages.create_storage(storages.backends["scripts"]) |
| 21 | + if not isinstance(storage, ScriptFileSystemStorage): |
| 22 | + return |
| 23 | + |
| 24 | + ScriptModule = apps.get_model('extras', 'ScriptModule') |
| 25 | + script_root_path = normalize(settings.SCRIPTS_ROOT) |
| 26 | + for script in ScriptModule.objects.filter(file_path__startswith=script_root_path): |
| 27 | + script.file_path = script.file_path[len(script_root_path):] |
| 28 | + script.save() |
| 29 | + |
| 30 | + |
| 31 | +class Migration(migrations.Migration): |
| 32 | + |
| 33 | + dependencies = [ |
| 34 | + ('extras', '0128_tableconfig'), |
| 35 | + ] |
| 36 | + |
| 37 | + operations = [ |
| 38 | + migrations.RunPython(code=fix_script_paths, reverse_code=migrations.RunPython.noop), |
| 39 | + ] |
| 40 | + |
| 41 | + |
| 42 | +def oc_fix_script_paths(objectchange, reverting): |
| 43 | + script_root_path = normalize(settings.SCRIPTS_ROOT) |
| 44 | + |
| 45 | + for data in (objectchange.prechange_data, objectchange.postchange_data): |
| 46 | + if data is None: |
| 47 | + continue |
| 48 | + |
| 49 | + if file_path := data.get('file_path'): |
| 50 | + if file_path.startswith(script_root_path): |
| 51 | + data['file_path'] = file_path[len(script_root_path):] |
| 52 | + |
| 53 | + |
| 54 | +objectchange_migrators = { |
| 55 | + 'extras.scriptmodule': oc_fix_script_paths, |
| 56 | +} |
0 commit comments