main
John Lauer Improve 48 reference labels with preserved copper and native DRC; document saved-file fallback and review clips a4a06ac
#!/usr/bin/env python3
"""Create an isolated saved-file label candidate; preserve all other bytes."""
import copy, hashlib, json, math, re, shutil
from pathlib import Path
from sexp import parse,find,first

ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'design/silkscreen-review'
source=ROOT/'kicad/adom-custom-electronic-load.kicad_pcb'
raw=source.read_bytes();text=raw.decode()
board=parse(text);proposal=json.loads((OUT/'candidate-fields.json').read_text())
updates={r['id']:r for r in proposal['update']}
lookup={}
for f in find(board,'footprint'):
    a=first(f,'at');x,y=map(float,a[1:3]);angle=float(a[3]) if len(a)>3 else 0
    for p in find(f,'property'):
        u=first(p,'uuid')
        if u and u[1] in updates:lookup[u[1]]=(x,y,angle,p)
assert set(lookup)==set(updates)
# Balanced list spans, respecting quoted parentheses/escaped quotes.
stack=[];spans=[]
for match in re.finditer(r'"(?:\\.|[^"\\])*"|[()]',text):
    if match.group()=='(':stack.append(match.start())
    elif match.group()==')':
        start=stack.pop()
        if text.startswith('(property ',start):spans.append((start,match.end()))
edits=[]
for start,end in spans:
    fragment=text[start:end];u=re.search(r'\(uuid "([^"]+)"\)',fragment)
    if not u or u[1] not in updates:continue
    row=updates[u[1]];x,y,angle,p=lookup[u[1]]
    assert p[1] in ('Reference','Value')
    theta=math.radians(angle);dx=row['x']-x;dy=row['y']-y
    lx=dx*math.cos(theta)-dy*math.sin(theta);ly=dx*math.sin(theta)+dy*math.cos(theta)
    fragment,n=re.subn(r'\(at\s+[^()]+\)',f'(at {lx:.9g} {ly:.9g} {row["rotation"]:.9g})',fragment,count=1);assert n==1
    fragment,n=re.subn(r'\(size\s+[^()]+\)',f'(size {row["height"]:.9g} {row["width"]:.9g})',fragment,count=1);assert n==1
    edits.append((start,end,fragment))
assert len(edits)==len(updates)
for start,end,replacement in sorted(edits,reverse=True):text=text[:start]+replacement+text[end:]
new=parse(text)
def neutralize(b):
    b=copy.deepcopy(b)
    for f in find(b,'footprint'):
        for p in find(f,'property'):
            u=first(p,'uuid')
            if u and u[1] in updates:
                p[:]=['reviewed-field',u[1]]
    return b
assert neutralize(board)==neutralize(new),'Unrelated board data changed'
candidate=ROOT/'kicad/silkscreen-candidate.kicad_pcb';candidate.write_bytes(text.encode())
for suffix in ('.kicad_pro','.kicad_dru'):
    shutil.copyfile(source.with_suffix(suffix),candidate.with_suffix(suffix))
report=dict(status='isolated-saved-file-candidate',sourceSha256=hashlib.sha256(raw).hexdigest(),candidateSha256=hashlib.sha256(candidate.read_bytes()).hexdigest(),fieldCount=len(edits),onlySpecifiedPropertiesChanged=True,nativeDRCRequired=True,liveBoardChanged=False)
(OUT/'saved-candidate-review.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))