60 lines
2.7 KiB
Python
60 lines
2.7 KiB
Python
"""Run the delivered SFX and verify its files and every ZIP member against SHA256."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import time
|
|
import zipfile
|
|
|
|
|
|
def digest(stream):
|
|
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
|
|
|
|
|
def verify(manifest_path: Path, destination: Path):
|
|
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
|
root = manifest_path.resolve().parent
|
|
destination = destination.resolve()
|
|
if destination.exists():
|
|
raise FileExistsError('Use a fresh extraction destination')
|
|
for name, expected in manifest['artifacts'].items():
|
|
with (root/name).open('rb') as stream:
|
|
if digest(stream) != expected['sha256']:
|
|
raise ValueError('Artifact checksum mismatch: '+name)
|
|
version = manifest['version']
|
|
started = time.monotonic()
|
|
subprocess.run([str(root/f'DxPartReplace-{version}.exe'), '-y', '-o'+str(destination)],
|
|
check=True, timeout=1800, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
|
elapsed = time.monotonic()-started
|
|
actual = {p.relative_to(destination).as_posix(): p for p in destination.rglob('*') if p.is_file()}
|
|
if set(actual) != set(manifest['files']):
|
|
raise ValueError('Self-extracted file set differs from manifest')
|
|
for name, path in actual.items():
|
|
with path.open('rb') as stream:
|
|
if digest(stream) != manifest['files'][name]:
|
|
raise ValueError('Self-extracted checksum mismatch: '+name)
|
|
with zipfile.ZipFile(root/f'DxPartReplace-{version}.zip') as archive:
|
|
if len(archive.namelist()) != len(actual) or set(archive.namelist()) != set(actual):
|
|
raise ValueError('ZIP file set differs from manifest')
|
|
# Reading to EOF also checks ZIP CRC for every member.
|
|
for name in archive.namelist():
|
|
with archive.open(name) as stream:
|
|
if digest(stream) != manifest['files'][name]:
|
|
raise ValueError('ZIP checksum mismatch: '+name)
|
|
return dict(passed=True, files=len(actual), sfx_extraction_seconds=round(elapsed, 3),
|
|
actual_sfx_executed=True, zip_crc_and_sha256=True,
|
|
destination=str(destination))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('manifest', type=Path)
|
|
parser.add_argument('destination', type=Path)
|
|
parser.add_argument('--report', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
result = verify(args.manifest, args.destination)
|
|
args.report.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|