#!/usr/bin/env python3 """Prepare a pinned, private module copy; never change the download cache.""" import hashlib import json import os from pathlib import Path import shutil import tempfile root = Path(__file__).resolve().parent.parent upstream = root / 'work/toolchain/go/pkg/mod/github.com/sagernet/sing-box@v1.14.3' source = upstream / 'route/rule/rule_set_remote.go' mod = (root / 'engines/singbox/go.mod').read_text() if 'github.com/sagernet/sing-box v1.14.3' not in mod: raise SystemExit('Review the sing-box patch before changing the upstream version') # Hash below is filled from the unmodified, checksum-verified pinned module. EXPECTED = 'f7c0e48dfb47f1198fc7c243c3d0319872b5429f0948532d08e9e46bdc583825' if not source.exists() or hashlib.sha256(source.read_bytes()).hexdigest() != EXPECTED: raise SystemExit('Unexpected upstream rule-set source; refusing to apply patch') folder = root / 'work/singbox-patched' if not folder.exists(): temporary = Path(tempfile.mkdtemp(prefix='singbox-source-', dir=root / 'work')) try: shutil.copytree(upstream, temporary / 'module', copy_function=shutil.copyfile) # Go's cache directories are read-only; the owned copy must be writable. for directory, _, _ in os.walk(temporary / 'module'): os.chmod(directory, 0o755) try: os.rename(temporary / 'module', folder) except FileExistsError: pass finally: shutil.rmtree(temporary) patch = (root / 'engines/singbox/patches/rule_set_remote.go.txt').read_bytes() target = folder / 'route/rule/rule_set_remote.go' if target.read_bytes() != patch: fd, temporary = tempfile.mkstemp(prefix='remote-rule-', dir=target.parent) with os.fdopen(fd, 'wb') as stream: stream.write(patch) os.replace(temporary, target) altmod = root / 'work/singbox-patched.go.mod' value = mod + '\nreplace github.com/sagernet/sing-box => ' + json.dumps(str(folder)) + '\n' if not altmod.exists() or altmod.read_text() != value: altmod.write_text(value) checksum = (root / 'engines/singbox/go.sum').read_bytes() altsum = altmod.with_suffix('.sum') if not altsum.exists() or altsum.read_bytes() != checksum: fd, temporary = tempfile.mkstemp(prefix='singbox-checksum-', dir=root / 'work') with os.fdopen(fd, 'wb') as stream: stream.write(checksum) os.replace(temporary, altsum)