build: prepare V1.2.2 with portable 7-Zip self-extraction
This commit is contained in:
1 parent
453d288a6c
commit
5aeddacfc9
12 files changed
+345
-10
No files matched your search
@@ -0,0 +1,117 @@
|
||||
"""Create the ZIP and 7-Zip self-extracting artifacts for a release."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
|
||||
from self_extracting_release import build_sfx
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _zip_tree(source: Path, output: Path) -> int:
|
||||
files = 0
|
||||
with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=6, allowZip64=True) as archive:
|
||||
for path in sorted(source.rglob("*")):
|
||||
if path.is_file():
|
||||
archive.write(path, path.relative_to(source.parent).as_posix())
|
||||
files += 1
|
||||
return files
|
||||
|
||||
|
||||
def build_release(source_dir: Path, output_dir: Path, *, version: str, seven_zip: Path, sfx_stub: Path,
|
||||
license_path: Path | None = None) -> dict:
|
||||
source_dir = Path(source_dir).resolve(strict=True)
|
||||
output_dir = Path(output_dir).resolve()
|
||||
if not source_dir.is_dir():
|
||||
raise ValueError("source_dir must be a directory")
|
||||
if output_dir.is_relative_to(source_dir) or source_dir.is_relative_to(output_dir):
|
||||
raise ValueError('Output must not be inside or contain the source directory')
|
||||
if (source_dir / 'data').exists():
|
||||
raise ValueError('Release input must not include user data')
|
||||
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.]+)?', version):
|
||||
raise ValueError('Invalid release version')
|
||||
seven_zip = Path(seven_zip).resolve(strict=True)
|
||||
sfx_stub = Path(sfx_stub).resolve(strict=True)
|
||||
output_dir.mkdir(parents=True, exist_ok=False)
|
||||
|
||||
staging = output_dir / "staging" / "DxPartReplace"
|
||||
shutil.copytree(source_dir, staging)
|
||||
if license_path is not None:
|
||||
license_target = staging / "licenses" / "7-Zip-LICENSE.txt"
|
||||
license_target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(Path(license_path).resolve(strict=True), license_target)
|
||||
|
||||
archive_7z = output_dir / f"DxPartReplace-{version}.7z"
|
||||
subprocess.run([
|
||||
str(seven_zip), "a", "-t7z", "-mx=3", "-m0=LZMA2", "-mmt=4", "-ms=64m",
|
||||
str(archive_7z), "DxPartReplace"
|
||||
], cwd=staging.parent, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
timeout=3600)
|
||||
|
||||
zip_path = output_dir / f"DxPartReplace-{version}.zip"
|
||||
file_count = _zip_tree(staging, zip_path)
|
||||
sfx_path = output_dir / f"DxPartReplace-{version}.exe"
|
||||
build_sfx(sfx_stub, archive_7z, sfx_path)
|
||||
archive_7z.unlink()
|
||||
|
||||
manifest = {
|
||||
"version": version,
|
||||
"file_count": file_count,
|
||||
"artifacts": {
|
||||
zip_path.name: {"bytes": zip_path.stat().st_size, "sha256": _sha256(zip_path)},
|
||||
sfx_path.name: {"bytes": sfx_path.stat().st_size, "sha256": _sha256(sfx_path)},
|
||||
},
|
||||
"extractor": {
|
||||
"kind": "7zip-sfx",
|
||||
"stub": sfx_stub.name,
|
||||
"stub_sha256": _sha256(sfx_stub),
|
||||
"compressor": seven_zip.name,
|
||||
"compressor_sha256": _sha256(seven_zip),
|
||||
"version_output": subprocess.check_output([str(seven_zip)], text=True, errors='replace')[:500],
|
||||
"settings": "LZMA2 level 3, 4 threads, 64 MiB solid blocks",
|
||||
},
|
||||
"files": {path.relative_to(staging.parent).as_posix(): _sha256(path)
|
||||
for path in sorted(staging.rglob('*')) if path.is_file()},
|
||||
}
|
||||
(output_dir / f"release-manifest-{version}.json").write_text(
|
||||
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
(output_dir / f"SHA256SUMS-{version}.txt").write_text(
|
||||
"".join(f"{item['sha256']} {name}\n" for name, item in manifest["artifacts"].items()),
|
||||
encoding="ascii",
|
||||
)
|
||||
return manifest
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--source-dir", type=Path, required=True)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--seven-zip", type=Path, required=True)
|
||||
parser.add_argument("--sfx-stub", type=Path, required=True)
|
||||
parser.add_argument("--license", type=Path)
|
||||
args = parser.parse_args()
|
||||
manifest = build_release(args.source_dir, args.output_dir, version=args.version,
|
||||
seven_zip=args.seven_zip, sfx_stub=args.sfx_stub,
|
||||
license_path=args.license)
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Build a 7-Zip SFX wrapper around a prepared .7z release archive."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
|
||||
|
||||
def build_sfx(
|
||||
stub: Path,
|
||||
archive: Path,
|
||||
output: Path,
|
||||
) -> Path:
|
||||
"""Use the official 7z.sfx extractor (not the temporary installer stub).
|
||||
|
||||
Its native dialog selects a persistent destination. No installer config,
|
||||
registry modifications, temporary extraction or automatic launch is needed.
|
||||
"""
|
||||
stub = Path(stub)
|
||||
archive = Path(archive)
|
||||
output = Path(output)
|
||||
if not stub.is_file() or not archive.is_file():
|
||||
raise FileNotFoundError("SFX stub and archive must both exist")
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
with stub.open('rb') as stream:
|
||||
if stream.read(2) != b'MZ':
|
||||
raise ValueError('Expected Windows SFX executable')
|
||||
with archive.open('rb') as stream:
|
||||
if stream.read(6) != b'7z\xbc\xaf\x27\x1c':
|
||||
raise ValueError('Expected 7z archive')
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
||||
try:
|
||||
with temporary.open("xb") as target:
|
||||
for source in (stub, archive):
|
||||
with source.open('rb') as stream:
|
||||
shutil.copyfileobj(stream, target, 1024 * 1024)
|
||||
target.flush()
|
||||
os.fsync(target.fileno())
|
||||
os.replace(temporary, output)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return output
|
||||
@@ -0,0 +1,59 @@
|
||||
"""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))
|
||||
Reference in new issue
Block a user