"""Freeze an explicitly reviewed source delta without losing the parent inventory.""" import argparse import hashlib import json from pathlib import Path def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def freeze(root, parent, allowed): root, parent = Path(root).resolve(), Path(parent).resolve() if root == parent or parent in root.parents or root in parent.parents: raise ValueError('A separate derivative and immutable parent are required') receipt_path = root / 'REPAIR_V2_REVISION.json' if receipt_path.exists(): raise FileExistsError('Revision is already frozen') raw = (parent / 'BASE_SHA256SUMS').read_bytes() entries = {} for line in raw.decode().splitlines(): expected, name = line.split(' ', 1) relative = Path(name) if relative.is_absolute() or '..' in relative.parts or relative.parts[0] != 'source': raise ValueError('Invalid parent inventory path') if digest(parent / relative) != expected: raise ValueError('Parent source changed: ' + name) entries[name] = expected current = {str(path.relative_to(root)): digest(path) for path in sorted((root / 'source').rglob('*')) if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'} removed = sorted(entries.keys() - current.keys()) changed = {name: {'before': entries.get(name), 'after': value} for name, value in current.items() if entries.get(name) != value} if removed or set(changed) != set(allowed): raise ValueError('Reviewed source delta differs: ' + json.dumps( {'removed': removed, 'actual_changes': sorted(changed), 'allowed': sorted(allowed)})) snapshot = root / 'REPAIR_V2_PARENT_SHA256SUMS' if snapshot.exists(): raise FileExistsError('Parent snapshot already exists') snapshot.write_bytes(raw) inventory = ''.join(value + ' ' + name + '\n' for name, value in sorted(current.items())) receipt = dict(schema='rhg.repair-v2-source-revision.v1', parent=str(parent), parent_inventory_sha256=hashlib.sha256(raw).hexdigest(), source_changes=changed, removed_files=removed, inventory_sha256=hashlib.sha256(inventory.encode()).hexdigest(), implementation_sha256={str(p.relative_to(root)): digest(p) for p in sorted(root.rglob('*.py')) if not any(part in {'inputs', 'runtime_site', 'supervisor_site', 'vendor', 'runs', 'evidence', '__pycache__'} for part in p.relative_to(root).parts)}, qualification_claimed=False) (root / 'BASE_SHA256SUMS').write_text(inventory) receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + '\n') return receipt if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', required=True, type=Path) parser.add_argument('--parent', required=True, type=Path) parser.add_argument('--allow', action='append', default=[]) args = parser.parse_args() print(json.dumps(freeze(args.root, args.parent, args.allow), indent=2))