source_identity.py 1.5 KB

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