367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
53 lines
2.3 KiB
Python
53 lines
2.3 KiB
Python
"""Content-addressed local compiler cache with compiler-reported dependencies."""
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import shlex
|
|
import subprocess
|
|
|
|
|
|
def write_changed(path,text):
|
|
if not path.exists() or path.read_text()!=text:path.write_text(text)
|
|
|
|
|
|
class Cache:
|
|
def __init__(self,compiler):
|
|
self.version=subprocess.check_output([compiler,'--version'])
|
|
self.hashes={}
|
|
self.compiled=0
|
|
|
|
def digest(self,path):
|
|
path=Path(path)
|
|
if path not in self.hashes:self.hashes[path]=hashlib.sha256(path.read_bytes()).hexdigest()
|
|
return self.hashes[path]
|
|
|
|
def signature(self,command,inputs):
|
|
return hashlib.sha256(self.version+json.dumps([command,[(str(p),self.digest(p)) for p in inputs]],sort_keys=True).encode()).hexdigest()
|
|
|
|
def compile(self,flags,source,obj):
|
|
dep=obj.with_suffix('.d');record=obj.with_suffix('.cache.json')
|
|
command=[*flags,'-MMD','-MF',str(dep),'-c',str(source),'-o',str(obj)]
|
|
if record.exists() and obj.exists():
|
|
old=json.loads(record.read_text())
|
|
inputs=[Path(p) for p in old['inputs']]
|
|
if all(p.exists() for p in inputs) and self.signature(command,inputs)==old['signature'] and self.digest(obj)==old['object']:
|
|
return obj
|
|
# The prior executable is retained until every compile and link succeeds.
|
|
subprocess.run(command,check=True)
|
|
inputs=sorted({Path(p) for p in shlex.split(dep.read_text().replace('\\\n',' ').split(':',1)[1])})
|
|
self.hashes.pop(obj,None)
|
|
record.write_text(json.dumps({'inputs':list(map(str,inputs)),'signature':self.signature(command,inputs),'object':self.digest(obj)},sort_keys=True))
|
|
self.compiled+=1
|
|
return obj
|
|
|
|
def link(self,command,inputs,executable):
|
|
record=executable.with_suffix('.link.json');signature=self.signature(command,inputs)
|
|
if record.exists() and executable.exists():
|
|
old=json.loads(record.read_text())
|
|
if old['signature']==signature and old['executable']==self.digest(executable):return False
|
|
subprocess.run(command,check=True)
|
|
executable.with_suffix('.new').replace(executable)
|
|
self.hashes.pop(executable,None)
|
|
record.write_text(json.dumps({'signature':signature,'executable':self.digest(executable)}))
|
|
return True
|