forked from NMSCD/NMS-Save-Decoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.py
More file actions
39 lines (37 loc) · 1.97 KB
/
encode.py
File metadata and controls
39 lines (37 loc) · 1.97 KB
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
from nmssavetool import writeFile, compress
import json #standard, no package required
import sys #only if we pass command line arguments
from urllib.request import urlopen # only in case we want to fetch the mapping from github
def reverse_mapping(fl, mapdata):
#creates a data structure for compressing a hg file, reversing the mapping of a json file
mapping = dict()
for i in mapdata.get("Mapping"):
mapping[i.get("Value")]=i.get("Key")
#wrap the mapping in a hook for custom parsing
def hookwithmapping(obj):
mappedobj = dict()
try:
for i in obj:
mappedobj[mapping[i]] = obj[i]
return mappedobj
except:
return obj
#then extract the data structure using our custom hook to apply the name mapping:
return json.load(fl, object_hook=hookwithmapping)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: python encode.py <the json file to encode>")
else:
fn = sys.argv[1]
if fn[-5:] != '.json':
print("usage: python encode.py <the json file to encode> - argument must end with .json!")
else:
print("attempt to encode file:", fn)
#mapdata = json.load(open("sample/mapping.json")) # load the name mapping from a local copy or from github
mapdata = json.load(urlopen("https://github.com/monkeyman192/MBINCompiler/releases/latest/download/mapping.json"))
#apply the reverse mapping while loading the json save data, and encode the result as a json ansi bytearray
savedata = reverse_mapping(open(fn, "r", encoding="ansi"), mapdata)
savebytes = json.dumps(savedata, separators=(',', ':')).encode("ansi")
#compress the result to a hg file using nmssavetool.py by Robert Maupin:
writeFile(fn.replace("json", "hg"), compress(savebytes))
print("Done. A hg file of the same name was (over)written.")