am-freescan/scripts/verify_source_integrity.py

56 lines
2.0 KiB
Python
Raw Normal View History

2026-10-22 16:18:37 +08:00
"""Fingerprint the three read-only migration sources without writing into them."""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
SOURCES = [
Path('E:/workspace/frontend/cmvr-iot-frontend/CMVR-AIMA'),
Path('E:/workspace/frontend/cmvr-iot-frontend/cmvr-iot-common'),
Path('E:/workspace/backend/CMVR-IOT'),
]
BASELINE = ROOT / '.local/cmvr-source-integrity.json'
def snapshot(folder):
names = subprocess.check_output(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], cwd=folder)
files = {}
for name in names.decode('utf-8').split('\0'):
if not name:
continue
path = folder / name
if path.is_file():
with path.open('rb') as stream:
files[name] = hashlib.file_digest(stream, 'sha256').hexdigest()
return files
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--record', action='store_true')
args = parser.parse_args()
actual = {str(path): snapshot(path) for path in SOURCES}
if args.record:
if BASELINE.exists():
raise SystemExit('Baseline already exists; refusing to replace the original evidence')
BASELINE.parent.mkdir(exist_ok=True)
BASELINE.write_text(json.dumps(actual, ensure_ascii=False), encoding='utf-8')
print(json.dumps({'recorded': {key: len(value) for key, value in actual.items()}}))
return
before = json.loads(BASELINE.read_text(encoding='utf-8'))
differences = {}
for root in before.keys() | actual.keys():
first, second = before.get(root, {}), actual.get(root, {})
changed = [name for name in first.keys() | second.keys() if first.get(name) != second.get(name)]
if changed:
differences[root] = changed
print(json.dumps({'unchanged': not differences, 'differences': differences}, ensure_ascii=False))
if differences:
raise SystemExit(1)
if __name__ == '__main__':
main()