-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathconversionscript.py
executable file
·184 lines (174 loc) · 8.03 KB
/
conversionscript.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from OMPython import OMCSessionZMQ, pyparsing
import argparse
import glob
import json
import os
import psutil
import shutil
import subprocess
from multiprocessing import Pool
import time
parser = argparse.ArgumentParser(description='OpenModelica library testing tool')
parser.add_argument('libdir', nargs=1)
parser.add_argument('--diff', action="store_true")
parser.add_argument('--allowErrorsInDiff', action="store_true")
parser.add_argument('-n', type=int, default=psutil.cpu_count(logical=False))
args = parser.parse_args()
libdir = args.libdir[0]
numThreads = args.n
createDiff = args.diff
allowErrorsInDiff = args.allowErrorsInDiff
try:
shutil.rmtree("converted-libraries")
except:
pass
os.mkdir("converted-libraries")
os.mkdir("converted-libraries/.openmodelica")
os.mkdir("converted-libraries/.openmodelica/libraries")
def omcAssert(omc, cmd, extra=""):
res = omc.sendExpression(cmd)
if not res:
raise Exception(cmd + "\n" + extra + "\n" + (omc.sendExpression("getErrorString()") or ""))
def omcSendExpression(omc, cmd, extra=""):
try:
return omc.sendExpression(cmd)
except pyparsing.ParseException as e:
raise Exception(str(e) + "\n" + cmd + "\n" + extra + "\n" + (omc.sendExpression("getErrorString()") or ""))
mslPath = "%s/Modelica 4.0.0+maint.om/" % libdir
with open("%s/openmodelica.metadata.json" % mslPath) as f:
mslData = json.load(f)
convertFromVersion = mslData['convertFromVersion']
conversionScript = "%s/Resources/Scripts/Conversion/ConvertModelica_from_3.2.3_to_4.0.0.mos" % mslPath
def convertPackage(p):
errorsInDiff = []
with open(p) as f:
data = json.load(f)
uses=data.get('uses',{})
libnameOnFile = os.path.basename(os.path.dirname(p))
libname = libnameOnFile.split(" ")[0]
shutil.copytree(os.path.dirname(p), "converted-libraries/.openmodelica/libraries/%s" % libnameOnFile)
for root, dir, files in os.walk("converted-libraries/.openmodelica/libraries/%s" % libnameOnFile):
for file in files:
if file.endswith(".mo"):
try:
with open(os.path.join(root, file)) as fin:
fin.read()
except UnicodeDecodeError:
with open(os.path.join(root, file), encoding="ISO-8859-1") as fin:
latin1Data = fin.read()
with open(os.path.join(root, file), "w", encoding="UTF-8") as fout:
fout.write(latin1Data)
if libname in ["Modelica", "ModelicaServices", "Complex", "ModelicaTest", "ModelicaTestOverdetermined"]:
ver = libnameOnFile.split(" ")[1]
if ver.startswith("1.") or ver.startswith("3."):
return None
if libname in ["TAeZoSysPro_testsuite"] and "Modelica" not in uses:
uses['Modelica'] = '3.2.3'
data['uses'] = uses
if not uses.get('Modelica','0.0.0') in convertFromVersion:
return None
if libname in ["Modelica", "ModelicaServices", "Complex", "ModelicaTest", "ModelicaTestOverdetermined"]:
return None
print("Start working on %s" % libnameOnFile)
omc = OMCSessionZMQ()
libnameOnFileFullPath = "converted-libraries/.openmodelica/libraries/%s/package.mo" % libnameOnFile
omcAssert(omc, 'loadFile("%s", uses=false)' % libnameOnFileFullPath)
errString = omc.sendExpression("getErrorString()")
if errString:
print(errString)
loadedFilePath = omc.sendExpression("getSourceFile(%s)" % libname)
if libnameOnFileFullPath not in loadedFilePath:
raise Exception("Expected to have loaded %s but got %s" % (libnameOnFileFullPath, loadedFilePath))
gcProfStatsBeforeConversion = omc.sendExpression("GC_get_prof_stats()")
timeBeforeConvert = time.time()
omcAssert(omc, 'runConversionScript(%s, "%s")' % (libname, conversionScript))
print("runConversionScript(%s, %s) OK" % (libnameOnFile, conversionScript))
uses = data["uses"]
for (n,v) in data["uses"].items():
if n in ["Modelica", "ModelicaServices", "Complex"]:
omcAssert(omc, 'addClassAnnotation(%s, annotate=$annotation(uses(%s(version="4.0.0"))))' % (libname, n))
data["uses"][n] = "4.0.0"
names = omc.sendExpression('getClassNames(%s, sort=true, recursive=true)' % libname)
names = list(names)
names.reverse()
fileMapping = {}
for n in names:
f = omc.sendExpression('getSourceFile(%s)' % n)
fileMapping[f] = n
statsByFile = []
nFail = 0
nDiff = 0
gcProfStatsBefore = omc.sendExpression("GC_get_prof_stats()")
timeAfterConvert = time.time()
timeForConversion = timeAfterConvert - timeBeforeConvert
for (newFile, newClass) in fileMapping.items():
oldFile = os.path.join(libdir, newFile.split("converted-libraries/.openmodelica/libraries/")[1])
assert(newFile != oldFile)
before = omc.sendExpression('before := readFile("%s")' % newFile)
after = omc.sendExpression('after := listFile(%s)' % newClass)
if (not before) or (not after):
raise Exception("%s %s (%s). %s. before: %s after: %s" % (oldFile, newFile, newClass, omc.sendExpression('getErrorString()'), str(type(before)), str(type(after))))
omc.sendExpression("getErrorString()")
start = time.time()
if libname in []: # If we have libraries where the diff algorithm fails in the future
res = omc.sendExpression('res := after') # Skip the diff
else:
try:
res = omc.sendExpression('res := diffModelicaFileListings(before, after, OpenModelica.Scripting.DiffFormat.plain, failOnSemanticsChange=true)')
except pyparsing.ParseException as e:
errStr = omc.sendExpression('diffModelicaFileListings(before, after, OpenModelica.Scripting.DiffFormat.plain, failOnSemanticsChange=true)', parsed=False)
if errStr.strip():
print(errStr)
res = None
omc.sendExpression(omc, 'res := ""')
end = time.time()
isFail = False
if not res:
omc.sendExpression('writeFile("%s", after)' % newFile)
if allowErrorsInDiff:
errorsInDiff += [newFile]
omc.sendExpression('writeFile("%s.before",before)' % newFile)
omc.sendExpression('writeFile("%s.after",after)' % newFile)
res = after
nFail += 1
isFail = True
else:
errStr = omc.sendExpression("getErrorString()")
if errStr:
print(errStr)
raise Exception('--allowErrorsInDiff is not active:\necho(false);before:=readFile("%s");\nafter:=readFile("%s");echo(true);\ndiffModelicaFileListings(before, after, OpenModelica.Scripting.DiffFormat.plain, failOnSemanticsChange=true);\ngetErrorString();' % (oldFile, newFile))
else:
omcAssert(omc, 'writeFile("%s", res)' % (newFile))
isDiff = before != res
if before != res:
nDiff += 1
statsByFile +=[{"time": end-start, "size": len(before), "isDiff": isDiff, "fail": isFail}]
path = "converted-libraries/.openmodelica/libraries/%s/openmodelica.metadata.json" % libnameOnFile
with open(path, "w") as f:
gcProfStats = omc.sendExpression("GC_get_prof_stats()")
data["uses"] = dict(uses)
data["extraInfo"] = "Conversion script %s was applied" % conversionScript
json.dump(data, f)
if createDiff:
diffOutputFile = "converted-libraries/.openmodelica/libraries/%s.diff" % libnameOnFile
print("Creating %s" % diffOutputFile)
with open(diffOutputFile, "wb") as diffOut:
diffOutput = subprocess.call(["diff", "-ur", "--exclude", "openmodelica.metadata.json", os.path.dirname(p), "converted-libraries/.openmodelica/libraries/%s" % libnameOnFile], stdout=diffOut)
del omc
return {"errorsInDiff": errorsInDiff, "path": path, "timeForConversion": timeForConversion, "statsByFile": statsByFile, "gcProfStatsBeforeConversion": gcProfStatsBeforeConversion, "gcProfStatsBefore": gcProfStatsBefore, "gcProfStats": gcProfStats}
pat = "%s/*/openmodelica.metadata.json" % libdir
if numThreads==1:
res = [convertPackage(p) for p in sorted(glob.glob(pat))]
else:
with Pool(processes=numThreads) as pool:
res = pool.map(convertPackage, sorted(glob.glob(pat)))
for r in res:
if r is None:
continue
for f in r["errorsInDiff"]:
print("Ignored failed perform diff on %s" % f)
shutil.copyfile("%s/index.json" % libdir, "converted-libraries/.openmodelica/libraries/index.json")
with open("result.json", "w") as fout:
json.dump([r for r in res if r], fout)