by adom
Publish molecule sources to the Adom wiki (STEP, board, schematic, <slug>-fab.zip, export.json); the wiki's 3D model registry builds the GLB, footprint and symbol. Checks the bundle the way the registry does, publishes private, waits for the build, sets the hero from the built model, then makes the page public. Board mode still converts plain boards. Also writes APM render assets and component dependencies. Companion to adom-wiki model import.
master
AdityaAngajala
Publish 3.1.0
c9dc94a
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
"""Machine pins and contacts by reference designator: rule adom.molecule-pins/2.
A census of a board file's through-hole parts, classified as molecule-metadata-importer
1e045f7 classifies their pads, and the checks the rule applies to it. The values of the
rule (designator patterns, drill buckets, length words, library model lengths, furniture
names, machine pin counts, message templates) are pins.json; this file is the one
implementation of it.
Classification. A pad whose round hole is within drillToleranceMm of a drill bucket is a
medium or large contact or pin hole. A pin hole has a length when the part's hint holds a
length word (KiCad: footprint name and 3D model path; Fusion/EAGLE .brd: package name;
circuit JSON: the component's metadata, CAD record and part number) or, failing that, its
3D model file is one of libraryModelLengths.
Parts. A part with a pin hole and a length is a machine pin when it is named
designators.machinePin (MP1 to MP4), and an extra machine pin when it is named
designators.extraMachinePin (MS<n>): not one of the machine pins the build publishes, left
out as a part the census warns about is, though without a warning. It is refused when its
name is a machine pin's in the wrong case, or MP<n> outside 1 to 4; named anything else it
is not a machine pin, and the build warns. A single-pad part with a contact hole is a machine contact when it is named
designators.machineContact; it is refused when its name is in the wrong case or a machine
pin's (MP<n>), and warned about when named anything else. A multi-pad part with contact
holes is a group, warned about, unless it is named or packaged as furniture (nearMiss,
furniturePackages), when it is read as a contact. A pin hole without a length is warned
about on furniture, on a part named like a machine pin, and on any single-pad part; on any
other part it is listed as ignored. Furniture with no hole on the table is warned about.
Machine pins and contacts the build keeps have unique designators; a board has
machinePinCounts machine pins (two or four), all of one size and length with its extra
machine pins, and no extra machine pin lies further out than the machine pins toward any
corner (extraPinRule). A KiCad
test-point footprint on the front is a test point when named designators.testPoint, and
warned about otherwise; on .brd and circuit JSON a part named designators.testPoint is
one, and is not imported.
The build keeps what the census accepts (census accepted) and nothing else: metadata.mjs
filters the importer's machine pins, contacts and test points to those designators, so the
census and the importer agree pad for pad (compare).
An Altium .PcbDoc is read through the KiCad board pcbdoc.py (beside this file) writes from
it. A Fusion .fbrd is a zip; a Fusion PCB document holds its board as EAGLE XML
(electron.BlobParts/ExtFile.<id>.brd), which is read as a .brd.
Python 3.9 or newer, standard library only. Nothing in a board's contents raises: a file
that cannot be read becomes the failed check board-read.
A folder is read as a molecule page's repository: its board file is the one the recipes of
contract.json select for the page slug (--slug, default the folder's name), with its route.
names.py check <board file or folder> [--slug slug] [--route circuit|board] [--pins pins.json] [--contract contract.json] [--json]
names.py self-check [contract.json]
"""
import collections, fnmatch, hashlib, importlib.util, json, math, re, sys, tempfile, zipfile
import xml.etree.ElementTree as ET
from pathlib import Path, PurePosixPath
HERE = Path(__file__).resolve().parent
SCHEMA = 'adom.molecule-pins/2'
FAILS = ('board-read', 'pin-names', 'contact-names', 'hole-sizes', 'pin-count', 'corner-pins', 'designators-unique', 'pins-uniform')
# The four diagonals the corner rule compares along, with the corner each points to (y up).
CORNERS = (((-1, -1), 'front-left'), ((1, -1), 'front-right'), ((-1, 1), 'back-left'), ((1, 1), 'back-right'))
FORMATS = {'kicad_pcb': 'a KiCad board', 'brd': 'a Fusion/EAGLE .brd board', 'circuit_json': 'a tscircuit circuit.json', 'pcbdoc': 'an Altium board',
'fbrd': 'a Fusion .fbrd board'}
FBRD_BOARD = re.compile(r'(^|/)electron\.BlobParts/ExtFile\.[^/]+\.brd$')
DETAIL_MAX = 700
PIN_BUCKETS = ('mediumPin', 'largePin')
def pins_path(path=None):
"""pins.json: `path`, else beside this file, else vendor/molecule-contract/ below it."""
if path:
return Path(path)
for p in (HERE / 'pins.json', HERE / 'vendor/molecule-contract/pins.json'):
if p.is_file():
return p
raise FileNotFoundError('pins.json is neither beside names.py nor in vendor/molecule-contract/')
def contract_path(path=None):
"""contract.json: `path`, else beside this file, else vendor/molecule-contract/ below it."""
if path:
return Path(path)
for p in (HERE / 'contract.json', HERE / 'vendor/molecule-contract/contract.json'):
if p.is_file():
return p
raise FileNotFoundError('contract.json is neither beside names.py nor in vendor/molecule-contract/')
def _rx(spec):
return re.compile(spec['pattern'], re.I if 'i' in spec.get('flags', '') else 0)
class Rule:
"""pins.json, read and compiled. `sha256` is the hash of its bytes."""
def __init__(self, path=None):
raw = pins_path(path).read_bytes()
doc = json.loads(raw)
if doc.get('schema') != SCHEMA:
raise ValueError(f'pins.json is not {SCHEMA}')
self.doc, self.sha256 = doc, hashlib.sha256(raw).hexdigest()
d = doc['designators']
self.mp, self.mpn, self.ms, self.mc, self.tp, self.near = (_rx(d[k]) for k in ('machinePin', 'machinePinNumbered', 'extraMachinePin', 'machineContact', 'testPoint', 'nearMiss'))
self.corner_tol = doc['cornerToleranceMm']
self.buckets = [(k, v) for k in ('mediumContact', 'mediumPin', 'largeContact', 'largePin') for v in doc['drillBucketsMm'][k]]
self.tol = doc['drillToleranceMm']
self.words = doc['lengthWords']
self.models = {k.lower(): v for k, v in doc['libraryModelLengths']['models'].items()}
self.globs = [g.lower() for g in doc['furniturePackages']]
self.counts = doc['machinePinCounts']
self.msg = doc['messages']
def bucket(self, d):
if d is None:
return None
return next((k for k, v in self.buckets if abs(d - v) < self.tol), None)
def length(self, part):
"""(length, source): 'short' or 'standard' from a length word in the part's hint
(source 'hint'), else from libraryModelLengths by its 3D model's file name (source
'libraryModel'), else (None, None)."""
h = (part.get('hint') or '').lower()
for k in ('short', 'standard'):
if any(w in h for w in self.words[k]):
return k, 'hint'
name = PurePosixPath((part.get('model') or '').replace('\\', '/')).name.lower()
return (self.models[name], 'libraryModel') if name in self.models else (None, None)
def furniture(self, part):
if self.near.fullmatch(part['designator']):
return True
names = [part['package'], PurePosixPath(part.get('model', '').replace('\\', '/')).name]
return any(fnmatch.fnmatchcase(n.lower(), g) for n in names if n for g in self.globs)
# ---------------------------------------------------------------- readers
# Each returns parts: {designator, package (after its last ':'), model, hint, pads [{drill, oval}],
# at (x, y) mm, testpoint (None, 'front' or 'back')}, read the way the importer reads the file.
_NUM = re.compile(r'\s*[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?')
def _float(v):
"""JavaScript parseFloat: the longest leading number, else None."""
m = _NUM.match(v) if isinstance(v, str) else None
return float(m.group()) if m else None
def _number(v):
"""JavaScript Number() as safeNumber uses it: a whole numeric string, else 0."""
try:
n = float((v or '').strip() or 0)
except ValueError:
return 0.0
return n if math.isfinite(n) else 0.0
_TOK = re.compile(r'[()]|(?:[^ \t\r\n()"]+|"[^"]*"?)+')
def _sexpr(text):
# The importer's tokenizer: a double quote toggles quoting, with no escapes.
stack = [[]]
for m in _TOK.finditer(text):
t = m.group()
if t == '(':
stack.append([])
elif t == ')':
if len(stack) > 1:
x = stack.pop(); stack[-1].append(x)
else:
stack[-1].append(t[1:-1] if len(t) >= 2 and t[0] == t[-1] == '"' else t)
while len(stack) > 1:
x = stack.pop(); stack[-1].append(x)
return stack[0][0] if stack[0] and isinstance(stack[0][0], list) else []
def _s(x, i):
return x[i] if isinstance(x, list) and i < len(x) and isinstance(x[i], str) else ''
def _first(x, key):
return next((e for e in x if isinstance(e, list) and e and e[0] == key), None)
def _all(x, key):
out = []
for e in x:
if isinstance(e, list):
if e and e[0] == key:
out.append(e)
out.extend(_all(e, key))
return out
def read_kicad(text):
root = _sexpr(text)
if _s(root, 0) != 'kicad_pcb':
raise ValueError('it is not a KiCad PCB (no kicad_pcb root expression)')
parts = []
for fp in (e for e in root if isinstance(e, list) and e and e[0] == 'footprint'):
name = _s(fp, 1)
props = {_s(p, 1): _s(p, 2) for p in _all(fp, 'property') if len(p) >= 3}
if not props:
for t in _all(fp, 'fp_text'):
if len(t) >= 3 and _s(t, 1) in ('reference', 'value'):
props[_s(t, 1).capitalize()] = _s(t, 2)
at = _first(fp, 'at') or []
text_of = lambda k: _s(_first(fp, k) or [], 1)
model = text_of('model')
pads = []
for p in _all(fp, 'pad'):
if len(p) < 4:
continue
dr = _first(p, 'drill') or []
pads.append({'number': _s(p, 1), 'drill': _float(_s(dr, 1)) if len(dr) >= 2 else None, 'oval': _s(dr, 1) == 'oval'})
tp = 'test point' in f"{text_of('descr')} {text_of('tags')} {props.get('Description', '')}".lower()
parts.append({'designator': props.get('Reference') or name.split(':')[-1] or name, 'package': name.split(':')[-1], 'footprint': name,
'model': model, 'hint': f'{name} {model}'.strip(), 'pads': pads,
'at': (_float(_s(at, 1)) or 0.0, -(_float(_s(at, 2)) or 0.0)),
'testpoint': ('front' if text_of('layer').startswith('F.') else 'back') if tp else None})
return parts
def read_brd(text):
root = ET.fromstring(text)
board = root.find('./drawing/board') if root.tag == 'eagle' else None
if board is None:
raise ValueError('it is not a Fusion/EAGLE board (no eagle/drawing/board element)')
libs = {}
for lib in board.findall('./libraries/library'):
libs[lib.get('name') or ''] = {pk.get('name') or '': [{'number': p.get('name') or '', 'drill': _number(p.get('drill')), 'oval': False}
for p in pk.findall('pad')] for pk in lib.findall('./packages/package')}
parts = []
for el in board.findall('./elements/element'):
pads = libs.get(el.get('library') or '', {}).get(el.get('package') or '')
if pads is None:
continue
pkg = el.get('package') or ''
parts.append({'designator': el.get('name') or '', 'package': pkg.split(':')[-1], 'footprint': pkg, 'model': '', 'hint': pkg, 'pads': pads,
'at': (_number(el.get('x')), _number(el.get('y'))), 'testpoint': None})
return parts
def read_circuit(text):
a = json.loads(text)
if not isinstance(a, list):
raise ValueError('it is not a circuit JSON array')
a = [e for e in a if isinstance(e, dict)]
first = lambda kind, key, value: next((e for e in a if e.get('type') == kind and e.get(key) == value), None)
by_part = collections.OrderedDict()
for h in a:
if h.get('type') == 'pcb_plated_hole':
by_part.setdefault(h.get('pcb_component_id', ('hole', id(h))), []).append(h)
smt = collections.Counter(e.get('pcb_component_id') for e in a if e.get('type') == 'pcb_smtpad')
parts = []
for key, holes in by_part.items():
cid = key if not isinstance(key, tuple) else None
c = first('pcb_component', 'pcb_component_id', cid) if cid is not None else None
# The importer's lookups, including those of a hole without a component.
sc = first('source_component', 'source_component_id', (c or {}).get('source_component_id'))
cad = first('cad_component', 'pcb_component_id', (c or {}).get('pcb_component_id'))
hint = json.dumps([(c or {}).get('metadata'), cad, (sc or {}).get('manufacturer_part_number')], separators=(',', ':'), ensure_ascii=False)
url = next((v for k, v in (cad or {}).items() if k.startswith('model_') and k.endswith('_url') and isinstance(v, str)), '')
meta = (((c or {}).get('metadata') or {}).get('kicad_footprint') or {}) if isinstance((c or {}).get('metadata'), dict) else {}
desc = ((meta.get('properties') or {}).get('Description') or {}).get('value') if isinstance(meta.get('properties'), dict) else None
model = PurePosixPath(url.split('?')[0]).name if url and not url.startswith('data:') else ''
package = next((str(v) for v in (desc, PurePosixPath(model).stem if model else None, (sc or {}).get('manufacturer_part_number'), (sc or {}).get('ftype')) if v), '')
pads = [{'number': str((h.get('port_hints') or ['1'])[-1]), 'drill': h['hole_diameter'] if isinstance(h.get('hole_diameter'), (int, float)) and not isinstance(h.get('hole_diameter'), bool) and math.isfinite(h['hole_diameter']) else None, 'oval': False} for h in holes]
centre = (c or {}).get('center') or {'x': holes[0].get('x', 0), 'y': holes[0].get('y', 0)}
parts.append({'designator': str((sc or {}).get('name') or ''), 'package': package.split(':')[-1], 'footprint': package, 'model': model, 'hint': hint,
'pads': pads + [{'number': '', 'drill': None, 'oval': False}] * smt.get(cid, 0) if cid is not None else pads,
'at': (centre.get('x', 0), centre.get('y', 0)), 'testpoint': None})
# Components without plated holes count only as names (test points).
named = {p['designator'] for p in parts}
parts += [{'designator': str(e.get('name') or ''), 'package': '', 'model': '', 'hint': '', 'pads': [], 'at': (0, 0), 'testpoint': None, 'nameOnly': True}
for e in a if e.get('type') == 'source_component' and str(e.get('name') or '') not in named]
return parts
def board_format(path):
n = PurePosixPath(str(path).replace('\\', '/')).name.lower()
if n == 'circuit.json' or n.endswith('.circuit.json'):
return 'circuit_json'
return {'.kicad_pcb': 'kicad_pcb', '.brd': 'brd', '.pcbdoc': 'pcbdoc', '.fbrd': 'fbrd'}.get(PurePosixPath(n).suffix)
# ---------------------------------------------------------------- census
def _natural(name):
return [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', name)]
def _list(names, show=6, order=True):
names = sorted((n or '(unnamed)' for n in names), key=_natural) if order else [n or '(unnamed)' for n in names]
return ', '.join(names) if len(names) <= show else ', '.join(names[:show]) + f' and {len(names) - show} more'
def _say(rule, key, count, **values):
"""The message `key` of pins.json, in its singular form (key + 'One') when count is 1."""
return rule.msg[key + 'One' if count == 1 and key + 'One' in rule.msg else key].format(count=count, **values)
def _uniq(values):
out = []
for v in values:
if v not in out:
out.append(v)
return out
def _mm(d):
return 'no' if d is None else f'{d:.2f}'
def _cap(text, end=''):
body = text if not end else text + ' ' + end
if len(body) <= DETAIL_MAX:
return body
keep = DETAIL_MAX - (len(end) + 4 if end else 3)
return text[:keep].rstrip() + '...' + (' ' + end if end else '')
def read_pcbdoc(path):
"""The KiCad board text pcbdoc.py, beside this file, writes from the Altium board `path`."""
spec = importlib.util.spec_from_file_location('pcbdoc', HERE / 'pcbdoc.py')
if spec is None or not (HERE / 'pcbdoc.py').is_file():
raise ValueError('pcbdoc.py, the Altium reader, is not beside names.py')
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
with tempfile.TemporaryDirectory() as d:
out = Path(d) / 'board.kicad_pcb'
mod.convert(str(path), str(out))
return out.read_text(encoding='utf-8')
def read_fbrd(path):
"""The EAGLE board text the Fusion .fbrd `path` holds: the one zip member
electron.BlobParts/ExtFile.<id>.brd of a Fusion PCB document."""
try:
with zipfile.ZipFile(path) as z:
hits = [n for n in z.namelist() if FBRD_BOARD.search(n)]
if len(hits) != 1:
kinds = sorted({n.split('/')[0] for n in z.namelist() if '/' in n})
raise ValueError(f"it holds {len(hits)} EAGLE boards ({', '.join(kinds) or 'no Fusion asset'}), where a Fusion PCB document "
'holds one; export the board from Fusion as an EAGLE .brd and push it beside the STEP')
return z.read(hits[0]).decode('utf-8', errors='replace')
except zipfile.BadZipFile as e:
raise ValueError(f'it is not a zip, as Fusion saves a .fbrd: {e}') from None
def census(path, route, rule, text=None, role=None, repo_path=None, kicad=None):
"""The census of the board file `path`. `route` ('circuit', 'board') is the page's; the
rule is the same on both. An Altium board is read as the KiCad board `kicad` that
pcbdoc.py wrote from it, or, without one, as the board read_pcbdoc() writes; a Fusion
.fbrd as the EAGLE board read_fbrd() takes from it.
Returns {report, checks, attachments, accepted, positions, designators}: report is the census (report.names of
the molecule report), checks are [{id, level, pass, detail}] with level fail, warn or
info, in the order FAILS then warnings then info, attachments are the census's machine
pins and contacts as [(kind, designator, package, hole)], kind 'machinePin' or
'contact', one per pad the build keeps, and accepted is {machinePins, contacts,
testPoints, lengths}: the designators the build keeps of each, in board order, and the
lengths of kept pins taken from libraryModelLengths ({designator: length}), which
importer_board() writes into the board the importer reads. positions is
{pins, warned}: the board position [x, y] of each kept machine pin by designator, and
[{designator, class, at}] for each one-pad machine pin or contact the census warns about and
leaves out, at its board position; metadata.mjs maps the second into the importer's frame by
the first. designators is every part's designator on the board, in natural order; it is
missing when the board was not read.
"""
fmt = board_format(path)
src = {'role': role or ('circuit' if fmt == 'circuit_json' else 'board'), 'path': repo_path or PurePosixPath(str(path).replace('\\', '/')).name, 'format': fmt}
base = {'rule': SCHEMA, 'ruleSha256': rule.sha256}
none = {'machinePins': [], 'contacts': [], 'testPoints': [], 'lengths': {}}
if fmt not in ('kicad_pcb', 'brd', 'circuit_json', 'pcbdoc', 'fbrd'):
return {'report': {**base, 'applies': False, 'reason': 'no board file the build can read', 'source': src}, 'checks': [], 'attachments': [], 'accepted': none}
end = rule.msg['refusalEnd']
try:
if fmt == 'pcbdoc':
src['readAs'] = 'kicad_pcb'
text = Path(kicad).read_bytes().decode('utf-8', errors='replace') if kicad else read_pcbdoc(path)
elif fmt == 'fbrd':
src['readAs'] = 'brd'
text = read_fbrd(path) if text is None else text
elif text is None:
text = Path(path).read_bytes().decode('utf-8', errors='replace')
parts = {'kicad_pcb': read_kicad, 'pcbdoc': read_kicad, 'brd': read_brd, 'fbrd': read_brd, 'circuit_json': read_circuit}[fmt](text)
except (ValueError, ET.ParseError, RecursionError, OSError) as e:
why = str(e).splitlines()[0][:200] if str(e) else type(e).__name__
detail = _cap(rule.msg['boardRead'].format(file=src['path'], reason=why.rstrip('.')), end)
return {'report': {**base, 'applies': True, 'source': src, 'error': detail}, 'checks': [{'id': 'board-read', 'level': 'fail', 'pass': False, 'detail': detail}], 'attachments': [], 'accepted': none}
kicad_like = fmt in ('kicad_pcb', 'pcbdoc')
hole = lambda group: None if not group or group[0][0]['oval'] else group[0][0]['drill']
size = lambda group: 'large' if group[0][1] == 'largePin' else 'medium'
rows, atts, non_attachments = [], [], []
for part in parts:
des, pkg = part['designator'], part['package']
if part.get('nameOnly'):
continue
row = {'designator': des, 'package': pkg, 'holeMm': None, 'pads': len(part['pads']), 'class': None, 'result': None, 'at': part['at'], 'shown': part.get('footprint') or pkg}
if part['testpoint']:
named = bool(rule.tp.fullmatch(des))
row.update(result='ignored' if part['testpoint'] == 'back' else 'ok' if named else 'warned', **{'class': 'test-point'})
if row['result'] == 'warned':
row['reason'] = 'not-named'
rows.append(row)
continue
pins, contacts, dropped, off = [], [], [], []
length, length_from = rule.length(part)
furniture = rule.furniture(part)
# A jumper is an ordinary component even when its old 0.81 mm holes are
# outside the contact buckets. Its STEP contact body can sit at the part
# origin; record that origin without publishing a machine attachment.
jumper = bool(re.search(r'jumper', pkg, re.I) or re.fullmatch(r'JP[0-9]+', des))
if jumper and not furniture and len(part['pads']) >= 2 and all(
not p['oval'] and p['drill'] is not None and p['drill'] > 0 and
rule.bucket(p['drill']) not in PIN_BUCKETS for p in part['pads']):
non_attachments.append({'designator': des, 'class': 'jumper', 'at': list(part['at'])})
for pad in part['pads']:
b = rule.bucket(pad['drill'])
if b in PIN_BUCKETS:
(pins if length else dropped).append((pad, b))
elif b:
contacts.append((pad, b))
elif pad['drill'] is not None or pad['oval']:
off.append((pad, None))
lower = bool(rule.near.fullmatch(des)) and des[:2] not in ('MP', 'MC')
numbered = bool(rule.mpn.fullmatch(des))
extra = bool(rule.ms.fullmatch(des))
single = len(part['pads']) == 1
if pins:
row.update(holeMm=hole(pins), size=size(pins), length=length, **{'class': 'machine-pin'})
if length_from == 'libraryModel':
row['lengthFrom'] = length_from
if rule.mp.fullmatch(des):
row['result'] = 'ok'
elif extra:
row['result'] = 'extra'
else:
row.update(result='refused' if lower or numbered else 'warned', reason='lowercase' if lower else 'outside-mp1-mp4' if numbered else 'not-named')
elif contacts and not single and not furniture:
row.update(holeMm=hole(contacts), result='group', **{'class': 'group'})
elif contacts:
row.update(holeMm=hole(contacts), **{'class': 'machine-contact'})
if rule.mc.fullmatch(des):
row['result'] = 'ok'
else:
row.update(result='refused' if lower or numbered else 'warned', reason='lowercase' if lower else 'pin-name' if numbered else 'not-named')
elif dropped and (furniture or numbered or lower or extra):
row.update(holeMm=hole(dropped), size=size(dropped), result='warned', reason='no-length', **{'class': 'machine-pin'})
elif dropped and single:
row.update(holeMm=hole(dropped), size=size(dropped), result='warned', reason='not-named', **{'class': 'machine-pin'})
elif dropped:
row.update(holeMm=hole(dropped), result='ignored')
elif furniture:
# Named MP<n>, MC<n> or MS<n> on a round hole of no listed size (an older library drill):
# refused. Its name is checked too (nameReason), so one export fixes both.
pinlike = not (des.upper().startswith('MC') or 'contact' in f"{pkg} {part['model']}".lower())
reason = 'no-hole' if not off else 'slot' if hole(off) is None else 'hole-off-table'
refused = reason == 'hole-off-table' and bool(rule.near.fullmatch(des) or extra and pinlike)
row.update(holeMm=hole(off), result='refused' if refused else 'warned', reason=reason,
**{'class': 'machine-pin' if pinlike else 'machine-contact'})
if refused and (lower or numbered and not (pinlike and rule.mp.fullmatch(des))):
row['nameReason'] = 'lowercase' if lower else 'outside-mp1-mp4' if pinlike else 'pin-name'
else:
continue
if length_from == 'libraryModel' and row['class'] == 'machine-pin':
row['inject'] = length
if row['result'] == 'ok':
kind, group = ('machinePin', pins) if row['class'] == 'machine-pin' else ('contact', contacts)
atts += [(kind, des, row['shown'], p['drill']) for p, b in group]
rows.append(row)
kept = [r for r in rows if r['result'] in ('ok', 'extra') and r['class'] in ('machine-pin', 'machine-contact')]
seen = collections.Counter(r['designator'] for r in kept)
dups = collections.OrderedDict()
for r in kept:
if seen[r['designator']] > 1:
dups.setdefault(r['designator'], []).append(r)
r.update(result='refused', reason='duplicate')
atts = [a for a in atts if a[1] not in dups]
pin_rows = [r for r in rows if r['class'] == 'machine-pin']
contact_rows = [r for r in rows if r['class'] == 'machine-contact']
good_pins = [r for r in pin_rows if r['result'] == 'ok']
extras = [r for r in pin_rows if r['result'] == 'extra']
good_contacts = [r for r in contact_rows if r['result'] == 'ok']
checks = []
add = lambda id, level, ok, detail: checks.append({'id': id, 'level': level, 'pass': ok, 'detail': _cap(detail, end if level == 'fail' and not ok else '')})
names_of = lambda rs: _list([r['designator'] for r in rs])
because = lambda rs, reason: [r for r in rs if reason in (r.get('reason'), r.get('nameReason'))]
# Refusals: names, the number of machine pins, repeated designators, mixed pins.
case, outside = because(pin_rows, 'lowercase'), because(pin_rows, 'outside-mp1-mp4')
said = ([_say(rule, 'pinNumber', len(outside), parts=names_of(outside))] if outside else []) + ([_say(rule, 'designatorCase', len(case), parts=names_of(case))] if case else [])
add('pin-names', 'fail', not said, ' '.join(said) if said else f'{len(good_pins)} machine pins, each named MP1 to MP4')
case, as_pin = because(contact_rows, 'lowercase'), because(contact_rows, 'pin-name')
said = (([_say(rule, 'pinNameOnContact', len(as_pin), parts=names_of(as_pin), package=', '.join(_uniq(r['shown'] or '(none)' for r in as_pin)[:3]))] if as_pin else [])
+ ([_say(rule, 'designatorCase', len(case), parts=names_of(case))] if case else []))
add('contact-names', 'fail', not said, ' '.join(said) if said else f'{len(good_contacts)} machine contacts, each named MC<n>')
off = [r for r in rows if r['result'] == 'refused' and r.get('reason') == 'hole-off-table']
sizes = lambda *ks: ' or '.join(f"{v:.2f} mm ({k.replace('Pin', '').replace('Contact', '')})" for k in ks for v in rule.doc['drillBucketsMm'][k])
add('hole-sizes', 'fail', not off,
_say(rule, 'holeSizes', len(off), parts=_list([f"{r['designator']} ({r['shown'] or 'no package'}: {_mm(r['holeMm'])} mm)" for r in off], 4),
pins=sizes('mediumPin', 'largePin'), contacts=sizes('mediumContact', 'largeContact'), tol=f"{rule.tol:g}") if off
else 'every part named as a machine pin or contact is drilled a standard size')
n_pins = len(good_pins)
if n_pins == 0:
near = [r for r in pin_rows if r['result'] != 'ok']
found = (f'{len(near)} parts look like machine pins and are not accepted: {names_of(near)}.' if near
else '0 parts in this board are named MP<n> or use a machine-pin footprint.')
detail = rule.msg['pinNone'].format(found=found)
elif n_pins not in rule.counts:
fix = ('Add a second machine pin' if n_pins == 1 else 'Add a fourth machine pin, or remove one,' if n_pins == 3 else 'Remove the extra machine pins') + ' and export again.'
detail = _say(rule, 'pinCount', n_pins, parts=names_of(good_pins), fix=fix)
else:
detail = f'{n_pins} machine pins'
add('pin-count', 'fail', n_pins in rule.counts, detail)
# MP1 to MP4 are the outermost corner pins: along each diagonal, no MS<n> pin further out than every MP<n> pin.
beyond = collections.OrderedDict()
for (dx, dy), corner in CORNERS if good_pins else ():
reach = max(dx * r['at'][0] + dy * r['at'][1] for r in good_pins)
for r in extras:
if dx * r['at'][0] + dy * r['at'][1] > reach + rule.corner_tol:
beyond.setdefault(r['designator'], []).append(corner)
add('corner-pins', 'fail', not beyond,
rule.msg['cornerPins'].format(parts='; '.join(f"{d} lies further out than {names_of(good_pins)} toward the {' and '.join(c)} corner{'s' if len(c) > 1 else ''}"
for d, c in list(beyond.items())[:4]) + (f'; and {len(beyond) - 4} more' if len(beyond) > 4 else ''))
if beyond else 'no extra machine pins' if not extras else 'no machine pins to compare' if not good_pins
else f'{n_pins} machine pins are the outermost, beside {len(extras)} extra machine pins')
add('designators-unique', 'fail', not dups,
' '.join(_say(rule, 'duplicate', len(v), name=k, places=' and '.join(f"{round(r['at'][0], 2):g},{round(r['at'][1], 2):g}" for r in v[:4]))
for k, v in list(dups.items())[:6]) if dups
else f'{len(kept)} machine pins and contacts, no designator repeated')
kinds = collections.OrderedDict()
for r in good_pins + extras:
kinds.setdefault(f"{r['size']} {r['length']}", []).append(r['designator'])
add('pins-uniform', 'fail', len(kinds) <= 1,
rule.msg['pinsUniform'].format(groups='; '.join(f'{_list(v)} {"is" if len(v) == 1 else "are"} {k}' for k, v in kinds.items())) if len(kinds) > 1
else f'every machine pin is {next(iter(kinds))}' if kinds else 'no machine pins to compare')
# Warnings: parts that fit the standard only in part, groups, test points; then what the build leaves out.
why = {'not-named': 'not named {want}', 'no-length': 'its footprint names no length', 'hole-off-table': 'its hole is {hole} mm', 'no-hole': 'it has no drilled hole', 'slot': 'its hole is a slot'}
say_row = lambda r, want: f"{r['designator'] or '(unnamed)'} ({r['shown'] or 'no package'}: {why[r['reason']].format(want=want, hole=_mm(r['holeMm']))})"
loose = [r for r in pin_rows if r['result'] == 'warned']
if loose:
sizes = {r.get('size', 'medium') for r in loose}
one = next(iter(sizes)) if len(sizes) == 1 else None
suggest = ' or '.join(n for n in rule.doc['adomParts'] if n.startswith('MachinePin') and (one is None or one.capitalize() in n))
holes = ' or '.join(f'{v:.2f}' for k in PIN_BUCKETS if one is None or k.startswith(one) for v in rule.doc['drillBucketsMm'][k])
add('not-machine-pins', 'warn', True, _say(rule, 'notPins', len(loose), parts=_list([say_row(r, 'MP1 to MP4') for r in loose], 4, order=False), suggest=suggest, holes=holes))
loose = [r for r in contact_rows if r['result'] == 'warned']
if loose:
holes = ' or '.join(f'{v:.2f}' for k in ('mediumContact', 'largeContact') for v in rule.doc['drillBucketsMm'][k])
add('not-machine-contacts', 'warn', True, _say(rule, 'notContacts', len(loose), parts=_list([say_row(r, 'MC<n>') for r in loose], 4, order=False), holes=holes))
grouped = [r for r in rows if r['result'] == 'group']
if grouped:
shown, last = [], None
for r in sorted(grouped, key=lambda r: _natural(r['designator'])):
shown.append(r['designator'] + (f" ({r['pads']} pads)" if r['pads'] != last else ''))
last = r['pads']
add('groups', 'warn', True, _say(rule, 'groups', len(grouped), parts=_list(shown, order=False)))
named_tp = [p for p in parts if rule.tp.fullmatch(p['designator'])] if not kicad_like else []
unnamed_tp = [r for r in rows if r['class'] == 'test-point' and r['result'] == 'warned']
if named_tp or unnamed_tp:
add('test-points', 'warn', True, ' '.join(([_say(rule, 'testPoints', len(named_tp), parts=_list([p['designator'] for p in named_tp]), format=FORMATS[fmt])] if named_tp else [])
+ ([_say(rule, 'testPointNames', len(unnamed_tp), parts=names_of(unnamed_tp))] if unnamed_tp else [])))
if extras:
add('extra-pins', 'info', True, _say(rule, 'extraPins', len(extras), parts=names_of(extras)))
ignored = [r for r in rows if r['result'] == 'ignored' and r['class'] is None]
if ignored:
add('ignored', 'info', True, _say(rule, 'ignored', len(ignored), parts=_list([f"{r['designator'] or '(unnamed)'} ({r['shown'] or 'no package'}, {_mm(r['holeMm'])} mm)" for r in ignored], 4)))
accepted = {'machinePins': [r['designator'] for r in good_pins], 'contacts': _uniq(r['designator'] for r in good_contacts),
'testPoints': [r['designator'] for r in rows if r['class'] == 'test-point' and r['result'] == 'ok'],
'lengths': {r['designator']: r['inject'] for r in good_pins if r.get('inject')}}
positions = {'nonAttachments': non_attachments, 'pins': {r['designator']: list(r['at']) for r in good_pins},
'warned': [{'designator': r['designator'], 'class': r['class'], 'at': list(r['at'])} for r in rows
if r['result'] in ('warned', 'extra') and r['pads'] == 1 and r['class'] in ('machine-pin', 'machine-contact')]}
for r in rows:
r.pop('shown'); r.pop('at'); r.pop('size', None); r.pop('inject', None); r.pop('nameReason', None)
r['holeMm'] = None if r['holeMm'] is None else round(r['holeMm'], 3)
counts = {'machinePins': n_pins, 'extraMachinePins': len(extras), 'machineContacts': len(good_contacts), 'testPoints': len(accepted['testPoints']) if kicad_like else len(named_tp),
'groups': len(grouped), 'ignored': len(ignored), 'warned': sum(r['result'] == 'warned' for r in rows), 'refused': sum(r['result'] == 'refused' for r in rows)}
report = {**base, 'applies': True, 'source': src, 'anchorRule': None, 'testPointsImported': kicad_like, 'counts': counts, 'parts': rows}
designators = sorted({p['designator'] for p in parts if p['designator']}, key=_natural)
return {'report': report, 'checks': checks, 'attachments': atts, 'accepted': accepted, 'positions': positions, 'designators': designators}
def _spans(text, head):
"""(start, end) of each top-level list `(head ...)` of the KiCad board `text`, read with the
importer's tokenizer (a double quote toggles quoting, with no escapes)."""
out, depth, quoted, start = [], 0, False, None
for i, ch in enumerate(text):
if ch == '"':
quoted = not quoted
elif quoted:
continue
elif ch == '(':
depth += 1
if depth == 2 and text.startswith(head, i + 1) and not text[i + 1 + len(head):i + 2 + len(head)].isalnum():
start = i
elif ch == ')':
if depth == 2 and start is not None:
out.append((start, i + 1))
start = None
depth -= 1
return out
def _same(a, b):
return a is not None and b is not None and abs(a - b) < 1e-9
def importer_board(path, accepted, text=None, kicad=None):
"""The board text the importer reads for the board file `path` and the census's accepted
designators, or None when it is the board file's own text: for a kept pin whose length
comes from libraryModelLengths, the length word added to its 3D model path (KiCad) or CAD
record (circuit JSON), where the importer looks for it (accepted.lengths). An Altium board
is the KiCad board `kicad`, a Fusion .fbrd the EAGLE board it holds; an EAGLE board names no
3D model, so it is never rewritten."""
lengths = accepted.get('lengths') or {}
fmt = board_format(path)
if not lengths or fmt in ('brd', 'fbrd'):
return None
if text is None:
text = Path(kicad if fmt == 'pcbdoc' else path).read_bytes().decode('utf-8', errors='replace')
if fmt in ('kicad_pcb', 'pcbdoc'):
out, last = [], 0
for a, b in _spans(text, 'footprint'):
span = text[a:b]
des = read_kicad(f'(kicad_pcb {span})')[0]['designator']
if des in lengths:
span = re.sub(r'\(model\s+(?:"([^"]*)"|([^\s()"]+))', lambda m: f'(model "{m.group(1) or m.group(2)} {lengths[des]}"', span, count=1)
out += [text[last:a], span]
last = b
return ''.join(out + [text[last:]])
a = json.loads(text)
by_id = {e.get('source_component_id'): str(e.get('name') or '') for e in a if isinstance(e, dict) and e.get('type') == 'source_component'}
owner = {e.get('pcb_component_id'): by_id.get(e.get('source_component_id'), '') for e in a if isinstance(e, dict) and e.get('type') == 'pcb_component'}
for e in a:
if not isinstance(e, dict):
continue
des = owner.get(e.get('pcb_component_id'))
if e.get('type') == 'cad_component' and des in lengths:
e['adom_length_hint'] = lengths[des]
return json.dumps(a, separators=(',', ':'), ensure_ascii=False)
def compare(attachments, board, rule):
"""census-matches-metadata: [] when the census's machine pins and contacts, by designator,
are the importer's (board.machinePins and board.contacts by elementName), else the
differences as sentences."""
want = collections.Counter((k, d) for k, d, _, _ in attachments)
have = collections.Counter([('machinePin', str(p.get('elementName'))) for p in board.get('machinePins') or []] +
[('contact', str(c.get('elementName'))) for c in board.get('contacts') or []])
info = {(k, d): (p, h) for k, d, p, h in attachments}
noun = {'machinePin': ('machine pin', 'machine pins'), 'contact': ('machine contact', 'contacts')}
out = []
for (k, d), n in (want - have).items():
p, h = info[(k, d)]
out.append(f"{d} (package {p or '(none)'}, hole {_mm(h)} mm) is a {noun[k][0]} in the census and missing from the importer's {noun[k][1]}" + (f' ({n} pads)' if n > 1 else ''))
for (k, d), n in (have - want).items():
out.append(f"{d} is one of the importer's {noun[k][1]} and not in the census" + (f' ({n} pads)' if n > 1 else ''))
return out
def census_detail(differences, rule):
"""The census-matches-metadata detail for compare()'s differences."""
return _cap(_say(rule, 'census', len(differences), parts='; '.join(differences[:4]) + (f'; and {len(differences) - 4} more' if len(differences) > 4 else '')), rule.msg['refusalEnd'])
# ---------------------------------------------------------------- command line
SKIP_DIRS = re.compile(r'(^|/)(node_modules|\.git)(/|$)')
def source_pattern(pattern, slug=''):
"""A predicate over repo paths for one recipe source pattern, as the wiki's recipe engine
reads it: {slug} is `slug`, '*' any run of characters within one segment, a segment '**'
zero or more whole segments, case ignored; a pattern without '/' matches a file name at
any depth, one with '/' the whole path."""
parts = pattern.split('/')
segs = [s for i, s in enumerate(parts) if not (s == '**' and i and parts[i - 1] == '**')]
def seg(s):
return ''.join(re.escape(slug) if p == '{slug}' else '[^/]*' if p == '*' else re.escape(p) for p in re.split(r'(\{slug\}|\*)', s))
rx = ''
for i, s in enumerate(segs):
first, last = i == 0, i == len(segs) - 1
if s != '**':
rx += ('' if first or segs[i - 1] == '**' else '/') + seg(s)
elif first and last:
rx += '[^/]+(?:/[^/]+)*'
elif last:
rx += '(?:/[^/]+)*'
else:
rx += ('' if first else '/') + '(?:[^/]+/)*'
m = re.compile(rx, re.I)
whole = '/' in pattern
return lambda path: m.fullmatch(path if whole else path.rsplit('/', 1)[-1]) is not None
def board_source(paths, slug, recipes):
"""The board file a molecule page's build reads among its repo paths `paths`, as the
recipes `recipes` (contract.json's) select it for the page slug `slug`. The recipes that
apply to kind molecule are taken in order, each by its board file source (circuit on the
circuit route, else board) and only that source: its exclude patterns remove files, its
patterns are tried in order, the first that matches anything wins, and the shallowest of
its matches is the file. Returns {recipe, role, route, pattern, path} for the first recipe
whose source matches one file, {recipe, role, route, pattern, ambiguous: [paths]} when it
matches two or more at that depth (the build refuses the page), or None when none matches.
The recipes' other sources are not looked at, so a folder whose STEP is missing or
ambiguous still has a board file here."""
for r in recipes:
if 'molecule' not in (r.get('applies') or {}).get('kinds', []):
continue
route = r['pipeline']['options']['route']
role = 'circuit' if route == 'circuit' else 'board'
spec = r['sources'].get(role)
if not spec:
continue
excluded = [source_pattern(p, slug) for p in spec.get('exclude', [])]
files = [f for f in paths if not any(m(f) for m in excluded)]
for pattern in spec['match']:
m = source_pattern(pattern, slug)
hits = [f for f in files if m(f)]
if not hits:
continue
depth = min(f.count('/') for f in hits)
best = sorted(f for f in hits if f.count('/') == depth)
out = {'recipe': f"{r['name']}/{r['version']}", 'role': role, 'route': route, 'pattern': pattern}
return {**out, 'ambiguous': best} if len(best) > 1 else {**out, 'path': best[0]}
return None
def pick_board(folder, slug=None, contract=None):
"""The board file a molecule page's build reads when `folder` is its repository, by
board_source() with the recipes of contract.json (contract_path(contract)) and the page
slug `slug`, default the folder's name. Files under a .git or node_modules folder are left
out. Returns (path, route), or raises ValueError when the source is ambiguous or no recipe's
board file source matches."""
root = Path(folder)
slug = root.resolve().name if slug is None else slug
recipes = json.loads(contract_path(contract).read_text(encoding='utf-8'))['recipes']
files = sorted(p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and not SKIP_DIRS.search(p.relative_to(root).as_posix()))
hit = board_source(files, slug, recipes)
if hit is None:
raise ValueError(f'no file in {folder} is the board file of a molecule recipe (circuit.json, *.circuit.json, *.kicad_pcb, *.brd, *.PcbDoc, *.fbrd outside library folders)')
if 'ambiguous' in hit:
raise ValueError(f"{hit['recipe']} source {hit['role']} ({hit['pattern']}): ambiguous: {', '.join(hit['ambiguous'])}; "
f"a board named for the slug ({slug!r}) is taken first, so pass --slug if the page's slug is another")
return root / hit['path'], hit['route']
def self_check(contract=None):
out = {'namesPy': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'pins': hashlib.sha256(pins_path().read_bytes()).hexdigest()}
print(json.dumps(out, indent=2))
if contract:
v = json.loads(Path(contract).read_text(encoding='utf-8')).get('versions', {})
for k in out:
if v.get(k) != out[k]:
print(f'warning: {k} is {out[k]}, the contract names {v.get(k)}; this copy is older or newer than the contract', file=sys.stderr)
return 0
def main(argv):
if argv[:1] in (['self-check'], ['--self-check']):
return self_check(argv[1] if len(argv) > 1 else None)
if argv[:1] != ['check'] or len(argv) < 2:
print(__doc__.split('\n\n')[-1], file=sys.stderr)
return 2
opts = {argv[i]: argv[i + 1] for i in range(2, len(argv) - 1) if argv[i] in ('--route', '--pins', '--slug', '--contract')}
rule = Rule(opts.get('--pins'))
target = Path(argv[1])
try:
path, route = (pick_board(target, opts.get('--slug'), opts.get('--contract')) if target.is_dir()
else (target, 'circuit' if board_format(target) == 'circuit_json' else 'board'))
except (ValueError, OSError) as e:
print(f'error: {e}', file=sys.stderr)
return 2
route = opts.get('--route', route)
result = census(path, route, rule, repo_path=path.relative_to(target).as_posix() if target.is_dir() else path.name)
if '--json' in argv:
print(json.dumps({'census': result['report'], 'checks': result['checks'], 'accepted': result['accepted']}, indent=2))
else:
print(json.dumps(result['report'], indent=2))
for c in result['checks']:
if not c['pass'] or c['level'] != 'fail':
print(f"{'refused' if not c['pass'] else c['level']} {c['id']}: {c['detail']}")
return 1 if any(not c['pass'] for c in result['checks']) else 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))