235 lines
10 KiB
Python
235 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Build or refresh the clean, publishable copy of this repository.
|
|
|
|
The working repository carries a long recovery history, private runtime
|
|
leftovers and about 1.2 GB of evidence screenshots. This tool exports the
|
|
committed HEAD (tracked files only), leaves out what must not or need not be
|
|
published, and writes the result into a separate git repository:
|
|
|
|
first run -> a short history, one commit per part of the project
|
|
later runs -> one "Sync" commit with whatever changed since
|
|
|
|
It never pushes. Usage:
|
|
|
|
python3 ops/publish_export.py <target-dir> --identity "Name <mail>" [--trailer TEXT]
|
|
"""
|
|
import argparse
|
|
import io
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tarfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
LARGE_EVIDENCE = 5 * 1024 * 1024
|
|
OMISSIONS = 'docs/evidence/PUBLISHED_OMISSIONS.md'
|
|
# Tracked in the working repository but not part of the project.
|
|
UNRELATED = {'install-arch.sh'}
|
|
|
|
# First-run history: (commit title, path prefixes). Order is the reading order.
|
|
GROUPS = [
|
|
('Project overview, working rules and build system',
|
|
['README.md', 'AGENTS.md', 'CLAUDE.md', '.gitignore', 'CMakeLists.txt', 'cmake/', '.github/']),
|
|
('Protocol core: packet translation between source and native', ['include/', 'src/']),
|
|
('In-client stack: transport, session lifecycle and engine bridge', ['native/']),
|
|
('Client interface: addons, login-screen adapters and launcher',
|
|
['client_addons/', 'compat/', 'client_ui/', 'launcher/']),
|
|
('Content pipeline and operator tools', ['ops/', 'tools/', 'patches/']),
|
|
('Offline test fixtures', ['tests/']),
|
|
('Evidence records', ['docs/evidence/']),
|
|
('Design records', ['docs/']),
|
|
]
|
|
# Evidence is committed after the design records; it is listed first above only
|
|
# so its prefix wins over the broader docs/ prefix.
|
|
GROUP_ORDER = [0, 1, 2, 3, 4, 5, 7, 6]
|
|
|
|
|
|
def git(args, cwd, **kwargs):
|
|
return subprocess.run(['git', *args], cwd=cwd, check=True, **kwargs)
|
|
|
|
|
|
BLIZZARD_SUFFIXES = ('.lua', '.xml', '.bin', '.blp', '.db2', '.dbc', '.dump', '.m2', '.skin', '.wmo', '.adt')
|
|
|
|
|
|
def blizzard_derived(name):
|
|
"""Client files copied or patched from the Blizzard client must never be published (owner rule)."""
|
|
parts = name.split('/')
|
|
lower = name.lower()
|
|
if 'pins' in parts[:-1]:
|
|
return True # before/after copies of client DB2s and Lua chosen by content steps
|
|
if name.startswith('ops/content-') and lower.endswith(BLIZZARD_SUFFIXES):
|
|
return True # patched native UI files and client blobs of content steps
|
|
if name.startswith(('tests/fixtures/', 'docs/evidence/')) and lower.endswith(('.bin', '.blp', '.db2', '.dbc', '.m2', '.skin')):
|
|
return True
|
|
return name in BLIZZARD_FILES
|
|
|
|
|
|
BLIZZARD_FILES = {
|
|
'tests/fixtures/native_group_loot_frame.lua', # full copy of the 70334 GroupLootFrame.lua
|
|
}
|
|
|
|
|
|
def omitted_reason(name, size):
|
|
"""Why a tracked file is left out of the published copy, or None."""
|
|
if name.startswith('runtime/'):
|
|
return 'runtime'
|
|
if blizzard_derived(name):
|
|
return 'blizzard'
|
|
if name in UNRELATED:
|
|
return 'unrelated'
|
|
if '/__pycache__/' in name or name.endswith('.pyc') or '.bak' in Path(name).name:
|
|
return 'leftover'
|
|
if name.startswith('docs/evidence/'):
|
|
if name.lower().endswith(('.png', '.jpg', '.jpeg')):
|
|
return 'screenshot'
|
|
if size > LARGE_EVIDENCE:
|
|
return 'large'
|
|
return None
|
|
|
|
|
|
def secret_findings(name, data, private_mail):
|
|
"""Reasons this file must stop the export. Checked on text files only."""
|
|
if b'\0' in data[:4096]:
|
|
return []
|
|
found = []
|
|
if re.search(rb'-----BEGIN [A-Z ]*PRIVATE KEY-----', data):
|
|
found.append('private key block')
|
|
if private_mail and private_mail.lower().encode() in data.lower():
|
|
found.append('configured git e-mail address')
|
|
return found
|
|
|
|
|
|
def export(private_mail):
|
|
"""Return ({name: (bytes, mode)}, omissions, findings) for committed HEAD."""
|
|
archive = git(['archive', '--format=tar', 'HEAD'], ROOT, stdout=subprocess.PIPE).stdout
|
|
files, omitted, findings = {}, {}, {}
|
|
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
|
|
for member in tar:
|
|
if not member.isfile():
|
|
continue
|
|
reason = omitted_reason(member.name, member.size)
|
|
if reason:
|
|
omitted.setdefault(reason, []).append((member.name, member.size))
|
|
continue
|
|
data = tar.extractfile(member).read()
|
|
hits = secret_findings(member.name, data, private_mail)
|
|
if hits:
|
|
findings[member.name] = hits
|
|
files[member.name] = (data, 0o755 if member.mode & 0o100 else 0o644)
|
|
return files, omitted, findings
|
|
|
|
|
|
def omissions_note(omitted, head):
|
|
def total(kind):
|
|
rows = omitted.get(kind, [])
|
|
return len(rows), sum(size for _, size in rows) / 1048576
|
|
lines = ['# Left out of the published copy', '',
|
|
f'Generated by `ops/publish_export.py` from working commit `{head}`.',
|
|
'The files below exist in the working repository and are referenced by some',
|
|
'records and tests here; they are not published.', '',
|
|
'| What | Files | Size |', '|---|---|---|']
|
|
for kind, label in (('screenshot', 'Screenshots under `docs/evidence/` (game windows)'),
|
|
('large', 'Evidence data files over 5 MB'),
|
|
('runtime', 'Tracked leftovers under `runtime/` (private logs and receipts)'),
|
|
('unrelated', 'Files unrelated to the project'),
|
|
('leftover', 'Caches and backup copies'),
|
|
('blizzard', 'Client files copied or patched from the Blizzard client (UI Lua/XML, DB2/DBC, textures, executable bytes)')):
|
|
count, size = total(kind)
|
|
lines.append(f'| {label} | {count} | {size:.0f} MB |')
|
|
large = sorted(omitted.get('large', []))
|
|
if large:
|
|
lines += ['', '## Large evidence data files', '']
|
|
lines += [f'- `{name}` ({size / 1048576:.0f} MB)' for name, size in large]
|
|
return '\n'.join(lines) + '\n'
|
|
|
|
|
|
def write_tree(target, files):
|
|
for entry in target.iterdir():
|
|
if entry.name == '.git':
|
|
continue
|
|
shutil.rmtree(entry) if entry.is_dir() and not entry.is_symlink() else entry.unlink()
|
|
for name, (data, mode) in files.items():
|
|
path = target / name
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(data)
|
|
path.chmod(mode)
|
|
|
|
|
|
def group_of(name):
|
|
for index, (_, prefixes) in enumerate(GROUPS):
|
|
if any(name == prefix or (prefix.endswith('/') and name.startswith(prefix)) for prefix in prefixes):
|
|
return index
|
|
return None
|
|
|
|
|
|
def commit(target, title, body, trailer):
|
|
message = title + ('\n\n' + body if body else '') + ('\n\n' + trailer if trailer else '')
|
|
git(['commit', '-q', '-m', message], target)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument('target', type=Path)
|
|
parser.add_argument('--identity', required=True, help='commit author for the published copy, "Name <mail>"')
|
|
parser.add_argument('--trailer', default='', help='line appended to every commit message')
|
|
options = parser.parse_args()
|
|
identity = re.fullmatch(r'\s*(.+?)\s*<([^<>\s]+)>\s*', options.identity)
|
|
if not identity:
|
|
parser.error('--identity must look like "Name <mail>"')
|
|
target = options.target.resolve()
|
|
if target == ROOT or ROOT in target.parents:
|
|
parser.error('target must be outside the working repository')
|
|
|
|
head = git(['rev-parse', '--short', 'HEAD'], ROOT, stdout=subprocess.PIPE, text=True).stdout.strip()
|
|
private_mail = subprocess.run(['git', 'config', 'user.email'], cwd=ROOT, stdout=subprocess.PIPE,
|
|
text=True).stdout.strip()
|
|
if private_mail.lower() == identity.group(2).lower():
|
|
private_mail = '' # the author chose to publish this address
|
|
files, omitted, findings = export(private_mail)
|
|
if findings:
|
|
print('Export stopped; these tracked files contain private material:', file=sys.stderr)
|
|
for name, hits in sorted(findings.items()):
|
|
print(f' {name}: {", ".join(hits)}', file=sys.stderr)
|
|
return 2
|
|
files[OMISSIONS] = (omissions_note(omitted, head).encode(), 0o644)
|
|
|
|
first = not (target / '.git').exists()
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
if first:
|
|
git(['init', '-q', '-b', 'main'], target)
|
|
git(['config', 'user.name', identity.group(1)], target)
|
|
git(['config', 'user.email', identity.group(2)], target)
|
|
write_tree(target, files)
|
|
|
|
if first:
|
|
names = sorted(files)
|
|
for index in GROUP_ORDER:
|
|
members = [name for name in names if group_of(name) == index]
|
|
if not members:
|
|
continue
|
|
git(['add', '--pathspec-from-file=-'], target, input='\n'.join(members).encode())
|
|
commit(target, GROUPS[index][0], f'{len(members)} files, from working commit {head}.', options.trailer)
|
|
rest = [name for name in names if group_of(name) is None]
|
|
if rest:
|
|
git(['add', '-A'], target)
|
|
commit(target, 'Remaining files', f'{len(rest)} files, from working commit {head}.', options.trailer)
|
|
else:
|
|
git(['add', '-A'], target)
|
|
if subprocess.run(['git', 'diff', '--cached', '--quiet'], cwd=target).returncode == 0:
|
|
print('Published copy already matches', head)
|
|
return 0
|
|
commit(target, f'Sync with working repository at {head}', '', options.trailer)
|
|
|
|
count = git(['rev-list', '--count', 'HEAD'], target, stdout=subprocess.PIPE, text=True).stdout.strip()
|
|
size = sum(len(data) for data, _ in files.values()) / 1048576
|
|
print(f'{len(files)} files, {size:.0f} MB, {count} commits in {target}')
|
|
for kind, rows in sorted(omitted.items()):
|
|
print(f'left out ({kind}): {len(rows)} files, {sum(s for _, s in rows) / 1048576:.0f} MB')
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|