Skip to content

Instantly share code, notes, and snippets.

@maiksprenger
Created July 15, 2014 13:12
Show Gist options
  • Save maiksprenger/05e047e0205f576da1a6 to your computer and use it in GitHub Desktop.
Save maiksprenger/05e047e0205f576da1a6 to your computer and use it in GitHub Desktop.
Converts Oscar abstract models to new syntax
from shutil import move
from tempfile import mkstemp
import os
import re
def get_model_files():
root_path = os.path.dirname(os.path.realpath(__file__))
paths = []
for path, subfolders, all_files in os.walk(root_path):
files = [path + '/' + f for f in all_files if f == 'models.py']
paths += files
return paths
def process_file(mf):
print mf
#Create temp file
fh, abs_path = mkstemp()
new_file = open(abs_path,'w')
old_file = open(mf)
indent_counter = 0
seen_oscar_import = False
for line in old_file:
if 'oscar' in line and not seen_oscar_import:
seen_oscar_import = True
new_file.write('from oscar.core.loading import model_registered\n')
match = re.search(r'\(Abstract([\w]+)\)', line)
if match:
model_name = match.group(1)
app_label = re.search(r'oscar/apps/([\w]+)/', mf).group(1)
new_file.write("if not model_registered('%s', '%s'):\n" % (app_label, model_name))
indent_counter = 2
if indent_counter:
new_file.write(' ')
indent_counter -= 1
new_file.write(line)
#close temp file
new_file.close()
os.close(fh)
old_file.close()
#Remove original file
os.remove(mf)
#Move new file
move(abs_path, mf)
model_files = get_model_files()
for mf in model_files:
process_file(mf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment