# Released under the MIT License. See LICENSE for details.#"""A system for sanity testing parallel build isolation."""from__future__importannotationsfromtypingimportTYPE_CHECKINGimportosifTYPE_CHECKING:fromtypingimportAnyLOCK_DIR_PATH='.cache/buildlocks'
[docs]classBuildLock:"""Tries to ensure a build is not getting stomped on/etc."""def__init__(self,name:str,projroot:str)->None:self.name=nameself.projroot=projrootif'/'innameor'\\'inname:raiseValueError(f"Illegal BuildLock name: '{name}'.")self.lockpath=os.path.join(self.projroot,LOCK_DIR_PATH,name)def__enter__(self)->None:lockdir=os.path.dirname(self.lockpath)ifnotos.path.exists(lockdir):os.makedirs(lockdir,exist_ok=True)# Note: we aren't doing anything super accurate/atomic here.# This is more intended as a gross check to make noise on# clearly broken build logic; it isn't important that it catch# every corner case perfectly.ifos.path.exists(self.lockpath):raiseRuntimeError(f"Build-lock: lock '{self.name}' exists."' This probably means multiple builds'' are running at once that should not be.')withopen(self.lockpath,'w',encoding='utf-8')asoutfile:outfile.write('')def__exit__(self,exc_type:Any,exc_value:Any,traceback:Any)->Any:ifnotos.path.exists(self.lockpath):raiseRuntimeError(f"Build-lock: lock '{self.name}' not found at tear-down.")os.unlink(self.lockpath)