AVA2 client Windows parity passes (gr2 BitKnit2/64-bit, GamePhase handlers, python modules)

- gr2: BitKnit2 decompression, 64-bit LE files, compressed curves
- net: remaining GamePhase handlers, generated GC packet table
- python: event/chat/chr/minimap/guild/quest/messenger/shop-search and
  other native modules ported against the AVA2 Windows client
- render: D3D8 fixed-function lighting in Gr2ModelRenderer, terrain
  without baked shade; cape/NPC equipment attachment
- tests + audits updated; docs/PORT-PLAN.md and WINDOWS-PARITY.md

Batch 4 (render pipeline: background.*, app.RenderGame/UpdateGame,
camera bindings, main.cpp fake-content removal) is still in progress.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-08 10:43:01 +09:00
co-authored by Claude Opus 5.5
parent 9f748eb05a
commit 9077aa389a
145 changed files with 22692 additions and 6584 deletions
+1 -1
View File
@@ -21,7 +21,7 @@ for body in re.findall(r'\benum\s*\w*\s*\{(.*?)\}',processed,re.S):
aliases={'HEADER_CG_CHARACTER_CREATE':'HEADER_CG_PLAYER_CREATE','HEADER_CG_CHARACTER_DELETE':'HEADER_CG_PLAYER_DESTROY','HEADER_CG_MOVE':'HEADER_CG_CHARACTER_MOVE','HEADER_CG_CHARACTER_SELECT':'HEADER_CG_PLAYER_SELECT','HEADER_GC_CHARACTER_CREATE_SUCCESS':'HEADER_GC_PLAYER_CREATE_SUCCESS','HEADER_GC_CHARACTER_CREATE_FAILURE':'HEADER_GC_PLAYER_CREATE_FAILURE','HEADER_GC_CHARACTER_DELETE_SUCCESS':'HEADER_GC_PLAYER_DELETE_SUCCESS','PHASE_OFFLINE':'PHASE_CLOSE'}
port=(root/'src/eter_net/Packet.h').read_text()
checked=[];mismatches=[];unmatched=[]
for name,value in re.findall(r'\b((?:HEADER_[CG][GC]_|PHASE_|EXCHANGE_SUBHEADER_)[A-Z0-9_]+)\s*=\s*(0x[0-9a-fA-F]+|\d+)',port):
for name,value in re.findall(r'\b((?:HEADER_[CG][GC]_|PHASE_|EXCHANGE_SUBHEADER_|MESSENGER_SUBHEADER_CG_|GUILD_SUBHEADER_CG_)[A-Z0-9_]+)\s*=\s*(0x[0-9a-fA-F]+|\d+)',port):
reference=aliases.get(name,name)
if reference not in values: unmatched.append(name);continue
row={'name':name,'windows_name':reference,'windows':values[reference],'port':int(value,0)}
+17 -4
View File
@@ -19,16 +19,29 @@ def modules(paths,preprocess=False):
for call in re.finditer(r'Py_InitModule\s*\(\s*"([^"\n]+)"\s*,\s*(\w+)',source):
candidates=[t for t in tables if t[1]==call[2] and t.start()<call.start()]
if not candidates: continue
methods={name:handler for name,handler in re.findall(r'\{\s*"([^"\n]+)"\s*,\s*(\w+)\s*,',candidates[-1][2])}
result[call[1]]={'path':str(path.relative_to(root)),'methods':methods}
methods={name:handler for name,handler in re.findall(r'\{\s*"([^"\n]+)"\s*,\s*(\w+(?:<[^>{}]*>)?)\s*,',candidates[-1][2])}
if call[1] in result:
result[call[1]]['methods'].update(methods)
else:
result[call[1]]={'path':str(path.relative_to(root)),'methods':methods}
return result
windows=modules(sorted((root/'upstream/ava2-client').rglob('*Module.cpp')),True)
# Only translation units listed in AVA2's Windows build are reference modules.
# Orphan .cpp files (e.g. guild_ranking) do not define the shipped client API.
import xml.etree.ElementTree as ET
compiled=set()
for project in (root/'upstream/ava2-client').rglob('*.vcxproj'):
for node in ET.parse(project).getroot().iter():
if node.tag.rsplit('}',1)[-1]=='ClCompile' and 'Include' in node.attrib:
compiled.add((project.parent/node.attrib['Include'].replace('\\','/')).resolve())
reference_paths=[p for p in sorted(compiled) if p.is_file() and
re.search(r'\bPy_InitModule\s*\(',p.read_text(errors='replace'))]
windows=modules(reference_paths,True)
port=modules(sorted((root/'src').glob('python_*.cpp')))
rows=[]
for name,reference in sorted(windows.items()):
target=port.get(name,{'methods':{}});original=set(reference['methods']);current=set(target['methods'])
rows.append({'module':name,'windows_file':reference['path'],'port_file':target.get('path'),'windows_methods':len(original),'missing':sorted(original-current),'extra':sorted(current-original),'placeholder':sorted(method for method in original&current if 'dummy' in target['methods'][method])})
report={'basis':'AVA2 Windows active method tables; module constants/signatures/behavior require further audit','modules':rows,'missing_method_count':sum(len(r['missing']) for r in rows),'placeholder_method_count':sum(len(r['placeholder']) for r in rows)}
report={'basis':'AVA2 Windows project-compiled active method tables; module constants/signatures/behavior require further audit','modules':rows,'missing_method_count':sum(len(r['missing']) for r in rows),'placeholder_method_count':sum(len(r['placeholder']) for r in rows)}
(root/'docs/AVA2-PYTHON-INTERFACES.json').write_text(json.dumps(report,indent=2)+'\n')
print(f"{len(rows)} Windows modules compared; {report['missing_method_count']} missing methods; {report['placeholder_method_count']} overlapping placeholder methods")
for row in rows:
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Generate src/eter_net/Ava2GcPacketTable.inc from the AVA2 Windows reference.
Source of truth:
* UserInterface/PythonNetworkStream.cpp CMainPacketHeaderMap (header -> size, static/dynamic)
* UserInterface/PythonNetworkStreamPhaseGame.cpp GamePhase() switch (headers with a handler)
* UserInterface/Packet.h + Locale_inc.h struct layouts and feature defines
sizeof() is evaluated by clang for i686-pc-windows-msvc (the Win32 client ABI) with
_USE_32BIT_TIME_T semantics (StdAfx.h), so the table is the Win32 wire size, not a
guess. Only constants used by Packet.h are stubbed; they are copied from the reference.
"""
import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path
root = Path(__file__).resolve().parents[1]
ui = root / "upstream/ava2-client/UserInterface"
out = root / "src/eter_net/Ava2GcPacketTable.inc"
def ascii_text(path):
return re.sub(r"[^\t\n\r\x20-\x7e]", "", path.read_bytes().decode("latin1"))
PRELUDE = """
#include <stdint.h>
typedef uint8_t BYTE; typedef uint16_t WORD; typedef uint32_t DWORD; typedef int32_t LONG;
typedef int BOOL; typedef uint32_t UINT; typedef int INT; typedef int64_t LONGLONG;
typedef uint64_t ULONGLONG; typedef int16_t SHORT; typedef char CHAR; typedef float FLOAT;
#define NULL 0
typedef int time_t; /* StdAfx.h: _USE_32BIT_TIME_T */
typedef unsigned int size_t;
extern "C" void* memset(void*, int, size_t); extern "C" float sqrtf(float);
class CResource {}; struct TPixelPosition { float x, y, z; };
namespace std { template<class T> struct vector { T* a; T* b; T* c; }; struct string { char b[24]; };
template<class K, class V, class C = int> struct map {}; template<class A, class B> struct pair { A first; B second; }; }
/* UserInterface/StdAfx.h */
enum { POINT_MAX_NUM = 255, CHARACTER_NAME_MAX_LEN = 24, PLAYER_NAME_MAX_LEN = 12 };
"""
# GameLib/ItemData.h CItemData enum values referenced by Packet.h / GameType.h
ITEMDATA = """#pragma once
class CItemData { public: enum { ITEM_NAME_MAX_LEN = 24, ITEM_LIMIT_MAX_NUM = 2, ITEM_VALUES_MAX_NUM = 6,
ITEM_APPLY_MAX_NUM = 3, ITEM_SOCKET_MAX_NUM = 8, WEAR_MAX_NUM = 32, DS_SLOT_NUM_TYPES = 6 }; };
"""
def header_map_body():
text = ascii_text(ui / "PythonNetworkStream.cpp")
start = text.index("CMainPacketHeaderMap()")
body_start = text.index("{", start) + 1
end = text.index("\n};", body_start)
body = text[body_start:end].rstrip()
assert body.endswith("}")
return body[:-1]
def game_switch_body():
text = ascii_text(ui / "PythonNetworkStreamPhaseGame.cpp")
start = text.index("void CPythonNetworkStream::GamePhase()")
end = text.index("RecvDefaultPacket(header)", start)
lines = []
body = re.sub(r"/\*.*?\*/", "", text[start:end], flags=re.S)
for line in body.splitlines():
s = line.split("//", 1)[0].strip()
if re.match(r"#\s*(if|ifdef|ifndef|else|elif|endif)\b", s):
lines.append(s)
else:
for m in re.finditer(r"case\s+(HEADER_GC_\w+)\s*:", s):
lines.append(f"handled[{m.group(1)}] = 1;")
return "\n".join(lines)
GEN = """#include "Locale_inc.h"
#include "GameType.h"
#include "Packet.h"
struct CNetworkPacketHeaderMap { struct TPacketType { int s, d; constexpr TPacketType(int a = 0, int b = 0) : s(a), d(b) {} }; };
struct Table {
enum { STATIC_SIZE_PACKET = 0, DYNAMIC_SIZE_PACKET = 1 };
int size[256] = {}; int dyn[256] = {}; int set[256] = {}; int handled[256] = {};
constexpr void Set(int h, CNetworkPacketHeaderMap::TPacketType t) { size[h] = t.s; dyn[h] = t.d; set[h] = 1; }
constexpr Table() {
#include "map.inc"
#include "switch.inc"
}
};
extern "C" const Table exported_table = Table();
"""
def main():
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / "x").mkdir()
(tmp / "GameLib").mkdir()
for name in ("Packet.h", "GameType.h", "Locale_inc.h"):
(tmp / "x" / name).write_bytes((ui / name).read_bytes())
(tmp / "x" / "Locale.h").write_text("")
(tmp / "GameLib" / "ItemData.h").write_text(ITEMDATA)
(tmp / "GameLib" / "RaceData.h").write_text("")
(tmp / "prelude.h").write_text(PRELUDE)
(tmp / "map.inc").write_text(header_map_body())
(tmp / "switch.inc").write_text(game_switch_body())
(tmp / "gen.cpp").write_text(GEN)
cmd = ["clang++", "-target", "i686-pc-windows-msvc", "-fms-extensions", "-fms-compatibility",
"-std=c++17", "-S", "-emit-llvm", "-o", str(tmp / "gen.ll"), "-I", str(tmp / "x"),
"-I", str(tmp), "-include", str(tmp / "prelude.h"), str(tmp / "gen.cpp")]
subprocess.run(cmd, check=True)
ir = (tmp / "gen.ll").read_text()
line = next(l for l in ir.splitlines() if l.startswith("@exported_table"))
values = []
for m in re.finditer(r"\[(\d+) x i32\] zeroinitializer|(?<![x\[] )i32 (-?\d+)", line.split("} {", 1)[1]):
values += [0] * int(m.group(1)) if m.group(1) else [int(m.group(2))]
if len(values) != 1024:
sys.exit(f"unexpected IR table length {len(values)}")
size, dyn, present, handled = (values[i * 256:(i + 1) * 256] for i in range(4))
rows = []
for h in range(256):
if present[h] or handled[h]:
rows.append(f" {{{h}, {size[h]}, {int(bool(dyn[h]))}, {int(bool(present[h]))}, {int(bool(handled[h]))}}},")
out.write_text(
"// Generated by tools/generate_ava2_gc_packet_table.py from the AVA2 Windows reference\n"
"// (CMainPacketHeaderMap in PythonNetworkStream.cpp + GamePhase() switch, Win32 i686 layout).\n"
"// {header, size, dynamic, in CMainPacketHeaderMap, handled by GamePhase()}\n"
+ "\n".join(rows) + "\n")
print(f"{sum(present)} mapped headers, {sum(handled)} GamePhase handlers -> {out.relative_to(root)}")
if __name__ == "__main__":
main()
+56 -2
View File
@@ -6,9 +6,9 @@ root=Path(__file__).resolve().parents[1]
packet=(root/'upstream/ava2-client/UserInterface/Packet.h').read_text(errors='replace')
game=(root/'upstream/ava2-client/UserInterface/GameType.h').read_text(errors='replace')
def decl(source,name):
matches=re.findall(r'typedef struct '+name+r'\s*\{.*?\}\s*\w+\s*;',source,re.S)
matches=re.findall(r'typedef\s+struct\s+'+name+r'\s*\{.*?\}\s*\w+\s*;',source,re.S)
assert matches,name
return matches[-1].replace('long long','std::int64_t').replace('long','std::int32_t').replace('CItemData::ITEM_NAME_MAX_LEN','24')
return matches[-1].replace('unsigned long long','std::uint64_t').replace('long long','std::int64_t').replace('long','std::int32_t').replace('CItemData::ITEM_NAME_MAX_LEN','24')
constants=game[game.index('enum\n{\n\tITEM_SOCKET_SLOT_MAX_NUM'):]
constants=constants[:constants.index('\n};')+3]
stdafx=(root/'upstream/ava2-client/UserInterface/StdAfx.h').read_text(errors='replace')
@@ -42,4 +42,58 @@ for name in ('ITEM_NAME_MAX_LEN','ITEM_LIMIT_MAX_NUM','ITEM_APPLY_MAX_NUM','ITEM
assert value,name
item_constants+='constexpr int '+name+'='+value.group(1)+';\n'
text+='namespace ava2_windows_proto {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;\n'+item_constants+'#pragma pack(push,1)\n'+item_decls+'\n#pragma pack(pop)\n}\n'
quest_flags=re.search(r'enum\s*\{\s*QUEST_SEND_IS_BEGIN.*?\};',packet,re.S)
assert quest_flags
text+='namespace ava2_windows_quest { using BYTE=std::uint8_t;using WORD=std::uint16_t;\n'+quest_flags.group()+'\n#pragma pack(push,1)\n'+decl(packet,'packet_quest_info')+'\n#pragma pack(pop)\n}\n'
messenger_decls='\n'.join(decl(packet,name) for name in ('packet_messenger','packet_messenger_list_offline','packet_messenger_list_online','packet_messenger_login','packet_messenger_logout'))
messenger_enums=[]
for start in ('MESSENGER_SUBHEADER_GC_LIST','MESSENGER_CONNECTED_STATE_OFFLINE'):
match=re.search(r'enum\s*\{\s*'+start+r'.*?\};',packet,re.S)
assert match,start
messenger_enums.append(match.group())
text+='namespace ava2_windows_messenger {using BYTE=std::uint8_t;using WORD=std::uint16_t;\n'+'\n'.join(messenger_enums)+'\n#pragma pack(push,1)\n'+messenger_decls+'\n#pragma pack(pop)\n}\n'
cube_enum=re.search(r'enum\s*\{\s*CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE.*?\};',packet,re.S)
assert cube_enum
cube_decls='\n'.join(decl(packet,name) for name in ('packet_send_cube_renewal','dates_cube_renewal','packet_receive_cube_renewal'))
text+='namespace ava2_windows_cube {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_CUBE_RENEWAL=221;\n'+cube_enum.group()+'\n#pragma pack(push,1)\n'+cube_decls+'\n#pragma pack(pop)\n}\n'
search_decls='\n'.join(decl(packet,name) for name in ('packet_offline_shop_item','packet_priv_shop_item_set','command_shop_search'))
text+='namespace ava2_windows_search {using BYTE=std::uint8_t;using DWORD=std::uint32_t;using TPlayerItemAttribute=ava2_windows_item::TPlayerItemAttribute;constexpr int ITEM_SOCKET_SLOT_MAX_NUM=ava2_windows_item::ITEM_SOCKET_SLOT_MAX_NUM,ITEM_ATTRIBUTE_SLOT_MAX_NUM=ava2_windows_item::ITEM_ATTRIBUTE_SLOT_MAX_NUM,CHARACTER_NAME_MAX_LEN=24;\n#pragma pack(push,1)\n'+search_decls+'\n#pragma pack(pop)\n}\n'
guild_decls='\n'.join(decl(packet,name) for name in ('packet_guild','packet_guild_sub_grade','packet_guild_sub_member','packet_guild_sub_info','packet_guild_war','SPacketGuildWarPoint'))
guild_enums='\n'.join(re.search(r'enum(?: EGuildWarState)?\s*\{\s*'+start+r'.*?\};',packet,re.S).group() for start in ('GUILD_SUBHEADER_GC_LOGIN','GUILD_AUTH_ADD_MEMBER','GUILD_WAR_NONE'))
text+='namespace ava2_windows_guild {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;constexpr int GUILD_NAME_MAX_LEN=12,GUILD_GRADE_NAME_MAX_LEN=8;\n'+guild_enums+'\n#pragma pack(push,1)\n'+guild_decls+'\n#pragma pack(pop)\n}\n'
battle_enum=re.search(r'enum\s*\{\s*BATTLEPASS_SUB_HEADER_OPEN.*?\};',packet,re.S)
assert battle_enum
battle_decls='\n'.join(decl(packet,name) for name in ('info_item_battlepass','info_battlepass','packet_cg_battlepass','packet_gc_battlepass'))
text+='namespace ava2_windows_battlepass {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_BATTLEPASS=230;\n'+battle_enum.group()+'\n#pragma pack(push,1)\n'+battle_decls+'\n#pragma pack(pop)\n}\n'
drop_enum=re.search(r'enum\s*\{\s*DROP_ITEM_SUB_HEADER_OPEN.*?\};',packet,re.S)
assert drop_enum
drop_decls='\n'.join(decl(packet,name) for name in ('packet_send_drop_item_system','info_drop_item_system','packet_receive_drop_item_system'))
text+='namespace ava2_windows_drop {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_DROP_ITEM_SYSTEM=220;\n'+drop_enum.group()+'\n#pragma pack(push,1)\n'+drop_decls+'\n#pragma pack(pop)\n}\n'
dungeon_enum=re.search(r'enum\s*\{\s*DUNGEON_INFO_SUB_HEADER_OPEN.*?\};',packet,re.S)
assert dungeon_enum
dungeon_decls='\n'.join(decl(packet,name) for name in ('packet_send_dungeon_info_system','SFDateInfoPacket','SFDateRanking','SFDateMision','SPacketGCDungeonInfoReceive'))
text+='namespace ava2_windows_dungeon {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_DUNGEON_INFO_SYSTEM=217;\n'+dungeon_enum.group()+'\n#pragma pack(push,1)\n'+dungeon_decls+'\n#pragma pack(pop)\n}\n'
switch=(root/'upstream/ava2-client/UserInterface/PythonSwitchbot.h').read_text(errors='replace')
switch_decls=[]
for name in ('TSwitchbotAttributeAlternativeTable','TSwitchbotTable','TSwitchbottAttributeTable'):
found=re.search(r'struct '+name+r'\s*\{.*?\};',switch,re.S)
assert found,name
switch_decls.append(found.group().replace('long','std::int32_t'))
for name in ('TPacketCGSwitchbot','TPacketGCSwitchbot','TSwitchbotUpdateItem'):
found=re.search(r'struct '+name+r'\s*\{.*?\};',packet,re.S)
assert found,name
switch_decls.append(found.group().replace('long','std::int32_t'))
switch_enums='\n'.join(re.search(r'enum '+name+r'\s*\{.*?\};',source,re.S).group() for source,name in ((game,'ESwitchbotValues'),(game,'EAttributeSet'),(packet,'ECGSwitchbotSubheader'),(packet,'EGCSwitchbotSubheader')))
text+='namespace ava2_windows_switchbot {using BYTE=std::uint8_t;using DWORD=std::uint32_t;using WORD=std::uint16_t;using TPlayerItemAttribute=ava2_windows_item::TPlayerItemAttribute;constexpr int ITEM_SOCKET_SLOT_MAX_NUM=8,ITEM_ATTRIBUTE_SLOT_MAX_NUM=15;\n'+switch_enums+'\n#pragma pack(push,1)\n'+'\n'.join(switch_decls)+'\n#pragma pack(pop)\n}\n'
ishop_enum=re.search(r'enum\s*\{\s*ITEMSHOP_LOAD.*?\};',packet,re.S)
assert ishop_enum
ishop_decls='\n'.join(decl(packet,name) for name in ('SIShopData','SIShopLogData','SPacketGCItemShop'))
text+='namespace ava2_windows_itemshop {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr int CHARACTER_NAME_MAX_LEN=24;\n'+ishop_enum.group()+'\n#pragma pack(push,1)\n'+ishop_decls+'\n#pragma pack(pop)\n}\n'
offline_enum=re.search(r'enum EPacketShopSubHeaders\s*\{.*?\};',packet,re.S)
assert offline_enum
offline_decls='\n'.join(decl(packet,name) for name in ('packet_shop','ShopLog','SShopDecoration','SOfflineShopItemTable','SPacketCGMyOfflineShop','packet_offline_shop_start','packet_offline_shop_update_item'))
text+='namespace ava2_windows_offline_shop {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;using TItemPos=ava2_windows_item::TItemPos;using TOfflineShopItemData=ava2_windows_search::TOfflineShopItemData;constexpr int CHARACTER_NAME_MAX_LEN=24,SHOP_SIGN_MAX_LEN=45,OFFLINE_SHOP_HOST_ITEM_MAX_NUM=80;\n'+offline_enum.group()+'\n#pragma pack(push,1)\n'+offline_decls+'\n#pragma pack(pop)\n}\n'
python_item=(root/'upstream/ava2-client/UserInterface/PythonItem.h').read_text(errors='replace')
sound_enums='\n'.join(re.search(r'enum\s*\{\s*'+start+r'.*?\};',python_item,re.S).group() for start in ('USESOUND_NONE','DROPSOUND_DEFAULT'))
text+='namespace ava2_windows_item_sound {\n'+sound_enums+'\n}\n'
out=Path(sys.argv[1]);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(text)
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Build a client-root style run directory for asset-backed tests.
The decoded AVA2 pack_maker tree keeps each pack in its own folder, and each
pack's <name>_create.xml lists the root-relative path ("ArchivedPath") the
Windows pack manager serves for every file (d:/ymir work/pc/..., icon/item/...,
locale/es/ui/...). This rebuilds that single root out of per-file symlinks,
without copying any asset:
1. every upstream/python-root file (the repository's scripts win)
2. every *_create.xml entry, "d:/" stripped; packs PC, ETC, root first, then
the rest alphabetically; first file wins, names compared case-insensitively
3. map -> pack_maker/Maps (tests read map/metin2_map_a1/...)
mark, svside -> pack_maker/../<name> (loose client-root folders, not in any pack)
The output is generated data: keep it out of the repository (default
build/dev/test-rundir, which CMake passes to the tests as AVA2_TEST_RUNDIR).
usage: tools/make_test_rundir.py [--pack-maker DIR] [--python-root DIR] [--out DIR]
"""
import argparse
import os
import re
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
MARKER = ".ava2_test_rundir"
FIRST_PACKS = ["PC", "ETC", "root"]
DIR_LINKS = {
"map": "Maps",
"mark": "../mark",
"svside": "../svside",
}
MANIFEST_ENTRY = re.compile(r'ArchivedPath="([^"]*)"><!\[CDATA\[([^\]]*)\]\]>')
def pack_manifests(pack_maker):
packs = sorted(p.name[: -len("_create.xml")] for p in pack_maker.glob("*_create.xml"))
first = [p for p in FIRST_PACKS if p in packs]
for pack in first + [p for p in packs if p not in first]:
yield pack_maker / f"{pack}_create.xml"
class RunDir:
"""Per-file symlink tree; the first file for a case-insensitive path wins."""
def __init__(self, out):
self.out = out
self.dirs = {"": out} # lower-case relative dir -> real directory
self.files = set()
def _dir(self, parts):
key = ""
for part in parts:
parent = self.dirs[key]
key = f"{key}/{part.lower()}" if key else part.lower()
if key not in self.dirs:
self.dirs[key] = parent / part
self.dirs[key].mkdir()
return self.dirs[key]
def add(self, rel, source):
parts = [p for p in rel.replace("\\", "/").split("/") if p]
key = "/".join(parts).lower()
if not parts or key in self.files or key in self.dirs:
return False
self.files.add(key)
os.symlink(source, self._dir(parts[:-1]) / parts[-1])
return True
def archived_root_path(archived):
archived = archived.replace("\\", "/")
return archived[3:] if archived.lower().startswith("d:/") else archived
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--pack-maker", type=Path,
default=ROOT.parent / "AVA2" / "TEST" / "1. Client DEV" / "pack_maker")
ap.add_argument("--python-root", type=Path, default=ROOT / "upstream" / "python-root")
ap.add_argument("--out", type=Path, default=ROOT / "build" / "dev" / "test-rundir")
args = ap.parse_args()
pack_maker = args.pack_maker.resolve()
out = args.out.resolve()
if not pack_maker.is_dir():
sys.exit(f"pack_maker not found: {pack_maker}")
# Only ever replace a directory this script made.
if out.exists():
if not (out / MARKER).exists():
sys.exit(f"refusing to replace {out}: not made by this script (no {MARKER})")
shutil.rmtree(out)
out.mkdir(parents=True)
(out / MARKER).write_text(f"pack_maker={pack_maker}\n")
tree = RunDir(out)
linked = 0
python_root = args.python_root.resolve()
if python_root.is_dir():
for dirpath, _dirnames, filenames in os.walk(python_root):
for name in sorted(filenames):
source = Path(dirpath) / name
linked += tree.add(source.relative_to(python_root).as_posix(), source)
else:
print(f"warning: missing {python_root}", file=sys.stderr)
for manifest in pack_manifests(pack_maker):
text = manifest.read_text(encoding="latin-1")
for archived, source in MANIFEST_ENTRY.findall(text):
# CDATA sources are relative to the directory holding pack_maker.
source = pack_maker.parent / source
if source.is_file():
linked += tree.add(archived_root_path(archived), source)
for name, rel in DIR_LINKS.items():
target = (pack_maker / rel).resolve()
if target.is_dir() and name not in tree.dirs:
os.symlink(target, out / name)
else:
print(f"warning: not linking {name} -> {target}", file=sys.stderr)
print(f"{out}: {linked} files linked")
if __name__ == "__main__":
main()