Files
WoW-Hybrid-gateway/ops/item_tooltip_dependencies.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

91 lines
7.5 KiB
Python

"""Stage source set dependency data; install only a new owned removable addon."""
from pathlib import Path
import argparse,hashlib,json,re,subprocess
from item_package_preflight import read_compatibility_package
from item_sparse_compat import ROOT
def stage(package_path,source_sets,output):
output=Path(output).resolve()
if not output.is_relative_to(ROOT/'runtime')or output.exists():raise ValueError('Fresh owned dependency stage required')
package,pin=read_compatibility_package(package_path);sets={};items={};set_spells={};item_spells={};excluded=[];non_roster=[]
from item_set_compat import source_set
source_raw=Path(source_sets).read_bytes();source=json.loads(source_raw)
if not isinstance(source,list)or not 1<=len(source)<=4096:raise ValueError('Bounded explicit source set roster required')
for row in source:
try:
parent,bonuses=source_set(row);ident=parent['ID'];members=[i for i in parent['ItemID']if i]
if ident in sets:raise ValueError('Duplicate source set identity')
if len(members)!=len(set(members)):raise ValueError('Duplicate source set member')
if members:sets[ident]=members;set_spells[ident]=[spell for _,spell,_ in bonuses]
except ValueError as error:excluded.append(dict(set_id=row.get('id'),reason=str(error)))
for row in package['rows']:
if row['table_name']!='ItemSparse'or row.get('record_status','valid')!='valid':continue
ident=row['record']['ItemSet']
if ident not in sets or not re.fullmatch('[0-9a-f]{64}',row.get('source_record_sha256','')):continue
if row['id']not in sets[ident]:non_roster.append(row['id']) # Alternate source items can share a set without replacing its canonical roster.
items[row['id']]=ident
if not items or not sets:raise ValueError('Source set dependency data required')
from turtle_data import inventory_item_snapshot
from item_batch_stage import source_hash
source_items={r['identity'][1]:r['raw_fields']for r in inventory_item_snapshot(ROOT/'runtime/all-item-templates-20261017')['records']}
for row in package['rows']:
if row['table_name']!='ItemSparse'or row.get('record_status','valid')!='valid':continue
p=source_items.get(row['id'])
if p is None or row.get('source_record_sha256')!=source_hash(p):continue
roots=sorted({p['spellid_'+str(i)]for i in range(1,6)}-{0})
if roots:item_spells[row['id']]=roots
code='GWItemDependencyData = { version = 1, itemSets = {\n'+''.join('[%d]=%d,\n'%(i,s)for i,s in sorted(items.items()))+'}, sets = {\n'+''.join('[%d]={%s},\n'%(i,','.join(map(str,m)))for i,m in sorted(sets.items()))+'}, setSpells = {\n'+''.join('[%d]={%s},\n'%(i,','.join(map(str,m)))for i,m in sorted(set_spells.items()))+'}, itemSpells = {\n'+''.join('[%d]={%s},\n'%(i,','.join(map(str,m)))for i,m in sorted(item_spells.items()))+'} }\n'
files={p.name:p.read_bytes()for p in(ROOT/'client_addons/WoWHybridItemDependencies').iterdir()if p.is_file()};files['ItemDependencyData.lua']=code.encode()
if set(files)!={'WoWHybridItemDependencies.toc','ItemDependencies.lua','ItemDependencyData.lua'}:raise ValueError('Reviewed dependency addon files required')
for name,raw in files.items():
if name.endswith('.lua'):subprocess.run(['luac','-p','-'],input=raw,check=True,capture_output=True)
output.mkdir();manifest=dict(kind='source-item-set-tooltip-dependency-stage',schema_version=1,package_sha256=pin,source_sets_sha256=hashlib.sha256(source_raw).hexdigest(),sets=len(sets),items=len(items),spell_dependency_items=len(item_spells),set_bonus_spell_references=sum(map(len,set_spells.values())),excluded_sets=excluded,non_roster_linked_items=non_roster,files={n:hashlib.sha256(v).hexdigest()for n,v in files.items()},installed=False,engine_verified=False)
for name,raw in files.items():(output/name).write_bytes(raw)
(output/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n');return manifest
def install(stage_path,journal,previous=None):
from octo_icon_assets import private_icon_client
stage=Path(stage_path).resolve();journal=Path(journal).resolve()
if not stage.is_relative_to(ROOT/'runtime')or not journal.is_relative_to(ROOT/'runtime')or journal.exists():raise ValueError('Owned stage/new journal required')
client,identity=private_icon_client();manifest=json.loads((stage/'manifest.json').read_text())
if manifest.get('kind')!='source-item-set-tooltip-dependency-stage':raise ValueError('Reviewed source dependency stage required')
expected={'WoWHybridItemDependencies.toc','ItemDependencies.lua','ItemDependencyData.lua'}
if set(manifest['files'])!=expected:raise ValueError('Reviewed addon file identities required')
target=client/'Interface/AddOns/WoWHybridItemDependencies'
if any(p.is_symlink()for p in(target,target.parent,target.parent.parent,target.parent.parent.parent)):raise ValueError('Linked dependency addon target preserved')
backup=None
if target.exists():
if previous is None:raise ValueError('Existing addon preserved; explicit owned update required')
previous=Path(previous).resolve()
if not previous.is_relative_to(ROOT/'runtime'):raise ValueError('Owned previous addon journal required')
old=json.loads(previous.read_text())
actual={p.name:hashlib.sha256(p.read_bytes()).hexdigest()for p in target.iterdir()if p.is_file()and not p.is_symlink()}
if old.get('kind')!=manifest['kind']or old.get('target')!=str(target)or actual!=old.get('files')or len(list(target.iterdir()))!=len(actual):raise ValueError('Changed addon preserved')
backup=ROOT/'recovery'/('item-dependencies-'+stage.name)
elif previous is not None:raise ValueError('Previous addon installation missing')
files={}
for name,pin in manifest['files'].items():
source=stage/name
if source.is_symlink():raise ValueError('Linked dependency source rejected')
raw=source.read_bytes()
if hashlib.sha256(raw).hexdigest()!=pin:raise ValueError('Staged dependency bytes differ')
if name.endswith('.lua'):subprocess.run(['luac','-p','-'],input=raw,check=True,capture_output=True)
files[name]=raw
if backup is not None:
import shutil
backup.mkdir();shutil.copytree(target,backup/'previous-addon');shutil.copy2(previous,backup/'previous-install.json')
report=dict(manifest,previous_backup=None if backup is None else str(backup.relative_to(ROOT)),stage=str(stage),target=str(target),client_identity=identity,status='PREPARED',rollback='Close owned client, verify files against this journal, then move only this addon into recovery.')
journal.write_text(json.dumps(report,indent=2)+'\n');target.mkdir(exist_ok=backup is not None)
for name in('ItemDependencyData.lua','ItemDependencies.lua','WoWHybridItemDependencies.toc'):
temporary=target/(name+'.new')
with temporary.open('xb')as stream:stream.write(files[name])
temporary.replace(target/name)
if backup is not None:report['rollback']='Close owned client, verify current addon file hashes, then restore previous-addon from previous_backup.'
report.update(installed=True,status='NATIVE_VERIFICATION_PENDING');journal.write_text(json.dumps(report,indent=2)+'\n');return report
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);m=p.add_mutually_exclusive_group(required=True);m.add_argument('--package',type=Path);m.add_argument('--install-stage',type=Path);p.add_argument('--source-sets',type=Path);p.add_argument('--previous-install',type=Path);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
if a.package and not a.source_sets:p.error('Source set rosters required for dependency staging')
r=stage(a.package,a.source_sets,a.output)if a.package else install(a.install_stage,a.output,a.previous_install);print(json.dumps({k:r[k]for k in('kind','sets','items','installed')}))