Files

48 lines
2.0 KiB
Python

"""Remote installer invoked by deploy.sh; no Gitea credentials or restart needed."""
from pathlib import Path, PurePosixPath
import datetime
import json
import os
import shutil
import sys
import tarfile
staging, assets, backup_root = map(Path, sys.argv[1:])
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
backup = backup_root / stamp
backup.mkdir(parents=True, mode=0o700)
paths = []
with tarfile.open(staging / 'theme.tar.gz') as archive:
for member in archive:
rel = PurePosixPath(member.name)
if rel.is_absolute() or '..' in rel.parts or not rel.parts or rel.parts[0] not in ('css', 'fonts'):
raise ValueError(f'Unsafe asset path: {member.name}')
if member.isdir():
continue
if not member.isfile():
raise ValueError(f'Unsupported archive entry: {member.name}')
dest = assets / rel
if dest.is_symlink() or any(p.is_symlink() for p in dest.parents if p != assets.parent):
raise ValueError(f'Refusing symlink destination: {dest}')
previous = backup / rel
existed = dest.exists()
if existed:
previous.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(dest, previous)
dest.parent.mkdir(parents=True, exist_ok=True)
temp = dest.with_name(dest.name + '.yorha-new')
with archive.extractfile(member) as source, temp.open('wb') as target:
shutil.copyfileobj(source, target)
temp.chmod(0o644)
paths.append((str(rel), existed))
(backup / 'manifest.json').write_text(json.dumps({'assets': str(assets), 'files': paths}, indent=2) + '\n')
# Publish dependencies before the entrypoint, which activates this revision.
for rel, _ in sorted(paths, key=lambda item: item[0].startswith('css/theme-yorha-')):
dest = assets / rel
os.replace(dest.with_name(dest.name + '.yorha-new'), dest)
shutil.rmtree(staging)
print(f'Deployed {len(paths)} files to {assets}')
print(f'Backup: {backup}')