Files
kefu/deploy/admin-en-20261008/prepare_bundle.py
T
2026-11-16 09:39:42 +08:00

115 lines
6.6 KiB
Python

"""Assemble the server bundle locally (frontend only): payload + tests + manifest + tar.gz. No upload, no deployment.
python prepare_bundle.py
Frontend: web-antd rebuilt from the publishing source C:/wechat_rpa/admin-web. Evidence that nothing else changed:
`frontend-head-build/` is the same tree with every edit of this release reversed (head-build/aen_reverse.py replays the
sub-agents' Edit calls and replacement scripts from their transcripts plus my own scripted edits; the pre-release files
are in head-build/pre-release-src and are served by the vite pre-plugin head-build/pbtn_build_base.mjs, so the tree is
never modified). Its page graph must equal production's, except the bootstrap CSS may contain exactly the extra Tailwind
rules listed in release-plan 'headBuildCssOnlyInHead' (Tailwind scans the files on disk, i.e. the new English dictionaries,
where the word 'table' produces `.table{display:table}`; no element uses that class).
"""
from pathlib import Path
import hashlib, json, re, shutil, tarfile
folder = Path(__file__).resolve().parent
kefu = folder.parent.parent
plan = json.loads((folder / 'release-plan.json').read_text(encoding='utf-8'))
base = json.loads((folder / 'server-baseline.json').read_text(encoding='utf-8'))
sha = lambda data: hashlib.sha256(data).hexdigest()
lf = lambda data: data.replace(b'\r\n', b'\n')
snapshot = folder / 'baseline-snapshot'
assert plan['backendFiles'] == []
assert sha((snapshot / 'web-dist' / 'index.html').read_bytes()) == base['expected'][plan['frontendDir'] + '/index.html']
payload = folder / 'payload'
if payload.exists():
shutil.rmtree(payload)
frontend = plan['frontendDir']
dist = Path(plan['frontendSource'])
live = snapshot / 'web-dist'
REF = re.compile(r'[A-Za-z0-9_.-]+?-[A-Za-z0-9_-]{8}\.(?:js|css)')
unhash = lambda name: re.sub(r'-[A-Za-z0-9_-]{8}(?=\.(js|css)$)', '', name)
def graph(root):
names = {p.name: p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()}
seen, todo = {}, ['index.html']
while todo:
rel = todo.pop()
if rel in seen:
continue
seen[rel] = (root / rel).read_text(encoding='utf-8', errors='replace')
todo += [names[m] for m in REF.findall(seen[rel]) if m in names and names[m] not in seen]
return {unhash(rel): REF.sub(lambda m: unhash(m.group(0)), text) for rel, text in seen.items()}
BUILD_TIME = re.compile(r'buildTime:`[^`]*`|Date Created: \d{4}-\d{2}-\d{2}')
rules = lambda css: set(re.findall(r'[^{}]+\{[^{}]*\}', css))
old_graph, head_graph, new_graph = graph(live), graph(folder / plan['frontendHeadBuild']), graph(dist)
assert set(old_graph) == set(head_graph), 'head build page graph differs from production'
head_changed = sorted(k for k in head_graph if BUILD_TIME.sub('', head_graph[k]) != BUILD_TIME.sub('', old_graph[k]))
assert head_changed == ['css/bootstrap.css'], 'Pre-release source does not build to production: ' + repr(head_changed)
assert not rules(old_graph['css/bootstrap.css']) - rules(head_graph['css/bootstrap.css'])
only_head = rules(head_graph['css/bootstrap.css']) - rules(old_graph['css/bootstrap.css'])
assert sorted(only_head) == sorted(plan['headBuildCssOnlyInHead']), sorted(only_head)
dictionaries = ''.join(p.read_text(encoding='utf-8') for p in Path('C:/wechat_rpa/admin-web/apps/web-antd/src/locales/en').glob('*.ts'))
assert re.search(r'\btable\b', dictionaries), 'the extra .table rule should come from the English dictionaries'
assert set(old_graph) - set(new_graph) == set(plan['frontendRemovedPages']), sorted(set(old_graph) - set(new_graph))
assert set(new_graph) - set(old_graph) == set(plan['frontendNewPages']), sorted(set(new_graph) - set(old_graph))
live_files = {p.relative_to(live).as_posix(): sha(p.read_bytes()) for p in live.rglob('*') if p.is_file()}
new_files = {p.relative_to(dist).as_posix(): sha(p.read_bytes()) for p in dist.rglob('*') if p.is_file()}
assert sorted(k for k in new_files if k not in live_files) == sorted(plan['frontendAdded'])
assert [k for k in new_files if k in live_files and live_files[k] != new_files[k]] == plan['frontendReplaced']
for rel in plan['frontendReplaced'] + plan['frontendAdded']:
target = payload / frontend / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes((dist / rel).read_bytes())
entry = next(rel for rel in plan['frontendAdded'] if rel.startswith('jse/index-index-'))
assert entry in (dist / 'index.html').read_text(encoding='utf-8'), 'index.html does not load the new entry'
chunk = lambda prefix: (dist / next(rel for rel in plan['frontendAdded'] if rel.startswith(prefix))).read_text(encoding='utf-8')
assert 'Zhenyang AI Customer Service' in chunk('js/t-') and 'Knowledge Workbench' in chunk('js/t-')
assert 'ann.vben@gmail.com' not in chunk('js/basic-') and 'vbenjs' not in chunk('js/basic-')
tests = folder / 'tests'
if tests.exists():
shutil.rmtree(tests)
tests.mkdir()
for module in sorted({m.split('.')[0] for m in plan['serverTestModules']}):
data = lf((kefu / f'wechat_rpa/{module}.py').read_bytes())
compile(data, module, 'exec')
(tests / f'{module}.py').write_bytes(data)
scripts = ['release-plan.json', 'server-baseline.json', 'Dockerfile.overlay', 'remote_server_guard.py',
'01-preflight.sh', '02-build.sh', '03-deploy.sh', '04-verify.sh', 'rollback.sh']
manifest = []
for path in sorted(p for p in list(payload.rglob('*')) + list(tests.rglob('*')) if p.is_file()):
data = path.read_bytes()
manifest.append({'path': path.relative_to(folder).as_posix(), 'sha256': sha(data), 'bytes': len(data)})
(folder / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
bundle = folder / 'server-bundle'
if bundle.exists():
shutil.rmtree(bundle)
bundle.mkdir()
shutil.copytree(payload, bundle / 'payload')
shutil.copytree(tests, bundle / 'tests')
for name in scripts + ['manifest.json']:
(bundle / name).write_bytes(lf((folder / name).read_bytes()))
archive = folder / 'admin-en-server-bundle.tar.gz'
if archive.exists():
archive.unlink()
with tarfile.open(archive, 'x:gz') as tf:
for p in sorted(bundle.rglob('*')):
if p.is_file():
arc = p.relative_to(bundle).as_posix(); assert not arc.startswith(('/', '..'))
info = tf.gettarinfo(str(p), arcname=arc)
info.mode = 0o755 if arc.endswith('.sh') else 0o644
info.uid = info.gid = 0
info.uname = info.gname = ''
with p.open('rb') as handle:
tf.addfile(info, handle)
print(json.dumps({'archive': str(archive), 'bytes': archive.stat().st_size, 'sha256': sha(archive.read_bytes()),
'files': len(manifest), 'frontend_added': len(plan['frontendAdded']), 'uploaded': False}, indent=1))