"""Read Git identity or the existing exported workspace snapshot metadata.""" from pathlib import Path import hashlib,json,re,subprocess def source_identity(root: Path) -> dict: root=Path(root).resolve() if (root/'.git').exists(): def git(*args): return subprocess.check_output(['git',*args],cwd=root,text=True).strip() dirty=git('status','--porcelain') return {'source_kind':'git','commit':git('rev-parse','HEAD'),'tree':git('rev-parse','HEAD^{tree}'), 'branch':git('branch','--show-current'),'clean':not dirty,'git_status':dirty} path=root/'WORKSPACE-SNAPSHOT.json' if not path.is_file(): raise ValueError('source has neither a Git checkout nor WORKSPACE-SNAPSHOT.json') data=json.loads(path.read_text(encoding='utf-8')) if data.get('schema')!='prod2u-workspace-snapshot-v1': raise ValueError('exported workspace identity schema mismatch') matches=[x for x in data.get('repos',[]) if x.get('name')=='cpld-temperature-control'] if len(matches)!=1 or any(not re.fullmatch(r'[0-9a-f]{40}',str(matches[0].get(k,''))) for k in ('commit','tree')): raise ValueError('exported CPLD commit/tree identity is missing or ambiguous') return {'source_kind':'exported','commit':matches[0]['commit'],'tree':matches[0]['tree'], 'branch':None,'clean':None,'git_status':None,'snapshot_id':data.get('snapshot_id'), 'identity_file_sha256':hashlib.sha256(path.read_bytes()).hexdigest()}