185 lines
9.0 KiB
Python
185 lines
9.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Export one deleted spawn from OctoEditorUndo SavedVariables. Never runs Lua or SQL."""
|
|
import argparse
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
import spawn_export
|
|
|
|
# WoW's serializer emits these data-only forms. The numeric row payload is always
|
|
# quoted text so float rounding in Lua/Python cannot change database precision.
|
|
TOKEN = re.compile(r'\s+|--[^\n]*|"[^"\\\r\n]*"|[A-Za-z_][A-Za-z_0-9]*|[0-9]+|[{}\[\]=,;]')
|
|
|
|
|
|
def read_saved_variables(text):
|
|
if len(text) > 1024 * 1024:
|
|
raise ValueError('SavedVariables export exceeds 1 MiB')
|
|
tokens = []
|
|
pos = 0
|
|
while pos < len(text):
|
|
m = TOKEN.match(text, pos)
|
|
if not m:
|
|
raise ValueError('Unsupported SavedVariables syntax (data only)')
|
|
word = m.group(); pos = m.end()
|
|
if not word.isspace() and not word.startswith('--'):
|
|
tokens.append(word)
|
|
i = 0
|
|
|
|
def take(expected=None):
|
|
nonlocal i
|
|
if i == len(tokens) or (expected is not None and tokens[i] != expected):
|
|
raise ValueError('Incomplete or invalid SavedVariables')
|
|
word = tokens[i]; i += 1
|
|
return word
|
|
|
|
def value(depth=0):
|
|
if depth > 8:
|
|
raise ValueError('SavedVariables nesting too deep')
|
|
word = take()
|
|
if word.startswith('"'):
|
|
return word[1:-1]
|
|
if word.isdigit():
|
|
return int(word)
|
|
if word != '{':
|
|
raise ValueError('Only tables, strings and integer indices are accepted')
|
|
result = {}; implicit = 1
|
|
while i < len(tokens) and tokens[i] != '}':
|
|
if tokens[i] == '[':
|
|
take('['); key = value(depth + 1); take(']'); take('=')
|
|
if not isinstance(key, (str, int)):
|
|
raise ValueError('Invalid table key')
|
|
item = value(depth + 1)
|
|
elif i + 1 < len(tokens) and tokens[i + 1] == '=':
|
|
key = take(); take('='); item = value(depth + 1)
|
|
else:
|
|
key = implicit; implicit += 1; item = value(depth + 1)
|
|
if key in result:
|
|
raise ValueError('Duplicate table key')
|
|
result[key] = item
|
|
if i < len(tokens) and tokens[i] in (',', ';'):
|
|
take()
|
|
elif i == len(tokens) or tokens[i] != '}':
|
|
raise ValueError('Missing table separator')
|
|
take('}')
|
|
return result
|
|
|
|
take('OctoEditorUndo'); take('='); result = value()
|
|
if i < len(tokens) and tokens[i] == ';': take(';')
|
|
if i != len(tokens):
|
|
raise ValueError('Trailing Lua statements are not accepted')
|
|
return result
|
|
|
|
|
|
def array(data):
|
|
if not isinstance(data, dict) or set(data) != set(range(1, len(data) + 1)):
|
|
raise ValueError('Expected a dense SavedVariables array')
|
|
return [data[i] for i in range(1, len(data) + 1)]
|
|
|
|
|
|
def restore(saved, current, entry, new_guid=None):
|
|
spawn_export.validate(current)
|
|
if not isinstance(saved, dict) or set(saved) != {'format', 'rows'} or saved['format'] != 1:
|
|
raise ValueError('Unsupported undo format')
|
|
rows = array(saved['rows'])
|
|
if not 1 <= len(rows) <= 20 or not 1 <= entry <= len(rows):
|
|
raise ValueError('Select an entry in the 1..20 row undo export')
|
|
record = rows[entry - 1]
|
|
if not isinstance(record, dict) or set(record) != {'table', 'columns', 'values'} or record['table'] not in spawn_export.TABLES:
|
|
raise ValueError('Invalid deleted-row record')
|
|
table = record['table']; columns = array(record['columns']); values = array(record['values'])
|
|
if columns != current['tables'][table]['columns'] or len(values) != len(columns):
|
|
raise ValueError('Complete row and exact current column order required')
|
|
values = [None if v == 'NULL' else v for v in values]
|
|
for v in values: spawn_export.literal(v)
|
|
index = columns.index('guid'); old_guid = values[index]
|
|
def guid(v):
|
|
if not isinstance(v, str) or not re.fullmatch(r'[1-9][0-9]*', v) or not 1 <= int(v) <= 0xffffffff:
|
|
raise ValueError('GUID must be a positive uint32 decimal string')
|
|
return v
|
|
guid(old_guid)
|
|
target = guid(new_guid) if new_guid is not None else old_guid
|
|
existing = current['tables'][table]['rows']
|
|
if old_guid in existing or target in existing:
|
|
raise ValueError('Original or requested GUID is occupied; no restore exported')
|
|
values[index] = target
|
|
return ('-- LOCAL deleted spawn restore; review and apply manually. No SQL executed.\n'
|
|
'-- Apply with editors stopped; ordinary INSERT refuses a concurrent GUID collision.\n'
|
|
'-- Database restore only: restart LOCAL mangosd before inspection to reload its spawn cache.\n'
|
|
'-- No transaction guarantee for MyISAM. Verify one affected row.\n'
|
|
'USE `tw_world`;\nINSERT INTO `%s` (%s) VALUES (%s);\n' %
|
|
(table, ','.join('`%s`' % c for c in columns), ','.join(map(spawn_export.literal, values))))
|
|
|
|
|
|
|
|
def undo_operation(saved, current, entry, snapshots):
|
|
import copy
|
|
import session_capture
|
|
spawn_export.validate(current)
|
|
if saved.get('format') != 2 or not isinstance(saved.get('session'), str):
|
|
raise ValueError('Unsupported editor session export')
|
|
meta=json.loads((Path(snapshots).parent/'session.json').read_text())
|
|
if saved['session'] != meta['session']:
|
|
raise ValueError('Snapshot session differs from addon export')
|
|
operations=array(saved.get('operations', {}))
|
|
if not 1 <= entry <= len(operations) <= 200:
|
|
raise ValueError('Select an operation in the 1..200 session undo list')
|
|
op=operations[entry-1]
|
|
if not isinstance(op,dict) or op.get('kind') not in ('add','move','delete') or op.get('table') not in spawn_export.TABLES:
|
|
raise ValueError('Invalid editor operation')
|
|
table=op['table'];guid=op.get('guid');ident=op.get('entry');at=op.get('at')
|
|
if not isinstance(guid,str) or not guid.isdigit() or not 0<int(guid)<=0xffffffff or not isinstance(ident,str) or not ident.isdigit() or not isinstance(at,int):
|
|
raise ValueError('Invalid editor operation identity')
|
|
import gzip
|
|
import datetime
|
|
capture_id=op.get('capture_id')
|
|
if not isinstance(capture_id,str) or not re.fullmatch(r'capture-[0-9]{20}\.json\.gz',capture_id):
|
|
raise ValueError('Missing exact pre-operation capture identity')
|
|
before=json.loads(gzip.decompress((Path(snapshots)/capture_id).read_bytes()))
|
|
spawn_export.validate(before)
|
|
captured=datetime.datetime.fromisoformat(before['captured_utc']).timestamp()
|
|
if captured>=at+1:raise ValueError('Capture is later than the operation')
|
|
if op['kind']=='delete':
|
|
before=session_capture.newest(snapshots,table,guid,max(at,captured))
|
|
cols=current['tables'][table]['columns']
|
|
if cols!=before['tables'][table]['columns']:raise ValueError('Spawn schema changed')
|
|
old=before['tables'][table]['rows'].get(guid);now=current['tables'][table]['rows'].get(guid)
|
|
id_index=cols.index('id')
|
|
if op['kind']=='delete':
|
|
if old is None or old[id_index]!=ident:raise ValueError('Deleted row identity mismatch')
|
|
record={'table':table,'columns':dict(enumerate(cols,1)),'values':dict(enumerate([v if v is not None else 'NULL' for v in old],1))}
|
|
return restore({'format':1,'rows':{1:record}},current,1)
|
|
if now is None or now[id_index]!=ident:raise ValueError('Current GUID missing or belongs to another entry')
|
|
desired=copy.deepcopy(current)
|
|
if op['kind']=='add':
|
|
if old is not None:raise ValueError('Added GUID already existed in its pre-operation capture')
|
|
del desired['tables'][table]['rows'][guid]
|
|
else:
|
|
if old is None or old[id_index]!=ident:raise ValueError('Pre-move row identity mismatch')
|
|
if old==now:raise ValueError('Move is unchanged or already undone')
|
|
desired['tables'][table]['rows'][guid]=old
|
|
return spawn_export.diff(current,desired)[0]
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('saved_variables', type=Path)
|
|
parser.add_argument('output', type=Path)
|
|
parser.add_argument('--entry', type=int, required=True, help='1-based exported deleted-row index')
|
|
parser.add_argument('--snapshots', type=Path, help='Rolling snapshot directory for format-2 session operations')
|
|
parser.add_argument('--new-guid', help='Optional unused uint32 GUID; defaults to original GUID')
|
|
parser.add_argument('--current', type=Path, help='Offline current snapshot; otherwise read LOCAL')
|
|
args = parser.parse_args()
|
|
saved = read_saved_variables(args.saved_variables.read_text())
|
|
current = json.loads(args.current.read_text()) if args.current else spawn_export.snapshot()
|
|
if saved.get('format') == 2:
|
|
if not args.snapshots or args.new_guid:raise ValueError('Session undo requires --snapshots and keeps the captured GUID')
|
|
sql = undo_operation(saved,current,args.entry,args.snapshots)
|
|
else:
|
|
sql = restore(saved, current, args.entry, args.new_guid)
|
|
with args.output.open('x') as f: f.write(sql)
|
|
print('Restore SQL exported (not applied):', args.output)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|